hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7acae51e9ab34b040270e07fb1bf9e3816e4a705 | 26,054 | cpp | C++ | measurer/hotspot-measurer/hotspot/agent/src/os/win32/SwDbgSub.cpp | armoredsoftware/protocol | e3b0c1df8bc1027865caec6d117e5925f71f26d2 | [
"BSD-3-Clause"
] | null | null | null | measurer/hotspot-measurer/hotspot/agent/src/os/win32/SwDbgSub.cpp | armoredsoftware/protocol | e3b0c1df8bc1027865caec6d117e5925f71f26d2 | [
"BSD-3-Clause"
] | null | null | null | measurer/hotspot-measurer/hotspot/agent/src/os/win32/SwDbgSub.cpp | armoredsoftware/protocol | e3b0c1df8bc1027865caec6d117e5925f71f26d2 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
// This is the source code for the subprocess forked by the Simple
// Windows Debug Server. It assumes most of the responsibility for the
// debug session, and processes all of the commands sent by clients.
// Disable too-long symbol warnings
#pragma warning ( disable : 4786 )
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <assert.h>
// Must come before windows.h
#include <winsock2.h>
#include <windows.h>
#include "IOBuf.hpp"
#include "libInfo.hpp"
#include "LockableList.hpp"
#include "Message.hpp"
#include "Monitor.hpp"
#include "nt4internals.hpp"
// Uncomment the #define below to get messages on stderr
// #define DEBUGGING
using namespace std;
DWORD pid;
HANDLE procHandle;
IOBuf* ioBuf;
// State flags indicating whether the attach to the remote process
// definitively succeeded or failed
volatile bool attachFailed = false;
volatile bool attachSucceeded = false;
// State flag indicating whether the target process is suspended.
// Modified by suspend()/resume(), viewed by debug thread, but only
// under cover of the threads lock.
volatile bool suspended = false;
// State flags indicating whether we are considered to be attached to
// the target process and are therefore queuing up events to be sent
// back to the debug server. These flags are only accessed and
// modified under the cover of the eventLock.
Monitor* eventLock;
// The following is set to true when a client is attached to this process
volatile bool generateDebugEvents = false;
// Pointer to current debug event; non-NULL indicates a debug event is
// waiting to be sent to the client. Main thread sets this to NULL to
// indicate that the event has been consumed; also sets
// passEventToClient, below.
volatile DEBUG_EVENT* curDebugEvent = NULL;
// Set by main thread to indicate whether the most recently posted
// debug event should be passed on to the target process.
volatile bool passEventToClient = true;
void conditionalPostDebugEvent(DEBUG_EVENT* ev, DWORD* continueOrNotHandledFlag) {
// FIXME: make it possible for the client to enable and disable
// certain types of events (have to do so in a platform-independent
// manner)
switch (ev->dwDebugEventCode) {
case EXCEPTION_DEBUG_EVENT:
switch (ev->u.Exception.ExceptionRecord.ExceptionCode) {
case EXCEPTION_BREAKPOINT: break;
case EXCEPTION_SINGLE_STEP: break;
case EXCEPTION_ACCESS_VIOLATION: break;
default: return;
}
}
eventLock->lock();
if (generateDebugEvents) {
curDebugEvent = ev;
while (curDebugEvent != NULL) {
eventLock->wait();
}
if (passEventToClient) {
*continueOrNotHandledFlag = DBG_EXCEPTION_NOT_HANDLED;
} else {
*continueOrNotHandledFlag = DBG_CONTINUE;
}
}
eventLock->unlock();
}
//----------------------------------------------------------------------
// Module list
//
vector<LibInfo> libs;
//----------------------------------------------------------------------
// Thread list
//
struct ThreadInfo {
DWORD tid;
HANDLE thread;
ThreadInfo(DWORD tid, HANDLE thread) {
this->tid = tid;
this->thread = thread;
}
};
class ThreadList : public LockableList<ThreadInfo> {
public:
bool removeByThreadID(DWORD tid) {
for (InternalListType::iterator iter = internalList.begin();
iter != internalList.end(); iter++) {
if ((*iter).tid == tid) {
internalList.erase(iter);
return true;
}
}
return false;
}
HANDLE threadIDToHandle(DWORD tid) {
for (InternalListType::iterator iter = internalList.begin();
iter != internalList.end(); iter++) {
if ((*iter).tid == tid) {
return (*iter).thread;
}
}
return NULL;
}
};
ThreadList threads;
//----------------------------------------------------------------------
// INITIALIZATION AND TERMINATION
//
void
printError(const char* prefix) {
DWORD detail = GetLastError();
LPTSTR message;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
0,
detail,
0,
(LPTSTR) &message,
1,
NULL);
// FIXME: This is signaling an error: "The handle is invalid." ?
// Do I have to do all of my WaitForDebugEvent calls from the same thread?
cerr << prefix << ": " << message << endl;
LocalFree(message);
}
void
endProcess(bool waitForProcess = true) {
NT4::unloadNTDLL();
if (waitForProcess) {
// Though we're exiting because of an error, do not tear down the
// target process.
WaitForSingleObject(procHandle, INFINITE);
}
CloseHandle(procHandle);
exit(0);
}
DWORD WINAPI
debugThreadEntry(void*) {
#ifdef DEBUGGING
DWORD lastMsgId = 0;
int count = 0;
#endif
if (!DebugActiveProcess(pid)) {
attachFailed = true;
return 0;
}
// Wait for debug events. We keep the information from some of these
// on the side in anticipation of later queries by the client. NOTE
// that we leave the process running. The main thread is responsible
// for suspending and resuming all currently-active threads upon
// client attach and detach.
while (true) {
DEBUG_EVENT ev;
if (!WaitForDebugEvent(&ev, INFINITE)) {
#ifdef DEBUGGING
if (++count < 10) {
// FIXME: This is signaling an error: "The handle is invalid." ?
// Do I have to do all of my WaitForDebugEvent calls from the same thread?
printError("WaitForDebugEvent failed");
}
#endif
} else {
#ifdef DEBUGGING
if (ev.dwDebugEventCode != lastMsgId) {
lastMsgId = ev.dwDebugEventCode;
count = 0;
cerr << "Debug thread received event " << ev.dwDebugEventCode << endl;
} else {
if (++count < 10) {
cerr << "Debug thread received event " << ev.dwDebugEventCode << endl;
}
}
#endif
DWORD dbgContinueMode = DBG_CONTINUE;
switch (ev.dwDebugEventCode) {
case LOAD_DLL_DEBUG_EVENT:
conditionalPostDebugEvent(&ev, &dbgContinueMode);
break;
case UNLOAD_DLL_DEBUG_EVENT:
conditionalPostDebugEvent(&ev, &dbgContinueMode);
break;
case CREATE_PROCESS_DEBUG_EVENT:
threads.lock();
// FIXME: will this deal properly with child processes? If
// not, is it possible to make it do so?
#ifdef DEBUGGING
cerr << "CREATE_PROCESS_DEBUG_EVENT " << ev.dwThreadId
<< " " << ev.u.CreateProcessInfo.hThread << endl;
#endif
if (ev.u.CreateProcessInfo.hThread != NULL) {
threads.add(ThreadInfo(ev.dwThreadId, ev.u.CreateProcessInfo.hThread));
}
threads.unlock();
break;
case CREATE_THREAD_DEBUG_EVENT:
threads.lock();
#ifdef DEBUGGING
cerr << "CREATE_THREAD_DEBUG_EVENT " << ev.dwThreadId
<< " " << ev.u.CreateThread.hThread << endl;
#endif
if (suspended) {
// Suspend this thread before adding it to the thread list
SuspendThread(ev.u.CreateThread.hThread);
}
threads.add(ThreadInfo(ev.dwThreadId, ev.u.CreateThread.hThread));
threads.unlock();
break;
case EXIT_THREAD_DEBUG_EVENT:
threads.lock();
#ifdef DEBUGGING
cerr << "EXIT_THREAD_DEBUG_EVENT " << ev.dwThreadId << endl;
#endif
threads.removeByThreadID(ev.dwThreadId);
threads.unlock();
break;
case EXCEPTION_DEBUG_EVENT:
// cerr << "EXCEPTION_DEBUG_EVENT" << endl;
switch (ev.u.Exception.ExceptionRecord.ExceptionCode) {
case EXCEPTION_BREAKPOINT:
// cerr << "EXCEPTION_BREAKPOINT" << endl;
if (!attachSucceeded && !attachFailed) {
attachSucceeded = true;
}
break;
default:
dbgContinueMode = DBG_EXCEPTION_NOT_HANDLED;
break;
}
conditionalPostDebugEvent(&ev, &dbgContinueMode);
break;
case EXIT_PROCESS_DEBUG_EVENT:
endProcess(false);
// NOT REACHED
break;
default:
#ifdef DEBUGGING
cerr << "Received debug event " << ev.dwDebugEventCode << endl;
#endif
break;
}
ContinueDebugEvent(ev.dwProcessId, ev.dwThreadId, dbgContinueMode);
}
}
}
bool
attachToProcess() {
// Create event lock
eventLock = new Monitor();
// Get a process handle for later
procHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
if (procHandle == NULL) {
return false;
}
// Start up the debug thread
DWORD debugThreadId;
if (CreateThread(NULL, 0, &debugThreadEntry, NULL, 0, &debugThreadId) == NULL) {
// Failed to make background debug thread. Fail.
return false;
}
while ((!attachSucceeded) && (!attachFailed)) {
Sleep(1);
}
if (attachFailed) {
return false;
}
assert(attachSucceeded);
return true;
}
bool
readMessage(Message* msg) {
DWORD numRead;
if (!ReadFile(GetStdHandle(STD_INPUT_HANDLE),
msg,
sizeof(Message),
&numRead,
NULL)) {
return false;
}
if (numRead != sizeof(Message)) {
return false;
}
// For "poke" messages, must follow up by reading raw data
if (msg->type == Message::POKE) {
char* dataBuf = new char[msg->pokeArg.numBytes];
if (dataBuf == NULL) {
return false;
}
if (!ReadFile(GetStdHandle(STD_INPUT_HANDLE),
dataBuf,
msg->pokeArg.numBytes,
&numRead,
NULL)) {
delete[] dataBuf;
return false;
}
if (numRead != msg->pokeArg.numBytes) {
delete[] dataBuf;
return false;
}
msg->pokeArg.data = (void *) dataBuf;
}
return true;
}
void
handlePeek(Message* msg) {
#ifdef DEBUGGING
cerr << "Entering handlePeek()" << endl;
#endif
char* memBuf = new char[msg->peekArg.numBytes];
if (memBuf == NULL) {
ioBuf->writeString("B");
ioBuf->writeBinChar(0);
ioBuf->flush();
delete[] memBuf;
return;
}
// Try fast case first
DWORD numRead;
BOOL res = ReadProcessMemory(procHandle,
(LPCVOID) msg->peekArg.address,
memBuf,
msg->peekArg.numBytes,
&numRead);
if (res && (numRead == msg->peekArg.numBytes)) {
// OK, complete success. Phew.
#ifdef DEBUGGING
cerr << "Peek success case" << endl;
#endif
ioBuf->writeString("B");
ioBuf->writeBinChar(1);
ioBuf->writeBinUnsignedInt(numRead);
ioBuf->writeBinChar(1);
ioBuf->writeBinBuf(memBuf, numRead);
} else {
#ifdef DEBUGGING
cerr << "*** Peek slow case ***" << endl;
#endif
ioBuf->writeString("B");
ioBuf->writeBinChar(1);
// Use VirtualQuery to speed things up a bit
DWORD numLeft = msg->peekArg.numBytes;
char* curAddr = (char*) msg->peekArg.address;
while (numLeft > 0) {
MEMORY_BASIC_INFORMATION memInfo;
VirtualQueryEx(procHandle, curAddr, &memInfo, sizeof(memInfo));
DWORD numToRead = memInfo.RegionSize;
if (numToRead > numLeft) {
numToRead = numLeft;
}
DWORD numRead;
if (memInfo.State == MEM_COMMIT) {
// Read the process memory at this address for this length
// FIXME: should check the result of this read
ReadProcessMemory(procHandle, curAddr, memBuf,
numToRead, &numRead);
// Write this out
#ifdef DEBUGGING
cerr << "*** Writing " << numToRead << " bytes as mapped ***" << endl;
#endif
ioBuf->writeBinUnsignedInt(numToRead);
ioBuf->writeBinChar(1);
ioBuf->writeBinBuf(memBuf, numToRead);
} else {
// Indicate region is free
#ifdef DEBUGGING
cerr << "*** Writing " << numToRead << " bytes as unmapped ***" << endl;
#endif
ioBuf->writeBinUnsignedInt(numToRead);
ioBuf->writeBinChar(0);
}
curAddr += numToRead;
numLeft -= numToRead;
}
}
ioBuf->flush();
delete[] memBuf;
#ifdef DEBUGGING
cerr << "Exiting handlePeek()" << endl;
#endif
}
void
handlePoke(Message* msg) {
#ifdef DEBUGGING
cerr << "Entering handlePoke()" << endl;
#endif
DWORD numWritten;
BOOL res = WriteProcessMemory(procHandle,
(LPVOID) msg->pokeArg.address,
msg->pokeArg.data,
msg->pokeArg.numBytes,
&numWritten);
if (res && (numWritten == msg->pokeArg.numBytes)) {
// Success
ioBuf->writeBoolAsInt(true);
#ifdef DEBUGGING
cerr << " (Succeeded)" << endl;
#endif
} else {
// Failure
ioBuf->writeBoolAsInt(false);
#ifdef DEBUGGING
cerr << " (Failed)" << endl;
#endif
}
ioBuf->writeEOL();
ioBuf->flush();
// We clean up the data
char* dataBuf = (char*) msg->pokeArg.data;
delete[] dataBuf;
#ifdef DEBUGGING
cerr << "Exiting handlePoke()" << endl;
#endif
}
bool
suspend() {
if (suspended) {
return false;
}
// Before we suspend, we must take a snapshot of the loaded module
// names and base addresses, since acquiring this snapshot requires
// starting and exiting a thread in the remote process (at least on
// NT 4).
libs.clear();
#ifdef DEBUGGING
cerr << "Starting suspension" << endl;
#endif
libInfo(pid, libs);
#ifdef DEBUGGING
cerr << " Got lib info" << endl;
#endif
threads.lock();
#ifdef DEBUGGING
cerr << " Got thread lock" << endl;
#endif
suspended = true;
int j = 0;
for (int i = 0; i < threads.size(); i++) {
j++;
SuspendThread(threads.get(i).thread);
}
#ifdef DEBUGGING
cerr << "Suspended " << j << " threads" << endl;
#endif
threads.unlock();
return true;
}
bool
resume() {
if (!suspended) {
return false;
}
threads.lock();
suspended = false;
for (int i = 0; i < threads.size(); i++) {
ResumeThread(threads.get(i).thread);
}
threads.unlock();
#ifdef DEBUGGING
cerr << "Resumed process" << endl;
#endif
return true;
}
int
main(int argc, char **argv)
{
if (argc != 2) {
// Should only be used by performing CreateProcess within SwDbgSrv
exit(1);
}
if (sscanf(argv[1], "%u", &pid) != 1) {
exit(1);
}
// Try to attach to process
if (!attachToProcess()) {
// Attach failed. Notify parent by writing result to stdout file
// handle.
char res = 0;
DWORD numBytes;
WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), &res, sizeof(res),
&numBytes, NULL);
exit(1);
}
// Server is expecting success result back.
char res = 1;
DWORD numBytes;
WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), &res, sizeof(res),
&numBytes, NULL);
// Initialize our I/O buffer
ioBuf = new IOBuf(32768, 131072);
ioBuf->setOutputFileHandle(GetStdHandle(STD_OUTPUT_HANDLE));
// At this point we are attached. Enter our main loop which services
// requests from the server. Note that in order to handle attach/
// detach properly (i.e., resumption of process upon "detach") we
// will need another thread which handles debug events.
while (true) {
// Read a message from the server
Message msg;
if (!readMessage(&msg)) {
endProcess();
}
#ifdef DEBUGGING
cerr << "Main thread read message: " << msg.type << endl;
#endif
switch (msg.type) {
// ATTACH and DETACH messages MUST come in pairs
case Message::ATTACH:
suspend();
eventLock->lock();
generateDebugEvents = true;
eventLock->unlock();
break;
case Message::DETACH:
eventLock->lock();
generateDebugEvents = false;
// Flush remaining event if any
if (curDebugEvent != NULL) {
curDebugEvent = NULL;
eventLock->notifyAll();
}
eventLock->unlock();
resume();
break;
case Message::LIBINFO:
{
if (!suspended) {
ioBuf->writeInt(0);
} else {
// Send back formatted text
ioBuf->writeInt(libs.size());
for (int i = 0; i < libs.size(); i++) {
ioBuf->writeSpace();
ioBuf->writeInt(1);
ioBuf->writeSpace();
ioBuf->writeInt(libs[i].name.size());
ioBuf->writeSpace();
ioBuf->writeString(libs[i].name.c_str());
ioBuf->writeSpace();
ioBuf->writeAddress(libs[i].base);
}
}
ioBuf->writeEOL();
ioBuf->flush();
break;
}
case Message::PEEK:
handlePeek(&msg);
break;
case Message::POKE:
handlePoke(&msg);
break;
case Message::THREADLIST:
{
if (!suspended) {
ioBuf->writeInt(0);
} else {
threads.lock();
ioBuf->writeInt(threads.size());
for (int i = 0; i < threads.size(); i++) {
ioBuf->writeSpace();
ioBuf->writeAddress((void*) threads.get(i).thread);
}
threads.unlock();
}
ioBuf->writeEOL();
ioBuf->flush();
break;
}
case Message::DUPHANDLE:
{
HANDLE dup;
if (DuplicateHandle(procHandle,
msg.handleArg.handle,
GetCurrentProcess(),
&dup,
0,
FALSE,
DUPLICATE_SAME_ACCESS)) {
ioBuf->writeBoolAsInt(true);
ioBuf->writeSpace();
ioBuf->writeAddress((void*) dup);
} else {
ioBuf->writeBoolAsInt(false);
}
ioBuf->writeEOL();
ioBuf->flush();
break;
}
case Message::CLOSEHANDLE:
{
CloseHandle(msg.handleArg.handle);
break;
}
case Message::GETCONTEXT:
{
if (!suspended) {
ioBuf->writeBoolAsInt(false);
} else {
CONTEXT context;
context.ContextFlags = CONTEXT_FULL | CONTEXT_DEBUG_REGISTERS;
if (GetThreadContext(msg.handleArg.handle, &context)) {
ioBuf->writeBoolAsInt(true);
// EAX, EBX, ECX, EDX, ESI, EDI, EBP, ESP, EIP, DS, ES, FS, GS,
// CS, SS, EFLAGS, DR0, DR1, DR2, DR3, DR6, DR7
// See README-commands.txt
ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Eax);
ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Ebx);
ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Ecx);
ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Edx);
ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Esi);
ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Edi);
ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Ebp);
ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Esp);
ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Eip);
ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.SegDs);
ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.SegEs);
ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.SegFs);
ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.SegGs);
ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.SegCs);
ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.SegSs);
ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.EFlags);
ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Dr0);
ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Dr1);
ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Dr2);
ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Dr3);
ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Dr6);
ioBuf->writeSpace(); ioBuf->writeAddress((void*) context.Dr7);
} else {
ioBuf->writeBoolAsInt(false);
}
}
ioBuf->writeEOL();
ioBuf->flush();
break;
}
case Message::SETCONTEXT:
{
if (!suspended) {
ioBuf->writeBoolAsInt(false);
} else {
CONTEXT context;
context.ContextFlags = CONTEXT_FULL | CONTEXT_DEBUG_REGISTERS;
context.Eax = msg.setContextArg.Eax;
context.Ebx = msg.setContextArg.Ebx;
context.Ecx = msg.setContextArg.Ecx;
context.Edx = msg.setContextArg.Edx;
context.Esi = msg.setContextArg.Esi;
context.Edi = msg.setContextArg.Edi;
context.Ebp = msg.setContextArg.Ebp;
context.Esp = msg.setContextArg.Esp;
context.Eip = msg.setContextArg.Eip;
context.SegDs = msg.setContextArg.Ds;
context.SegEs = msg.setContextArg.Es;
context.SegFs = msg.setContextArg.Fs;
context.SegGs = msg.setContextArg.Gs;
context.SegCs = msg.setContextArg.Cs;
context.SegSs = msg.setContextArg.Ss;
context.EFlags = msg.setContextArg.EFlags;
context.Dr0 = msg.setContextArg.Dr0;
context.Dr1 = msg.setContextArg.Dr1;
context.Dr2 = msg.setContextArg.Dr2;
context.Dr3 = msg.setContextArg.Dr3;
context.Dr6 = msg.setContextArg.Dr6;
context.Dr7 = msg.setContextArg.Dr7;
if (SetThreadContext(msg.setContextArg.handle, &context)) {
ioBuf->writeBoolAsInt(true);
} else {
ioBuf->writeBoolAsInt(false);
}
}
ioBuf->writeEOL();
ioBuf->flush();
break;
}
case Message::SELECTORENTRY:
{
LDT_ENTRY entry;
if (GetThreadSelectorEntry(msg.selectorArg.handle,
msg.selectorArg.selector,
&entry)) {
ioBuf->writeBoolAsInt(true);
ioBuf->writeSpace(); ioBuf->writeAddress((void*) entry.LimitLow);
ioBuf->writeSpace(); ioBuf->writeAddress((void*) entry.BaseLow);
ioBuf->writeSpace(); ioBuf->writeAddress((void*) entry.HighWord.Bytes.BaseMid);
ioBuf->writeSpace(); ioBuf->writeAddress((void*) entry.HighWord.Bytes.Flags1);
ioBuf->writeSpace(); ioBuf->writeAddress((void*) entry.HighWord.Bytes.Flags2);
ioBuf->writeSpace(); ioBuf->writeAddress((void*) entry.HighWord.Bytes.BaseHi);
} else {
ioBuf->writeBoolAsInt(false);
}
ioBuf->writeEOL();
ioBuf->flush();
break;
}
case Message::SUSPEND:
suspend();
break;
case Message::RESUME:
resume();
break;
case Message::POLLEVENT:
eventLock->lock();
if (curDebugEvent == NULL) {
ioBuf->writeBoolAsInt(false);
} else {
ioBuf->writeBoolAsInt(true);
ioBuf->writeSpace();
threads.lock();
ioBuf->writeAddress((void*) threads.threadIDToHandle(curDebugEvent->dwThreadId));
threads.unlock();
ioBuf->writeSpace();
ioBuf->writeUnsignedInt(curDebugEvent->dwDebugEventCode);
// Figure out what else to write
switch (curDebugEvent->dwDebugEventCode) {
case LOAD_DLL_DEBUG_EVENT:
ioBuf->writeSpace();
ioBuf->writeAddress(curDebugEvent->u.LoadDll.lpBaseOfDll);
break;
case UNLOAD_DLL_DEBUG_EVENT:
ioBuf->writeSpace();
ioBuf->writeAddress(curDebugEvent->u.UnloadDll.lpBaseOfDll);
break;
case EXCEPTION_DEBUG_EVENT:
{
DWORD code = curDebugEvent->u.Exception.ExceptionRecord.ExceptionCode;
ioBuf->writeSpace();
ioBuf->writeUnsignedInt(code);
ioBuf->writeSpace();
ioBuf->writeAddress(curDebugEvent->u.Exception.ExceptionRecord.ExceptionAddress);
switch (curDebugEvent->u.Exception.ExceptionRecord.ExceptionCode) {
case EXCEPTION_ACCESS_VIOLATION:
ioBuf->writeSpace();
ioBuf->writeBoolAsInt(curDebugEvent->u.Exception.ExceptionRecord.ExceptionInformation[0] != 0);
ioBuf->writeSpace();
ioBuf->writeAddress((void*) curDebugEvent->u.Exception.ExceptionRecord.ExceptionInformation[1]);
break;
default:
break;
}
break;
}
default:
break;
}
}
eventLock->unlock();
ioBuf->writeEOL();
ioBuf->flush();
break;
case Message::CONTINUEEVENT:
eventLock->lock();
if (curDebugEvent == NULL) {
ioBuf->writeBoolAsInt(false);
} else {
curDebugEvent = NULL;
passEventToClient = msg.boolArg.val;
ioBuf->writeBoolAsInt(true);
eventLock->notify();
}
eventLock->unlock();
ioBuf->writeEOL();
ioBuf->flush();
break;
}
}
endProcess();
// NOT REACHED
return 0;
}
| 29.472851 | 110 | 0.598411 | [
"vector"
] |
7ad257e8bf30a31799b0c9f15f35de77aeed5a74 | 81,756 | cpp | C++ | sim/simx/execute.cpp | troyguo/vortex-1 | 77002dd06ad51dd71497d2a17842c3f5b1989db6 | [
"BSD-3-Clause"
] | null | null | null | sim/simx/execute.cpp | troyguo/vortex-1 | 77002dd06ad51dd71497d2a17842c3f5b1989db6 | [
"BSD-3-Clause"
] | null | null | null | sim/simx/execute.cpp | troyguo/vortex-1 | 77002dd06ad51dd71497d2a17842c3f5b1989db6 | [
"BSD-3-Clause"
] | 1 | 2021-11-28T02:19:01.000Z | 2021-11-28T02:19:01.000Z | #include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
#include <bitset>
#include <climits>
#include <sys/types.h>
#include <sys/stat.h>
#include <assert.h>
#include <util.h>
#include <rvfloats.h>
#include "warp.h"
#include "instr.h"
#include "core.h"
using namespace vortex;
union reg_data_t {
Word i;
FWord f;
uint64_t _;
};
static bool HasDivergentThreads(const ThreadMask &thread_mask,
const std::vector<std::vector<Word>> ®_file,
unsigned reg) {
bool cond;
size_t thread_idx = 0;
size_t num_threads = reg_file.size();
for (; thread_idx < num_threads; ++thread_idx) {
if (thread_mask[thread_idx]) {
cond = bool(reg_file[thread_idx][reg]);
break;
}
}
assert(thread_idx != num_threads);
for (; thread_idx < num_threads; ++thread_idx) {
if (thread_mask[thread_idx]) {
if (cond != (bool(reg_file[thread_idx][reg]))) {
return true;
}
}
}
return false;
}
inline uint32_t get_fpu_rm(uint32_t func3, Core* core, uint32_t tid, uint32_t wid) {
return (func3 == 0x7) ? core->get_csr(CSR_FRM, tid, wid) : func3;
}
static void update_fcrs(uint32_t fflags, Core* core, uint32_t tid, uint32_t wid) {
if (fflags) {
core->set_csr(CSR_FCSR, core->get_csr(CSR_FCSR, tid, wid) | fflags, tid, wid);
core->set_csr(CSR_FFLAGS, core->get_csr(CSR_FFLAGS, tid, wid) | fflags, tid, wid);
}
}
inline uint64_t nan_box(uint32_t value) {
uint64_t mask = 0xffffffff00000000;
return value | mask;
}
inline bool is_nan_boxed(uint64_t value) {
return (uint32_t(value >> 32) == 0xffffffff);
}
static bool checkBoxedArgs(FWord* out, FWord a, FWord b, uint32_t* fflags) {
bool xa = is_nan_boxed(a);
bool xb = is_nan_boxed(b);
if (xa && xb)
return true;
if (xa) {
// a is NaN boxed but b isn't
*out = nan_box((uint32_t)a);
} else if (xb) {
// b is NaN boxed but a isn't
*out = nan_box(0xffc00000);
} else {
// Both a and b aren't NaN boxed
*out = nan_box(0x7fc00000);
}
*fflags = 0;
return false;
}
static bool checkBoxedArgs(FWord* out, FWord a, uint32_t* fflags) {
bool xa = is_nan_boxed(a);
if (xa)
return true;
*out = nan_box(0x7fc00000);
*fflags = 0;
return false;
}
static bool checkBoxedCmpArgs(Word* out, FWord a, FWord b, uint32_t* fflags) {
bool xa = is_nan_boxed(a);
bool xb = is_nan_boxed(b);
if (xa && xb)
return true;
*out = 0;
*fflags = 0;
return false;
}
void Warp::execute(const Instr &instr, pipeline_trace_t *trace) {
assert(tmask_.any());
auto nextPC = PC_ + core_->arch().wsize();
auto func2 = instr.getFunc2();
auto func3 = instr.getFunc3();
auto func6 = instr.getFunc6();
auto func7 = instr.getFunc7();
auto opcode = instr.getOpcode();
auto rdest = instr.getRDest();
auto rsrc0 = instr.getRSrc(0);
auto rsrc1 = instr.getRSrc(1);
auto rsrc2 = instr.getRSrc(2);
auto immsrc = sext((Word)instr.getImm(), 32);
auto vmask = instr.getVmask();
auto num_threads = core_->arch().num_threads();
std::vector<reg_data_t[3]> rsdata(num_threads);
std::vector<reg_data_t> rddata(num_threads);
auto num_rsrcs = instr.getNRSrc();
if (num_rsrcs) {
for (uint32_t i = 0; i < num_rsrcs; ++i) {
DPH(2, "Src Reg [" << std::dec << i << "]: ");
auto type = instr.getRSType(i);
auto reg = instr.getRSrc(i);
switch (type) {
case RegType::Integer:
DPN(2, type << std::dec << reg << "={");
for (uint32_t t = 0; t < num_threads; ++t) {
if (t) DPN(2, ", ");
if (!tmask_.test(t)) {
DPN(2, "-");
continue;
}
rsdata[t][i].i = ireg_file_.at(t)[reg];
DPN(2, std::hex << rsdata[t][i].i);
}
DPN(2, "}" << std::endl);
break;
case RegType::Float:
DPN(2, type << std::dec << reg << "={");
for (uint32_t t = 0; t < num_threads; ++t) {
if (t) DPN(2, ", ");
if (!tmask_.test(t)) {
DPN(2, "-");
continue;
}
rsdata[t][i].f = freg_file_.at(t)[reg];
DPN(2, std::hex << rsdata[t][i].f);
}
DPN(2, "}" << std::endl);
break;
default:
std::abort();
break;
}
}
}
bool rd_write = false;
switch (opcode) {
case NOP:
break;
// RV32I: LUI
case LUI_INST: {
trace->exe_type = ExeType::ALU;
trace->alu.type = AluType::ARITH;
for (uint32_t t = 0; t < num_threads; ++t) {
if (!tmask_.test(t))
continue;
rddata[t].i = immsrc << 12;
}
rd_write = true;
break;
}
// RV32I: AUIPC
case AUIPC_INST: {
trace->exe_type = ExeType::ALU;
trace->alu.type = AluType::ARITH;
for (uint32_t t = 0; t < num_threads; ++t) {
if (!tmask_.test(t))
continue;
rddata[t].i = (immsrc << 12) + PC_;
}
rd_write = true;
break;
}
case R_INST: {
trace->exe_type = ExeType::ALU;
trace->alu.type = AluType::ARITH;
trace->used_iregs.set(rsrc0);
trace->used_iregs.set(rsrc1);
for (uint32_t t = 0; t < num_threads; ++t) {
if (!tmask_.test(t))
continue;
if (func7 & 0x1) {
switch (func3) {
case 0: {
// RV32M: MUL
rddata[t].i = (WordI)rsdata[t][0].i * (WordI)rsdata[t][1].i;
trace->alu.type = AluType::IMUL;
break;
}
case 1: {
// RV32M: MULH
DWordI first = sext((DWord)rsdata[t][0].i, XLEN);
DWordI second = sext((DWord)rsdata[t][1].i, XLEN);
rddata[t].i = (first * second) >> XLEN;
trace->alu.type = AluType::IMUL;
break;
}
case 2: {
// RV32M: MULHSU
DWordI first = sext((DWord)rsdata[t][0].i, XLEN);
DWord second = rsdata[t][1].i;
rddata[t].i = (first * second) >> XLEN;
trace->alu.type = AluType::IMUL;
break;
}
case 3: {
// RV32M: MULHU
DWord first = rsdata[t][0].i;
DWord second = rsdata[t][1].i;
rddata[t].i = (first * second) >> XLEN;
trace->alu.type = AluType::IMUL;
break;
}
case 4: {
// RV32M: DIV
WordI dividen = rsdata[t][0].i;
WordI divisor = rsdata[t][1].i;
WordI largest_negative = WordI(1) << (XLEN-1);
if (divisor == 0) {
rddata[t].i = -1;
} else if (dividen == largest_negative && divisor == -1) {
rddata[t].i = dividen;
} else {
rddata[t].i = dividen / divisor;
}
trace->alu.type = AluType::IDIV;
break;
}
case 5: {
// RV32M: DIVU
Word dividen = rsdata[t][0].i;
Word divisor = rsdata[t][1].i;
if (divisor == 0) {
rddata[t].i = -1;
} else {
rddata[t].i = dividen / divisor;
}
trace->alu.type = AluType::IDIV;
break;
}
case 6: {
// RV32M: REM
WordI dividen = rsdata[t][0].i;
WordI divisor = rsdata[t][1].i;
WordI largest_negative = WordI(1) << (XLEN-1);
if (rsdata[t][1].i == 0) {
rddata[t].i = dividen;
} else if (dividen == largest_negative && divisor == -1) {
rddata[t].i = 0;
} else {
rddata[t].i = dividen % divisor;
}
trace->alu.type = AluType::IDIV;
break;
}
case 7: {
// RV32M: REMU
Word dividen = rsdata[t][0].i;
Word divisor = rsdata[t][1].i;
if (rsdata[t][1].i == 0) {
rddata[t].i = dividen;
} else {
rddata[t].i = dividen % divisor;
}
trace->alu.type = AluType::IDIV;
break;
}
default:
std::abort();
}
} else {
switch (func3) {
case 0: {
if (func7) {
// RV32I: SUB
rddata[t].i = rsdata[t][0].i - rsdata[t][1].i;
} else {
// RV32I: ADD
rddata[t].i = rsdata[t][0].i + rsdata[t][1].i;
}
break;
}
case 1: {
// RV32I: SLL
Word shamt_mask = (Word(1) << log2up(XLEN)) - 1;
Word shamt = rsdata[t][1].i & shamt_mask;
rddata[t].i = rsdata[t][0].i << shamt;
break;
}
case 2: {
// RV32I: SLT
rddata[t].i = WordI(rsdata[t][0].i) < WordI(rsdata[t][1].i);
break;
}
case 3: {
// RV32I: SLTU
rddata[t].i = Word(rsdata[t][0].i) < Word(rsdata[t][1].i);
break;
}
case 4: {
// RV32I: XOR
rddata[t].i = rsdata[t][0].i ^ rsdata[t][1].i;
break;
}
case 5: {
Word shamt_mask = ((Word)1 << log2up(XLEN)) - 1;
Word shamt = rsdata[t][1].i & shamt_mask;
if (func7) {
// RV32I: SRA
rddata[t].i = WordI(rsdata[t][0].i) >> shamt;
} else {
// RV32I: SRL
rddata[t].i = Word(rsdata[t][0].i) >> shamt;
}
break;
}
case 6: {
// RV32I: OR
rddata[t].i = rsdata[t][0].i | rsdata[t][1].i;
break;
}
case 7: {
// RV32I: AND
rddata[t].i = rsdata[t][0].i & rsdata[t][1].i;
break;
}
default:
std::abort();
}
}
}
rd_write = true;
break;
}
case I_INST: {
trace->exe_type = ExeType::ALU;
trace->alu.type = AluType::ARITH;
trace->used_iregs.set(rsrc0);
for (uint32_t t = 0; t < num_threads; ++t) {
if (!tmask_.test(t))
continue;
switch (func3) {
case 0: {
// RV32I: ADDI
rddata[t].i = rsdata[t][0].i + immsrc;
break;
}
case 1: {
// RV64I: SLLI
rddata[t].i = rsdata[t][0].i << immsrc;
break;
}
case 2: {
// RV32I: SLTI
rddata[t].i = WordI(rsdata[t][0].i) < WordI(immsrc);
break;
}
case 3: {
// RV32I: SLTIU
rddata[t].i = rsdata[t][0].i < immsrc;
break;
}
case 4: {
// RV32I: XORI
rddata[t].i = rsdata[t][0].i ^ immsrc;
break;
}
case 5: {
if (func7) {
// RV64I: SRAI
Word result = WordI(rsdata[t][0].i) >> immsrc;
rddata[t].i = result;
} else {
// RV64I: SRLI
Word result = Word(rsdata[t][0].i) >> immsrc;
rddata[t].i = result;
}
break;
}
case 6: {
// RV32I: ORI
rddata[t].i = rsdata[t][0].i | immsrc;
break;
}
case 7: {
// RV32I: ANDI
rddata[t].i = rsdata[t][0].i & immsrc;
break;
}
}
}
rd_write = true;
break;
}
case R_INST_W: {
trace->exe_type = ExeType::ALU;
trace->alu.type = AluType::ARITH;
trace->used_iregs.set(rsrc0);
trace->used_iregs.set(rsrc1);
for (uint32_t t = 0; t < num_threads; ++t) {
if (!tmask_.test(t))
continue;
if (func7 & 0x1){
switch (func3) {
case 0: {
// RV64M: MULW
int32_t product = (int32_t)rsdata[t][0].i * (int32_t)rsdata[t][1].i;
rddata[t].i = sext((uint64_t)product, 32);
trace->alu.type = AluType::IMUL;
break;
}
case 4: {
// RV64M: DIVW
int32_t dividen = (int32_t)rsdata[t][0].i;
int32_t divisor = (int32_t)rsdata[t][1].i;
int32_t quotient;
int32_t largest_negative = 0x80000000;
if (divisor == 0){
quotient = -1;
} else if (dividen == largest_negative && divisor == -1) {
quotient = dividen;
} else {
quotient = dividen / divisor;
}
rddata[t].i = sext((uint64_t)quotient, 32);
trace->alu.type = AluType::IDIV;
break;
}
case 5: {
// RV64M: DIVUW
uint32_t dividen = (uint32_t)rsdata[t][0].i;
uint32_t divisor = (uint32_t)rsdata[t][1].i;
uint32_t quotient;
if (divisor == 0){
quotient = -1;
} else {
quotient = dividen / divisor;
}
rddata[t].i = sext((uint64_t)quotient, 32);
trace->alu.type = AluType::IDIV;
break;
}
case 6: {
// RV64M: REMW
int32_t dividen = (uint32_t)rsdata[t][0].i;
int32_t divisor = (uint32_t)rsdata[t][1].i;
int32_t remainder;
int32_t largest_negative = 0x80000000;
if (divisor == 0){
remainder = dividen;
} else if (dividen == largest_negative && divisor == -1) {
remainder = 0;
} else {
remainder = dividen % divisor;
}
rddata[t].i = sext((uint64_t)remainder, 32);
trace->alu.type = AluType::IDIV;
break;
}
case 7: {
// RV64M: REMUW
uint32_t dividen = (uint32_t)rsdata[t][0].i;
uint32_t divisor = (uint32_t)rsdata[t][1].i;
uint32_t remainder;
if (divisor == 0){
remainder = dividen;
} else {
remainder = dividen % divisor;
}
rddata[t].i = sext((uint64_t)remainder, 32);
trace->alu.type = AluType::IDIV;
break;
}
default:
std::abort();
}
} else {
switch (func3) {
case 0: {
if (func7){
// RV64I: SUBW
uint32_t result = (uint32_t)rsdata[t][0].i - (uint32_t)rsdata[t][1].i;
rddata[t].i = sext((uint64_t)result, 32);
}
else{
// RV64I: ADDW
uint32_t result = (uint32_t)rsdata[t][0].i + (uint32_t)rsdata[t][1].i;
rddata[t].i = sext((uint64_t)result, 32);
}
break;
}
case 1: {
// RV64I: SLLW
uint32_t shamt_mask = 0x1F;
uint32_t shamt = rsdata[t][1].i & shamt_mask;
uint32_t result = (uint32_t)rsdata[t][0].i << shamt;
rddata[t].i = sext((uint64_t)result, 32);
break;
}
case 5: {
uint32_t shamt_mask = 0x1F;
uint32_t shamt = rsdata[t][1].i & shamt_mask;
uint32_t result;
if (func7) {
// RV64I: SRAW
result = (int32_t)rsdata[t][0].i >> shamt;
} else {
// RV64I: SRLW
result = (uint32_t)rsdata[t][0].i >> shamt;
}
rddata[t].i = sext((uint64_t)result, 32);
break;
}
default:
std::abort();
}
}
}
rd_write = true;
break;
}
case I_INST_W: {
trace->exe_type = ExeType::ALU;
trace->alu.type = AluType::ARITH;
trace->used_iregs.set(rsrc0);
for (uint32_t t = 0; t < num_threads; ++t) {
if (!tmask_.test(t))
continue;
switch (func3) {
case 0: {
// RV64I: ADDIW
uint32_t result = (uint32_t)rsdata[t][0].i + (uint32_t)immsrc;
rddata[t].i = sext((uint64_t)result, 32);
break;
}
case 1: {
// RV64I: SLLIW
uint32_t shamt_mask = 0x1F;
uint32_t shamt = immsrc & shamt_mask;
uint32_t result = rsdata[t][0].i << shamt;
rddata[t].i = sext((uint64_t)result, 32);
break;
}
case 5: {
uint32_t shamt_mask = 0x1F;
uint32_t shamt = immsrc & shamt_mask;
uint32_t result;
if (func7) {
// RV64I: SRAIW
result = (int32_t)rsdata[t][0].i >> shamt;
} else {
// RV64I: SRLIW
result = (uint32_t)rsdata[t][0].i >> shamt;
}
rddata[t].i = sext((uint64_t)result, 32);
break;
}
default:
std::abort();
}
}
rd_write = true;
break;
}
case B_INST: {
trace->exe_type = ExeType::ALU;
trace->alu.type = AluType::BRANCH;
trace->used_iregs.set(rsrc0);
trace->used_iregs.set(rsrc1);
for (uint32_t t = 0; t < num_threads; ++t) {
if (!tmask_.test(t))
continue;
switch (func3) {
case 0: {
// RV32I: BEQ
if (rsdata[t][0].i == rsdata[t][1].i) {
nextPC = uint32_t(PC_ + immsrc);
}
break;
}
case 1: {
// RV32I: BNE
if (rsdata[t][0].i != rsdata[t][1].i) {
nextPC = uint32_t(PC_ + immsrc);
}
break;
}
case 4: {
// RV32I: BLT
if (WordI(rsdata[t][0].i) < WordI(rsdata[t][1].i)) {
nextPC = uint32_t(PC_ + immsrc);
}
break;
}
case 5: {
// RV32I: BGE
if (WordI(rsdata[t][0].i) >= WordI(rsdata[t][1].i)) {
nextPC = uint32_t(PC_ + immsrc);
}
break;
}
case 6: {
// RV32I: BLTU
if (Word(rsdata[t][0].i) < Word(rsdata[t][1].i)) {
nextPC = uint32_t(PC_ + immsrc);
}
break;
}
case 7: {
// RV32I: BGEU
if (Word(rsdata[t][0].i) >= Word(rsdata[t][1].i)) {
nextPC = uint32_t(PC_ + immsrc);
}
break;
}
default:
std::abort();
}
break; // runonce
}
trace->fetch_stall = true;
break;
}
// RV32I: JAL
case JAL_INST: {
trace->exe_type = ExeType::ALU;
trace->alu.type = AluType::BRANCH;
for (uint32_t t = 0; t < num_threads; ++t) {
if (!tmask_.test(t))
continue;
rddata[t].i = nextPC;
nextPC = uint32_t(PC_ + immsrc);
trace->fetch_stall = true;
break; // runonce
}
rd_write = true;
break;
}
// RV32I: JALR
case JALR_INST: {
trace->exe_type = ExeType::ALU;
trace->alu.type = AluType::BRANCH;
trace->used_iregs.set(rsrc0);
for (uint32_t t = 0; t < num_threads; ++t) {
if (!tmask_.test(t))
continue;
rddata[t].i = nextPC;
nextPC = uint32_t(rsdata[t][0].i + immsrc);
trace->fetch_stall = true;
break; // runOnce
}
rd_write = true;
break;
}
case L_INST:
case FL: {
trace->exe_type = ExeType::LSU;
trace->lsu.type = LsuType::LOAD;
trace->used_iregs.set(rsrc0);
if ((opcode == L_INST )
|| (opcode == FL && func3 == 2)
|| (opcode == FL && func3 == 3)) {
uint32_t mem_bytes = 1 << (func3 & 0x3);
for (uint32_t t = 0; t < num_threads; ++t) {
if (!tmask_.test(t))
continue;
uint64_t mem_addr = rsdata[t][0].i + immsrc;
uint64_t mem_data = 0;
core_->dcache_read(&mem_data, mem_addr, mem_bytes);
trace->mem_addrs.at(t).push_back({mem_addr, mem_bytes});
DP(4, "LOAD MEM: ADDRESS=0x" << std::hex << mem_addr << ", DATA=0x" << mem_data);
switch (func3) {
case 0:
// RV32I: LB
rddata[t].i = sext((Word)mem_data, 8);
break;
case 1:
// RV32I: LH
rddata[t].i = sext((Word)mem_data, 16);
break;
case 2:
if (opcode == L_INST) {
// RV32I: LW
rddata[t].i = sext((Word)mem_data, 32);
} else {
// RV32F: FLW
rddata[t].f = nan_box((uint32_t)mem_data);
}
break;
case 3: // RV64I: LD
// RV32D: FLD
case 4: // RV32I: LBU
case 5: // RV32I: LHU
case 6: // RV64I: LWU
rddata[t]._ = mem_data;
break;
default:
std::abort();
}
}
} else {
auto &vd = vreg_file_.at(rdest);
switch (instr.getVlsWidth()) {
case 6: {
for (uint32_t i = 0; i < vl_; i++) {
Word mem_addr = ((rsdata[i][0].i) & 0xFFFFFFFC) + (i * vtype_.vsew / 8);
Word mem_data = 0;
core_->dcache_read(&mem_data, mem_addr, 4);
Word *result_ptr = (Word *)(vd.data() + i);
*result_ptr = mem_data;
DP(4, "LOAD MEM: ADDRESS=0x" << std::hex << mem_addr << ", DATA=0x" << mem_data);
}
break;
}
default:
std::abort();
}
}
rd_write = true;
break;
}
case S_INST:
case FS: {
trace->exe_type = ExeType::LSU;
trace->lsu.type = LsuType::STORE;
trace->used_iregs.set(rsrc0);
trace->used_iregs.set(rsrc1);
if ((opcode == S_INST)
|| (opcode == FS && func3 == 2)
|| (opcode == FS && func3 == 3)) {
uint32_t mem_bytes = 1 << (func3 & 0x3);
uint64_t mask = ((uint64_t(1) << (8 * mem_bytes))-1);
for (uint32_t t = 0; t < num_threads; ++t) {
if (!tmask_.test(t))
continue;
uint64_t mem_addr = rsdata[t][0].i + immsrc;
uint64_t mem_data = rsdata[t][1]._;
if (mem_bytes < 8) {
mem_data &= mask;
}
trace->mem_addrs.at(t).push_back({mem_addr, mem_bytes});
DP(4, "STORE MEM: ADDRESS=0x" << std::hex << mem_addr << ", DATA=0x" << mem_data);
switch (func3) {
case 0:
case 1:
case 2:
case 3:
core_->dcache_write(&mem_data, mem_addr, mem_bytes);
break;
default:
std::abort();
}
}
} else {
for (uint32_t i = 0; i < vl_; i++) {
uint64_t mem_addr = rsdata[i][0].i + (i * vtype_.vsew / 8);
switch (instr.getVlsWidth()) {
case 6: {
// store word and unit strided (not checking for unit stride)
uint32_t mem_data = *(uint32_t *)(vreg_file_.at(instr.getVs3()).data() + i);
core_->dcache_write(&mem_data, mem_addr, 4);
DP(4, "STORE MEM: ADDRESS=0x" << std::hex << mem_addr << ", DATA=0x" << mem_data);
break;
}
default:
std::abort();
}
}
}
break;
}
case SYS_INST: {
for (uint32_t t = 0; t < num_threads; ++t) {
if (!tmask_.test(t))
continue;
uint32_t csr_addr = immsrc;
uint32_t csr_value;
if (func3 == 0) {
trace->exe_type = ExeType::ALU;
trace->alu.type = AluType::SYSCALL;
trace->fetch_stall = true;
switch (csr_addr) {
case 0: { // RV32I: ECALL
core_->trigger_ecall();
break;
}
case 1: { // RV32I: EBREAK
core_->trigger_ebreak();
break;
}
case 0x002: // URET
case 0x102: // SRET
case 0x302: // MRET
break;
default:
std::abort();
}
} else {
trace->exe_type = ExeType::CSR;
csr_value = core_->get_csr(csr_addr, t, id_);
switch (func3) {
case 1: {
// RV32I: CSRRW
rddata[t].i = csr_value;
core_->set_csr(csr_addr, rsdata[t][0].i, t, id_);
trace->used_iregs.set(rsrc0);
rd_write = true;
break;
}
case 2: {
// RV32I: CSRRS
rddata[t].i = csr_value;
core_->set_csr(csr_addr, csr_value | rsdata[t][0].i, t, id_);
trace->used_iregs.set(rsrc0);
rd_write = true;
break;
}
case 3: {
// RV32I: CSRRC
rddata[t].i = csr_value;
core_->set_csr(csr_addr, csr_value & ~rsdata[t][0].i, t, id_);
trace->used_iregs.set(rsrc0);
rd_write = true;
break;
}
case 5: {
// RV32I: CSRRWI
rddata[t].i = csr_value;
core_->set_csr(csr_addr, rsrc0, t, id_);
rd_write = true;
break;
}
case 6: {
// RV32I: CSRRSI;
rddata[t].i = csr_value;
core_->set_csr(csr_addr, csr_value | rsrc0, t, id_);
rd_write = true;
break;
}
case 7: {
// RV32I: CSRRCI
rddata[t].i = csr_value;
core_->set_csr(csr_addr, csr_value & ~rsrc0, t, id_);
rd_write = true;
break;
}
default:
break;
}
}
}
break;
}
// RV32I: FENCE
case FENCE: {
trace->exe_type = ExeType::LSU;
trace->lsu.type = LsuType::FENCE;
break;
}
case FCI: {
trace->exe_type = ExeType::FPU;
for (uint32_t t = 0; t < num_threads; ++t) {
if (!tmask_.test(t))
continue;
uint32_t frm = get_fpu_rm(func3, core_, t, id_);
uint32_t fflags = 0;
switch (func7) {
case 0x00: { // RV32F: FADD.S
if (checkBoxedArgs(&rddata[t].f, rsdata[t][0].f, rsdata[t][1].f, &fflags)) {
rddata[t].f = nan_box(rv_fadd_s(rsdata[t][0].f, rsdata[t][1].f, frm, &fflags));
}
trace->fpu.type = FpuType::FMA;
trace->used_fregs.set(rsrc0);
trace->used_fregs.set(rsrc1);
break;
}
case 0x01: { // RV32D: FADD.D
rddata[t].f = rv_fadd_d(rsdata[t][0].f, rsdata[t][1].f, frm, &fflags);
trace->fpu.type = FpuType::FMA;
trace->used_fregs.set(rsrc0);
trace->used_fregs.set(rsrc1);
break;
}
case 0x04: { // RV32F: FSUB.S
if (checkBoxedArgs(&rddata[t].f, rsdata[t][0].f, rsdata[t][1].f, &fflags)) {
rddata[t].f = nan_box(rv_fsub_s(rsdata[t][0].f, rsdata[t][1].f, frm, &fflags));
}
trace->fpu.type = FpuType::FMA;
trace->used_fregs.set(rsrc0);
trace->used_fregs.set(rsrc1);
break;
}
case 0x05: { // RV32D: FSUB.D
rddata[t].f = rv_fsub_d(rsdata[t][0].f, rsdata[t][1].f, frm, &fflags);
trace->fpu.type = FpuType::FMA;
trace->used_fregs.set(rsrc0);
trace->used_fregs.set(rsrc1);
break;
}
case 0x08: { // RV32F: FMUL.S
if (checkBoxedArgs(&rddata[t].f, rsdata[t][0].f, rsdata[t][1].f, &fflags)) {
rddata[t].f = nan_box(rv_fmul_s(rsdata[t][0].f, rsdata[t][1].f, frm, &fflags));
}
trace->fpu.type = FpuType::FMA;
trace->used_fregs.set(rsrc0);
trace->used_fregs.set(rsrc1);
break;
}
case 0x09: { // RV32D: FMUL.D
rddata[t].f = rv_fmul_d(rsdata[t][0].f, rsdata[t][1].f, frm, &fflags);
trace->fpu.type = FpuType::FMA;
trace->used_fregs.set(rsrc0);
trace->used_fregs.set(rsrc1);
break;
}
case 0x0c: { // RV32F: FDIV.S
if (checkBoxedArgs(&rddata[t].f, rsdata[t][0].f, rsdata[t][1].f, &fflags)) {
rddata[t].f = nan_box(rv_fdiv_s(rsdata[t][0].f, rsdata[t][1].f, frm, &fflags));
}
trace->fpu.type = FpuType::FDIV;
trace->used_fregs.set(rsrc0);
trace->used_fregs.set(rsrc1);
break;
}
case 0x0d: { // RV32D: FDIV.D
rddata[t].f = rv_fdiv_d(rsdata[t][0].f, rsdata[t][1].f, frm, &fflags);
trace->fpu.type = FpuType::FDIV;
trace->used_fregs.set(rsrc0);
trace->used_fregs.set(rsrc1);
break;
}
case 0x2c: { // RV32F: FSQRT.S
if (checkBoxedArgs(&rddata[t].f, rsdata[t][0].f, &fflags)) {
rddata[t].f = nan_box(rv_fsqrt_s(rsdata[t][0].f, frm, &fflags));
}
trace->fpu.type = FpuType::FSQRT;
trace->used_fregs.set(rsrc0);
break;
}
case 0x2d: { // RV32D: FSQRT.D
rddata[t].f = rv_fsqrt_d(rsdata[t][0].f, frm, &fflags);
trace->fpu.type = FpuType::FSQRT;
trace->used_fregs.set(rsrc0);
break;
}
case 0x10: {
if (checkBoxedArgs(&rddata[t].f, rsdata[t][0].f, rsdata[t][1].f, &fflags)) {
switch (func3) {
case 0: // RV32F: FSGNJ.S
rddata[t].f = nan_box(rv_fsgnj_s(rsdata[t][0].f, rsdata[t][1].f));
break;
case 1: // RV32F: FSGNJN.S
rddata[t].f = nan_box(rv_fsgnjn_s(rsdata[t][0].f, rsdata[t][1].f));
break;
case 2: // RV32F: FSGNJX.S
rddata[t].f = nan_box(rv_fsgnjx_s(rsdata[t][0].f, rsdata[t][1].f));
break;
}
}
trace->fpu.type = FpuType::FNCP;
trace->used_fregs.set(rsrc0);
trace->used_fregs.set(rsrc1);
break;
}
case 0x11: {
switch (func3) {
case 0: // RV32D: FSGNJ.D
rddata[t].f = rv_fsgnj_d(rsdata[t][0].f, rsdata[t][1].f);
break;
case 1: // RV32D: FSGNJN.D
rddata[t].f = rv_fsgnjn_d(rsdata[t][0].f, rsdata[t][1].f);
break;
case 2: // RV32D: FSGNJX.D
rddata[t].f = rv_fsgnjx_d(rsdata[t][0].f, rsdata[t][1].f);
break;
}
trace->fpu.type = FpuType::FNCP;
trace->used_fregs.set(rsrc0);
trace->used_fregs.set(rsrc1);
break;
}
case 0x14: {
if (checkBoxedArgs(&rddata[t].f, rsdata[t][0].f, rsdata[t][1].f, &fflags)) {
if (func3) {
// RV32F: FMAX.S
rddata[t].f = nan_box(rv_fmax_s(rsdata[t][0].f, rsdata[t][1].f, &fflags));
} else {
// RV32F: FMIN.S
rddata[t].f = nan_box(rv_fmin_s(rsdata[t][0].f, rsdata[t][1].f, &fflags));
}
}
trace->fpu.type = FpuType::FNCP;
trace->used_fregs.set(rsrc0);
trace->used_fregs.set(rsrc1);
break;
}
case 0x15: {
if (func3) {
// RV32D: FMAX.D
rddata[t].f = rv_fmax_d(rsdata[t][0].f, rsdata[t][1].f, &fflags);
} else {
// RV32D: FMIN.D
rddata[t].f = rv_fmin_d(rsdata[t][0].f, rsdata[t][1].f, &fflags);
}
trace->fpu.type = FpuType::FNCP;
trace->used_fregs.set(rsrc0);
trace->used_fregs.set(rsrc1);
break;
}
case 0x20: {
// RV32D: FCVT.S.D
rddata[t].f = nan_box(rv_dtof(rsdata[t][0].f));
trace->fpu.type = FpuType::FNCP;
trace->used_fregs.set(rsrc0);
trace->used_fregs.set(rsrc1);
break;
}
case 0x21: {
// RV32D: FCVT.D.S
rddata[t].f = rv_ftod(rsdata[t][0].f);
trace->fpu.type = FpuType::FNCP;
trace->used_fregs.set(rsrc0);
trace->used_fregs.set(rsrc1);
break;
}
case 0x60: {
switch (rsrc1) {
case 0:
// RV32F: FCVT.W.S
rddata[t].i = sext((uint64_t)rv_ftoi_s(rsdata[t][0].f, frm, &fflags), 32);
break;
case 1:
// RV32F: FCVT.WU.S
rddata[t].i = sext((uint64_t)rv_ftou_s(rsdata[t][0].f, frm, &fflags), 32);
break;
case 2:
// RV64F: FCVT.L.S
rddata[t].i = rv_ftol_s(rsdata[t][0].f, frm, &fflags);
break;
case 3:
// RV64F: FCVT.LU.S
rddata[t].i = rv_ftolu_s(rsdata[t][0].f, frm, &fflags);
break;
}
trace->fpu.type = FpuType::FCVT;
trace->used_fregs.set(rsrc0);
break;
}
case 0x61: {
switch (rsrc1) {
case 0:
// RV32D: FCVT.W.D
rddata[t].i = sext((uint64_t)rv_ftoi_d(rsdata[t][0].f, frm, &fflags), 32);
break;
case 1:
// RV32D: FCVT.WU.D
rddata[t].i = sext((uint64_t)rv_ftou_d(rsdata[t][0].f, frm, &fflags), 32);
break;
case 2:
// RV64D: FCVT.L.D
rddata[t].i = rv_ftol_d(rsdata[t][0].f, frm, &fflags);
break;
case 3:
// RV64D: FCVT.LU.D
rddata[t].i = rv_ftolu_d(rsdata[t][0].f, frm, &fflags);
break;
}
trace->fpu.type = FpuType::FCVT;
trace->used_fregs.set(rsrc0);
break;
}
case 0x70: {
if (func3) {
// RV32F: FCLASS.S
rddata[t].i = rv_fclss_s(rsdata[t][0].f);
} else {
// RV32F: FMV.X.W
uint32_t result = (uint32_t)rsdata[t][0].f;
rddata[t].i = sext((uint64_t)result, 32);
}
trace->fpu.type = FpuType::FNCP;
trace->used_fregs.set(rsrc0);
break;
}
case 0x71: {
if (func3) {
// RV32D: FCLASS.D
rddata[t].i = rv_fclss_d(rsdata[t][0].f);
} else {
// RV64D: FMV.X.D
rddata[t].i = rsdata[t][0].f;
}
trace->fpu.type = FpuType::FNCP;
trace->used_fregs.set(rsrc0);
break;
}
case 0x50: {
if (checkBoxedCmpArgs(&rddata[t].i, rsdata[t][0].f, rsdata[t][1].f, &fflags)) {
switch (func3) {
case 0:
// RV32F: FLE.S
rddata[t].i = rv_fle_s(rsdata[t][0].f, rsdata[t][1].f, &fflags);
break;
case 1:
// RV32F: FLT.S
rddata[t].i = rv_flt_s(rsdata[t][0].f, rsdata[t][1].f, &fflags);
break;
case 2:
// RV32F: FEQ.S
rddata[t].i = rv_feq_s(rsdata[t][0].f, rsdata[t][1].f, &fflags);
break;
}
}
trace->fpu.type = FpuType::FNCP;
trace->used_fregs.set(rsrc0);
trace->used_fregs.set(rsrc1);
break;
}
case 0x51: {
switch (func3) {
case 0:
// RV32D: FLE.D
rddata[t].i = rv_fle_d(rsdata[t][0].f, rsdata[t][1].f, &fflags);
break;
case 1:
// RV32D: FLT.D
rddata[t].i = rv_flt_d(rsdata[t][0].f, rsdata[t][1].f, &fflags);
break;
case 2:
// RV32D: FEQ.D
rddata[t].i = rv_feq_d(rsdata[t][0].f, rsdata[t][1].f, &fflags);
break;
}
trace->fpu.type = FpuType::FNCP;
trace->used_fregs.set(rsrc0);
trace->used_fregs.set(rsrc1);
break;
}
case 0x68: {
switch (rsrc1) {
case 0:
// RV32F: FCVT.S.W
rddata[t].f = nan_box(rv_itof_s(rsdata[t][0].i, frm, &fflags));
break;
case 1:
// RV32F: FCVT.S.WU
rddata[t].f = nan_box(rv_utof_s(rsdata[t][0].i, frm, &fflags));
break;
case 2:
// RV64F: FCVT.S.L
rddata[t].f = nan_box(rv_ltof_s(rsdata[t][0].i, frm, &fflags));
break;
case 3:
// RV64F: FCVT.S.LU
rddata[t].f = nan_box(rv_lutof_s(rsdata[t][0].i, frm, &fflags));
break;
}
trace->fpu.type = FpuType::FCVT;
trace->used_iregs.set(rsrc0);
break;
}
case 0x69: {
switch (rsrc1) {
case 0:
// RV32D: FCVT.D.W
rddata[t].f = rv_itof_d(rsdata[t][0].i, frm, &fflags);
break;
case 1:
// RV32D: FCVT.D.WU
rddata[t].f = rv_utof_d(rsdata[t][0].i, frm, &fflags);
break;
case 2:
// RV64D: FCVT.D.L
rddata[t].f = rv_ltof_d(rsdata[t][0].i, frm, &fflags);
break;
case 3:
// RV64D: FCVT.D.LU
rddata[t].f = rv_lutof_d(rsdata[t][0].i, frm, &fflags);
break;
}
trace->fpu.type = FpuType::FCVT;
trace->used_iregs.set(rsrc0);
break;
}
case 0x78: { // RV32F: FMV.W.X
rddata[t].f = nan_box((uint32_t)rsdata[t][0].i);
trace->fpu.type = FpuType::FNCP;
trace->used_iregs.set(rsrc0);
break;
}
case 0x79: { // RV64D: FMV.D.X
rddata[t].f = rsdata[t][0].i;
trace->fpu.type = FpuType::FNCP;
trace->used_iregs.set(rsrc0);
break;
}
}
update_fcrs(fflags, core_, t, id_);
}
rd_write = true;
break;
}
case FMADD:
case FMSUB:
case FMNMADD:
case FMNMSUB: {
trace->fpu.type = FpuType::FMA;
trace->used_fregs.set(rsrc0);
trace->used_fregs.set(rsrc1);
trace->used_fregs.set(rsrc2);
for (uint32_t t = 0; t < num_threads; ++t) {
if (!tmask_.test(t))
continue;
uint32_t frm = get_fpu_rm(func3, core_, t, id_);
uint32_t fflags = 0;
switch (opcode) {
case FMADD:
if (func2)
// RV32D: FMADD.D
rddata[t].f = rv_fmadd_d(rsdata[t][0].f, rsdata[t][1].f, rsdata[t][2].f, frm, &fflags);
else
// RV32F: FMADD.S
rddata[t].f = nan_box(rv_fmadd_s(rsdata[t][0].f, rsdata[t][1].f, rsdata[t][2].f, frm, &fflags));
break;
case FMSUB:
if (func2)
// RV32D: FMSUB.D
rddata[t].f = rv_fmsub_d(rsdata[t][0].f, rsdata[t][1].f, rsdata[t][2].f, frm, &fflags);
else
// RV32F: FMSUB.S
rddata[t].f = nan_box(rv_fmsub_s(rsdata[t][0].f, rsdata[t][1].f, rsdata[t][2].f, frm, &fflags));
break;
case FMNMADD:
if (func2)
// RV32D: FNMADD.D
rddata[t].f = rv_fnmadd_d(rsdata[t][0].f, rsdata[t][1].f, rsdata[t][2].f, frm, &fflags);
else
// RV32F: FNMADD.S
rddata[t].f = nan_box(rv_fnmadd_s(rsdata[t][0].f, rsdata[t][1].f, rsdata[t][2].f, frm, &fflags));
break;
case FMNMSUB:
if (func2)
// RV32D: FNMSUB.D
rddata[t].f = rv_fnmsub_d(rsdata[t][0].f, rsdata[t][1].f, rsdata[t][2].f, frm, &fflags);
else
// RV32F: FNMSUB.S
rddata[t].f = nan_box(rv_fnmsub_s(rsdata[t][0].f, rsdata[t][1].f, rsdata[t][2].f, frm, &fflags));
break;
default:
break;
}
update_fcrs(fflags, core_, t, id_);
}
rd_write = true;
break;
}
case GPGPU: {
uint32_t ts = 0;
for (uint32_t t = 0; t < num_threads; ++t) {
if (tmask_.test(t)) {
ts = t;
break;
}
}
switch (func3) {
case 0: {
// TMC
trace->exe_type = ExeType::GPU;
trace->gpu.type = GpuType::TMC;
trace->used_iregs.set(rsrc0);
trace->fetch_stall = true;
if (rsrc1) {
// predicate mode
ThreadMask pred;
for (uint32_t t = 0; t < num_threads; ++t) {
pred[t] = tmask_.test(t) ? (ireg_file_.at(t).at(rsrc0) != 0) : 0;
}
if (pred.any()) {
tmask_ &= pred;
}
} else {
tmask_.reset();
for (uint32_t t = 0; t < num_threads; ++t) {
tmask_.set(t, rsdata.at(ts)[0].i & (1 << t));
}
}
DPH(3, "*** New TMC: ");
for (uint32_t i = 0; i < num_threads; ++i)
DPN(3, tmask_.test(num_threads-i-1));
DPN(3, std::endl);
active_ = tmask_.any();
trace->gpu.active_warps.reset();
trace->gpu.active_warps.set(id_, active_);
} break;
case 1: {
// WSPAWN
trace->exe_type = ExeType::GPU;
trace->gpu.type = GpuType::WSPAWN;
trace->used_iregs.set(rsrc0);
trace->used_iregs.set(rsrc1);
trace->fetch_stall = true;
trace->gpu.active_warps = core_->wspawn(rsdata.at(ts)[0].i, rsdata.at(ts)[1].i);
} break;
case 2: {
// SPLIT
trace->exe_type = ExeType::GPU;
trace->gpu.type = GpuType::SPLIT;
trace->used_iregs.set(rsrc0);
trace->fetch_stall = true;
if (HasDivergentThreads(tmask_, ireg_file_, rsrc0)) {
ThreadMask tmask;
for (uint32_t t = 0; t < num_threads; ++t) {
tmask[t] = tmask_.test(t) && !ireg_file_.at(t).at(rsrc0);
}
DomStackEntry e(tmask, nextPC);
dom_stack_.push(tmask_);
dom_stack_.push(e);
for (uint32_t t = 0, n = e.tmask.size(); t < n; ++t) {
tmask_.set(t, !e.tmask.test(t) && tmask_.test(t));
}
active_ = tmask_.any();
DPH(3, "*** Split: New TM=");
for (uint32_t t = 0; t < num_threads; ++t) DPN(3, tmask_.test(num_threads-t-1));
DPN(3, ", Pushed TM=");
for (uint32_t t = 0; t < num_threads; ++t) DPN(3, e.tmask.test(num_threads-t-1));
DPN(3, ", PC=0x" << std::hex << e.PC << "\n");
} else {
DP(3, "*** Unanimous pred");
DomStackEntry e(tmask_);
e.unanimous = true;
dom_stack_.push(e);
}
} break;
case 3: {
// JOIN
trace->exe_type = ExeType::GPU;
trace->gpu.type = GpuType::JOIN;
trace->fetch_stall = true;
if (!dom_stack_.empty() && dom_stack_.top().unanimous) {
DP(3, "*** Uninimous branch at join");
tmask_ = dom_stack_.top().tmask;
active_ = tmask_.any();
dom_stack_.pop();
} else {
if (!dom_stack_.top().fallThrough) {
nextPC = dom_stack_.top().PC;
DP(3, "*** Join: next PC: " << std::hex << nextPC << std::dec);
}
tmask_ = dom_stack_.top().tmask;
active_ = tmask_.any();
DPH(3, "*** Join: New TM=");
for (uint32_t t = 0; t < num_threads; ++t) DPN(3, tmask_.test(num_threads-t-1));
DPN(3, "\n");
dom_stack_.pop();
}
} break;
case 4: {
// BAR
trace->exe_type = ExeType::GPU;
trace->gpu.type = GpuType::BAR;
trace->used_iregs.set(rsrc0);
trace->used_iregs.set(rsrc1);
trace->fetch_stall = true;
trace->gpu.active_warps = core_->barrier(rsdata[ts][0].i, rsdata[ts][1].i, id_);
} break;
case 5: {
// PREFETCH
trace->exe_type = ExeType::LSU;
trace->lsu.type = LsuType::PREFETCH;
trace->used_iregs.set(rsrc0);
for (uint32_t t = 0; t < num_threads; ++t) {
if (!tmask_.test(t))
continue;
auto mem_addr = rsdata[t][0].i;
trace->mem_addrs.at(t).push_back({mem_addr, 4});
}
} break;
default:
std::abort();
}
} break;
case GPU: {
switch (func3) {
case 0: { // TEX
trace->exe_type = ExeType::GPU;
trace->gpu.type = GpuType::TEX;
trace->used_iregs.set(rsrc0);
trace->used_iregs.set(rsrc1);
trace->used_iregs.set(rsrc2);
for (uint32_t t = 0; t < num_threads; ++t) {
if (!tmask_.test(t))
continue;
auto unit = func2;
auto u = rsdata[t][0].i;
auto v = rsdata[t][1].i;
auto lod = rsdata[t][2].i;
auto color = core_->tex_read(unit, u, v, lod, &trace->mem_addrs.at(t));
rddata[t].i = color;
}
rd_write = true;
} break;
case 1:
switch (func2) {
case 0: { // CMOV
trace->exe_type = ExeType::ALU;
trace->alu.type = AluType::CMOV;
trace->used_iregs.set(rsrc0);
trace->used_iregs.set(rsrc1);
trace->used_iregs.set(rsrc2);
for (uint32_t t = 0; t < num_threads; ++t) {
if (!tmask_.test(t))
continue;
rddata[t].i = rsdata[t][0].i ? rsdata[t][1].i : rsdata[t][2].i;
}
rd_write = true;
} break;
default:
std::abort();
}
break;
default:
std::abort();
}
} break;
case VSET: {
uint32_t VLEN = core_->arch().vsize() * 8;
uint32_t VLMAX = (instr.getVlmul() * VLEN) / instr.getVsew();
switch (func3) {
case 0: // vector-vector
switch (func6) {
case 0: {
auto& vr1 = vreg_file_.at(rsrc0);
auto& vr2 = vreg_file_.at(rsrc1);
auto& vd = vreg_file_.at(rdest);
auto& mask = vreg_file_.at(0);
if (vtype_.vsew == 8) {
for (uint32_t i = 0; i < vl_; i++) {
uint8_t emask = *(uint8_t *)(mask.data() + i);
uint8_t value = emask & 0x1;
if (vmask || (!vmask && value)) {
uint8_t first = *(uint8_t *)(vr1.data() + i);
uint8_t second = *(uint8_t *)(vr2.data() + i);
uint8_t result = first + second;
DP(3, "Adding " << first << " + " << second << " = " << result);
*(uint8_t *)(vd.data() + i) = result;
}
}
} else if (vtype_.vsew == 16) {
for (uint32_t i = 0; i < vl_; i++) {
uint16_t emask = *(uint16_t *)(mask.data() + i);
uint16_t value = emask & 0x1;
if (vmask || (!vmask && value)) {
uint16_t first = *(uint16_t *)(vr1.data() + i);
uint16_t second = *(uint16_t *)(vr2.data() + i);
uint16_t result = first + second;
DP(3, "Adding " << first << " + " << second << " = " << result);
*(uint16_t *)(vd.data() + i) = result;
}
}
} else if (vtype_.vsew == 32) {
for (uint32_t i = 0; i < vl_; i++) {
uint32_t emask = *(uint32_t *)(mask.data() + i);
uint32_t value = emask & 0x1;
if (vmask || (!vmask && value)) {
uint32_t first = *(uint32_t *)(vr1.data() + i);
uint32_t second = *(uint32_t *)(vr2.data() + i);
uint32_t result = first + second;
DP(3, "Adding " << first << " + " << second << " = " << result);
*(uint32_t *)(vd.data() + i) = result;
}
}
}
} break;
case 24: {
// vmseq
auto &vr1 = vreg_file_.at(rsrc0);
auto &vr2 = vreg_file_.at(rsrc1);
auto &vd = vreg_file_.at(rdest);
if (vtype_.vsew == 8) {
for (uint32_t i = 0; i < vl_; i++) {
uint8_t first = *(uint8_t *)(vr1.data() + i);
uint8_t second = *(uint8_t *)(vr2.data() + i);
uint8_t result = (first == second) ? 1 : 0;
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint8_t *)(vd.data() + i) = result;
}
} else if (vtype_.vsew == 16) {
for (uint32_t i = 0; i < vl_; i++) {
uint16_t first = *(uint16_t *)(vr1.data() + i);
uint16_t second = *(uint16_t *)(vr2.data() + i);
uint16_t result = (first == second) ? 1 : 0;
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint16_t *)(vd.data() + i) = result;
}
} else if (vtype_.vsew == 32) {
for (uint32_t i = 0; i < vl_; i++) {
uint32_t first = *(uint32_t *)(vr1.data() + i);
uint32_t second = *(uint32_t *)(vr2.data() + i);
uint32_t result = (first == second) ? 1 : 0;
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint32_t *)(vd.data() + i) = result;
}
}
} break;
case 25: {
// vmsne
auto &vr1 = vreg_file_.at(rsrc0);
auto &vr2 = vreg_file_.at(rsrc1);
auto &vd = vreg_file_.at(rdest);
if (vtype_.vsew == 8) {
for (uint32_t i = 0; i < vl_; i++) {
uint8_t first = *(uint8_t *)(vr1.data() + i);
uint8_t second = *(uint8_t *)(vr2.data() + i);
uint8_t result = (first != second) ? 1 : 0;
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint8_t *)(vd.data() + i) = result;
}
} else if (vtype_.vsew == 16) {
for (uint32_t i = 0; i < vl_; i++) {
uint16_t first = *(uint16_t *)(vr1.data() + i);
uint16_t second = *(uint16_t *)(vr2.data() + i);
uint16_t result = (first != second) ? 1 : 0;
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint16_t *)(vd.data() + i) = result;
}
} else if (vtype_.vsew == 32) {
for (uint32_t i = 0; i < vl_; i++) {
uint32_t first = *(uint32_t *)(vr1.data() + i);
uint32_t second = *(uint32_t *)(vr2.data() + i);
uint32_t result = (first != second) ? 1 : 0;
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint32_t *)(vd.data() + i) = result;
}
}
} break;
case 26: {
// vmsltu
auto &vr1 = vreg_file_.at(rsrc0);
auto &vr2 = vreg_file_.at(rsrc1);
auto &vd = vreg_file_.at(rdest);
if (vtype_.vsew == 8) {
for (uint32_t i = 0; i < vl_; i++) {
uint8_t first = *(uint8_t *)(vr1.data() + i);
uint8_t second = *(uint8_t *)(vr2.data() + i);
uint8_t result = (first < second) ? 1 : 0;
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint8_t *)(vd.data() + i) = result;
}
} else if (vtype_.vsew == 16) {
for (uint32_t i = 0; i < vl_; i++) {
uint16_t first = *(uint16_t *)(vr1.data() + i);
uint16_t second = *(uint16_t *)(vr2.data() + i);
uint16_t result = (first < second) ? 1 : 0;
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint16_t *)(vd.data() + i) = result;
}
} else if (vtype_.vsew == 32) {
for (uint32_t i = 0; i < vl_; i++) {
uint32_t first = *(uint32_t *)(vr1.data() + i);
uint32_t second = *(uint32_t *)(vr2.data() + i);
uint32_t result = (first < second) ? 1 : 0;
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint32_t *)(vd.data() + i) = result;
}
}
} break;
case 27: {
// vmslt
auto &vr1 = vreg_file_.at(rsrc0);
auto &vr2 = vreg_file_.at(rsrc1);
auto &vd = vreg_file_.at(rdest);
if (vtype_.vsew == 8) {
for (uint32_t i = 0; i < vl_; i++) {
int8_t first = *(int8_t *)(vr1.data() + i);
int8_t second = *(int8_t *)(vr2.data() + i);
int8_t result = (first < second) ? 1 : 0;
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint8_t *)(vd.data() + i) = result;
}
} else if (vtype_.vsew == 16) {
for (uint32_t i = 0; i < vl_; i++) {
int16_t first = *(int16_t *)(vr1.data() + i);
int16_t second = *(int16_t *)(vr2.data() + i);
int16_t result = (first < second) ? 1 : 0;
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(int16_t *)(vd.data() + i) = result;
}
} else if (vtype_.vsew == 32) {
for (uint32_t i = 0; i < vl_; i++) {
int32_t first = *(int32_t *)(vr1.data() + i);
int32_t second = *(int32_t *)(vr2.data() + i);
int32_t result = (first < second) ? 1 : 0;
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(int32_t *)(vd.data() + i) = result;
}
}
} break;
case 28: {
// vmsleu
auto &vr1 = vreg_file_.at(rsrc0);
auto &vr2 = vreg_file_.at(rsrc1);
auto &vd = vreg_file_.at(rdest);
if (vtype_.vsew == 8) {
for (uint32_t i = 0; i < vl_; i++) {
uint8_t first = *(uint8_t *)(vr1.data() + i);
uint8_t second = *(uint8_t *)(vr2.data() + i);
uint8_t result = (first <= second) ? 1 : 0;
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint8_t *)(vd.data() + i) = result;
}
} else if (vtype_.vsew == 16) {
for (uint32_t i = 0; i < vl_; i++) {
uint16_t first = *(uint16_t *)(vr1.data() + i);
uint16_t second = *(uint16_t *)(vr2.data() + i);
uint16_t result = (first <= second) ? 1 : 0;
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint16_t *)(vd.data() + i) = result;
}
} else if (vtype_.vsew == 32) {
for (uint32_t i = 0; i < vl_; i++) {
uint32_t first = *(uint32_t *)(vr1.data() + i);
uint32_t second = *(uint32_t *)(vr2.data() + i);
uint32_t result = (first <= second) ? 1 : 0;
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint32_t *)(vd.data() + i) = result;
}
}
} break;
case 29: {
// vmsle
auto &vr1 = vreg_file_.at(rsrc0);
auto &vr2 = vreg_file_.at(rsrc1);
auto &vd = vreg_file_.at(rdest);
if (vtype_.vsew == 8) {
for (uint32_t i = 0; i < vl_; i++) {
int8_t first = *(int8_t *)(vr1.data() + i);
int8_t second = *(int8_t *)(vr2.data() + i);
int8_t result = (first <= second) ? 1 : 0;
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint8_t *)(vd.data() + i) = result;
}
} else if (vtype_.vsew == 16) {
for (uint32_t i = 0; i < vl_; i++) {
int16_t first = *(int16_t *)(vr1.data() + i);
int16_t second = *(int16_t *)(vr2.data() + i);
int16_t result = (first <= second) ? 1 : 0;
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(int16_t *)(vd.data() + i) = result;
}
} else if (vtype_.vsew == 32) {
for (uint32_t i = 0; i < vl_; i++) {
int32_t first = *(int32_t *)(vr1.data() + i);
int32_t second = *(int32_t *)(vr2.data() + i);
int32_t result = (first <= second) ? 1 : 0;
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(int32_t *)(vd.data() + i) = result;
}
}
} break;
case 30: {
// vmsgtu
auto &vr1 = vreg_file_.at(rsrc0);
auto &vr2 = vreg_file_.at(rsrc1);
auto &vd = vreg_file_.at(rdest);
if (vtype_.vsew == 8) {
for (uint32_t i = 0; i < vl_; i++) {
uint8_t first = *(uint8_t *)(vr1.data() + i);
uint8_t second = *(uint8_t *)(vr2.data() + i);
uint8_t result = (first > second) ? 1 : 0;
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint8_t *)(vd.data() + i) = result;
}
} else if (vtype_.vsew == 16) {
for (uint32_t i = 0; i < vl_; i++) {
uint16_t first = *(uint16_t *)(vr1.data() + i);
uint16_t second = *(uint16_t *)(vr2.data() + i);
uint16_t result = (first > second) ? 1 : 0;
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint16_t *)(vd.data() + i) = result;
}
} else if (vtype_.vsew == 32) {
for (uint32_t i = 0; i < vl_; i++) {
uint32_t first = *(uint32_t *)(vr1.data() + i);
uint32_t second = *(uint32_t *)(vr2.data() + i);
uint32_t result = (first > second) ? 1 : 0;
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint32_t *)(vd.data() + i) = result;
}
}
} break;
case 31: {
// vmsgt
auto &vr1 = vreg_file_.at(rsrc0);
auto &vr2 = vreg_file_.at(rsrc1);
auto &vd = vreg_file_.at(rdest);
if (vtype_.vsew == 8) {
for (uint32_t i = 0; i < vl_; i++) {
int8_t first = *(int8_t *)(vr1.data() + i);
int8_t second = *(int8_t *)(vr2.data() + i);
int8_t result = (first > second) ? 1 : 0;
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint8_t *)(vd.data() + i) = result;
}
} else if (vtype_.vsew == 16) {
for (uint32_t i = 0; i < vl_; i++) {
int16_t first = *(int16_t *)(vr1.data() + i);
int16_t second = *(int16_t *)(vr2.data() + i);
int16_t result = (first > second) ? 1 : 0;
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(int16_t *)(vd.data() + i) = result;
}
} else if (vtype_.vsew == 32) {
for (uint32_t i = 0; i < vl_; i++) {
int32_t first = *(int32_t *)(vr1.data() + i);
int32_t second = *(int32_t *)(vr2.data() + i);
int32_t result = (first > second) ? 1 : 0;
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(int32_t *)(vd.data() + i) = result;
}
}
} break;
}
break;
case 2: {
switch (func6) {
case 24: {
// vmandnot
auto &vr1 = vreg_file_.at(rsrc0);
auto &vr2 = vreg_file_.at(rsrc1);
auto &vd = vreg_file_.at(rdest);
if (vtype_.vsew == 8) {
for (uint32_t i = 0; i < vl_; i++) {
uint8_t first = *(uint8_t *)(vr1.data() + i);
uint8_t second = *(uint8_t *)(vr2.data() + i);
uint8_t first_value = (first & 0x1);
uint8_t second_value = (second & 0x1);
uint8_t result = (first_value & !second_value);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint8_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint8_t *)(vd.data() + i) = 0;
}
} else if (vtype_.vsew == 16) {
for (uint32_t i = 0; i < vl_; i++) {
uint16_t first = *(uint16_t *)(vr1.data() + i);
uint16_t second = *(uint16_t *)(vr2.data() + i);
uint16_t first_value = (first & 0x1);
uint16_t second_value = (second & 0x1);
uint16_t result = (first_value & !second_value);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint16_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint16_t *)(vd.data() + i) = 0;
}
} else if (vtype_.vsew == 32) {
for (uint32_t i = 0; i < vl_; i++) {
uint32_t first = *(uint32_t *)(vr1.data() + i);
uint32_t second = *(uint32_t *)(vr2.data() + i);
uint32_t first_value = (first & 0x1);
uint32_t second_value = (second & 0x1);
uint32_t result = (first_value & !second_value);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint32_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint32_t *)(vd.data() + i) = 0;
}
}
} break;
case 25: {
// vmand
auto &vr1 = vreg_file_.at(rsrc0);
auto &vr2 = vreg_file_.at(rsrc1);
auto &vd = vreg_file_.at(rdest);
if (vtype_.vsew == 8) {
for (uint32_t i = 0; i < vl_; i++) {
uint8_t first = *(uint8_t *)(vr1.data() + i);
uint8_t second = *(uint8_t *)(vr2.data() + i);
uint8_t first_value = (first & 0x1);
uint8_t second_value = (second & 0x1);
uint8_t result = (first_value & second_value);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint8_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint8_t *)(vd.data() + i) = 0;
}
} else if (vtype_.vsew == 16) {
for (uint32_t i = 0; i < vl_; i++) {
uint16_t first = *(uint16_t *)(vr1.data() + i);
uint16_t second = *(uint16_t *)(vr2.data() + i);
uint16_t first_value = (first & 0x1);
uint16_t second_value = (second & 0x1);
uint16_t result = (first_value & second_value);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint16_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint16_t *)(vd.data() + i) = 0;
}
} else if (vtype_.vsew == 32) {
for (uint32_t i = 0; i < vl_; i++) {
uint32_t first = *(uint32_t *)(vr1.data() + i);
uint32_t second = *(uint32_t *)(vr2.data() + i);
uint32_t first_value = (first & 0x1);
uint32_t second_value = (second & 0x1);
uint32_t result = (first_value & second_value);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint32_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint32_t *)(vd.data() + i) = 0;
}
}
} break;
case 26: {
// vmor
auto &vr1 = vreg_file_.at(rsrc0);
auto &vr2 = vreg_file_.at(rsrc1);
auto &vd = vreg_file_.at(rdest);
if (vtype_.vsew == 8) {
for (uint32_t i = 0; i < vl_; i++) {
uint8_t first = *(uint8_t *)(vr1.data() + i);
uint8_t second = *(uint8_t *)(vr2.data() + i);
uint8_t first_value = (first & 0x1);
uint8_t second_value = (second & 0x1);
uint8_t result = (first_value | second_value);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint8_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint8_t *)(vd.data() + i) = 0;
}
} else if (vtype_.vsew == 16) {
for (uint32_t i = 0; i < vl_; i++) {
uint16_t first = *(uint16_t *)(vr1.data() + i);
uint16_t second = *(uint16_t *)(vr2.data() + i);
uint16_t first_value = (first & 0x1);
uint16_t second_value = (second & 0x1);
uint16_t result = (first_value | second_value);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint16_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint16_t *)(vd.data() + i) = 0;
}
} else if (vtype_.vsew == 32) {
for (uint32_t i = 0; i < vl_; i++) {
uint32_t first = *(uint32_t *)(vr1.data() + i);
uint32_t second = *(uint32_t *)(vr2.data() + i);
uint32_t first_value = (first & 0x1);
uint32_t second_value = (second & 0x1);
uint32_t result = (first_value | second_value);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint32_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint32_t *)(vd.data() + i) = 0;
}
}
} break;
case 27: {
// vmxor
auto &vr1 = vreg_file_.at(rsrc0);
auto &vr2 = vreg_file_.at(rsrc1);
auto &vd = vreg_file_.at(rdest);
if (vtype_.vsew == 8) {
for (uint32_t i = 0; i < vl_; i++) {
uint8_t first = *(uint8_t *)(vr1.data() + i);
uint8_t second = *(uint8_t *)(vr2.data() + i);
uint8_t first_value = (first & 0x1);
uint8_t second_value = (second & 0x1);
uint8_t result = (first_value ^ second_value);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint8_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint8_t *)(vd.data() + i) = 0;
}
} else if (vtype_.vsew == 16) {
for (uint32_t i = 0; i < vl_; i++) {
uint16_t first = *(uint16_t *)(vr1.data() + i);
uint16_t second = *(uint16_t *)(vr2.data() + i);
uint16_t first_value = (first & 0x1);
uint16_t second_value = (second & 0x1);
uint16_t result = (first_value ^ second_value);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint16_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint16_t *)(vd.data() + i) = 0;
}
} else if (vtype_.vsew == 32) {
for (uint32_t i = 0; i < vl_; i++) {
uint32_t first = *(uint32_t *)(vr1.data() + i);
uint32_t second = *(uint32_t *)(vr2.data() + i);
uint32_t first_value = (first & 0x1);
uint32_t second_value = (second & 0x1);
uint32_t result = (first_value ^ second_value);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint32_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint32_t *)(vd.data() + i) = 0;
}
}
} break;
case 28: {
// vmornot
auto &vr1 = vreg_file_.at(rsrc0);
auto &vr2 = vreg_file_.at(rsrc1);
auto &vd = vreg_file_.at(rdest);
if (vtype_.vsew == 8) {
for (uint32_t i = 0; i < vl_; i++) {
uint8_t first = *(uint8_t *)(vr1.data() + i);
uint8_t second = *(uint8_t *)(vr2.data() + i);
uint8_t first_value = (first & 0x1);
uint8_t second_value = (second & 0x1);
uint8_t result = (first_value | !second_value);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint8_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint8_t *)(vd.data() + i) = 0;
}
} else if (vtype_.vsew == 16) {
for (uint32_t i = 0; i < vl_; i++) {
uint16_t first = *(uint16_t *)(vr1.data() + i);
uint16_t second = *(uint16_t *)(vr2.data() + i);
uint16_t first_value = (first & 0x1);
uint16_t second_value = (second & 0x1);
uint16_t result = (first_value | !second_value);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint16_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint16_t *)(vd.data() + i) = 0;
}
} else if (vtype_.vsew == 32) {
for (uint32_t i = 0; i < vl_; i++) {
uint32_t first = *(uint32_t *)(vr1.data() + i);
uint32_t second = *(uint32_t *)(vr2.data() + i);
uint32_t first_value = (first & 0x1);
uint32_t second_value = (second & 0x1);
uint32_t result = (first_value | !second_value);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint32_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint32_t *)(vd.data() + i) = 0;
}
}
} break;
case 29: {
// vmnand
auto &vr1 = vreg_file_.at(rsrc0);
auto &vr2 = vreg_file_.at(rsrc1);
auto &vd = vreg_file_.at(rdest);
if (vtype_.vsew == 8) {
for (uint32_t i = 0; i < vl_; i++) {
uint8_t first = *(uint8_t *)(vr1.data() + i);
uint8_t second = *(uint8_t *)(vr2.data() + i);
uint8_t first_value = (first & 0x1);
uint8_t second_value = (second & 0x1);
uint8_t result = !(first_value & second_value);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint8_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint8_t *)(vd.data() + i) = 0;
}
} else if (vtype_.vsew == 16) {
for (uint32_t i = 0; i < vl_; i++) {
uint16_t first = *(uint16_t *)(vr1.data() + i);
uint16_t second = *(uint16_t *)(vr2.data() + i);
uint16_t first_value = (first & 0x1);
uint16_t second_value = (second & 0x1);
uint16_t result = !(first_value & second_value);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint16_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint16_t *)(vd.data() + i) = 0;
}
} else if (vtype_.vsew == 32) {
for (uint32_t i = 0; i < vl_; i++) {
uint32_t first = *(uint32_t *)(vr1.data() + i);
uint32_t second = *(uint32_t *)(vr2.data() + i);
uint32_t first_value = (first & 0x1);
uint32_t second_value = (second & 0x1);
uint32_t result = !(first_value & second_value);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint32_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint32_t *)(vd.data() + i) = 0;
}
}
} break;
case 30: {
// vmnor
auto &vr1 = vreg_file_.at(rsrc0);
auto &vr2 = vreg_file_.at(rsrc1);
auto &vd = vreg_file_.at(rdest);
if (vtype_.vsew == 8) {
for (uint32_t i = 0; i < vl_; i++) {
uint8_t first = *(uint8_t *)(vr1.data() + i);
uint8_t second = *(uint8_t *)(vr2.data() + i);
uint8_t first_value = (first & 0x1);
uint8_t second_value = (second & 0x1);
uint8_t result = !(first_value | second_value);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint8_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint8_t *)(vd.data() + i) = 0;
}
} else if (vtype_.vsew == 16) {
for (uint32_t i = 0; i < vl_; i++) {
uint16_t first = *(uint16_t *)(vr1.data() + i);
uint16_t second = *(uint16_t *)(vr2.data() + i);
uint16_t first_value = (first & 0x1);
uint16_t second_value = (second & 0x1);
uint16_t result = !(first_value | second_value);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint16_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint16_t *)(vd.data() + i) = 0;
}
} else if (vtype_.vsew == 32) {
for (uint32_t i = 0; i < vl_; i++) {
uint32_t first = *(uint32_t *)(vr1.data() + i);
uint32_t second = *(uint32_t *)(vr2.data() + i);
uint32_t first_value = (first & 0x1);
uint32_t second_value = (second & 0x1);
uint32_t result = !(first_value | second_value);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint32_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint32_t *)(vd.data() + i) = 0;
}
}
} break;
case 31: {
// vmxnor
auto &vr1 = vreg_file_.at(rsrc0);
auto &vr2 = vreg_file_.at(rsrc1);
auto &vd = vreg_file_.at(rdest);
if (vtype_.vsew == 8) {
for (uint32_t i = 0; i < vl_; i++) {
uint8_t first = *(uint8_t *)(vr1.data() + i);
uint8_t second = *(uint8_t *)(vr2.data() + i);
uint8_t first_value = (first & 0x1);
uint8_t second_value = (second & 0x1);
uint8_t result = !(first_value ^ second_value);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint8_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint8_t *)(vd.data() + i) = 0;
}
} else if (vtype_.vsew == 16) {
for (uint32_t i = 0; i < vl_; i++) {
uint16_t first = *(uint16_t *)(vr1.data() + i);
uint16_t second = *(uint16_t *)(vr2.data() + i);
uint16_t first_value = (first & 0x1);
uint16_t second_value = (second & 0x1);
uint16_t result = !(first_value ^ second_value);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint16_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint16_t *)(vd.data() + i) = 0;
}
} else if (vtype_.vsew == 32) {
for (uint32_t i = 0; i < vl_; i++) {
uint32_t first = *(uint32_t *)(vr1.data() + i);
uint32_t second = *(uint32_t *)(vr2.data() + i);
uint32_t first_value = (first & 0x1);
uint32_t second_value = (second & 0x1);
uint32_t result = !(first_value ^ second_value);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint32_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint32_t *)(vd.data() + i) = 0;
}
}
} break;
case 37: {
// vmul
auto &vr1 = vreg_file_.at(rsrc0);
auto &vr2 = vreg_file_.at(rsrc1);
auto &vd = vreg_file_.at(rdest);
if (vtype_.vsew == 8) {
for (uint32_t i = 0; i < vl_; i++) {
uint8_t first = *(uint8_t *)(vr1.data() + i);
uint8_t second = *(uint8_t *)(vr2.data() + i);
uint8_t result = (first * second);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint8_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint8_t *)(vd.data() + i) = 0;
}
} else if (vtype_.vsew == 16) {
for (uint32_t i = 0; i < vl_; i++) {
uint16_t first = *(uint16_t *)(vr1.data() + i);
uint16_t second = *(uint16_t *)(vr2.data() + i);
uint16_t result = (first * second);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint16_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint16_t *)(vd.data() + i) = 0;
}
} else if (vtype_.vsew == 32) {
for (uint32_t i = 0; i < vl_; i++) {
uint32_t first = *(uint32_t *)(vr1.data() + i);
uint32_t second = *(uint32_t *)(vr2.data() + i);
uint32_t result = (first * second);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint32_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint32_t *)(vd.data() + i) = 0;
}
}
} break;
case 45: {
// vmacc
auto &vr1 = vreg_file_.at(rsrc0);
auto &vr2 = vreg_file_.at(rsrc1);
auto &vd = vreg_file_.at(rdest);
if (vtype_.vsew == 8) {
for (uint32_t i = 0; i < vl_; i++) {
uint8_t first = *(uint8_t *)(vr1.data() + i);
uint8_t second = *(uint8_t *)(vr2.data() + i);
uint8_t result = (first * second);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint8_t *)(vd.data() + i) += result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint8_t *)(vd.data() + i) = 0;
}
} else if (vtype_.vsew == 16) {
for (uint32_t i = 0; i < vl_; i++) {
uint16_t first = *(uint16_t *)(vr1.data() + i);
uint16_t second = *(uint16_t *)(vr2.data() + i);
uint16_t result = (first * second);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint16_t *)(vd.data() + i) += result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint16_t *)(vd.data() + i) = 0;
}
} else if (vtype_.vsew == 32) {
for (uint32_t i = 0; i < vl_; i++) {
uint32_t first = *(uint32_t *)(vr1.data() + i);
uint32_t second = *(uint32_t *)(vr2.data() + i);
uint32_t result = (first * second);
DP(3, "Comparing " << first << " + " << second << " = " << result);
*(uint32_t *)(vd.data() + i) += result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint32_t *)(vd.data() + i) = 0;
}
}
} break;
}
} break;
case 6: {
switch (func6) {
case 0: {
auto &vr2 = vreg_file_.at(rsrc1);
auto &vd = vreg_file_.at(rdest);
if (vtype_.vsew == 8) {
for (uint32_t i = 0; i < vl_; i++) {
uint8_t second = *(uint8_t *)(vr2.data() + i);
uint8_t result = (rsdata[i][0].i + second);
DP(3, "Comparing " << rsdata[i][0].i << " + " << second << " = " << result);
*(uint8_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint8_t *)(vd.data() + i) = 0;
}
} else if (vtype_.vsew == 16) {
for (uint32_t i = 0; i < vl_; i++) {
uint16_t second = *(uint16_t *)(vr2.data() + i);
uint16_t result = (rsdata[i][0].i + second);
DP(3, "Comparing " << rsdata[i][0].i << " + " << second << " = " << result);
*(uint16_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint16_t *)(vd.data() + i) = 0;
}
} else if (vtype_.vsew == 32) {
for (uint32_t i = 0; i < vl_; i++) {
uint32_t second = *(uint32_t *)(vr2.data() + i);
uint32_t result = (rsdata[i][0].i + second);
DP(3, "Comparing " << rsdata[i][0].i << " + " << second << " = " << result);
*(uint32_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint32_t *)(vd.data() + i) = 0;
}
}
} break;
case 37: {
// vmul.vx
auto &vr2 = vreg_file_.at(rsrc1);
auto &vd = vreg_file_.at(rdest);
if (vtype_.vsew == 8) {
for (uint32_t i = 0; i < vl_; i++) {
uint8_t second = *(uint8_t *)(vr2.data() + i);
uint8_t result = (rsdata[i][0].i * second);
DP(3, "Comparing " << rsdata[i][0].i << " + " << second << " = " << result);
*(uint8_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint8_t *)(vd.data() + i) = 0;
}
} else if (vtype_.vsew == 16) {
for (uint32_t i = 0; i < vl_; i++) {
uint16_t second = *(uint16_t *)(vr2.data() + i);
uint16_t result = (rsdata[i][0].i * second);
DP(3, "Comparing " << rsdata[i][0].i << " + " << second << " = " << result);
*(uint16_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint16_t *)(vd.data() + i) = 0;
}
} else if (vtype_.vsew == 32) {
for (uint32_t i = 0; i < vl_; i++) {
uint32_t second = *(uint32_t *)(vr2.data() + i);
uint32_t result = (rsdata[i][0].i * second);
DP(3, "Comparing " << rsdata[i][0].i << " + " << second << " = " << result);
*(uint32_t *)(vd.data() + i) = result;
}
for (uint32_t i = vl_; i < VLMAX; i++) {
*(uint32_t *)(vd.data() + i) = 0;
}
}
} break;
}
} break;
case 7: {
vtype_.vill = 0;
vtype_.vediv = instr.getVediv();
vtype_.vsew = instr.getVsew();
vtype_.vlmul = instr.getVlmul();
DP(3, "lmul:" << vtype_.vlmul << " sew:" << vtype_.vsew << " ediv: " << vtype_.vediv << "rsrc_" << rsdata[0][0].i << "VLMAX" << VLMAX);
auto s0 = rsdata[0][0].i;
if (s0 <= VLMAX) {
vl_ = s0;
} else if (s0 < (2 * VLMAX)) {
vl_ = (uint32_t)ceil((s0 * 1.0) / 2.0);
} else if (s0 >= (2 * VLMAX)) {
vl_ = VLMAX;
}
rddata[0].i = vl_;
} break;
default:
std::abort();
}
} break;
default:
std::abort();
}
if (rd_write) {
trace->wb = true;
DPH(2, "Dest Reg: ");
auto type = instr.getRDType();
switch (type) {
case RegType::Integer:
if (rdest) {
DPN(2, type << std::dec << rdest << "={");
for (uint32_t t = 0; t < num_threads; ++t) {
if (t) DPN(2, ", ");
if (!tmask_.test(t)) {
DPN(2, "-");
continue;
}
ireg_file_.at(t)[rdest] = rddata[t].i;
DPN(2, "0x" << std::hex << rddata[t].i);
}
DPN(2, "}" << std::endl);
trace->used_iregs[rdest] = 1;
}
break;
case RegType::Float:
DPN(2, type << std::dec << rdest << "={");
for (uint32_t t = 0; t < num_threads; ++t) {
if (t) DPN(2, ", ");
if (!tmask_.test(t)) {
DPN(2, "-");
continue;
}
freg_file_.at(t)[rdest] = rddata[t].f;
DPN(2, "0x" << std::hex << rddata[t].f);
}
DPN(2, "}" << std::endl);
trace->used_fregs[rdest] = 1;
break;
default:
std::abort();
break;
}
}
PC_ += core_->arch().wsize();
if (PC_ != nextPC) {
DP(3, "*** Next PC: " << std::hex << nextPC << std::dec);
PC_ = nextPC;
}
} | 34.760204 | 142 | 0.452346 | [
"vector"
] |
7ad39ad8cb0bb64394276feabb1b45a07c83b599 | 16,933 | cpp | C++ | libethcore/Block.cpp | imtypist/FISCO-BCOS | 30a281d31e83ca666ef203193963a6d32e39e36a | [
"Apache-2.0"
] | null | null | null | libethcore/Block.cpp | imtypist/FISCO-BCOS | 30a281d31e83ca666ef203193963a6d32e39e36a | [
"Apache-2.0"
] | null | null | null | libethcore/Block.cpp | imtypist/FISCO-BCOS | 30a281d31e83ca666ef203193963a6d32e39e36a | [
"Apache-2.0"
] | null | null | null | /*
* @CopyRight:
* FISCO-BCOS 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.
*
* FISCO-BCOS 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 FISCO-BCOS. If not, see <http://www.gnu.org/licenses/>
* (c) 2016-2018 fisco-dev contributors.
*/
/**
* @brief basic data structure for block
*
* @file Block.cpp
* @author: yujiechem, jimmyshi
* @date 2018-09-20
*/
#include "Block.h"
#include "TxsParallelParser.h"
#include "libdevcrypto/CryptoInterface.h"
#include <libdevcore/Guards.h>
#include <libdevcore/RLP.h>
#include <tbb/parallel_for.h>
#define BLOCK_LOG(LEVEL) \
LOG(LEVEL) << "[Block]" \
<< "[line:" << __LINE__ << "]"
namespace dev
{
namespace eth
{
Block::Block(
bytesConstRef _data, CheckTransaction const _option, bool _withReceipt, bool _withTxHash)
: m_transactions(std::make_shared<Transactions>()),
m_transactionReceipts(std::make_shared<TransactionReceipts>()),
m_sigList(nullptr)
{
m_blockSize = _data.size();
decode(_data, _option, _withReceipt, _withTxHash);
}
Block::Block(
bytes const& _data, CheckTransaction const _option, bool _withReceipt, bool _withTxHash)
: m_transactions(std::make_shared<Transactions>()),
m_transactionReceipts(std::make_shared<TransactionReceipts>()),
m_sigList(nullptr)
{
m_blockSize = _data.size();
decode(ref(_data), _option, _withReceipt, _withTxHash);
}
Block::Block(Block const& _block)
: m_blockHeader(_block.blockHeader()),
m_transactions(std::make_shared<Transactions>(*_block.transactions())),
m_transactionReceipts(std::make_shared<TransactionReceipts>(*_block.transactionReceipts())),
m_sigList(std::make_shared<SigListType>(*_block.sigList())),
m_txsCache(_block.m_txsCache),
m_tReceiptsCache(_block.m_tReceiptsCache),
m_transRootCache(_block.m_transRootCache),
m_receiptRootCache(_block.m_receiptRootCache)
{}
Block& Block::operator=(Block const& _block)
{
m_blockHeader = _block.blockHeader();
/// init transactions
m_transactions = std::make_shared<Transactions>(*_block.transactions());
/// init transactionReceipts
m_transactionReceipts = std::make_shared<TransactionReceipts>(*_block.transactionReceipts());
/// init sigList
m_sigList = std::make_shared<SigListType>(*_block.sigList());
m_txsCache = _block.m_txsCache;
m_tReceiptsCache = _block.m_tReceiptsCache;
m_transRootCache = _block.m_transRootCache;
m_receiptRootCache = _block.m_receiptRootCache;
return *this;
}
/**
* @brief : generate block using specified params
*
* @param _out : bytes of generated block
* @param block_header : bytes of the block_header
* @param hash : hash of the block hash
* @param sig_list : signature list
*/
void Block::encode(bytes& _out) const
{
if (g_BCOSConfig.version() >= RC2_VERSION)
{
encodeRC2(_out);
return;
}
m_blockHeader.verify();
calTransactionRoot(false);
calReceiptRoot(false);
bytes headerData;
m_blockHeader.encode(headerData);
/// get block RLPStream
RLPStream block_stream;
block_stream.appendList(5);
// append block header
block_stream.appendRaw(headerData);
// append transaction list
block_stream.appendRaw(m_txsCache);
// append transactionReceipts list
block_stream.appendRaw(m_tReceiptsCache);
// append block hash
block_stream.append(m_blockHeader.hash());
// append sig_list
block_stream.appendVector(*m_sigList);
block_stream.swapOut(_out);
}
void Block::encodeRC2(bytes& _out) const
{
m_blockHeader.verify();
calTransactionRoot(false);
calReceiptRoot(false);
bytes headerData;
m_blockHeader.encode(headerData);
/// get block RLPStream
RLPStream block_stream;
block_stream.appendList(5);
// append block header
block_stream.appendRaw(headerData);
// append transaction list
block_stream.append(ref(m_txsCache));
// append block hash
block_stream.append(m_blockHeader.hash());
// append sig_list
block_stream.appendVector(*m_sigList);
// append transactionReceipts list
block_stream.appendRaw(m_tReceiptsCache);
block_stream.swapOut(_out);
}
/// encode transactions to bytes using rlp-encoding when transaction list has been changed
void Block::calTransactionRoot(bool update) const
{
if (g_BCOSConfig.version() >= V2_2_0)
{
calTransactionRootV2_2_0(update);
return;
}
if (g_BCOSConfig.version() >= RC2_VERSION)
{
calTransactionRootRC2(update);
return;
}
WriteGuard l(x_txsCache);
RLPStream txs;
txs.appendList(m_transactions->size());
if (m_txsCache == bytes())
{
BytesMap txsMapCache;
for (size_t i = 0; i < m_transactions->size(); i++)
{
RLPStream s;
s << i;
bytes trans_data;
(*m_transactions)[i]->encode(trans_data);
txs.appendRaw(trans_data);
txsMapCache.insert(std::make_pair(s.out(), trans_data));
}
txs.swapOut(m_txsCache);
m_transRootCache = hash256(txsMapCache);
}
if (update == true)
{
m_blockHeader.setTransactionsRoot(m_transRootCache);
}
}
void Block::calTransactionRootV2_2_0(bool update) const
{
TIME_RECORD(
"Calc transaction root, count:" + boost::lexical_cast<std::string>(m_transactions->size()));
WriteGuard l(x_txsCache);
if (m_txsCache == bytes())
{
std::vector<dev::bytes> transactionList;
transactionList.resize(m_transactions->size());
tbb::parallel_for(tbb::blocked_range<size_t>(0, m_transactions->size()),
[&](const tbb::blocked_range<size_t>& _r) {
for (uint32_t i = _r.begin(); i < _r.end(); ++i)
{
RLPStream s;
s << i;
dev::bytes byteValue = s.out();
dev::h256 hValue = ((*m_transactions)[i])->hash();
byteValue.insert(byteValue.end(), hValue.begin(), hValue.end());
transactionList[i] = byteValue;
}
});
m_txsCache = TxsParallelParser::encode(m_transactions);
m_transRootCache = dev::getHash256(transactionList);
}
if (update == true)
{
m_blockHeader.setTransactionsRoot(m_transRootCache);
}
}
std::shared_ptr<std::map<std::string, std::vector<std::string>>> Block::getTransactionProof() const
{
if (g_BCOSConfig.version() < V2_2_0)
{
BLOCK_LOG(ERROR) << "calTransactionRootV2_2_0 only support after by v2.2.0";
BOOST_THROW_EXCEPTION(
MethodNotSupport() << errinfo_comment("method not support in this version"));
}
std::shared_ptr<std::map<std::string, std::vector<std::string>>> merklePath =
std::make_shared<std::map<std::string, std::vector<std::string>>>();
std::vector<dev::bytes> transactionList;
transactionList.resize(m_transactions->size());
tbb::parallel_for(tbb::blocked_range<size_t>(0, m_transactions->size()),
[&](const tbb::blocked_range<size_t>& _r) {
for (uint32_t i = _r.begin(); i < _r.end(); ++i)
{
RLPStream s;
s << i;
dev::bytes byteValue = s.out();
dev::h256 hValue = ((*m_transactions)[i])->hash();
byteValue.insert(byteValue.end(), hValue.begin(), hValue.end());
transactionList[i] = byteValue;
}
});
dev::getMerkleProof(transactionList, merklePath);
return merklePath;
}
void Block::getReceiptAndHash(RLPStream& txReceipts, std::vector<dev::bytes>& receiptList) const
{
txReceipts.appendList(m_transactionReceipts->size());
receiptList.resize(m_transactionReceipts->size());
tbb::parallel_for(tbb::blocked_range<size_t>(0, m_transactionReceipts->size()),
[&](const tbb::blocked_range<size_t>& _r) {
for (uint32_t i = _r.begin(); i < _r.end(); ++i)
{
(*m_transactionReceipts)[i]->receipt();
dev::bytes receiptHash = (*m_transactionReceipts)[i]->hash();
RLPStream s;
s << i;
dev::bytes receiptValue = s.out();
receiptValue.insert(receiptValue.end(), receiptHash.begin(), receiptHash.end());
receiptList[i] = receiptValue;
}
});
for (size_t i = 0; i < m_transactionReceipts->size(); i++)
{
txReceipts.appendRaw((*m_transactionReceipts)[i]->receipt());
}
}
void Block::calReceiptRootV2_2_0(bool update) const
{
TIME_RECORD("Calc receipt root, count:" +
boost::lexical_cast<std::string>(m_transactionReceipts->size()));
WriteGuard l(x_txReceiptsCache);
if (m_tReceiptsCache == bytes())
{
RLPStream txReceipts;
std::vector<dev::bytes> receiptList;
getReceiptAndHash(txReceipts, receiptList);
txReceipts.swapOut(m_tReceiptsCache);
m_receiptRootCache = dev::getHash256(receiptList);
}
if (update == true)
{
m_blockHeader.setReceiptsRoot(m_receiptRootCache);
}
}
std::shared_ptr<std::map<std::string, std::vector<std::string>>> Block::getReceiptProof() const
{
if (g_BCOSConfig.version() < V2_2_0)
{
BLOCK_LOG(ERROR) << "calReceiptRootV2_2_0 only support after by v2.2.0";
BOOST_THROW_EXCEPTION(
MethodNotSupport() << errinfo_comment("method not support in this version"));
}
RLPStream txReceipts;
std::vector<dev::bytes> receiptList;
getReceiptAndHash(txReceipts, receiptList);
std::shared_ptr<std::map<std::string, std::vector<std::string>>> merklePath =
std::make_shared<std::map<std::string, std::vector<std::string>>>();
dev::getMerkleProof(receiptList, merklePath);
return merklePath;
}
void Block::calTransactionRootRC2(bool update) const
{
WriteGuard l(x_txsCache);
if (m_txsCache == bytes())
{
m_txsCache = TxsParallelParser::encode(m_transactions);
m_transRootCache = crypto::Hash(m_txsCache);
}
if (update == true)
{
m_blockHeader.setTransactionsRoot(m_transRootCache);
}
}
/// encode transactionReceipts to bytes using rlp-encoding when transaction list has been changed
void Block::calReceiptRoot(bool update) const
{
if (g_BCOSConfig.version() >= V2_2_0)
{
calReceiptRootV2_2_0(update);
return;
}
if (g_BCOSConfig.version() >= RC2_VERSION)
{
calReceiptRootRC2(update);
return;
}
WriteGuard l(x_txReceiptsCache);
if (m_tReceiptsCache == bytes())
{
RLPStream txReceipts;
txReceipts.appendList(m_transactionReceipts->size());
BytesMap mapCache;
for (size_t i = 0; i < m_transactionReceipts->size(); i++)
{
RLPStream s;
s << i;
bytes tranReceipts_data;
(*m_transactionReceipts)[i]->encode(tranReceipts_data);
// BLOCK_LOG(DEBUG) << LOG_KV("index", i) << "receipt=" << *(*m_transactionReceipts)[i];
txReceipts.appendRaw(tranReceipts_data);
mapCache.insert(std::make_pair(s.out(), tranReceipts_data));
}
txReceipts.swapOut(m_tReceiptsCache);
m_receiptRootCache = hash256(mapCache);
}
if (update == true)
{
m_blockHeader.setReceiptsRoot(m_receiptRootCache);
}
}
void Block::calReceiptRootRC2(bool update) const
{
WriteGuard l(x_txReceiptsCache);
if (m_tReceiptsCache == bytes())
{
size_t receiptsNum = m_transactionReceipts->size();
std::vector<dev::bytes> receiptsRLPs(receiptsNum, bytes());
tbb::parallel_for(
tbb::blocked_range<size_t>(0, receiptsNum), [&](const tbb::blocked_range<size_t>& _r) {
for (size_t i = _r.begin(); i != _r.end(); ++i)
{
RLPStream s;
s << i;
dev::bytes receiptRLP;
(*m_transactionReceipts)[i]->encode(receiptRLP);
receiptsRLPs[i] = receiptRLP;
}
});
// auto record_time = utcTime();
RLPStream txReceipts;
txReceipts.appendList(receiptsNum);
for (size_t i = 0; i < receiptsNum; ++i)
{
txReceipts.appendRaw(receiptsRLPs[i]);
}
txReceipts.swapOut(m_tReceiptsCache);
// auto appenRLP_time_cost = utcTime() - record_time;
// record_time = utcTime();
m_receiptRootCache = crypto::Hash(ref(m_tReceiptsCache));
// auto hashReceipts_time_cost = utcTime() - record_time;
/*
LOG(DEBUG) << LOG_BADGE("Receipt") << LOG_DESC("Calculate receipt root cost")
<< LOG_KV("appenRLPTimeCost", appenRLP_time_cost)
<< LOG_KV("hashReceiptsTimeCost", hashReceipts_time_cost)
<< LOG_KV("receipts num", receiptsNum);
*/
}
if (update == true)
{
m_blockHeader.setReceiptsRoot(m_receiptRootCache);
}
}
/**
* @brief : decode specified data of block into Block class
* @param _block : the specified data of block
*/
void Block::decode(
bytesConstRef _block_bytes, CheckTransaction const _option, bool _withReceipt, bool _withTxHash)
{
if (g_BCOSConfig.version() >= RC2_VERSION)
{
decodeRC2(_block_bytes, _option, _withReceipt, _withTxHash);
return;
}
/// no try-catch to throw exceptions directly
/// get RLP of block
RLP block_rlp = BlockHeader::extractBlock(_block_bytes);
/// get block header
m_blockHeader.populate(block_rlp[0]);
/// get transaction list
RLP transactions_rlp = block_rlp[1];
m_transactions->resize(transactions_rlp.itemCount());
for (size_t i = 0; i < transactions_rlp.itemCount(); i++)
{
(*m_transactions)[i] = std::make_shared<dev::eth::Transaction>();
(*m_transactions)[i]->decode(transactions_rlp[i], _option);
}
/// get txsCache
m_txsCache = transactions_rlp.data().toBytes();
/// get transactionReceipt list
RLP transactionReceipts_rlp = block_rlp[2];
m_transactionReceipts->resize(transactionReceipts_rlp.itemCount());
for (size_t i = 0; i < transactionReceipts_rlp.itemCount(); i++)
{
(*m_transactionReceipts)[i] = std::make_shared<dev::eth::TransactionReceipt>();
(*m_transactionReceipts)[i]->decode(transactionReceipts_rlp[i]);
}
/// get hash
h256 hash = block_rlp[3].toHash<h256>();
if (hash != m_blockHeader.hash())
{
BOOST_THROW_EXCEPTION(ErrorBlockHash() << errinfo_comment("BlockHeader hash error"));
}
/// get sig_list
m_sigList = std::make_shared<SigListType>(
block_rlp[4].toVector<std::pair<u256, std::vector<unsigned char>>>());
}
void Block::decodeRC2(
bytesConstRef _block_bytes, CheckTransaction const _option, bool _withReceipt, bool _withTxHash)
{
/// no try-catch to throw exceptions directly
/// get RLP of block
RLP block_rlp = BlockHeader::extractBlock(_block_bytes);
/// get block header
m_blockHeader.populate(block_rlp[0]);
/// get transaction list
RLP transactions_rlp = block_rlp[1];
/// get txsCache
m_txsCache = transactions_rlp.toBytes();
/// decode transaction
TxsParallelParser::decode(m_transactions, ref(m_txsCache), _option, _withTxHash);
/// get hash
h256 hash = block_rlp[2].toHash<h256>();
if (hash != m_blockHeader.hash())
{
BOOST_THROW_EXCEPTION(ErrorBlockHash() << errinfo_comment("BlockHeader hash error"));
}
/// get sig_list
m_sigList = std::make_shared<SigListType>(
block_rlp[3].toVector<std::pair<u256, std::vector<unsigned char>>>());
/// get transactionReceipt list
if (_withReceipt)
{
RLP transactionReceipts_rlp = block_rlp[4];
m_transactionReceipts->resize(transactionReceipts_rlp.itemCount());
for (size_t i = 0; i < transactionReceipts_rlp.itemCount(); i++)
{
(*m_transactionReceipts)[i] = std::make_shared<TransactionReceipt>();
(*m_transactionReceipts)[i]->decode(transactionReceipts_rlp[i]);
}
}
}
void Block::encodeProposal(std::shared_ptr<bytes> _out, bool const&)
{
encode(*_out);
}
void Block::decodeProposal(bytesConstRef _block, bool const&)
{
decode(_block);
}
} // namespace eth
} // namespace dev
| 33.267191 | 100 | 0.64265 | [
"vector"
] |
7ad8f86fef91007ee50cbe03668373973542af1e | 2,036 | cpp | C++ | Tests/PerformanceTests/DFPCs/PerformanceTestInterface.cpp | H2020-InFuse/cdff | e55fd48f9a909d0c274c3dfa4fe2704bc5071542 | [
"BSD-2-Clause"
] | 7 | 2019-02-26T15:09:50.000Z | 2021-09-30T07:39:01.000Z | Tests/PerformanceTests/DFPCs/PerformanceTestInterface.cpp | H2020-InFuse/cdff | e55fd48f9a909d0c274c3dfa4fe2704bc5071542 | [
"BSD-2-Clause"
] | null | null | null | Tests/PerformanceTests/DFPCs/PerformanceTestInterface.cpp | H2020-InFuse/cdff | e55fd48f9a909d0c274c3dfa4fe2704bc5071542 | [
"BSD-2-Clause"
] | 1 | 2020-12-06T12:09:05.000Z | 2020-12-06T12:09:05.000Z | /* --------------------------------------------------------------------------
*
* (C) Copyright …
*
* ---------------------------------------------------------------------------
*/
/*!
* @file PerformanceTestInterface.cpp
* @date 16/03/2018
* @author Alessandro Bianco
*/
/*!
* @addtogroup GuiTests
*
* Implementation of the performance test interface class.
*
*
* @{
*/
/* --------------------------------------------------------------------------
*
* Includes
*
* --------------------------------------------------------------------------
*/
#include "PerformanceTestInterface.hpp"
#include <Errors/Assert.hpp>
/* --------------------------------------------------------------------------
*
* Public Member Functions
*
* --------------------------------------------------------------------------
*/
PerformanceTestInterface::PerformanceTestInterface(const std::string& folderPath, const std::string& baseConfigurationFileName, const std::string& performanceMeasuresFileName) :
PerformanceTestBase(folderPath, std::vector<std::string>({baseConfigurationFileName}), performanceMeasuresFileName)
{
ASSERT(temporaryConfigurationFilePathsList.size() == 1, "Initialization did not work as expected, wrong number");
}
PerformanceTestInterface::~PerformanceTestInterface()
{
}
void PerformanceTestInterface::SetDfpc(CDFF::DFPC::DFPCCommonInterface* dfpc)
{
this->dfpc = dfpc;
}
/* --------------------------------------------------------------------------
*
* Private Member Functions
*
* --------------------------------------------------------------------------
*/
void PerformanceTestInterface::Configure()
{
ASSERT(temporaryConfigurationFilePathsList.size() == 1, "Configuration error, only one configuration file should be provided for one tested DFN");
dfpc->setConfigurationFile(temporaryConfigurationFilePathsList.at(0));
dfpc->setup();
}
void PerformanceTestInterface::Process()
{
ExecuteDfpc();
}
void PerformanceTestInterface::ExecuteDfpc()
{
dfpc->run();
}
/** @} */
| 25.135802 | 177 | 0.50835 | [
"vector"
] |
7ae10c8e6caa2a992715ddbc6f06286d70aa1124 | 1,401 | hpp | C++ | include/nav2_mpc_controller/mpc_core.hpp | harderthan/nav2_mpc_controller | 825990a3e5c008bdde4329cbe465c94ccb19f556 | [
"Apache-2.0"
] | 6 | 2021-06-09T13:07:01.000Z | 2022-01-30T23:27:21.000Z | include/nav2_mpc_controller/mpc_core.hpp | harderthan/nav2_mpc_controller | 825990a3e5c008bdde4329cbe465c94ccb19f556 | [
"Apache-2.0"
] | null | null | null | include/nav2_mpc_controller/mpc_core.hpp | harderthan/nav2_mpc_controller | 825990a3e5c008bdde4329cbe465c94ccb19f556 | [
"Apache-2.0"
] | 4 | 2021-08-04T11:31:33.000Z | 2021-10-14T02:56:23.000Z | /*
# Copyright 2021 Harderthan
# Original Code is from https://github.com/Geonhee-LEE/mpc_ros
#
# 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 MPC_H
#define MPC_H
#include <Eigen/Core>
#include <map>
#include <vector>
using namespace std;
class MPCCore {
public:
MPCCore();
// Solve the model given an initial state and polynomial coefficients.
// Return the first actuatotions.
vector<double> Solve(Eigen::VectorXd state, Eigen::VectorXd coeffs);
vector<double> mpc_x;
vector<double> mpc_y;
vector<double> mpc_theta;
void LoadParams(const std::map<string, double> ¶ms);
private:
// Parameters for mpc solver
double _max_angvel, _max_throttle, _bound_value;
int _mpc_steps, _x_start, _y_start, _theta_start, _v_start, _cte_start,
_etheta_start, _angvel_start, _a_start;
std::map<string, double> _params;
unsigned int dis_cnt;
};
#endif /* MPC_H */
| 27.470588 | 74 | 0.744468 | [
"vector",
"model"
] |
7ae656c60cbafc043f4eaf90017972af1c65a2f4 | 1,012 | cpp | C++ | advent-of-code-2020/day7.2.cpp | ricekot/learning | 885c783a116b15a35ca7761a65040f57343f8c1b | [
"MIT"
] | null | null | null | advent-of-code-2020/day7.2.cpp | ricekot/learning | 885c783a116b15a35ca7761a65040f57343f8c1b | [
"MIT"
] | null | null | null | advent-of-code-2020/day7.2.cpp | ricekot/learning | 885c783a116b15a35ca7761a65040f57343f8c1b | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int total_bags_in(string);
map<string, vector<pair<int, string>>> bags_in;
int main(){
ifstream list("input/day7.txt");
string line;
while (getline(list, line)){
istringstream iss(line);
string parent_adjective, parent_colour;
iss >> parent_adjective >> parent_colour;
string parent = parent_adjective + ' ' + parent_colour;
string child_quantity, child_adjective, child_colour;
while (iss >> child_quantity >> child_adjective >> child_colour){
string child = child_adjective + ' ' + child_colour;
bags_in[parent].push_back(make_pair(stoi(child_quantity), child));
}
}
cout << total_bags_in("shiny gold") << '\n';
return 0;
}
int total_bags_in(string bag){
int total_bags = 0;
for (pair<int, string> child_bag : bags_in[bag]){
total_bags += child_bag.first + child_bag.first * total_bags_in(child_bag.second);
}
return total_bags;
}
| 29.764706 | 90 | 0.649209 | [
"vector"
] |
7ae682a7ce7cd3a4b0eb3896905c54fc3c55dd10 | 71,474 | cpp | C++ | Cpp/Parser/Parser.cpp | Gabidal/GAC | f36b76bceb6a39a87b50c393eb3540f4085bd879 | [
"MIT"
] | 5 | 2019-08-19T18:18:08.000Z | 2019-12-13T19:26:03.000Z | Cpp/Parser/Parser.cpp | Gabidal/GAC | f36b76bceb6a39a87b50c393eb3540f4085bd879 | [
"MIT"
] | 3 | 2019-04-15T19:24:36.000Z | 2020-02-29T13:09:07.000Z | Cpp/Parser/Parser.cpp | Gabidal/GAC | f36b76bceb6a39a87b50c393eb3540f4085bd879 | [
"MIT"
] | 2 | 2019-10-08T23:16:05.000Z | 2019-12-18T22:58:04.000Z | #include "../../H/Parser/Parser.h"
#include "../../H/UI/Safe.h"
#include "../../H/Docker/Mangler.h"
#include "../../H/UI/Usr.h"
#include "../../H/Parser/PostProsessor.h"
//this is for unamed parameters.
int arg_count = 0;
extern Usr* sys;
extern Safe* safe;
vector<int> Parser::Get_Amount_Of(int i, long Flag, bool All_in_Same_Line)
{
//<summary>
//check from the index to next and counts-
//how many componets match the flag given
//</summary>
vector<int> Indexes;
for (; i < Input.size(); i++) {
if (Input[i].is(Flag))
Indexes.push_back(i);
else
if (Input[i].is(Flags::END_COMPONENT) ||
(Input[i].is(Flags::COMMENT_COMPONENT))) {
if (All_in_Same_Line)
break;
continue;
}
else
break;
}
return Indexes;
}
vector<int> Parser::Get_Amount_Of(int i, vector<int> Flags, bool All_in_Same_Line)
{
vector<int> Indexes;
for (; i < Input.size(); i++) {
for (auto f : Flags) {
if (Input[i].is(f)) {
Indexes.push_back(i);
goto Success;
}
}
//this happends if there was no correlatoin between the flags and the input at i
if (Input[i].is(Flags::END_COMPONENT) ||
(Input[i].is(Flags::COMMENT_COMPONENT))) {
if (All_in_Same_Line)
break;
continue;
}
else
break;
Success:;
}
return Indexes;
}
vector<Component> Parser::Get_Inheritting_Components(int i)
{
//import int ptr func a
vector<Component> Result;
for (; i < Input.size(); i++) {
if (Input[i].is(Flags::KEYWORD_COMPONENT) || (Scope->Find(Input[i].Value, Scope, false) != nullptr))
Result.push_back(Input[i]);
else
break;
}
return Result;
}
//Internal.Allocate(){} -> [Internal.Allocate]()
void Parser::Combine_Dot_In_Member_Functions(int& i)
{
if (!Scope->is(CLASS_NODE) || !Scope->is("static"))
return;
if (Input[i].Value != ".")
return;
//This is nice and handy, but what happends when you try to call a namespace function from out function scope?
//Internal.Allocate<int>()
bool Is_Call_Node = false;
if (i + 1 < Input.size() && Input[i + 1].is(Flags::TEXT_COMPONENT)){
int j = i + 2;
if (i + 2 < Input.size() && Input[i + 2].is(Flags::TEMPLATE_COMPONENT)){
j++;
}
if (Get_Amount_Of(j, Flags::PAREHTHESIS_COMPONENT, false).size() == 1){
Is_Call_Node = true;
}
}
if (!Is_Call_Node){
Math_Pattern(i, { "." }, OPERATOR_NODE, true);
}
}
void Parser::Template_Pattern(int& i)
{
if (Input[i].Value != "<")
return;
//if (s < 1 && s > 0)
int j = i;
int This_Scopes_Open_Template_Operators = 1;
while (Input[j].Value != ">" || This_Scopes_Open_Template_Operators > 0) {
j++;
if (j > Input.size() - 1)
break;
if (Input[j].Value == "<")
This_Scopes_Open_Template_Operators++;
if (Input[j].Value == ">")
This_Scopes_Open_Template_Operators--;
else if (Input[j].Value != ">" && Input[j].Value != "<" && !Input[j].is(Flags::TEXT_COMPONENT) && !Input[j].is(Flags::KEYWORD_COMPONENT) )
break;
}
//this is not a template holding operator.
if (This_Scopes_Open_Template_Operators > 0)
return;
if (Input[j].Value != ">")
return;
Input[i].Flags = Flags::TEMPLATE_COMPONENT;
Input[i].Value = "<>";
for (int k = i + 1; k < j; k++) {
Input[i].Components.push_back(Input[k]);
}
Input.erase(Input.begin() + i + 1, Input.begin() + j + 1);
Parser p(Scope);
p.Input = { Input[i].Components };
p.Dont_Give_Error_On_Templates = true;
p.Factory();
Input[i].Components = p.Input;
//for difinition pattern.
i--;
}
void Parser::Construct_Virtual_Class_To_Represent_Multiple_Template_Inputs(Component& i)
{
if (!i.is(Flags::TEMPLATE_COMPONENT))
return;
//<int ptr, char>
vector<vector<string>> Template_Pairs;
vector<pair<string, bool>> Output;
//first sort template pair type by comma.
vector<string> Current_Template_Pair;
for (auto T : i.Components) {
if (T.Value == ",") {
Template_Pairs.push_back(Current_Template_Pair);
Current_Template_Pair.clear();
}
else {
if (T.is(Flags::TEMPLATE_COMPONENT)) {
//<int ptr, List<T ptr>>
Construct_Virtual_Class_To_Represent_Multiple_Template_Inputs(T);
}
Current_Template_Pair.push_back(T.Value);
}
}
if (Current_Template_Pair.size() > 0) {
Template_Pairs.push_back(Current_Template_Pair);
Current_Template_Pair.clear();
}
//Now create a class for every template pair.
for (auto& Template_Pair : Template_Pairs) {
//ofcourse avoid same class redefinition.
if (Template_Pair.size() == 1) {
Output.push_back({ Template_Pair[0], false });
continue;
}
string Template_Pair_Class_Name = "____";
for (auto T : Template_Pair) {
Template_Pair_Class_Name += T + "_";
}
if (Scope->Find(Template_Pair_Class_Name, Scope, CLASS_NODE) != nullptr) {
Output.push_back({ Template_Pair_Class_Name, true });
}
else {
Node* New_Template_Pair_Class = new Node(CLASS_NODE, (new Position(i.Location)));
New_Template_Pair_Class->Inheritted = Template_Pair;
New_Template_Pair_Class->Name = Template_Pair_Class_Name;
New_Template_Pair_Class->Scope = Global_Scope;
Global_Scope->Defined.push_back(New_Template_Pair_Class);
Output.push_back({ Template_Pair_Class_Name, true });
}
}
i.Components.clear();
for (auto j : Output) {
Component C = Component(j.first, i.Location, Flags::TEXT_COMPONENT);
i.Components.push_back(C);
}
Parser p(Global_Scope);
p.Input = i.Components;
p.Dont_Give_Error_On_Templates = true;
p.Factory();
i.Components = p.Input;
}
void Parser::Operator_Combinator(int i)
{
if (Input[i].Value != ">")
return;
string All_Combined_Operators = ">";
for (int j = i + 1; j < Input.size() && Input[j].Value == ">"; j++)
All_Combined_Operators += ">";
if (All_Combined_Operators.size() == 1)
return;
Input.erase(Input.begin() + i + 1, Input.begin() + i + All_Combined_Operators.size() - 1);
Input[i].Value = All_Combined_Operators;
}
void Parser::Nodize_Template_Pattern(int i)
{
if (!Input[i].is(Flags::TEMPLATE_COMPONENT))
return;
if (Input[i].node != nullptr)
return;
Input[i].node = new Node(TEMPLATE_NODE, "<>", &Input[i].Location);
//List<List<int>, List<int>>
for (auto& T : Input[i].Components) {
//check that the value is defined not as a template but as a class.
//Or. If the current scope is a namespace (for template class definitions)
if (Scope->Find(T.Value)) {
Parser p(Scope);
p.Input = { T };
p.Factory();
Input[i].node->Templates.push_back(p.Input.back().node);
}
else if (Scope->Find_Template(T.Value) || (Scope->is("static") && Scope->is(CLASS_NODE))) {
return;
}
else {
Report(Observation(ERROR, "Uknown template type '" + T.Value + "'", T.Location, ""));
}
}
}
void Parser::Template_Type_Constructor(int i)
{
if (Input[i].node == nullptr)
return;
if (Input[i].node->Templates.size() == 0)
return;
if (!Scope->Find(Input[i].Value, Scope, CLASS_NODE))
return;
string New_Name = Input[i].node->Construct_Template_Type_Name();
if (Scope->Find(New_Name) != nullptr) {
Input[i].Value = New_Name;
Node* Constructed_Template_Class = Scope->Find(New_Name, Scope, CLASS_NODE);
if (Constructed_Template_Class)
Input[i].node->Inheritable_templates = Constructed_Template_Class->Inheritable_templates;
return;
}
//Search the original template class
Node* Og_Type = Input[i].node->Find(Input[i].node, Scope, CLASS_NODE);
//copy this template class to be non template
Node* Type;
Scope->Copy_Node(Type, Og_Type, Og_Type->Scope);
Type->Parsed_By = 0; //reset the parsed flags
//copy all functions becuase the copy_node by default skips function copying
for (auto &j : Type->Defined) {
if (j->is(FUNCTION_NODE))
Scope->Copy_Node(j, new Node(*j), Type);
}
//give the templates back to this new template class for template type refilling
Type->Templates = Input[i].node->Templates;
//turns List<T> into List<int>
for (int T = 0; T < Input[i].node->Templates.size(); T++) {
string T_Arg = Og_Type->Templates[T]->Name;
string T_Type = Type->Templates[T]->Name;
for (auto& Defined : Type->Template_Children) {
for (auto n : Defined.Get_all())
if (n->Value == T_Arg)
n->Value = T_Type;
}
/*for (auto& Inheritted : Type->Un_Initialized_Template_Inheritance) {
for (auto n : Inheritted.first.Get_all())
if (n->Value == T_Arg)
n->Value = T_Type;
}*/
}
vector<Component> New_Constructed_Template_Class_Code;
vector<Component> New_Constructed_Template_Code;
//re-Construct the class
/*for (auto j : Type->Un_Initialized_Template_Inheritance)
New_Constructed_Template_Code.push_back(j.first);*/
for (auto j : Type->Inheritted)
New_Constructed_Template_Class_Code.push_back(Component(j, *Type->Location, Lexer::GetComponent(j).Flags));
New_Constructed_Template_Class_Code.push_back(Component(New_Name, *Type->Location, Flags::TEXT_COMPONENT));
Component Content = Component("{", *Type->Location, Flags::PAREHTHESIS_COMPONENT);
Content.Components = Type->Template_Children;
New_Constructed_Template_Class_Code.push_back(Content);
New_Constructed_Template_Class_Code.push_back(Lexer::GetComponent("\n"));
//now Construct all member funcitons as well.
for (auto& Func : Type->Defined) {
for (int T = 0; T < Func->Templates.size(); T++) {
string T_Arg = Func->Templates[T]->Name;
string T_Type = Type->Templates[T]->Name;
if (Func->Templates[T]->Name == T_Arg)
Func->Templates[T]->Name = T_Type;
}
if (Func->Fetcher == nullptr)
continue; //inside type defined functions dont need to be rewritten again.
//if (Func->Templates.size() == 0)
Func->Fetcher = Type;
vector<Component> tmp = Template_Function_Constructor(Func, Og_Type->Templates, Type->Templates);
New_Constructed_Template_Code.insert(New_Constructed_Template_Code.end(), tmp.begin(), tmp.end());
}
Type->Name = New_Name;
Type->Defined.clear();
Type->Childs.clear();
//the constructed template class members are pushed to the old namespace altough the namespace has vbeen inlined
Node* Closest_Namespace = Scope->Get_Scope_As(CLASS_NODE, {"static"}, Scope);
Parser p(Closest_Namespace);
p.Input = New_Constructed_Template_Class_Code;
p.Factory();
Type->Scope->Find(Type->Name)->Inheritable_templates = Input[i].node->Templates;
Input[i].node->Inheritable_templates = Input[i].node->Templates;
Input[i].node->Templates.clear();
p = Parser(Closest_Namespace);
p.Input = New_Constructed_Template_Code;
p.Factory();
//for erasing the <>
//Input.erase(Input.begin() + i + 1);
Input[i].Value = Type->Name;
}
vector<Component> Parser::Template_Function_Constructor(Node* Func, vector<Node*> T_Args, vector<Node*> T_Types)
{
vector<Component> New_Constructed_Template_Code;
string New_Name = Func->Construct_Template_Type_Name();
if (Scope->Find(New_Name) != nullptr) {
if (Func->Compare_Fetchers(Scope->Find(New_Name))) {
Func->Name = New_Name;
return New_Constructed_Template_Code;
}
}
if (!Func->is(FUNCTION_NODE))
return New_Constructed_Template_Code;
vector<Component> Return_Type;
for (auto& Inheritted : Func->Inheritted) {
for (int T = 0; T < T_Args.size(); T++) {
string T_Arg = T_Args[T]->Name;
string T_Type = T_Types[T]->Name;
if (Inheritted == T_Arg) {
Inheritted = T_Type;
Func->Is_Template_Object = true;
}
}
Return_Type.push_back(Lexer::GetComponent(Inheritted));
}
for (auto& Inheritted : Func->Un_Initialized_Template_Inheritance) {
for (int T = 0; T < T_Args.size(); T++) {
string T_Arg = T_Args[T]->Name;
string T_Type = T_Types[T]->Name;
for (auto& j : Inheritted.first.Get_all())
if (j->Value == T_Arg) {
j->Value = T_Type;
Func->Is_Template_Object = true;
}
}
Return_Type.insert(Return_Type.begin() + Inheritted.second, Inheritted.first);
Return_Type.insert(Return_Type.begin() + Inheritted.second + 1, Inheritted.first.Components[0]);
}
vector<Component> Fetchers;
if (Func->Fetcher) {
//How TF can there be more than one fetcher Gabe?
//for (auto* Fetcher : Func->Get_All_Fetchers()) {
Node* Fetcher = Func->Fetcher;
Node* New_Fetcher;
Fetcher->Copy_Node(New_Fetcher, Fetcher, Fetcher->Scope);
for (int T = 0; T < T_Args.size(); T++) {
string T_Arg = T_Args[T]->Name;
string T_Type = T_Types[T]->Name;
for (auto& t : New_Fetcher->Templates)
if (t->Name == T_Arg)
t->Name = T_Type;
}
Component Fetcher_Component = Lexer::GetComponent(New_Fetcher->Construct_Template_Type_Name());
Fetchers.push_back(Fetcher_Component);
Fetchers.push_back(Lexer::GetComponent("."));
}
for (int T = 0; T < T_Args.size(); T++)
for (auto& Defined : Func->Template_Children)
for (auto n : Defined.Get_all())
if (n->Value == T_Args[T]->Name) {
n->Value = T_Types[T]->Name;
}
Component Name = Lexer::GetComponent(New_Name);
Name.Value = New_Name;
New_Constructed_Template_Code.insert(New_Constructed_Template_Code.end(), Return_Type.begin(), Return_Type.end());
New_Constructed_Template_Code.insert(New_Constructed_Template_Code.end(), Fetchers.begin(), Fetchers.end());
New_Constructed_Template_Code.insert(New_Constructed_Template_Code.end(), Name);
New_Constructed_Template_Code.insert(New_Constructed_Template_Code.end(), Func->Template_Children.begin(), Func->Template_Children.end());
New_Constructed_Template_Code.push_back(Lexer::GetComponent("\n"));
return New_Constructed_Template_Code;
}
void Parser::Inject_Template_Into_Member_Function_Fetcher(int& i)
{
// i-1 should have the class fetcher that feches the member.
if (i - 1 < 0)
return;
if (!Input[i - 1].is(Flags::TEXT_COMPONENT))
return;
if (Input[i - 1].node == nullptr)
return;
if (Scope->Find(Input[i - 1].Value, Scope, CLASS_NODE) == nullptr)
return;
// i should have the template <>
if (!Input[i].is(Flags::TEMPLATE_COMPONENT))
return;
for (auto T : Input[i].Components) {
Node* Template = new Node(TEMPLATE_NODE, T.Value, &T.Location);
Template->Inheritted.push_back("type");
Input[i - 1].node->Templates.push_back(Template);
}
Input.erase(Input.begin() + i--);
}
void Parser::Combine_Comment(int i)
{
if (!Input[i].is(Flags::COMMENT_COMPONENT))
return;
if (i + 1 >= Input.size() || !Input[i+1].is(Flags::COMMENT_COMPONENT))
return;
Input[i].Value += "\n" + Input[i + 1].Value;
Input.erase(Input.begin() + i + 1);
Combine_Comment(i);
}
void Parser::Remove_All_Excess_Comments(int i)
{
if (!Input[i].is(Flags::COMMENT_COMPONENT))
return;
Input.erase(Input.begin() + i--);
if (i >= 0)
Remove_All_Excess_Comments(i);
}
void Parser::Definition_Pattern(int i)
{
//foo ptr a = ...|bool is(int f) | bool is(string f)
//<summary>
//list all previusly defined and find the last as an text to define a new object
//put that result object into parents defined list and also into-
//the INPUT[i + object index] the newly created object
//</summary>
vector<int> Words = Get_Amount_Of(i, { Flags::KEYWORD_COMPONENT, Flags::TEXT_COMPONENT, Flags::TEMPLATE_COMPONENT });
//object definition needs atleast one type and one raw text
if (Words.size() > 0 && Input[Words.back()].is(Flags::TEMPLATE_COMPONENT))
Words.pop_back();
if (Words.size() < 2)
return;
//the last word must be a raw text not a keyword to be defined as a new object
if (Input[Words.back()].is(Flags::KEYWORD_COMPONENT))
return;
//this is because of the syntax of label jumping exmp: "jump somewhere" is same as a variable declaration exmp: "int somename".
for (auto j : Words)
//import keywords have theyre own function to parse theyre own patterns.
if (Input[j].Value == "jump" || Input[j].Value == "return" || Input[j].Value == "use")
return;
//int ptr a
Node* New_Defined_Object = new Node(OBJECT_DEFINTION_NODE, new Position(Input[Words[0]].Location));
if (i - 1 >= 0 && Input[i - 1].is(Flags::COMMENT_COMPONENT)) {
New_Defined_Object->Comment.Deprication_Information = Input[i - 1].Value;
replace(New_Defined_Object->Comment.Deprication_Information.begin(), New_Defined_Object->Comment.Deprication_Information.end(), '#', ' ');
}
New_Defined_Object->Name = Input[Words.back()].Value;
New_Defined_Object->Scope = Scope;
//transform the indecies into strings, and the -1 means that we want to skip the last element in the list (the name)
for (int j = 0; j < Words.size() - 1; j++) {
//the define is something like tihs:
//T a
//then there would be no problem because the T would have been found by the Find function
//The issue here is if there is template construction like:
//List<T> a
//that will construct a new List class that type is T, and that is wrong.
if (Input[Words[j]].is(Flags::TEMPLATE_COMPONENT)) {
//insure that this isn't a template parameter
//<int, T, R>
//check that all the templates are defined as a classes
bool All_Templates_Are_Defined_As_Classes = true;
for (auto T : Input[Words[j]].Components)
if (Scope->Find(T.Value) == nullptr)
All_Templates_Are_Defined_As_Classes = false;
//insire that all of the templates are from scopes templates and not classes
for (auto T : Input[Words[j]].Components)
if (Scope->Find_Template(T.Value))
//this means that the template type is not a class
All_Templates_Are_Defined_As_Classes = false;
if (All_Templates_Are_Defined_As_Classes == false) {
//normal 'T a' will not trigger this code because the T is not wrapped into a <>
Input[Words[j - 1]].Components.push_back(Input[Words[j]]);
New_Defined_Object->Un_Initialized_Template_Inheritance.push_back({ Input[Words[j - 1]] , j - 1 });
}
else {
//List<List<int>> a
//-> .List_List_int a
Parser p(Scope);
p.Input = { Input[Words[j - 1]], Input[Words[j]] };
p.Factory();
if ((!Scope->is("static") || !Scope->is(CLASS_NODE)) || All_Templates_Are_Defined_As_Classes) {
New_Defined_Object->Inheritted.push_back(p.Input.back().Value);
New_Defined_Object->Inheritable_templates = p.Input.back().node->Inheritable_templates;
}
else {
//This is for if the function return a templated return type like:
//List<T> a
//because the upper scope is not same as the function that this return type belongs to the upper code will not work
//and thats why this is here.
New_Defined_Object->Un_Initialized_Template_Inheritance.push_back({ p.Input.back(), j});
}
}
}
else if (j + 1 < Words.size() && !Input[Words[j + 1]].is(Flags::TEMPLATE_COMPONENT))
New_Defined_Object->Inheritted.push_back(Input[Words[j]].Value);
}
//Almost Namespace combination system 2000 (:
// The rest is made in the Type_Pattern dude
//if the current made object already exists
Node* Namespace = Scope->Find(New_Defined_Object, Scope, {CLASS_NODE, OBJECT_DEFINTION_NODE}, false);
//if the namespace is already a static class type and this one too then combine
//int std._Max_int_(int a, int b)
if (Namespace && Namespace->is("static") && Input[Words.back() + 1].Value == ".") {
//the operator below will erase the int inheritance of the namespace!!!
vector<string> Inheritted = New_Defined_Object->Inheritted;
New_Defined_Object->Inheritted = Namespace->Inheritted;
New_Defined_Object->Fetching_Inheritance = Inheritted;
}
else if (Namespace && (Namespace->is(CLASS_NODE) || ((Get_Amount_Of(Words.back() + 1, { Flags::PAREHTHESIS_COMPONENT }, false).size() == 1) && (Input[Words.back() + 1].Value[0] == '{'))) && Namespace->is("static")) {
New_Defined_Object = Namespace;
}
//if the object is static and the namespace is not
else if (Namespace != nullptr && New_Defined_Object->is("static") && !Namespace->is("static")) {
Report({
Observation(ERROR, "'" + New_Defined_Object->Name + "'", *New_Defined_Object->Location, "Colliding definitions of"),
Observation(ERROR, "'" + Namespace->Name + "'", *Namespace->Location, "Colliding definitions of")
});
}
//if the namespace is already a static class but this is not a static class or both are non static.
else if (Namespace != nullptr && Namespace->is(CLASS_NODE) && !Namespace->is("static")) {
bool Skip_Templates = false;
if (Words.back() + 1 < Input.size() && Input[Words.back() + 1].is(Flags::TEMPLATE_COMPONENT))
Skip_Templates = true;
vector<int> Parenthesises = Get_Amount_Of(Words.back() + 1 + Skip_Templates, { Flags::PAREHTHESIS_COMPONENT }, false);
if ((Parenthesises.size() == 1) && (Input[Parenthesises[0]].Value[0] == '{')) {
//check if the other one is namespace and the other not
if (New_Defined_Object->is("static")) {
Report(Observation(ERROR, "Cannot combine non static classes as namespaces!", *Namespace->Location, ""));
}
else {
Report({
Observation(ERROR, "'" + New_Defined_Object->Name + "'", *New_Defined_Object->Location, "Colliding definitions of"),
Observation(ERROR, "'" + Namespace->Name + "'", *Namespace->Location, "Colliding definitions of")
});
}
}
else
Scope->Defined.push_back(New_Defined_Object);
}
else if (Namespace != nullptr && !Namespace->Has({ IMPORT, EXPORT, FUNCTION_NODE }) && !Input[Words.back() + 1].is(CONTENT_NODE)) {
if (!Input[Words.back() + 1].is(CONTENT_NODE))
Report(Observation(ERROR, "'" + New_Defined_Object->Name + "' is already defined at '" + Namespace->Location->ToString() + "'", *New_Defined_Object->Location, "Colliding definitions of"));
}
else
Scope->Defined.push_back(New_Defined_Object);
//for later AST use:int ptr a = 123
Input[Words.back()].node = New_Defined_Object;
Input.erase(Input.begin() + i, Input.begin() + Words.back());
}
void Parser::Constructor_Pattern(int i)
{
vector<Component> ReturnType = Get_Inheritting_Components(i);
if (!(ReturnType.size() > 1))
return;
if (ReturnType[ReturnType.size() - 1].is(Flags::KEYWORD_COMPONENT))
return; //the last list index is the name and thus cannot be a keyword
if (!Scope->Find(ReturnType[ReturnType.size() - 1].Value, Scope)->is(CLASS_NODE))
return; //the name must be same as some class name to represent as the constructor of that class
for (auto j : ReturnType) {
if (j.Value == "return" || j.Value == "jump" || j.Value == "use")
return;
}
Node* Constructor = new Node(OBJECT_DEFINTION_NODE, new Position(ReturnType.back().Location));
Constructor->Name = ReturnType.back().Value;
for (int j = 0; j < ReturnType.size() - 1; j++)
Constructor->Inheritted.push_back(ReturnType[j].Value);
Input[i + Constructor->Inheritted.size() - 1 + 1].node = Constructor;
Input.erase(Input.begin() + i, Input.begin() + i + Constructor->Inheritted.size());
return;
}
void Parser::Prototype_Pattern(int i)
{
if (!Scope->is("static"))
return;
//int abc = banana()
//if ()
//func banana(int, short)\n
vector<int> Words = Get_Amount_Of(i, { Flags::TEXT_COMPONENT, Flags::KEYWORD_COMPONENT, Flags::TEMPLATE_COMPONENT });
//Words list must be a at leat two size for the type and for the name to be inside it
if (Words.size() == 0)
return;
//Banana<abc>() <- NO | int Banana<abc>() <- YES
if (Words.size() - Input[Words.back()].is(Flags::TEMPLATE_COMPONENT) < 2)
return;
vector<int> Paranthesis = Get_Amount_Of(Words.back() + 1, Flags::PAREHTHESIS_COMPONENT);
if (Paranthesis.size() != 1)
return;
if (Input[Paranthesis[0]].Value[0] != '(')
return;
//this is here because the jump can have a function call
//label get_jump(int x)
//jump get_jump(123);
for (auto c : Words)
if (Input[c].Value == "jump" || Input[c].Value == "return" || Input[c].Value == "import" || Input[c].Value == "use")
return;
Node* New_Defined_Object = new Node(PROTOTYPE, new Position(Input[Words.back()].Location));
if (Input[Words.back()].is(Flags::TEMPLATE_COMPONENT)) {
if (Input[Words.back()].is(Flags::TEMPLATE_COMPONENT)) {
for (auto T : Input[Words.back()].Components) {
Node* Template = new Node(TEMPLATE_NODE, T.Value, &T.Location);
Template->Inheritted.push_back("type");
New_Defined_Object->Templates.push_back(Template);
}
}
Words.pop_back();
New_Defined_Object->Is_Template_Object = true;
}
//type a
vector<string> Inheritted;
//skip the last that is the name index.
for (int j = 0; j < Words.size() - 1; j++) {
Inheritted.push_back(Input[Words[j]].Value);
}
New_Defined_Object->Inheritted = Inheritted;
New_Defined_Object->Name = Input[Words.back()].Value;
New_Defined_Object->Scope = Scope;
vector<Component> Types;
for (auto j : Input[Paranthesis[0]].Components) {
if (j.Value == ",") {
Node* p = new Node(OBJECT_DEFINTION_NODE, &j.Location);
if (Types.back().is(Flags::KEYWORD_COMPONENT)) {
p->Name = "ARG" + to_string(arg_count++);
p->Is_Template_Object = true;
}
else {
p->Name = Types.back().Value;
Types.pop_back();
}
p->Scope = New_Defined_Object;
for (auto k : Types)
p->Inheritted.push_back(k.Value);
if (p->is("type"))
p->Is_Template_Object = true;
New_Defined_Object->Parameters.push_back(p);
Types.clear();
}
else {
Types.push_back(j);
}
}
if (Types.size() > 0) {
//for the last parameter
Node* p = new Node(OBJECT_DEFINTION_NODE, &Types.back().Location);
if (Types.back().is(Flags::KEYWORD_COMPONENT)) {
p->Name = "ARG" + to_string(arg_count++);
p->Is_Template_Object = true;
}
else {
p->Name = Types.back().Value;
Types.pop_back();
}
p->Scope = New_Defined_Object;
for (auto k : Types)
p->Inheritted.push_back(k.Value);
if (p->is("type"))
p->Is_Template_Object = true;
New_Defined_Object->Parameters.push_back(p);
}
//erase inherittes as well the name as well the pearameters from the input list
Input.erase(Input.begin() + Words[0], Input.begin() + Paranthesis[0] + 1);
Scope->Defined.push_back(New_Defined_Object);
if (i < Input.size())
Prototype_Pattern(i);
return;
}
void Parser::Combine_Import_Shattered_Return_Info(int i)
{
//import func 4 integer banana(4 integer)
//import func 8 decimal banana(4 integer)
if (i + 1 >= Input.size())
return;
if (!Input[i].is(Flags::NUMBER_COMPONENT) || !Input[i + 1].is(Flags::TEXT_COMPONENT))
return;
Node* Numerical_Type = new Node(NUMBER_NODE, &Input[i].Location);
Numerical_Type->Name = Input[i].Value;
Numerical_Type->Format = Input[i + 1].Value;
Input[i].Flags = Flags::NUMERICAL_TYPE_COMPONENT;
Input[i].node = Numerical_Type;
Input.erase(Input.begin() + i + 1);
}
void Parser::Import_Pattern(int i)
{
//func banana(int, short)\n
vector<int> Words = Get_Amount_Of(i, { Flags::TEXT_COMPONENT, Flags::KEYWORD_COMPONENT, Flags::TEMPLATE_COMPONENT, Flags::NUMERICAL_TYPE_COMPONENT });
//Words list must be a at leat two size for the type and for the name to be inside it
if (Words.size() < 2)
return;
vector<int> Paranthesis = Get_Amount_Of(Words.back() + 1, Flags::PAREHTHESIS_COMPONENT);
if (Paranthesis.size() != 1)
return;
if (Input[Paranthesis[0]].Value[0] != '(')
return;
bool Has_Import_Keyword = false;
for (auto c : Words)
if (Input[c].Value == "import")
Has_Import_Keyword = true;
if (!Has_Import_Keyword)
return;
Node* New_Defined_Object = new Node(IMPORT, new Position(Input[Words.back()].Location));
if (Input[Words.back()].is(Flags::TEMPLATE_COMPONENT)) {
for (auto T : Input[Words.back()].Components) {
Node* Template = new Node(TEMPLATE_NODE, T.Value, new Position(T.Location));
Template->Inheritted.push_back("type");
New_Defined_Object->Templates.push_back(Template);
}
Words.pop_back();
New_Defined_Object->Is_Template_Object = true;
}
//type a
vector<string> Inheritted;
//skip the last that is the name index.
for (int j = 0; j < Words.size() - 1; j++) {
if (Input[Words[j]].is(Flags::NUMERICAL_TYPE_COMPONENT)) {
New_Defined_Object->Numerical_Return_Types.push_back(Input[Words[j]].node);
}
else
Inheritted.push_back(Input[Words[j]].Value);
}
New_Defined_Object->Inheritted = Inheritted;
New_Defined_Object->Name = Input[Words.back()].Value;
New_Defined_Object->Scope = Scope;
vector<Component> Types;
for (auto j : Input[Paranthesis[0]].Components) {
if (j.Value == ",") {
string Format = "";
for (int j = 0; j < Types.size(); j++) {
if (Types[j].Value == "decimal" || Types[j].Value == "integer") {
Format = Types[j].Value;
Types.erase(Types.begin() + j);
}
}
Node* p;
if (Types.back().is(Flags::NUMBER_COMPONENT))
p = new Node(NUMBER_NODE, new Position(j.Location), Format);
else
p = new Node(OBJECT_DEFINTION_NODE, new Position(j.Location), Format);
if (Types.back().is(Flags::KEYWORD_COMPONENT)) {
p->Name = "ARG" + to_string(arg_count++);
p->Is_Template_Object = true;
}
else {
p->Name = Types.back().Value;
Types.pop_back();
}
p->Scope = New_Defined_Object;
for (auto k : Types)
p->Inheritted.push_back(k.Value);
if (p->is("type"))
p->Is_Template_Object = true;
New_Defined_Object->Parameters.push_back(p);
Types.clear();
}
else {
Types.push_back(j);
}
}
if (Types.size() > 0) {
//for the last parameter
string Format = "";
for (int j = 0; j < Types.size(); j++) {
if (Types[j].Value == "decimal" || Types[j].Value == "integer") {
Format = Types[j].Value;
Types.erase(Types.begin() + j);
}
}
Node* p = nullptr;
if (Types.back().is(Flags::NUMBER_COMPONENT))
p = new Node(NUMBER_NODE, new Position(Types.back().Location), Format);
else
p = new Node(OBJECT_DEFINTION_NODE, new Position(Types.back().Location));
if (Types.back().is(Flags::KEYWORD_COMPONENT)) {
p->Name = "ARG" + to_string(arg_count++);
p->Is_Template_Object = true;
}
else {
p->Name = Types.back().Value;
Types.pop_back();
}
p->Scope = New_Defined_Object;
for (auto k : Types)
p->Inheritted.push_back(k.Value);
if (p->is("type"))
p->Is_Template_Object = true;
New_Defined_Object->Parameters.push_back(p);
}
//erase inherittes as well the name as well the pearameters from the input list
Input.erase(Input.begin() + Words[0], Input.begin() + Paranthesis[0] + 1);
Scope->Defined.push_back(New_Defined_Object);
if (i < Input.size())
Import_Pattern(i);
return;
}
void Parser::Object_Pattern(int i)
{
//<summary>
//Find defined text components and implant-
//the node repective of that component into the input[i]
//</summary>
if (!Input[i].is(Flags::TEXT_COMPONENT))
return;
//{ PARAMETER_NODE, OBJECT_DEFINTION_NODE, OBJECT_NODE, TEMPLATE_NODE, CLASS_NODE }
if (!Scope->Find(Input[i].Value, Scope, false)){
if (Dont_Give_Error_On_Templates)
return;
if (Input[i].Value == "address" || Input[i].Value == "size" || Input[i].Value == "format" || Input[i].Value == "integer" || Input[i].Value == "decimal")
return;
if (i - 1 >= 0 && Input[i - 1].Value == ".")
return;
for (auto& parmaeter : Scope->Parameters){
if (parmaeter->Name != "this")
return;
//Make an emulation by placing 'this' into the Input node to see if this is a memebr of the class.
//This is for template function callers.
Node* Emulation_Node = Input[i].node;
Emulation_Node->Fetcher = parmaeter;
string Emulation_Name = Emulation_Node->Name;
if (Emulation_Node->Get_Template().size() > 0){
Emulation_Name = Emulation_Node->Construct_Template_Type_Name();
}
if (Scope->Find(Emulation_Name, Scope)){
//This is a member of the class.
Input[i].node->Fetcher = nullptr;
return;
}
else{
Input[i].node->Fetcher = nullptr;
}
}
Report(Observation(ERROR, "'" + Input[i].Value + "'", Input[i].Location, DEFINITION_ERROR));
}
if (Input[i].node != nullptr)
return; //we dont want to rewrite the content
//{ PARAMETER_NODE, OBJECT_DEFINTION_NODE, OBJECT_NODE, TEMPLATE_NODE, CLASS_NODE }
Scope->Copy_Node(Input[i].node, new Node(*Scope->Find(Input[i].Value, Scope, false)), Scope);
Input[i].node->Location = new Position(Input[i].Location);
Input[i].node->Defined.clear();
//List<int> a -> __List_int a
if (Input[i].node->Templates.size() > 0) {
//this means that the next element is a template
if (i+1 >= Input.size() || !Input[i + 1].is(Flags::TEMPLATE_COMPONENT))
Report(Observation(ERROR, Input[i].Value, Input[i].Location, "Missing template arguments"));
Input[i].node->Templates = Input[i + 1].node->Templates;
Input.erase(Input.begin() + i + 1);
}
else if (i + 1 < Input.size() && Input[i + 1].is(Flags::TEMPLATE_COMPONENT)) {
//check if the current scope is a namespace or global scope
if (!Scope->is("static") || !Scope->is(CLASS_NODE)) {
for (auto T : Input[i + 1].Components)
Input[i].node->Templates.push_back(T.node);
if (Scope->Find(Input[i].node, Scope) == nullptr) {
Report(Observation(ERROR, "This object does not take template arguments '" + Input[i].Value + "'", Input[i].Location, ""));
}
Input[i].node = Scope->Find(Input[i].node, Scope);
Input[i].node->Templates = Input[i + 1].node->Templates;
Input.erase(Input.begin() + i + 1);
}
else {
//List<T> a -> List<T> a
//this will conserve the template as source code for the template manifestation
//Input[i] = Component("Un_initialized", Flags::UN_INITIALIZED_TEMPLATES, { Input[i], Input[i + 1] });
Input[i].Components.push_back(Input[i + 1]);
Input.erase(Input.begin() + i + 1);
return;
}
}
if (Input[i].node->is(OBJECT_DEFINTION_NODE))
Input[i].node->Type = OBJECT_NODE;
else if (Input[i].node->is(PARAMETER_NODE))
Input[i].node->Type = PARAMETER_NODE;
else if (Input[i].node->is(LABEL_NODE))
Input[i].node->Type = LABEL_NODE;
else if (Input[i].node->is(FUNCTION_NODE)) //this happends for function pointer adress geting prosess
Input[i].node->Type = OBJECT_NODE;
Input[i].node->Scope = Scope;
return;
}
void Parser::This_Pattern(int i)
{
}
void Parser::Complex_Cast(int i)
{
//this needs to be called before any paranthesis parser
//x->(T ptr ptr)
//this function creates a new virtual class that repesents the cast types
if (i - 1 < 0)
return;
if (!Input[i].is(Flags::PAREHTHESIS_COMPONENT))
return;
if (Input[i - 1].Value != "->")
return;
Input[i] = *Construct_Virtual_Class_For_Complex_Cast(Input[i]);
}
void Parser::Parenthesis_Pattern(int i)
{
// a = (a + b) * c
//<summary>
//go the content of the paranthesis and resurn an object
//put that result object into the INPUT[i + object index] the newly created paranthesis
//</summary>
if (!Input[i].is(Flags::PAREHTHESIS_COMPONENT))
return;
//if (Input[i].Value[0] == '{')
// if (Scope->is(CLASS_NODE) && Scope->is("static") != -1)
// return; //this is for member functions
//create an content Node and output will be in the same input.
Node* Paranthesis = new Node(CONTENT_NODE, new Position(Input[i].Location));
Paranthesis->Scope = Scope;
Parser TMP_Parser(Scope);
TMP_Parser.Input = Input[i].Components;
TMP_Parser.Factory();
for (Component j : TMP_Parser.Input)
if (j.node != nullptr) {
//j.node->Context = Paranthesis;
//j.node->Parent = Paranthesis;
Node* New_j;
j.node->Copy_Node(New_j, j.node, Scope);
Paranthesis->Childs.push_back(New_j);
}
Paranthesis->Paranthesis_Type = Input[i].Value[0];
Input[i].Components = TMP_Parser.Input;
Input[i].node = Paranthesis;
return;
}
void Parser::Math_Pattern(int& i, vector<string> Operators, int F, bool Change_Index)
{
//<summary>
//This function paternises the math order.
//Before this function the variables/functioncalls/parenthesis/ need to be-
//already made into Nodes and saved into the Components node member.
//</summary>
//a = b + c * d
if (!Input[i].is(Flags::OPERATOR_COMPONENT))
return;
if (i - 1 < 0)
return;
if (((size_t)i + 1) > Input.size())
return;
if (Input[i].node != nullptr)
return;
bool op_Pass = false;
for (string s : Operators)
if (Input[i].Value == s)
op_Pass = true;
if (!op_Pass)
return;
Node* Operator = new Node(F, new Position(Input[i].Location));
Operator->Name = Input[i].Value;
Operator->Scope = Scope;
if (Input[(size_t)i - 1].node != nullptr)
Operator->Left = Input[(size_t)i - 1].node;
else {
//Dont worry about function calls
Node* new_member = new Node(OBJECT_DEFINTION_NODE, new Position(Input[(size_t)i + 1].Location));
new_member->Name = Input[(size_t)i - 1].Value;
new_member->Scope = Operator->Scope;
Operator->Left = new_member;
}
if (Input[(size_t)i + 1].node != nullptr)
Operator->Right = Input[(size_t)i + 1].node;
else {
//test.a.m //these a.m are in different localscope.
//the right side does not need to be determined as well the left.
//Dont worry about function calls
Node* new_member = new Node(OBJECT_DEFINTION_NODE, new Position(Input[(size_t)i + 1].Location));
new_member->Name = Input[(size_t)i + 1].Value;
new_member->Scope = Operator->Scope;
Operator->Right = new_member;
}
//this is for algebra only!!
if (Input[i].Value == "-"){
Node* Coefficient = new Node(NUMBER_NODE, new Position(Input[i].Location));
Coefficient->Name = "-1";
Operator->Right->Coefficient = Coefficient;
}
if (Operator->Name == "=")
if (Scope->Name == "GLOBAL_SCOPE")
Scope->Find(Operator->Left->Name)->Inheritted.push_back("const");
//give the left and right operators the right holder information
Operator->Left->Context = Operator;
Operator->Right->Context = Operator;
Input[i].node = Operator;
Input.erase(Input.begin() + i + 1);
if (Change_Index)
i--;
Input.erase(Input.begin() + i - !Change_Index);
if ((size_t)i + 1 + Change_Index > Input.size() - 1)
return;
if (Input[i + Change_Index].is(Flags::OPERATOR_COMPONENT))
Math_Pattern(i += Change_Index, Operators, F, Change_Index);
return;
}
void Parser::Number_Pattern(int i)
{
//<summary>
//Make component numbers into real number_node.
//</summary>
if (!Input[i].is(Flags::NUMBER_COMPONENT))
return;
Node* Num = new Node(NUMBER_NODE, new Position(Input[i].Location));
Num->Name = Input[i].Value;
Num->Scope = Scope;
for (int j = 0; j < Num->Name.size(); j++)
if (Num->Name[j] == '.') {
Num->Format = "decimal";
break;
}
if (Num->Format == "decimal") {
int Dot_Index = Num->Name.find_first_of('.');
int Decimal_Precission = Num->Name.substr(Dot_Index, Num->Name.size() - 1).size();
if (Decimal_Precission > 8) {
Num->Size = 8;
}
else {
Num->Size = 4;
}
}
else {
if (atoll(Num->Name.c_str()) > INT32_MAX)
Num->Size = 8;
else
Num->Size = 4;
}
Input[i].node = Num;
return;
}
// String a = "123456"
void Parser::String_Pattern(int i)
{
if (!Input[i].is(Flags::STRING_COMPONENT))
return;
Node* String = new Node(STRING_NODE, new Position(Input[i].Location));
String->Name = Input[i].Value;
Input[i].node = String;
return;
}
// -a | --a | ++a
void Parser::Operator_PreFix_Pattern(int i, vector<string> Prefixes)
{
bool op_Pass = false;
for (string s : Prefixes)
if (Input[i].Value == s)
op_Pass = true;
if (!op_Pass)
return;
if (i + 1 > Input.size() - 1)
return;
if (Input[i + 1].is(Flags::END_COMPONENT))
return;
if (Input[i].node != nullptr)
return;
if (!Input[i].is(Flags::OPERATOR_COMPONENT))
return;
//return if the left side of the operator is a computable oject.
if (Input[(size_t)i - 1].Has({ Flags::TEXT_COMPONENT, Flags::NUMBER_COMPONENT, Flags::PAREHTHESIS_COMPONENT })) //a -b
return;
//to prevent this bullshit
//text.Size() -1
if (Input[(size_t)i - 1].Value == ".") {
return;
}
if (Input[i].Value == "-" && Input[i + 1].is(Flags::NUMBER_COMPONENT)) {
Input[i + 1].Value = "-" + Input[i + 1].Value;
Input.erase(Input.begin() + i);
}
else {
Node* PreFix = new Node(PREFIX_NODE, new Position(Input[i].Location));
PreFix->Scope = Scope;
//name
PreFix->Name = Input[i].Value;
PreFix->Right = Input[(size_t)i + 1].node;
PreFix->Right->Context = PreFix;
PreFix->Right->Scope = PreFix->Scope;
//Operator_Node PreFix; //++a/-a/--a
//Operator_Node PostFix; //a++/a--
Input[i].node = PreFix;
Input.erase(Input.begin() + i + 1);
}
}
void Parser::Operator_PostFix_Pattern(int i, vector<string> Postfix)
{
//<summary>
//a--/b()--
//a++/b()++
//Adds the Operator_Postfix into the previus object
//</summary>
if (i -1 < 0)
return;
if (Input[i].node != nullptr)
return;
if (!Input[i].is(Flags::OPERATOR_COMPONENT))
return;
//check if this operator is meant to be a prefix, not postfix.
if ((size_t)i + 1 < Input.size() - 1) {
if (Input[(size_t)i + 1].is(Flags::TEXT_COMPONENT))
return; //++ abc
if (Input[(size_t)i + 1].is(Flags::PAREHTHESIS_COMPONENT))
return; //++ (..)
}
bool op_Pass = false;
for (string s : Postfix)
if (Input[i].Value == s)
op_Pass = true;
if (!op_Pass)
return;
Node* post = new Node(POSTFIX_NODE, new Position(Input[i].Location));
post->Name = Input[i].Value;
post->Scope = Scope;
//set the node to postfix as left
post->Left = Input[(size_t)i - 1].node;
post->Left->Context = post;
post->Left->Scope = post->Scope;
Input[i].node = post;
Input.erase(Input.begin() + i - 1);
return;
}
void Parser::Variable_Negate_Pattern(int i)
{
if (Input[i].Value != "-")
return;
if (i - 1 >= 0) {
if (Input[(size_t)i - 1].Has({ Flags::PAREHTHESIS_COMPONENT, Flags::NUMBER_COMPONENT, Flags::TEXT_COMPONENT, Flags::OPERATOR_COMPONENT}))
return;
}
if (((size_t)i + 1) > Input.size())
return;
Node* Coefficient = new Node(NUMBER_NODE, new Position(Input[i].Location));
Coefficient->Name = "-1";
Node* Coefficient_Operator = new Node(OPERATOR_NODE, new Position(Input[i].Location));
Coefficient_Operator->Name = "*";
Coefficient_Operator->Left = Input[(size_t)i + 1].node->Coefficient;
Coefficient_Operator->Right = Coefficient;
Input[(size_t)i+1].node->Coefficient = Coefficient_Operator;
//remove the negettor operator
Input.erase(Input.begin() + i);
return;
}
void Parser::Callation_Pattern(int i)
{
//<summary>
//Notice!!! the Parameter Paranthesis must be before this defined!!!
//Also the callation as an object should be already be in the node member
//</summary>
if (!Input[i].is(Flags::TEXT_COMPONENT))
return;
int Paranthesis_Offset = 1;
if (i + 1 < Input.size() && Input[i + 1].is(Flags::TEMPLATE_COMPONENT))
Paranthesis_Offset = 2;
vector<int> Paranthesis = Get_Amount_Of(i + Paranthesis_Offset, Flags::PAREHTHESIS_COMPONENT);
if (Paranthesis.size() == 0)
return;
if (Paranthesis.size() > 1 && Input[Paranthesis[1]].Value[0] != '[')
return;
if (Input[(size_t)i + Paranthesis_Offset].Value[0] != '(')
return;
Node* call = new Node(CALL_NODE, new Position(Input[i].Location));
call->Name = Input[i].Value;
if (Input[i + 1].is(Flags::TEMPLATE_COMPONENT)) {
//Nodize the template type 'int' for example.
Parser p(Scope);
p.Input = {Input[i + 1]};
p.Factory();
//save all the template types into the call node, for postprosessor to handle this.
for (auto T : p.Input.back().node->Templates)
call->Templates.push_back(T);
Input.erase(Input.begin() + i + 1);
}
//give the normal call the inheritance for future operator type determining
call->Scope = Scope;
if (Scope->is(CALL_NODE))
call->Context = Scope;
//initialize the parenthesis that contains the parameters
Parser p(Scope);
p.Input = {Input[(size_t)i + 1]};
p.Factory();
call->Parameters = p.Input.back().node->Childs;
for (auto P : call->Parameters) {
P->Context = call;
}
Input[i].node = call;
Input[i].Value = call->Name;
Input.erase(Input.begin() + i + 1);
return;
}
void Parser::Array_Pattern(int i)
{
//<summary>
//find paranthesis with signature of '[' and put it into Input[i]
//Notice!!! The paranthesis must be initialized before this unition of array operation!!!
//</summary>
if (!Input[i].is(Flags::TEXT_COMPONENT))
return;
if ((size_t)i + 1 > Input.size() - 1)
return;
if (!Input[(size_t)i + 1].is(Flags::PAREHTHESIS_COMPONENT))
return;
if (Input[(size_t)i + 1].node->Paranthesis_Type != '[')
return;
Node* arr = new Node(ARRAY_NODE, new Position(Input[i].Location));
arr->Scope = Scope;
if (Input[(size_t)i].node != nullptr)
arr->Left = Input[(size_t)i].node;
else {
//Dont worry about function calls
Node* new_member = new Node(OBJECT_DEFINTION_NODE, new Position(Input[i].Location));
new_member->Name = Input[(size_t)i].Value;
arr->Left = new_member;
arr->Left->Scope = Scope;
}
if (Input[(size_t)i + 1].node->Childs.size() > 1) {
arr->Right = new Node(CONTENT_NODE, new Position(Input[(size_t)i+1].Location));
arr->Right->Childs = Input[(size_t)i + 1].node->Childs;
}
else if (Input[(size_t)i + 1].node->Childs[0] != nullptr)
arr->Right = Input[(size_t)i + 1].node->Childs[0];
else {
//test.a.m //these a.m are in different localscope.
//the right side does not need to be determined as well the left.
//Dont worry about function calls
Node* new_member = new Node(OBJECT_DEFINTION_NODE, new Position(Input[(size_t)i+1].Location));
new_member->Name = Input[(size_t)i + 1].Components[0].Value;
arr->Right = new_member;
arr->Right->Scope = Scope;
}
//TODO:
//Needs more testing with more complex array usage like: a[x][y][z]
arr->Name = "[]";
Input[i].node = arr;
Input.erase(Input.begin() + i + 1);
Array_Pattern(i);
return;
}
void Parser::Function_Pattern(int i, Node* Class)
{
//import int func main() [\n] {..}
//<summary>
//Notice!!! The parameter parenthesis & Childs parenthesis must be already initialized!!!
//Notice!!! The construction of function must be done before this!!!
//Notice!!! The Including must be done before this!!!
//Notice!!! This must be done before Object_Pattern & after Defintitin_Pattern!!!
//Build the function as
//</summary>
if (Input[i].node == nullptr)
return;
if (Input[i].is(Flags::KEYWORD_COMPONENT))
return;
int Paranthesis_Offset = 1;
if (i + 1 < Input.size() && Input[i + 1].is(Flags::TEMPLATE_COMPONENT))
Paranthesis_Offset = 2;
vector<int> Parenthesis_Indexes = Get_Amount_Of(i + Paranthesis_Offset, Flags::PAREHTHESIS_COMPONENT, false);
if (Parenthesis_Indexes.size() != 2)
return;
if (Input[Parenthesis_Indexes[0]].Value[0] != '(')
return;
//first try to get the behaviour
Node* func = nullptr;
if (Input[i].node->Type == OBJECT_DEFINTION_NODE)
func = Input[i].node;
else if (Input[i].node->Name == ".") {
Member_Function_Pattern(i);
return;
}
else
func = Scope->Find(Input[i].Value, Scope, true);
if (func == nullptr) {
Report(Observation(ERROR, "Parser didnt find " + Input[i].node->Name + " constructor!", Input[i].Location));
}
//override the object definition node flag
func->Type = FUNCTION_NODE;
//set the other values
func->Name = Input[i].Value;
func->Scope = Scope;
if (Class == nullptr) {
Class = func->Get_Scope_As({ CLASS_NODE }, func, false);
if (Class->is("static"))
Class = nullptr;
}
func->Template_Children = { Input[Parenthesis_Indexes[0]], Input[Parenthesis_Indexes[1]] };
//Template Fucntions.
for (auto T : func->Inheritted)
if (func->Find_Template(T)) {
func->Is_Template_Object = true;
break;
}
//construct nodes from the component templates.
if (Paranthesis_Offset == 2) {
for (auto T : Input[i + 1].Components) {
Node* Template = new Node(TEMPLATE_NODE, T.Value, &T.Location);
Template->Inheritted.push_back("type");
func->Templates.push_back(Template);
}
func->Is_Template_Object = true;
}
if (Class) {
//Take class templates and make them into component AST format.
Component* Uninitialized_Templates;
if (Class->Is_Template_Object) {
string Result = Class->Get_Uninitialized_Templates();
vector<Component> tmp = Lexer::GetComponents(Result);
Node* tmp_Class = new Node(CLASS_NODE, new Position());
tmp_Class->Templates = Class->Templates;
Parser p(tmp_Class);
p.Input = tmp;
p.Dont_Give_Error_On_Templates = true;
p.Factory();
Uninitialized_Templates = new Component(Class->Generate_Uninitialized_Template_Component(p.Input));
}
//Add the this pointter to the function parameters
Node* This = new Node(PARAMETER_NODE, "this", func->Location);
if (Class->Is_Template_Object) {
This->Inheritted = { "ptr" };
This->Un_Initialized_Template_Inheritance = { { *Uninitialized_Templates, 0 } };
}
else {
This->Inheritted = { Class->Name, "ptr" };
}
This->Scope = func;
This->Size = _SYSTEM_BIT_SIZE_;
//This->Defined = Class->Defined;
This->Inheritable_templates = Class->Inheritable_templates;
func->Defined.push_back(This);
}
//if the functoin is a template typed, then we must be carefull with the parameters that use the template too
Parser p(func);
p.Input.push_back(Input[Parenthesis_Indexes[0]]);
p.Factory();
for (auto& j : func->Defined) {
j->Type = PARAMETER_NODE;
}
func->Parameters = func->Defined;
if (!func->Is_Template_Object) {
p.Input.clear();
p.Input.push_back(Input[Parenthesis_Indexes[1]]);
p.Factory();
func->Childs = p.Input[0].node->Childs;
p.Input.clear();
for (auto j : func->Defined) {
Safe s;
s.Check_For_Undefined_Inheritance(j);
}
func->Mangled_Name = MANGLER::Mangle(func, "");
}
Input[i].node = func;
Input.erase(Input.begin() + Parenthesis_Indexes[1]);
Input.erase(Input.begin() + Parenthesis_Indexes[0]);
if (func->Templates.size() > 0) {
Input.erase(Input.begin() + i + 1);
}
return;
}
void Parser::Type_Pattern(int i)
{
//type int{ size 4}
//<summary>
//Notice!!! The Parenthesis that contains the members needs to be initialized before this!!!
//Does same as the Function_Pattern but just one less parenthesis to worrie about.
//</summary>
if (!Input[i].is(Flags::TEXT_COMPONENT))
return;
if (Scope->Find(Input[i].Value, Scope, false) == nullptr)
return;
int Paranthesis_Offset = 1;
if (i+1 < Input.size() && Input[i + 1].is(Flags::TEMPLATE_COMPONENT))
Paranthesis_Offset = 2;
vector<int> Parenthesis_Indexes = Get_Amount_Of(i + Paranthesis_Offset, Flags::PAREHTHESIS_COMPONENT, false);
if (Parenthesis_Indexes.size() != 1)
return;
if (Input[Parenthesis_Indexes[0]].Value[0] != '{')
return;
Node* Type = nullptr;
if (Input[i].node != nullptr)
//dont worry this has same pointter as the one that is in the Defined list, so this point to it
Type = Input[i].node;
else
Type = Scope->Find(Input[i].Value, Scope, OBJECT_DEFINTION_NODE);
if (Type == nullptr) {
Report(Observation(ERROR, "Type definition was not found!", Input[i].Location));
throw::runtime_error("ERROR!");
}
//reset the value
Type->Type = CLASS_NODE;
//combine inheritted memebrs
Type->Get_Inheritted_Class_Members();
if (Input[i + 1].is(Flags::TEMPLATE_COMPONENT)) {
for (auto T : Input[i + 1].Components) {
Node* Template = new Node(TEMPLATE_NODE, T.Value, &T.Location);
Template->Inheritted.push_back("type");
Type->Templates.push_back(Template);
}
Type->Template_Children = Input[Parenthesis_Indexes[0]].Components;
Type->Is_Template_Object = true;
}
if (!Type->Is_Template_Object) {
Parser p(Type);
p.Input.push_back(Input[Parenthesis_Indexes[0]]);
p.Factory();
for (auto j : Type->Defined) {
Safe s;
s.Check_For_Undefined_Inheritance(j);
}
//before giving the node->Childs to the class as body, we need to first remove the
//only Object_Definition_Nodes and functions.
//size, Sum, etc
//Only left behind body intended nodes like operators.
for (int c = 0; c < p.Input[0].node->Childs.size(); c++) {
if (p.Input[0].node->Childs[c]->Has({ OBJECT_DEFINTION_NODE, FUNCTION_NODE })) {
p.Input[0].node->Childs.erase(p.Input[0].node->Childs.begin() + c);
c--;
}
}
Type->Append(Type->Childs, p.Input[0].node->Childs);
p.Input.clear();
}
//This means that the class is a namespace
//Namespace Combination system 5000
if (Type->is("static")) {
for (auto& j : Type->Defined) {
if (j->is("static"))
continue;
if (j->Has({ FUNCTION_NODE, CLASS_NODE }))
continue;
j->Inheritted.insert(j->Inheritted.begin(), "static");
}
}
//infiltrate the class type and inject this behemoth
/*if (MANGLER::Is_Base_Type(Type) == false && sys->Info.Reference_Count_Size > 0) {
Node* Reference_Count = new Node(OBJECT_DEFINTION_NODE, Type->Location);
Reference_Count->Name = "Reference_Count";
Reference_Count->Scope = Type;
Node* Size_Representer = Type->Find(sys->Info.Reference_Count_Size, Type, CLASS_NODE, "integer");
if (Size_Representer == nullptr) {
Report(Observation(WARNING, "Cannot find suitable size type for the reference countter", *Type->Location));
//we can still save this!
Node* Size = new Node(OBJECT_DEFINTION_NODE, Type->Location);
Size->Name = "size";
Size->Size = sys->Info.Reference_Count_Size;
Size->Inheritted.push_back("const");
Reference_Count->Defined.push_back(Size);
Reference_Count->Inheritted.push_back("type");
}
else
Reference_Count->Inheritted.push_back(Size_Representer->Name);
}*/
Input.erase(Input.begin() + Parenthesis_Indexes[0]);
if (i+1 < Input.size() && Input[i + 1].is(Flags::TEMPLATE_COMPONENT))
Input.erase(Input.begin() + i + 1);
Input.erase(Input.begin() + i);
if (i < Input.size())
Type_Pattern(i);
return;
}
void Parser::Member_Pattern(int i)
{
//foo.a = 1
//IF LEXER ALREADY USES DOT COMPONENT AS OPERATOR THEN WE DONT NEED TO DO ENYTHING HERE :D.
}
void Parser::If_Pattern(int i)
{
//<summary>
//make the AST of condition as IF
//if <condition/(condition)> <code-single-line/(multiline-code)>
//Notice!!! The two next components need to be initialized before this!!!
//</summary>
if (!Input[i].is(Flags::KEYWORD_COMPONENT))
return;
vector<int> Parenthesis_Indexes = Get_Amount_Of(i + 1, Flags::PAREHTHESIS_COMPONENT, false);
if (Parenthesis_Indexes.size() != 2)
return;
//if (){..}
//else (){..} //this works as 'else if'
//else {..} //and this as normal 'else'
//while (..){..} //loop
Node* con;
if (Input[i].Value == "if")
con = new Node(IF_NODE, new Position(Input[i].Location));
else if (Input[i].Value == "else")
con = new Node(ELSE_IF_NODE, new Position(Input[i].Location)); //this works for only else if because it requers 2 paranthesis
else if (Input[i].Value == "while")
con = new Node(WHILE_NODE, new Position(Input[i].Location));
else
return;
Parser p(con);
con->Name = Input[i].Value;
con->Scope = Scope;
p.Input.push_back(Input[Parenthesis_Indexes[0]]);
p.Factory();
con->Parameters = p.Input[0].node->Childs;
p.Input.clear();
p.Input.push_back(Input[Parenthesis_Indexes[1]]);
p.Factory();
con->Childs = p.Input[0].node->Childs;
Input[i].node = con;
Input.erase(Input.begin() + Parenthesis_Indexes[0]);
Input.erase(Input.begin() + Parenthesis_Indexes[1] - 1);
return;
}
void Parser::Else_Pattern(int i)
{
//here we patternise the else without a condition
if (!Input[i].is(Flags::KEYWORD_COMPONENT))
return;
vector<int> Parenthesis_Indexes = Get_Amount_Of(i + 1, Flags::PAREHTHESIS_COMPONENT, false);
if (Parenthesis_Indexes.size() != 1)
return;
if (Input[i].Value != "else")
return;
Node* Else = new Node(ELSE_NODE, new Position(Input[i].Location));
Parser p(Else);
Else->Name = Input[i].Value;
Else->Scope = Scope;
p.Input.push_back(Input[Parenthesis_Indexes[0]]);
p.Factory();
Else->Childs = p.Input[0].node->Childs;
Input[i].node = Else;
Input.erase(Input.begin() + Parenthesis_Indexes[0]);
return;
}
void Parser::Operator_Order()
{
if (Input.size() < 2)
return;
for (int i = 0; i < Input.size(); i++)
Math_Pattern(i, { "." }, OPERATOR_NODE);
for (int i = 0; i < Input.size(); i++)
Math_Pattern(i, { "->" }, NODE_CASTER);
for (int i = 0; i < Input.size(); i++)
Array_Pattern(i);
for (int i = 0; i < Input.size(); i++)
Variable_Negate_Pattern(i);
for (int i = 0; i < Input.size(); i++)
Operator_PreFix_Pattern(i, { "++", "--", "-"});
for (int i = 0; i < Input.size(); i++)
Operator_PostFix_Pattern(i, { "++", "--" });
//the combination and multilayering of operations.
for (int i = 0; i < Input.size(); i++)
Math_Pattern(i, { ":" }, OPERATOR_NODE);
for (int i = 0; i < Input.size(); i++)
Math_Pattern(i, { "^" }, OPERATOR_NODE);
for (int i = 0; i < Input.size(); i++)
Math_Pattern(i, { "*", "/" , "%" }, OPERATOR_NODE);
for (int i = 0; i < Input.size(); i++)
Math_Pattern(i, { "+", "-" }, OPERATOR_NODE);
for (int i = 0; i < Input.size(); i++)
Math_Pattern(i, { "<<", ">>" }, BIT_OPERATOR_NODE);
for (int i = 0; i < Input.size(); i++)
Math_Pattern(i, { "==", "!=", "<=", ">=", "!<", "!>" , "|=", "&=" }, CONDITION_OPERATOR_NODE);
for (int i = 0; i < Input.size(); i++)
Math_Pattern(i, { "&", "!&" }, BIT_OPERATOR_NODE);
//for (int i = 0; i < Input.size(); i++)
// Math_Pattern(i, { "?" }, BIT_OPERATOR_NODE);
for (int i = 0; i < Input.size(); i++)
Math_Pattern(i, { "¤" }, BIT_OPERATOR_NODE);
for (int i = 0; i < Input.size(); i++)
Math_Pattern(i, { "|", "!|" }, BIT_OPERATOR_NODE);
for (int i = 0; i < Input.size(); i++)
Math_Pattern(i, { "<", ">" }, CONDITION_OPERATOR_NODE);
for (int i = 0; i < Input.size(); i++)
Math_Pattern(i, { "&&", "||" }, LOGICAL_OPERATOR_NODE);
for (int i = 0; i < Input.size(); i++)
Math_Pattern(i, { "=", "+=", "-=", "*=", "/=" }, ASSIGN_OPERATOR_NODE);
}
void Parser::Return_Pattern(int i)
{
if (Input[i].Value != "return")
return;
if (Input[i].node != nullptr)
return;
bool No_Return_Value = (((size_t)i + 1 > Input.size() - 1) || (Input[i+1].node == nullptr));
//return a + b
//return;
Node* ret = new Node(FLOW_NODE, new Position(Input[i].Location));
ret->Name = "return";
ret->Scope = Scope;
if (!No_Return_Value) {
ret->Right = Input[(size_t)i + 1].node;
ret->Right->Context = ret;
Input.erase(Input.begin() + i + 1);
}
Input[i].node = ret;
return;
}
void Parser::Jump_Pattern(int i)
{
//jump banana
if (Input[i].Value != "jump")
return;
if (Input.size() < (size_t)i + 1)
return;
Node* jmp = new Node(FLOW_NODE, new Position(Input[i].Location));
jmp->Name = "jump";
Node* label = new Node(LABEL_NODE, new Position(Input[i].Location));
label->Name = Input[(size_t)i + 1].Value;
jmp->Right = label;
Input[i].node = jmp;
Input.erase(Input.begin() + i + 1);
}
void Parser::Label_Pattern(int i)
{
if (Input[i].node != nullptr)
return;
//test
//..
//labels are tricy because they are just one word
//so check that it isnt connectd to enythign
Node* l = Scope->Find(Input[i].Value, Scope);
if (l == nullptr)
return;
if (!l->is(LABEL_NODE))
return;
Node* L = new Node(LABEL_NODE, new Position(Input[i].Location));
L->Name = Input[i].Value;
L->Scope = Scope;
Input[i].node = L;
}
void Parser::Label_Definition(int i)
{
if (i - 1 <= 0)
return;
if ((size_t)i + 1 > Input.size()-1)
return;
if (Input[(size_t)i - 1].is(Flags::KEYWORD_COMPONENT))
return; //return label_name
if (Input[(size_t)i + 1].is(Flags::TEXT_COMPONENT))
return; //label_name obj_name(int)
if (Scope->Find(Input[i].Value, Scope) != nullptr)
return; //label_name(int), label_name = ..
if (!Input[i].is(Flags::TEXT_COMPONENT))
return; //only text name allowed
if (Input[i].Value == "\n")
return;
if (Input[(size_t)i - 1].is(Flags::OPERATOR_COMPONENT))
return;
if (Input[(size_t)i + 1].is(Flags::OPERATOR_COMPONENT))
return;
if (Input[i].Value == "size" || Input[i].Value == "format")
return;
//passes: label_name if (..)..
//passes: label_name (..)
//passes: label_name {..}
Node* label = new Node(LABEL_NODE, new Position(Input[i].Location));
label->Name = Input[i].Value;
label->Scope = Scope;
Input[i].node = label;
Scope->Defined.push_back(label);
}
void Parser::Break_Pattern(int i)
{
if (Input[i].Value != "break")
return;
Node* While = Scope->Get_Scope_As({ WHILE_NODE }, Scope, false);
if (!While) {
Report(Observation(ERROR, "Use of 'break' outside of 'while'.", Input[i].Location, SYNTAX_ERROR));
}
Node* Break = new Node(FLOW_NODE, &Input[i].Location);
//This will point straight to the while loop for conveniences.
Break->Scope = While;
Break->Name = "break";
Input[i].node = Break;
}
void Parser::Continue_Pattern(int i)
{
if (Input[i].Value != "continue")
return;
Node* While = Scope->Get_Scope_As({ WHILE_NODE }, Scope, false);
if (!While) {
Report(Observation(ERROR, "Use of 'continue' outside of 'while'.", Input[i].Location, SYNTAX_ERROR));
}
Node* Continue = new Node(FLOW_NODE, &Input[i].Location);
//This will point straight to the while loop for conveniences.
Continue->Scope = While;
Continue->Name = "continue";
Input[i].node = Continue;
}
void Parser::Size_Pattern(int i)
{
//size = 4
if (Input[i].Value != "size")
return;
if (!Scope->is(CLASS_NODE))
return;
if (Input[i].node != nullptr)
return;
if (i - 1 >= 0)
if (Input[(size_t)i - 1].is(Flags::OPERATOR_COMPONENT) || Input[(size_t)i - 1].is(Flags::TEXT_COMPONENT))
return;
if (Input[(size_t)i + 1].Value != "=")
return;
if (!Input[(size_t)i + 2].is(Flags::NUMBER_COMPONENT))
return;
Node* size = new Node(OBJECT_DEFINTION_NODE, new Position(Input[i].Location));
size->Size = atoi((Input[(size_t)i + 2].node)->Name.c_str());
size->Name = "size";
size->Inheritted.push_back("const"); //NOTICE:!!! this might be wrong type!!!
size->Scope = Scope;
Scope->Defined.push_back(size);
Input[i].node = size;
Input.erase(Input.begin() + i + 1);
Input.erase(Input.begin() + i + 1);
return;
}
void Parser::Format_Pattern(int i)
{
//format = decimal
if (Input[i].Value != "format")
return;
if (!Scope->is(CLASS_NODE))
return;
if (i - 1 >= 0)
if (Input[(size_t)i - 1].is(Flags::OPERATOR_COMPONENT) || Input[(size_t)i - 1].is(Flags::TEXT_COMPONENT) || Input[(size_t)i-1].is(Flags::KEYWORD_COMPONENT))
return;
if (Input[(size_t)i + 1].Value != "=")
return;
if (!Input[(size_t)i + 2].is(Flags::TEXT_COMPONENT))
return;
Node* format = new Node(OBJECT_DEFINTION_NODE, new Position(Input[i].Location));
format->Format = Input[(size_t)i + 2].Value;
format->Name = "format";
format->Inheritted.push_back("const"); //NOTICE:!!! this might be wrong type!!!
format->Scope = Scope;
Scope->Defined.push_back(format);
Input[i].node = format;
Input.erase(Input.begin() + i + 1);
Input.erase(Input.begin() + i + 1);
return;
}
void Parser::Member_Function_Pattern(int i)
{
//return_type class_name.funcname(){}
if (Scope->is(FUNCTION_NODE))
return;
if (Input[i].Value != ".")
return;
//the name must be connected with the fethcer already by the dot operator.
int Paranthesis_Offset = 1;
if (i + Paranthesis_Offset < Input.size() && Input[i + Paranthesis_Offset].is(Flags::TEMPLATE_COMPONENT))
Paranthesis_Offset = 2;
vector<int> Parenthesis_Indexes = Get_Amount_Of(i + Paranthesis_Offset, Flags::PAREHTHESIS_COMPONENT, false);
if (Parenthesis_Indexes.size() != 2)
return;
if (Input[Parenthesis_Indexes[1]].Value[0] != '{')
return;
if (Input[Parenthesis_Indexes[0]].Value[0] != '(')
return;
//set all the left sided of operators as the fetchers
Input[i].node->Left->Transform_Dot_To_Fechering(Input[i].node->Right);
//Find the scope that this function is set to as a member to.
Node* Class = Scope->Find(Input[i].node->Right->Fetcher, Scope, CLASS_NODE);
if (Class == nullptr)
Report(Observation(ERROR, Input[i].node->Right->Fetcher->Name + " was not found when creating " + Input[i].node->Right->Name, Input[i].Location));
//delete the tmp fecher defined in the parent scope.
Node* Ghost_Definition = Input[i].node->Left;
for (int j = 0; j < Scope->Defined.size(); j++)
if (Ghost_Definition == Scope->Defined[j])
Scope->Defined.erase(Scope->Defined.begin() + j);
//unwrap the . operator
Input[i].node->Right->Context = Input[i].node->Context;
Input[i].node->Right->Scope = Input[i].node->Scope;
Input[i].node = Input[i].node->Right;
Input[i].Value = Input[i].node->Name;
//port foward the fetcher magnetized inheritance to this function
if (!Input[i].node->Fetcher->is("static")) {
Input[i].node->Inheritted = Input[i].node->Fetcher->Inheritted;
}
else {
Input[i].node->Inheritted = Input[i].node->Fetcher->Fetching_Inheritance;
}
Input[i].node->Un_Initialized_Template_Inheritance = Input[i].node->Fetcher->Un_Initialized_Template_Inheritance;
//clear exess stuff
Input[i].node->Fetcher->Inheritted.clear();
Input[i].node->Fetcher->Un_Initialized_Template_Inheritance.clear();
Input[i].node->Is_Template_Object = Class->Is_Template_Object;
//replace all the class named fetchers by the Class node for future referencing.
//this code break c++ XD
/*vector<Node*> Fethcers = Input[i].node->Get_All_Fetchers();
for (auto& Fetcher : Fethcers) {
if (Fetcher->Name == Class->Name)
*Fetcher = *Class;
}*/
//Parser p(Class);
//p.Input = Input;
Function_Pattern(i, Class);
Class->Defined.push_back(Input[i].node);
//Input = p.Input;
//Node* Fethcer = Input[i].node->Fetcher;
//Input[i].node->Fetcher = nullptr;
//if (Class->Scope->Find(Input[i].node, Class->Scope, FUNCTION_NODE) == nullptr) {
// Class->Scope->Defined.push_back(Input[i].node);
// Input[i].node->Fetcher = Fethcer;
//}
////Input[i].node->Fetcher = Fethcer;
//else if (Input[i].node->Fetcher = Fethcer; !Input[i].node->Compare_Fetchers(Class->Scope->Find(Input[i].node, Class->Scope, FUNCTION_NODE)))
// Class->Scope->Defined.push_back(Input[i].node);
Input.erase(Input.begin() + i);
}
void Parser::Use_Pattern(int i)
{
//use foo
if ((size_t)i + 1 >= Input.size())
return;
if (Input[i].Value != "use")
return;
if (!Input[(size_t)i + 1].is(Flags::TEXT_COMPONENT))
return;
Node* Namespace = Scope->Find(Input[(size_t)i + 1].Value);
if (Namespace == nullptr)
return;
if (!Namespace->is("static") || !Namespace->is(CLASS_NODE))
return;
vector<Node*> Inlined = Namespace->Defined;
Scope->Append(Inlined, Namespace->Inlined_Items);
Node* Closest_Namespace = Scope->Get_Scope_As(CLASS_NODE, Scope);
//check if the same namespace is already inlined to this exact scope.
for (auto n : Closest_Namespace->Inlined_Namespaces)
if (n == Namespace || n->Name == Namespace->Name)
return;
Closest_Namespace->Inlined_Namespaces.push_back(Namespace);
for (auto &j : Inlined) {
if (j->Fetcher)
continue;
j->Fetcher = Namespace;
}
for (auto &j : Inlined) {
if (j->Is_Template_Object)
continue;
if (j->Has({ FUNCTION_NODE, CLASS_NODE }))
continue;
j->Update_Size();
}
Closest_Namespace->Append(Closest_Namespace->Inlined_Items, Inlined);
//This adds the init code to the new namespace.
Closest_Namespace->Append(Closest_Namespace->Childs, Namespace->Childs);
Input.erase(Input.begin() + i, Input.begin() + i + 2);
}
Component* Parser::Construct_Virtual_Class_For_Complex_Cast(Component Parenthesis)
{
Node* Virtual_Class = new Node(CLASS_NODE, new Position(Parenthesis.Location));
for (auto i : Parenthesis.Components) {
Virtual_Class->Inheritted.push_back(i.Value);
}
string Virtual_Class_Name = "____VIRTUAL_CLASS";
for (auto i : Virtual_Class->Get_Inheritted())
Virtual_Class_Name += "_" + i;
Component *Cast = new Component(Virtual_Class_Name, Flags::TEXT_COMPONENT);
if (Scope->Find(Virtual_Class_Name)) {
Scope->Copy_Node(Cast->node, Scope->Find(Virtual_Class_Name), Scope->Find(Virtual_Class_Name)->Scope);
return Cast;
}
Virtual_Class->Name = Virtual_Class_Name;
Virtual_Class->Scope = Scope->Get_Scope_As(CLASS_NODE, {"static"}, Scope);
Virtual_Class->Update_Size();
Node* New_Virtual_Class;
Scope->Copy_Node(New_Virtual_Class, Virtual_Class, Virtual_Class->Scope);
Virtual_Class->Scope->Defined.push_back(New_Virtual_Class);
Cast->node = Virtual_Class;
return Cast;
}
void Parser::Factory() {
for (int i = 0; i < Input.size(); i++)
Combine_Comment(i);
for (int i = 0; i < Input.size(); i++)
Combine_Import_Shattered_Return_Info(i);
for (int i = 0; i < Input.size(); i++)
Template_Pattern(i);
for (auto& i : Input)
Construct_Virtual_Class_To_Represent_Multiple_Template_Inputs(i);
for (int i = 0; i < Input.size(); i++) {
//variable/objects definator.
Prototype_Pattern(i); //Definition_pattern stoles this import functions, so this goes first
Import_Pattern(i);
//Template_Pattern(i);
Definition_Pattern(i);
Label_Definition(i);
}
for (int i = 0; i < Input.size(); i++)
Remove_All_Excess_Comments(i);
for (int i = 0; i < Input.size(); i++) {
//multiline AST stuff
Combine_Dot_In_Member_Functions(i);
Type_Pattern(i); //class constructor
Use_Pattern(i);
Inject_Template_Into_Member_Function_Fetcher(i);
if (Input.size() == 0 || i >= Input.size())
break;
Nodize_Template_Pattern(i);
Constructor_Pattern(i); //constructor needs the type to be defined as a class
Member_Function_Pattern(i);
Function_Pattern(i);
If_Pattern(i);
Else_Pattern(i);
Callation_Pattern(i);
Jump_Pattern(i);
Break_Pattern(i);
Continue_Pattern(i);
}
for (int i = 0; i < Input.size(); i++) {
//prepreattor for math operator AST combinator.
Object_Pattern(i);
Template_Type_Constructor(i);
Complex_Cast(i);
Parenthesis_Pattern(i);
String_Pattern(i);
Number_Pattern(i);
Label_Pattern(i);
}
for (int i = 0; i < Input.size(); i++) {
Size_Pattern(i);
Format_Pattern(i);
}
for (int i = 0; i < Input.size(); i++) {
Operator_Combinator(i);
}
//AST operator combinator.
Operator_Order();
for (int i = 0; i < Input.size(); i++) {
Return_Pattern(i);
}
}
| 30.505335 | 218 | 0.650418 | [
"object",
"vector",
"transform"
] |
7aec9033a436cb4e051d9253d32b5143d103d51f | 1,425 | cpp | C++ | Codejam/CodeJam2017QualificationC_BathRoom/CodeJam2017QualificationC_BathRoom/solve2.cpp | PuppyRush/Algorithms | 1bfb7622ffdc2c7d4b9e408b67a81f31395d9513 | [
"MIT"
] | 1 | 2019-02-23T01:17:05.000Z | 2019-02-23T01:17:05.000Z | Codejam/CodeJam2017QualificationC_BathRoom/CodeJam2017QualificationC_BathRoom/solve2.cpp | PuppyRush/Algorithms | 1bfb7622ffdc2c7d4b9e408b67a81f31395d9513 | [
"MIT"
] | null | null | null | Codejam/CodeJam2017QualificationC_BathRoom/CodeJam2017QualificationC_BathRoom/solve2.cpp | PuppyRush/Algorithms | 1bfb7622ffdc2c7d4b9e408b67a81f31395d9513 | [
"MIT"
] | null | null | null | #define _CRT_SECURE_NO_WARNINGS
#define MIN(a,b) ((a>b)?b:a)
#define MAX(a,b) ((a>b)?b:a)
#define FOR(i,size) for(i ; i < size ; ++i)
#define FOR_IN(i,size) for(i ; i <= size ; ++i)
#define FOR_REV(i) for(i ; i >=0 ; --i)
#define FOR_REV_SIZE(i,size) for(i ; i >=size ; --i)
#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
using namespace std;
typedef const int C_INT;
typedef unsigned int UINT;
typedef const unsigned int C_UINT;
typedef unsigned char UCHAR;
typedef const unsigned char C_UCHAR;
typedef const char C_CHAR;
typedef const unsigned long long C_ULL;
typedef unsigned long long ULL;
typedef std::pair<int, int> PINT;
typedef std::vector<std::vector<int>> V2INT;
typedef std::vector<int> VINT;
typedef std::vector<string> VSTR;
using namespace std;
UINT memo[100][100];
int _main() {
//freopen("C:\\Users\\goodd\\Downloads\\C-small-2-attempt0.in", "r", stdin);
//freopen("C:\\Users\\goodd\\Desktop\\C-small2.out", "w", stdout);
int size = 0;
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.precision(10);
int caseSize = 0;
scanf("%d", &caseSize);
for (int t = 0; t < caseSize; ++t) {
ULL stalls, mans;
scanf("%llu %llu", &stalls, &mans);
PINT solve;
if (stalls != mans) {
}
else
solve = PINT(0, 0);
printf("Case #%d: %d %d\n", (t + 1), solve.first, solve.second);
}
return 0;
}
| 20.357143 | 77 | 0.656842 | [
"vector"
] |
7aeeaf1276ec8f9acfb803bf68c2fa46a3fab9bb | 2,007 | cpp | C++ | cvt/gl/scene/GLSVisitor.cpp | tuxmike/cvt | c6a5df38af4653345e795883b8babd67433746e9 | [
"MIT"
] | 11 | 2017-04-04T16:38:31.000Z | 2021-08-04T11:31:26.000Z | cvt/gl/scene/GLSVisitor.cpp | tuxmike/cvt | c6a5df38af4653345e795883b8babd67433746e9 | [
"MIT"
] | null | null | null | cvt/gl/scene/GLSVisitor.cpp | tuxmike/cvt | c6a5df38af4653345e795883b8babd67433746e9 | [
"MIT"
] | 8 | 2016-04-11T00:58:27.000Z | 2022-02-22T07:35:40.000Z | /*
The MIT License (MIT)
Copyright (c) 2011 - 2013, Philipp Heise and Sebastian Klose
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <cvt/gl/scene/GLSVisitor.h>
#include <cvt/gl/scene/GLSRenderableGroup.h>
#include <cvt/gl/scene/GLSBaseModel.h>
namespace cvt {
void GLSRenderVisitor::visit( GLSRenderableGroup& group )
{
Matrix4f told = _shader.transformation();
Matrix4f tnew = told * group.transformation();
_shader.setTransformation( tnew );
group.visitChildren( *this );
_shader.setTransformation( told );
}
void GLSRenderVisitor::visit( GLSBaseModel& bmodel )
{
Matrix4f told = _shader.transformation();
Matrix4f tnew = told * bmodel.transformation();
// std::cout << _shader.transformation() << std::endl;
_shader.setMaterial( bmodel.material() );
_shader.bind();
_shader.setTransformation( tnew, true );
if( bmodel.mesh() )
bmodel.mesh()->draw();
_shader.unbind();
_shader.setTransformation( told );
}
}
| 33.45 | 80 | 0.736423 | [
"mesh"
] |
7af8360814ed897c29e6d23c47bb0ba0d9e242d2 | 16,108 | hpp | C++ | src/IO/Importers/Actions/ReadVolumeData.hpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | 1 | 2022-01-11T00:17:33.000Z | 2022-01-11T00:17:33.000Z | src/IO/Importers/Actions/ReadVolumeData.hpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | null | null | null | src/IO/Importers/Actions/ReadVolumeData.hpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | null | null | null | // Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
#include <cstddef>
#include <optional>
#include <string>
#include <tuple>
#include <variant>
#include <vector>
#include "DataStructures/DataBox/DataBox.hpp"
#include "DataStructures/DataBox/PrefixHelpers.hpp"
#include "DataStructures/DataBox/Tag.hpp"
#include "DataStructures/DataVector.hpp"
#include "DataStructures/Tensor/Tensor.hpp"
#include "Domain/Structure/ElementId.hpp"
#include "IO/H5/AccessType.hpp"
#include "IO/H5/File.hpp"
#include "IO/H5/VolumeData.hpp"
#include "IO/Importers/ObservationSelector.hpp"
#include "IO/Importers/Tags.hpp"
#include "IO/Observer/ArrayComponentId.hpp"
#include "Parallel/ArrayIndex.hpp"
#include "Parallel/GlobalCache.hpp"
#include "Parallel/Invoke.hpp"
#include "Utilities/ErrorHandling/Error.hpp"
#include "Utilities/FileSystem.hpp"
#include "Utilities/Gsl.hpp"
#include "Utilities/Literals.hpp"
#include "Utilities/Overloader.hpp"
#include "Utilities/Requires.hpp"
#include "Utilities/TMPL.hpp"
#include "Utilities/TaggedTuple.hpp"
/// \cond
namespace importers {
template <typename Metavariables>
struct ElementDataReader;
namespace Actions {
template <typename ImporterOptionsGroup, typename FieldTagsList,
typename ReceiveComponent>
struct ReadAllVolumeDataAndDistribute;
} // namespace Actions
} // namespace importers
/// \endcond
namespace importers::Tags {
/*!
* \brief Indicates an available tensor field is selected for importing, along
* with the name of the dataset in the volume data file.
*
* Set the value to a dataset name to import the `FieldTag` from that dataset,
* or to `std::nullopt` to skip importing the `FieldTag`. The dataset name
* excludes tensor component suffixes like "_x" or "_xy". These suffixes will be
* added automatically. A sensible value for the dataset name is often
* `db::tag_name<FieldTag>()`, but the user should generally be given the
* opportunity to set the dataset name in the input file.
*/
template <typename FieldTag>
struct Selected : db::SimpleTag {
using type = std::optional<std::string>;
};
} // namespace importers::Tags
namespace importers::Actions {
/*!
* \brief Read a volume data file and distribute the data to all registered
* elements.
*
* Invoke this action on the elements of an array parallel component to dispatch
* reading the volume data file specified by the options in
* `ImporterOptionsGroup`. The tensors in `FieldTagsList` will be loaded from
* the file and distributed to all elements that have previously registered. Use
* `importers::Actions::RegisterWithElementDataReader` to register the elements
* of the array parallel component in a previous phase.
*
* Note that the volume data file will only be read once per node, triggered by
* the first element that invokes this action. All subsequent invocations of
* this action on the node will do nothing. See
* `importers::Actions::ReadAllVolumeDataAndDistribute` for details.
*
* The data is distributed to the elements using `Parallel::receive_data`. The
* elements can monitor `importers::Tags::VolumeData` in their inbox to wait for
* the data and process it once it's available. We provide the action
* `importers::Actions::ReceiveVolumeData` that waits for the data and moves it
* directly into the DataBox. You can also implement a specialized action that
* might verify and post-process the data before populating the DataBox.
*
* \see Dev guide on \ref dev_guide_importing
*/
template <typename ImporterOptionsGroup, typename FieldTagsList>
struct ReadVolumeData {
using const_global_cache_tags =
tmpl::list<Tags::FileGlob<ImporterOptionsGroup>,
Tags::Subgroup<ImporterOptionsGroup>,
Tags::ObservationValue<ImporterOptionsGroup>>;
template <typename DbTagsList, typename... InboxTags, typename Metavariables,
typename ArrayIndex, typename ActionList,
typename ParallelComponent>
static std::tuple<db::DataBox<DbTagsList>&&> apply(
db::DataBox<DbTagsList>& box,
const tuples::TaggedTuple<InboxTags...>& /*inboxes*/,
Parallel::GlobalCache<Metavariables>& cache,
const ArrayIndex& /*array_index*/, const ActionList /*meta*/,
const ParallelComponent* const /*meta*/) {
// Not using `ckLocalBranch` here to make sure the simple action invocation
// is asynchronous.
auto& reader_component = Parallel::get_parallel_component<
importers::ElementDataReader<Metavariables>>(cache);
Parallel::simple_action<importers::Actions::ReadAllVolumeDataAndDistribute<
ImporterOptionsGroup, FieldTagsList, ParallelComponent>>(
reader_component);
return {std::move(box)};
}
};
/*!
* \brief Read a volume data file and distribute the data to all registered
* elements.
*
* This action can be invoked on the `importers::ElementDataReader` component
* once all elements have been registered with it. It opens the data file, reads
* the data for each registered element and uses `Parallel::receive_data` to
* distribute the data to the elements. The elements can monitor
* `importers::Tags::VolumeData` in their inbox to wait for the data and process
* it once it's available. You can use `importers::Actions::ReceiveVolumeData`
* to wait for the data and move it directly into the DataBox, or implement a
* specialized action that might verify and post-process the data.
*
* Note that instead of invoking this action directly on the
* `importers::ElementDataReader` component you can invoke the iterable action
* `importers::Actions::ReadVolumeData` on the elements of an array parallel
* component.
*
* - The `ImporterOptionsGroup` parameter specifies the \ref OptionGroupsGroup
* "options group" in the input file that provides the following run-time
* options:
* - `importers::OptionTags::FileGlob`
* - `importers::OptionTags::Subgroup`
* - `importers::OptionTags::ObservationValue`
* - The `FieldTagsList` parameter specifies a typelist of tensor tags that
* can be read from the file and provided to each element. The subset of tensors
* that will actually be read and distributed can be selected at runtime with
* the `selected_fields` argument that is passed to this simple action. See
* importers::Tags::Selected for details. By default, all tensors in the
* `FieldTagsList` are selected, and read from datasets named
* `db::tag_name<Tag>() + suffix`, where the `suffix` is empty for scalars, or
* `"_"` followed by the `Tensor::component_name` for each independent tensor
* component.
* - `Parallel::receive_data` is invoked on each registered element of the
* `ReceiveComponent` to populate `importers::Tags::VolumeData` in the element's
* inbox with a `tuples::tagged_tuple_from_typelist<FieldTagsList>` containing
* the tensor data for that element. The `ReceiveComponent` must the the same
* that was encoded into the `observers::ArrayComponentId` used to register the
* elements.
*
* \see Dev guide on \ref dev_guide_importing
*/
template <typename ImporterOptionsGroup, typename FieldTagsList,
typename ReceiveComponent>
struct ReadAllVolumeDataAndDistribute {
template <
typename ParallelComponent, typename DataBox, typename Metavariables,
typename ArrayIndex,
Requires<db::tag_is_retrievable_v<Tags::RegisteredElements, DataBox> and
db::tag_is_retrievable_v<Tags::ElementDataAlreadyRead,
DataBox>> = nullptr>
static void apply(DataBox& box, Parallel::GlobalCache<Metavariables>& cache,
const ArrayIndex& /*array_index*/,
tuples::tagged_tuple_from_typelist<
db::wrap_tags_in<Tags::Selected, FieldTagsList>>
selected_fields = select_all_fields(FieldTagsList{})) {
// Only read and distribute the volume data once
// This action will be invoked by `importers::Actions::ReadVolumeData` from
// every element on the node, but only the first invocation reads the file
// and distributes the data to all elements. Subsequent invocations do
// nothing. We use the `ImporterOptionsGroup` that specifies the data file
// to read in as the identifier for whether or not we have already read the
// requested data. Doing this at runtime avoids having to collect all
// data files that will be read in at compile-time to initialize a flag in
// the DataBox for each of them.
const auto& has_read_volume_data =
db::get<Tags::ElementDataAlreadyRead>(box);
const auto volume_data_id = pretty_type::get_name<ImporterOptionsGroup>();
if (has_read_volume_data.find(volume_data_id) !=
has_read_volume_data.end()) {
return;
}
db::mutate<Tags::ElementDataAlreadyRead>(
make_not_null(&box),
[&volume_data_id](const gsl::not_null<std::unordered_set<std::string>*>
local_has_read_volume_data) {
local_has_read_volume_data->insert(std::move(volume_data_id));
});
// Resolve the file glob
const std::string& file_glob =
Parallel::get<Tags::FileGlob<ImporterOptionsGroup>>(cache);
const std::vector<std::string> file_paths = file_system::glob(file_glob);
// Open every file in turn
std::optional<size_t> prev_observation_id{};
for (const std::string& file_name : file_paths) {
// Open the volume data file
h5::H5File<h5::AccessType::ReadOnly> h5file(file_name);
constexpr size_t version_number = 0;
const auto& volume_file = h5file.get<h5::VolumeData>(
"/" + Parallel::get<Tags::Subgroup<ImporterOptionsGroup>>(cache),
version_number);
// Select observation ID
const size_t observation_id = std::visit(
make_overloader(
[&volume_file](const double local_obs_value) {
return volume_file.find_observation_id(local_obs_value);
},
[&volume_file](const ObservationSelector local_obs_selector) {
const std::vector<size_t> all_observation_ids =
volume_file.list_observation_ids();
switch (local_obs_selector) {
case ObservationSelector::First:
return all_observation_ids.front();
case ObservationSelector::Last:
return all_observation_ids.back();
default:
ERROR("Unknown importers::ObservationSelector: "
<< local_obs_selector);
}
}),
Parallel::get<Tags::ObservationValue<ImporterOptionsGroup>>(cache));
if (prev_observation_id.has_value() and
prev_observation_id.value() != observation_id) {
ERROR("Inconsistent selection of observation ID in file "
<< file_name
<< ". Make sure all files select the same observation ID.");
}
prev_observation_id = observation_id;
// Read the tensor data for all elements at once, since that's how it's
// stored in the file
tuples::tagged_tuple_from_typelist<FieldTagsList> all_tensor_data{};
tmpl::for_each<FieldTagsList>([&all_tensor_data, &volume_file,
&observation_id,
&selected_fields](auto field_tag_v) {
using field_tag = tmpl::type_from<decltype(field_tag_v)>;
const auto& selection = get<Tags::Selected<field_tag>>(selected_fields);
if (not selection.has_value()) {
return;
}
auto& tensor_data = get<field_tag>(all_tensor_data);
for (size_t i = 0; i < tensor_data.size(); i++) {
tensor_data[i] = volume_file.get_tensor_component(
observation_id,
selection.value() + tensor_data.component_suffix(
tensor_data.get_tensor_index(i)));
}
});
// Retrieve the information needed to reconstruct which element the data
// belongs to
const auto all_grid_names = volume_file.get_grid_names(observation_id);
const auto all_extents = volume_file.get_extents(observation_id);
// Distribute the tensor data to the registered elements
for (auto& [element_array_component_id, grid_name] :
get<Tags::RegisteredElements>(box)) {
const CkArrayIndex& raw_element_index =
element_array_component_id.array_index();
// Check if the parallel component of the registered element matches the
// callback, because it's possible that elements from other components
// with the same index are also registered.
// Since the way the component is encoded in `ArrayComponentId` is
// private to that class, we construct one and compare.
if (element_array_component_id !=
observers::ArrayComponentId(
std::add_pointer_t<ReceiveComponent>{nullptr},
raw_element_index)) {
continue;
}
// Proceed with the registered element only if it's included in the
// volume file. It's possible that the volume file only contains data
// for a subset of elements, e.g., when each node of a simulation wrote
// volume data for its elements to a separate file.
if (std::find(all_grid_names.begin(), all_grid_names.end(),
grid_name) == all_grid_names.end()) {
continue;
}
// Find the data offset that corresponds to this element
const auto element_data_offset_and_length =
h5::offset_and_length_for_grid(grid_name, all_grid_names,
all_extents);
// Extract this element's data from the read-in dataset
tuples::tagged_tuple_from_typelist<FieldTagsList> element_data{};
tmpl::for_each<FieldTagsList>([&element_data,
&element_data_offset_and_length,
&all_tensor_data,
&selected_fields](auto field_tag_v) {
using field_tag = tmpl::type_from<decltype(field_tag_v)>;
const auto& selection =
get<Tags::Selected<field_tag>>(selected_fields);
if (not selection.has_value()) {
return;
}
auto& element_tensor_data = get<field_tag>(element_data);
// Iterate independent components of the tensor
for (size_t i = 0; i < element_tensor_data.size(); i++) {
const DataVector& data_tensor_component =
get<field_tag>(all_tensor_data)[i];
DataVector element_tensor_component{
element_data_offset_and_length.second};
// Retrieve data from slice of the contigious dataset
for (size_t j = 0; j < element_tensor_component.size(); j++) {
element_tensor_component[j] =
data_tensor_component[element_data_offset_and_length.first +
j];
}
element_tensor_data[i] = element_tensor_component;
}
});
// Pass the data to the element
const auto element_index =
Parallel::ArrayIndex<typename ReceiveComponent::array_index>(
raw_element_index)
.get_index();
Parallel::receive_data<
Tags::VolumeData<ImporterOptionsGroup, FieldTagsList>>(
Parallel::get_parallel_component<ReceiveComponent>(
cache)[element_index],
// Using `0` for the temporal ID since we only read the volume data
// once, so there's no need to keep track of the temporal ID.
0_st, std::move(element_data));
}
}
}
private:
template <typename... LocalFieldTags>
static tuples::TaggedTuple<Tags::Selected<LocalFieldTags>...>
select_all_fields(tmpl::list<LocalFieldTags...> /*meta*/) {
return {db::tag_name<LocalFieldTags>()...};
}
};
} // namespace importers::Actions
| 46.420749 | 80 | 0.678048 | [
"vector"
] |
7afac096f61f3b1f0476a5e8f3fb884897406cc9 | 3,350 | cpp | C++ | 1_course/5_week/5_longest_common_subseq3/cpp/main.cpp | claytonjwong/Algorithms-UCSD | 09d433a1cbc00dc8d913ece8716ac539b81340cd | [
"Unlicense"
] | 6 | 2019-11-13T01:19:28.000Z | 2021-08-10T19:19:57.000Z | 1_course/5_week/5_longest_common_subseq3/cpp/main.cpp | claytonjwong/Algorithms-UCSD | 09d433a1cbc00dc8d913ece8716ac539b81340cd | [
"Unlicense"
] | null | null | null | 1_course/5_week/5_longest_common_subseq3/cpp/main.cpp | claytonjwong/Algorithms-UCSD | 09d433a1cbc00dc8d913ece8716ac539b81340cd | [
"Unlicense"
] | 3 | 2019-11-13T03:11:15.000Z | 2020-11-28T20:05:38.000Z | /**
*
* C++ implementation to find the longest common subsequence between three strings
*
* (c) Copyright 2019 Clayton J. Wong ( http://www.claytonjwong.com )
*
**/
#include <iostream>
#include <sstream>
#include <iterator>
#include <algorithm>
#include <string>
#include <vector>
#include <unordered_map>
#include <cassert>
using namespace std;
using Collection = vector< int >;
namespace TopDown {
class Solution {
public:
using T3 = tuple< int,int,int >;
struct Hash {
size_t operator()( const T3& tuple ) const {
int i{ 0 }, j{ 0 }, k{ 0 };
tie( i, j, k ) = tuple;
return 101 * 101 * i + 101 * j + k;
}
};
using Memo = unordered_map< T3, int, Hash >;
int lcs( const Collection& A, const Collection& B, const Collection& C, Memo memo={} ){
auto M = static_cast< int >( A.size() ),
N = static_cast< int >( B.size() ),
O = static_cast< int >( C.size() );
return go( A, B, C, M-1, N-1, O-1, memo );
}
private:
int go( const Collection& A, const Collection& B, const Collection& C, int i, int j, int k, Memo& memo ){
auto key = make_tuple( i,j,k );
if( memo.find( key ) != memo.end() )
return memo[ key ];
if( i < 0 || j < 0 || k < 0 )
return memo[ key ] = 0;
if( A[ i ] == B[ j ] && A[ i ] == C[ k ])
return memo[ key ] = 1 + go( A, B, C, i-1, j-1, k-1, memo );
return memo[ key ] = max({ go( A, B, C, i-1, j, k, memo ),
go( A, B, C, i, j-1, k, memo ),
go( A, B, C, i, j, k-1, memo ), });
}
};
}
namespace BottomUp {
class Solution {
public:
using VI = vector< int >;
using VVI = vector< VI >;
using VVVI = vector< VVI >;
int lcs( const Collection& A, const Collection& B, const Collection& C ){
auto M = static_cast< int >( A.size() ),
N = static_cast< int >( B.size() ),
O = static_cast< int >( C.size() );
VVVI dp( M+1, VVI( N+1, VI( O+1, 0 )));
for( auto i{ 1 }; i <= M; ++i )
for( auto j{ 1 }; j <= N; ++j )
for( auto k{ 1 }; k <= O; ++k )
if( A[ i-1 ] == B[ j-1 ] && A[ i-1 ] == C[ k-1 ] )
dp[ i ][ j ][ k ] = 1 + dp[ i-1 ][ j-1 ][ k-1 ];
else
dp[ i ][ j ][ k ] = max({ dp[ i-1 ][ j ][ k ],
dp[ i ][ j-1 ][ k ],
dp[ i ][ j ][ k-1 ], });
return dp[ M ][ N ][ O ];
}
};
}
int main() {
Collection A, B, C;
auto M{ 0 }; cin >> M; copy_n( istream_iterator< int >( cin ), M, back_inserter( A ));
auto N{ 0 }; cin >> N; copy_n( istream_iterator< int >( cin ), N, back_inserter( B ));
auto O{ 0 }; cin >> O; copy_n( istream_iterator< int >( cin ), O, back_inserter( C ));
auto ans1 = TopDown::Solution().lcs( A, B, C );
auto ans2 = BottomUp::Solution().lcs( A, B, C );
assert( ans1 == ans2 );
cout << ans1 << endl;
return 0;
}
| 36.813187 | 113 | 0.428657 | [
"vector"
] |
bb058b52a0fe0b4727e3a3c1e984a5c6cd2ec9a7 | 2,564 | cpp | C++ | src/Account.cpp | AymenFJA/Stockmarket_Portfolio | 8bf4b5a7e89b147975ab04a4f8b1212461ee92b1 | [
"MIT"
] | null | null | null | src/Account.cpp | AymenFJA/Stockmarket_Portfolio | 8bf4b5a7e89b147975ab04a4f8b1212461ee92b1 | [
"MIT"
] | null | null | null | src/Account.cpp | AymenFJA/Stockmarket_Portfolio | 8bf4b5a7e89b147975ab04a4f8b1212461ee92b1 | [
"MIT"
] | 1 | 2018-12-02T20:17:33.000Z | 2018-12-02T20:17:33.000Z |
#include <stdlib.h>
#include <vector>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include "Account.h"
#include"Globales.h"
#include <time.h>
Account::Account() //constructor
{
}
int Account::PriceUpdate() //(put the values from the file in the vecotr) updatting vectors from stock price file
{
string symbol;
double price;
string data;
string str;
ifstream file1;
int prand = 0;
srand(time(NULL));
prand = rand() % 2 + 1;
//Reading from 2 Files Randomly Results.txt or Results2.txt
if (prand <= 1)
{
file1.open("Results.txt");
cout<<(L"Result1 ");
}
else
if(prand==2)
{
file1.open("Results2.txt");
cout<< (L"Result2 ");
}
//file1.open()
if (!file1)
{
pOUTPUT->MessageBox( L"\n Error in opening Results file "); //check if the file not found or can not open it
return 0;
}
while (!file1.eof()) //while not the End of the File
{
symbol.clear(); //to clear any previous data inside it to be ready to put new one
str.clear(); //to clear any previous data inside it to be ready to put new one
int space[2] = { 0 }; //record the space of one line
int j = 0; //loop counter
getline(file1, data); //to read from a line from the *FILE1*
for (int i = 0; i<data.length(); i++) //record the position of space in the string
if (isspace(data[i])) // isspace (cctype) Check if character is a white-space move to next (function ) (FROM C PLUS PLUS WEBSITE)
{
space[j] = i;
j++;
}
for (int i = 0; i<space[0]; i++) //read out the symbol //move no of spaces and read the symbol
symbol += data[i];
sym1.push_back(symbol);
for (int i = space[0] + 1; i<space[1]; i++) //read out the price //move no of spaces (move also the symbol chars) and read the price
str += data[i];
//change price variable from string to double
stringstream s(str);
s >> price;
pri1.push_back(price); //std::vector::push_back() (ready vector function to add new element to the End of vector)
}
file1.close();
return 0;
}
double Account::findPrice(string str) //find the price by symbol
{
int i;
double price = 0;
int si = sym1.size();
for (i = 0; i<si; i++) //the loop will move till i less than the symbol size (vector) size
if (sym1[i] == str) //if the symbol==string
{
price = pri1[i]; //save the price value of that string in the vector
return price;
}
if (i >= si) //not found
return 0;
}
| 22.491228 | 141 | 0.609984 | [
"vector"
] |
bb06e27f0cdbea4b8d652324820a6deecbb0bdbc | 590 | cpp | C++ | uva/UVa11078.cpp | Embracethemoon/hundreds_for_one | 3807c1aab16d2a709faf4abe934af53ce9d58b7c | [
"MIT"
] | null | null | null | uva/UVa11078.cpp | Embracethemoon/hundreds_for_one | 3807c1aab16d2a709faf4abe934af53ce9d58b7c | [
"MIT"
] | null | null | null | uva/UVa11078.cpp | Embracethemoon/hundreds_for_one | 3807c1aab16d2a709faf4abe934af53ce9d58b7c | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
void solve(){
int n;
scanf("%d", &n);
int foo, cur, res;
cur = -2e5;
res = -3e5;
while(n -- ){
scanf("%d", &foo);
res = max(res, cur - foo);
cur = max(cur, foo);
}
printf("%d\n", res);
}
int main()
{
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
int t;
scanf("%d", &t);
while(t -- ){
solve();
}
return 0;
}
| 14.75 | 34 | 0.579661 | [
"vector"
] |
bb0bfb94b18749602ad36d89c66b81f46ef9f8f5 | 271 | cpp | C++ | main.cpp | Ahmad-Sai/Huffman-Code | 7d41ee56c9f79db3949769d09b7a810d47985fce | [
"MIT"
] | null | null | null | main.cpp | Ahmad-Sai/Huffman-Code | 7d41ee56c9f79db3949769d09b7a810d47985fce | [
"MIT"
] | null | null | null | main.cpp | Ahmad-Sai/Huffman-Code | 7d41ee56c9f79db3949769d09b7a810d47985fce | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <cstring>
#include <fstream>
#include <math.h>
#include <bitset>
#include "priorityqueue.hpp"
#include "encoder.cpp"
#include "decoder.cpp"
using namespace std;
int main(){
encode();
decode();
return 1;
}
| 14.263158 | 28 | 0.667897 | [
"vector"
] |
bb0d3d917a9b71f86fa49e7ed3a40f9d2f492a01 | 289 | cpp | C++ | solutions/1001.n-repeated-element-in-size-2n-array/1001.n-repeated-element-in-size-2n-array.1558233725.cpp | nettee/leetcode | 19aa8d54d64cce3679db5878ee0194fad95d8fa1 | [
"MIT"
] | 1 | 2021-01-14T06:01:02.000Z | 2021-01-14T06:01:02.000Z | solutions/1001.n-repeated-element-in-size-2n-array/1001.n-repeated-element-in-size-2n-array.1558233725.cpp | nettee/leetcode | 19aa8d54d64cce3679db5878ee0194fad95d8fa1 | [
"MIT"
] | 8 | 2018-03-27T11:47:19.000Z | 2018-11-12T06:02:12.000Z | solutions/1001.n-repeated-element-in-size-2n-array/1001.n-repeated-element-in-size-2n-array.1558233725.cpp | nettee/leetcode | 19aa8d54d64cce3679db5878ee0194fad95d8fa1 | [
"MIT"
] | 2 | 2020-04-30T09:47:01.000Z | 2020-12-03T09:34:08.000Z | class Solution {
public:
int repeatedNTimes(vector<int>& A) {
unordered_set<int> s;
for (int d : A) {
if (s.find(d) == s.end()) {
s.insert(d);
} else {
return d;
}
}
return 0;
}
};
| 19.266667 | 40 | 0.377163 | [
"vector"
] |
bb1194ec315981393d37b177cb11cc598db67756 | 7,135 | cpp | C++ | src/common.cpp | jtlehtinen/win11-clock | 70b160e33ec7f54d490337c7f8051a9b180c5dc4 | [
"MIT"
] | null | null | null | src/common.cpp | jtlehtinen/win11-clock | 70b160e33ec7f54d490337c7f8051a9b180c5dc4 | [
"MIT"
] | null | null | null | src/common.cpp | jtlehtinen/win11-clock | 70b160e33ec7f54d490337c7f8051a9b180c5dc4 | [
"MIT"
] | null | null | null | #include "common.h"
#include <stdio.h>
#include <dwmapi.h>
#include <shellscalingapi.h>
namespace {
namespace registry {
DWORD read_dword(const std::wstring& subkey, const std::wstring& value) {
DWORD result = 0;
DWORD size = static_cast<DWORD>(sizeof(result));
if (RegGetValueW(HKEY_CURRENT_USER, subkey.c_str(), value.c_str(), RRF_RT_DWORD, nullptr, &result, &size) != ERROR_SUCCESS) return 0;
return result;
}
}
}
Settings load_settings(const std::wstring& filename) {
FILE* f = _wfopen(filename.c_str(), L"rb");
if (!f) return { };
Settings settings;
bool ok = (fread(&settings, sizeof(settings), 1, f) == 1);
fclose(f);
return ok ? settings : Settings{ };
}
bool save_settings(const std::wstring& filename, Settings settings) {
FILE* f = _wfopen(filename.c_str(), L"wb");
if (!f) return false;
bool ok = (fwrite(&settings, sizeof(settings), 1, f) == 1);
fclose(f);
return ok;
}
namespace common {
std::wstring get_temp_directory() {
wchar_t buffer[MAX_PATH + 1];
if (GetTempPathW(MAX_PATH + 1, buffer) == 0) return L"";
return buffer + std::wstring(L"Win11Clock\\");
}
std::wstring get_user_default_locale_name() {
wchar_t buffer[LOCALE_NAME_MAX_LENGTH];
if (GetUserDefaultLocaleName(buffer, static_cast<int>(std::size(buffer))) == 0) return L"";
return buffer;
}
std::wstring get_date_format(const std::wstring& locale, DWORD format_flag) {
auto callback = [](LPWSTR format_string, CALID calendar_id, LPARAM lparam) -> BOOL {
*reinterpret_cast<std::wstring*>(lparam) = format_string;
return FALSE; // @NOTE: We only care about the first one.
};
std::wstring result;
EnumDateFormatsExEx(callback, locale.c_str(), format_flag, reinterpret_cast<LPARAM>(&result));
return result;
}
std::wstring get_time_format(const std::wstring& locale, DWORD format_flag) {
auto callback = [](LPWSTR format_string, LPARAM lparam) -> BOOL {
*reinterpret_cast<std::wstring*>(lparam) = format_string;
return FALSE; // @NOTE: We only care about the first one.
};
std::wstring result;
EnumTimeFormatsEx(callback, locale.c_str(), format_flag, reinterpret_cast<LPARAM>(&result));
return result;
}
std::wstring format_date(SYSTEMTIME time, const std::wstring& locale, const std::wstring& date_format) {
constexpr int stack_buffer_size = 128;
wchar_t stack_buffer[stack_buffer_size];
if (GetDateFormatEx(locale.c_str(), 0, &time, date_format.c_str(), stack_buffer, stack_buffer_size, nullptr) != 0)
return stack_buffer;
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
int required = GetDateFormatEx(locale.c_str(), 0, &time, date_format.c_str(), nullptr, 0, nullptr);
int required_no_null = required - 1;
std::wstring buffer(static_cast<size_t>(required_no_null), '\0'); // @NOTE: Since C++11 always allocates +1 for null
GetDateFormatEx(locale.c_str(), 0, &time, date_format.c_str(), buffer.data(), required, nullptr);
return buffer;
}
return L"";
}
std::wstring format_time(SYSTEMTIME time, const std::wstring& locale, const std::wstring& time_format) {
constexpr int stack_buffer_size = 128;
wchar_t stack_buffer[stack_buffer_size];
if (GetTimeFormatEx(locale.c_str(), 0, &time, time_format.c_str(), stack_buffer, stack_buffer_size) != 0)
return stack_buffer;
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
int required = GetTimeFormatEx(locale.c_str(), 0, &time, time_format.c_str(), nullptr, 0);
int required_no_null = required - 1;
std::wstring buffer(static_cast<size_t>(required_no_null), '\0'); // @NOTE: Since C++11 always allocates +1 for null
GetTimeFormatEx(locale.c_str(), 0, &time, time_format.c_str(), buffer.data(), required);
return buffer;
}
return L"";
}
Int2 window_client_size(HWND window) {
RECT r;
GetClientRect(window, &r);
return {r.right - r.left, r.bottom - r.top};
}
Float2 get_dpi_scale(HMONITOR monitor) {
UINT dpix, dpiy;
if (GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &dpix, &dpiy) != S_OK) return {1.0f, 1.0f};
return {static_cast<float>(dpix) / 96.0f, static_cast<float>(dpiy) / 96.0f};
}
std::vector<Monitor> get_display_monitors() {
auto callback = [](HMONITOR monitor, HDC dc, LPRECT rect, LPARAM lparam) {
auto monitors = reinterpret_cast<std::vector<Monitor>*>(lparam);
const Int2 position = { rect->left, rect->top };
const Int2 size = { rect->right - rect->left, rect->bottom - rect->top };
const Float2 dpi = common::get_dpi_scale(monitor);
monitors->push_back(Monitor{ .handle = monitor, .position = position, .size = size, .dpi = dpi });
return TRUE;
};
std::vector<Monitor> result;
EnumDisplayMonitors(nullptr, nullptr, callback, reinterpret_cast<LPARAM>(&result));
return result;
}
Int2 compute_clock_window_size(Float2 dpi) {
constexpr float base_width = 205.0f;
constexpr float base_height = 48.0f;
return {static_cast<int>(base_width * dpi.x + 0.5f), static_cast<int>(base_height * dpi.y + 0.5f)};
}
Int2 compute_clock_window_position(Int2 window_size, Int2 monitor_position, Int2 monitor_size, Corner corner) {
if (corner == Corner::BottomLeft)
return {monitor_position.x, monitor_position.y + monitor_size.y - window_size.y};
if (corner == Corner::BottomRight)
return {monitor_position.x + monitor_size.x - window_size.x, monitor_position.y + monitor_size.y - window_size.y};
if (corner == Corner::TopLeft)
return {monitor_position.x, monitor_position.y};
return {monitor_position.x + monitor_size.x - window_size.x, monitor_position.y};
}
std::vector<HWND> get_desktop_windows() {
auto callback = [](HWND window, LPARAM lparam) -> BOOL {
reinterpret_cast<std::vector<HWND>*>(lparam)->push_back(window);
return TRUE;
};
std::vector<HWND> result;
result.reserve(512);
EnumDesktopWindows(nullptr, callback, reinterpret_cast<LPARAM>(&result));
return result;
}
bool monitor_has_fullscreen_window(HMONITOR monitor, const std::vector<HWND>& windows) {
MONITORINFO info = {.cbSize = sizeof(MONITORINFO)};
if (GetMonitorInfo(monitor, &info) == 0) return false;
for (HWND window : windows) {
if (IsWindowVisible(window)) {
RECT wr;
if (DwmGetWindowAttribute(window, DWMWA_EXTENDED_FRAME_BOUNDS, &wr, static_cast<DWORD>(sizeof(wr))) == S_OK) {
if (EqualRect(&info.rcMonitor, &wr)) return true;
}
}
}
return false;
}
bool read_use_light_theme_from_registry() {
return registry::read_dword(L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", L"SystemUsesLightTheme") == 1;
}
void open_region_control_panel() {
ShellExecuteW(nullptr, L"open", L"control.exe", L"/name Microsoft.RegionAndLanguage", nullptr, SW_SHOW);
}
void exit_with_error_message(const std::wstring& message) {
MessageBoxW(nullptr, message.c_str(), L"win11 clock", MB_ICONERROR);
ExitProcess(1);
}
}
| 34.635922 | 139 | 0.680729 | [
"vector"
] |
bb12690c5545031b8b64d8914577c57a2bfe1e87 | 10,059 | cpp | C++ | src/CQGnuPlotGroup.cpp | colinw7/CQGnuPlot | 8001b0a0d40c1fde8e5efe05ebe0c9b0541daa94 | [
"MIT"
] | null | null | null | src/CQGnuPlotGroup.cpp | colinw7/CQGnuPlot | 8001b0a0d40c1fde8e5efe05ebe0c9b0541daa94 | [
"MIT"
] | null | null | null | src/CQGnuPlotGroup.cpp | colinw7/CQGnuPlot | 8001b0a0d40c1fde8e5efe05ebe0c9b0541daa94 | [
"MIT"
] | 1 | 2019-04-01T13:08:45.000Z | 2019-04-01T13:08:45.000Z | #include <CQGnuPlotGroup.h>
#include <CQGnuPlotWindow.h>
#include <CQGnuPlotPlot.h>
#include <CQGnuPlotCanvas.h>
#include <CQGnuPlotDevice.h>
#include <CQGnuPlotRenderer.h>
#include <CQGnuPlotEnum.h>
#include <CQGnuPlotLabel.h>
#include <CQGnuPlotKey.h>
#include <CQGnuPlotRenderer.h>
#include <CQGnuPlotArrow.h>
#include <CQGnuPlotCircle.h>
#include <CQGnuPlotEllipse.h>
#include <CQGnuPlotPolygon.h>
#include <CQGnuPlotRectangle.h>
#include <CGnuPlotObject.h>
CQGnuPlotGroup::
CQGnuPlotGroup(CQGnuPlotWindow *window) :
CGnuPlotGroup(window), window_(window)
{
setObjectName("group");
}
CQGnuPlotGroup::
~CQGnuPlotGroup()
{
}
void
CQGnuPlotGroup::
setPainter(QPainter *p)
{
CQGnuPlotRenderer *renderer = qwindow()->qapp()->qdevice()->qrenderer();
renderer->setPainter(p);
}
void
CQGnuPlotGroup::
redraw()
{
window_->redraw();
}
double
CQGnuPlotGroup::
getRatio() const
{
return plotSize_.xratio.getValue(1);
}
void
CQGnuPlotGroup::
setRatio(double r)
{
plotSize_.xratio = r;
}
CQGnuPlotEnum::HistogramStyle
CQGnuPlotGroup::
histogramStyle() const
{
const CGnuPlotHistogramData &data = CGnuPlotGroup::getHistogramData();
return CQGnuPlotEnum::histogramStyleConv(data.style());
}
void
CQGnuPlotGroup::
setHistogramStyle(const CQGnuPlotEnum::HistogramStyle &s)
{
CGnuPlotHistogramData data = CGnuPlotGroup::getHistogramData();
data.setStyle(CQGnuPlotEnum::histogramStyleConv(s));
CGnuPlotGroup::setHistogramData(data);
}
CQGnuPlotEnum::DrawLayerType
CQGnuPlotGroup::
getBorderLayer() const
{
return CQGnuPlotEnum::drawLayerTypeConv(CGnuPlotGroup::getBorderLayer());
}
void
CQGnuPlotGroup::
setBorderLayer(const DrawLayerType &layer)
{
CGnuPlotGroup::setBorderLayer(CQGnuPlotEnum::drawLayerTypeConv(layer));
}
void
CQGnuPlotGroup::
draw()
{
CGnuPlotGroup::draw();
if (isSelected()) {
CGnuPlotRenderer *renderer = app()->renderer();
if (! is3D())
renderer->drawRect(bbox2D(), CRGBA(1,0,0), 2);
else
renderer->drawRect(bbox3D(), CRGBA(1,0,0), 2);
}
}
void
CQGnuPlotGroup::
mousePress(const CGnuPlotMouseEvent &mouseEvent)
{
if (! inside(mouseEvent)) return;
CGnuPlotRenderer *renderer = app()->renderer();
renderer->setRegion(region());
typedef std::vector<QObject *> Objects;
Objects objects;
//---
for (const auto &vann : varAnnotations_) {
for (const auto &ann : vann.second) {
if (ann->inside(mouseEvent))
continue;
CGnuPlotArrow *arrow = 0;
CGnuPlotCircle *circle = 0;
CGnuPlotEllipse *ellipse = 0;
CGnuPlotLabel *label = 0;
CGnuPlotPolygon *poly = 0;
CGnuPlotRectangle *rect = 0;
if ((arrow = dynamic_cast<CGnuPlotArrow *>(ann.get()))) {
CQGnuPlotArrow *qarrow = static_cast<CQGnuPlotArrow *>(arrow);
objects.push_back(qarrow);
}
else if ((circle = dynamic_cast<CGnuPlotCircle *>(ann.get()))) {
CQGnuPlotCircle *qcircle = static_cast<CQGnuPlotCircle *>(circle);
objects.push_back(qcircle);
}
else if ((ellipse = dynamic_cast<CGnuPlotEllipse *>(ann.get()))) {
CQGnuPlotEllipse *qellipse = static_cast<CQGnuPlotEllipse *>(ellipse);
objects.push_back(qellipse);
}
else if ((label = dynamic_cast<CGnuPlotLabel *>(ann.get()))) {
CQGnuPlotLabel *qlabel = static_cast<CQGnuPlotLabel *>(label);
objects.push_back(qlabel);
}
else if ((poly = dynamic_cast<CGnuPlotPolygon *>(ann.get()))) {
CQGnuPlotPolygon *qpoly = static_cast<CQGnuPlotPolygon *>(poly);
objects.push_back(qpoly);
}
else if ((rect = dynamic_cast<CGnuPlotRectangle *>(ann.get()))) {
CQGnuPlotRectangle *qrect = static_cast<CQGnuPlotRectangle *>(rect);
objects.push_back(qrect);
}
}
}
//---
for (auto &plot : plots()) {
if (! plot->isDisplayed())
continue;
plot->initRenderer(renderer);
CPoint2D window;
renderer->pixelToWindow(mouseEvent.pixel(), window);
double z = 0;
unmapLogPoint(1, 1, 1, &window.x, &window.y, &z);
CQGnuPlotPlot *qplot = static_cast<CQGnuPlotPlot *>(plot.get());
CGnuPlotMouseEvent mouseEvent2 = mouseEvent;
mouseEvent2.setWindow(window);
qplot->mousePress(mouseEvent2);
qplot->mouseObjects(mouseEvent2, objects);
}
renderer->setRange(getMappedDisplayRange(1, 1));
//---
CGnuPlotMouseEvent mouseEvent1 = mouseEvent;
CPoint2D window;
renderer->pixelToWindow(mouseEvent.pixel(), window);
mouseEvent1.setWindow(window);
//---
for (auto &vann : annotations()) {
for (auto &annotation : vann.second) {
if (annotation->getLayer() == CGnuPlotTypes::DrawLayer::BEHIND)
continue;
double z = 0;
unmapLogPoint(1, 1, 1, &window.x, &window.y, &z);
if (annotation->inside(mouseEvent1)) {
CQGnuPlotLabel *qann = static_cast<CQGnuPlotLabel *>(annotation.get());
objects.push_back(qann);
}
}
}
if (! objects.empty()) {
qwindow()->selectObjects(objects);
}
else {
CQGnuPlotKey *qkey = dynamic_cast<CQGnuPlotKey *>(key().get());
if (qkey) {
if (qkey->inside(mouseEvent1)) {
if (! qkey->mousePress(mouseEvent1))
objects.push_back(qkey);
}
}
if (! objects.empty())
qwindow()->selectObjects(objects);
}
//---
CGnuPlotGroup::mousePress(mouseEvent1);
}
void
CQGnuPlotGroup::
mouseMove(const CGnuPlotMouseEvent &mouseEvent, bool pressed)
{
if (! inside(mouseEvent)) return;
CGnuPlotRenderer *renderer = app()->renderer();
renderer->setRegion(region());
//---
for (auto &plot : plots()) {
if (! plot->isDisplayed())
continue;
plot->initRenderer(renderer);
CPoint2D window;
renderer->pixelToWindow(mouseEvent.pixel(), window);
double z = 0;
unmapLogPoint(1, 1, 1, &window.x, &window.y, &z);
CQGnuPlotPlot *qplot = static_cast<CQGnuPlotPlot *>(plot.get());
CGnuPlotMouseEvent mouseEvent1 = mouseEvent;
mouseEvent1.setWindow(window);
qplot->mouseMove(mouseEvent1, pressed);
}
}
void
CQGnuPlotGroup::
mouseRelease(const CGnuPlotMouseEvent &mouseEvent)
{
if (! inside(mouseEvent)) return;
CGnuPlotRenderer *renderer = app()->renderer();
renderer->setRegion(region());
//---
for (auto &plot : plots()) {
if (! plot->isDisplayed())
continue;
plot->initRenderer(renderer);
CPoint2D window;
renderer->pixelToWindow(mouseEvent.pixel(), window);
double z = 0;
unmapLogPoint(1, 1, 1, &window.x, &window.y, &z);
CQGnuPlotPlot *qplot = static_cast<CQGnuPlotPlot *>(plot.get());
CGnuPlotMouseEvent mouseEvent1 = mouseEvent;
mouseEvent1.setWindow(window);
qplot->mouseRelease(mouseEvent1);
}
}
bool
CQGnuPlotGroup::
mouseTip(const CGnuPlotMouseEvent &mouseEvent, CGnuPlotTipData &tip)
{
if (! inside(mouseEvent)) return false;
CGnuPlotRenderer *renderer = app()->renderer();
renderer->setRegion(region());
for (auto &plot : plots()) {
if (! plot->isDisplayed())
continue;
plot->initRenderer(renderer);
CPoint2D window;
renderer->pixelToWindow(mouseEvent.pixel(), window);
double z = 0;
unmapLogPoint(1, 1, 1, &window.x, &window.y, &z);
CQGnuPlotPlot *qplot = static_cast<CQGnuPlotPlot *>(plot.get());
CGnuPlotMouseEvent mouseEvent1 = mouseEvent;
mouseEvent1.setWindow(window);
if (qplot->mouseTip(mouseEvent1, tip))
return true;
}
renderer->setRange(getMappedDisplayRange(1, 1));
//---
CPoint2D window;
renderer->pixelToWindow(mouseEvent.pixel(), window);
for (auto &vann : annotations()) {
for (auto &annotation : vann.second) {
if (annotation->getLayer() == CGnuPlotTypes::DrawLayer::BEHIND)
continue;
double z = 0;
unmapLogPoint(1, 1, 1, &window.x, &window.y, &z);
CQGnuPlotAnnotation *qann = dynamic_cast<CQGnuPlotAnnotation *>(annotation.get());
CGnuPlotMouseEvent mouseEvent1 = mouseEvent;
mouseEvent1.setWindow(window);
if (qann->mouseTip(mouseEvent1, tip))
return true;
}
}
//---
return false;
}
void
CQGnuPlotGroup::
keyPress(const CGnuPlotKeyEvent &keyEvent)
{
CGnuPlotRenderer *renderer = app()->renderer();
renderer->setRegion(region());
CPoint2D window;
renderer->pixelToWindow(keyEvent.pixel(), window);
CGnuPlotKeyEvent keyEvent1 = keyEvent;
keyEvent1.setWindow(window);
CGnuPlotGroup::keyPress(keyEvent1);
}
void
CQGnuPlotGroup::
moveObjects(int key)
{
for (const auto &vann : varAnnotations_) {
for (const auto &annotation : vann.second) {
CQGnuPlotAnnotation *qann = dynamic_cast<CQGnuPlotAnnotation *>(annotation.get());
if (qann->obj()->isSelected())
qann->move(key);
}
}
//---
for (auto &plot : plots()) {
if (! plot->isDisplayed())
continue;
CQGnuPlotPlot *qplot = static_cast<CQGnuPlotPlot *>(plot.get());
qplot->moveObjects(key);
}
}
void
CQGnuPlotGroup::
pixelToWindow(const CPoint2D &p, CPoint2D &w)
{
QPoint pos(p.x, p.y);
CGnuPlotRenderer *renderer = app()->renderer();
renderer->setRegion(region());
renderer->setRange(getMappedDisplayRange(1, 1));
renderer->pixelToWindow(p, w);
double z = 0;
unmapLogPoint(1, 1, 1, &w.x, &w.y, &z);
}
void
CQGnuPlotGroup::
windowToPixel(const CPoint2D &w, CPoint2D &p)
{
QPointF pos(w.x, w.y);
CGnuPlotRenderer *renderer = app()->renderer();
renderer->setRegion(region());
renderer->setRange(getMappedDisplayRange(1, 1));
CPoint2D w1 = w;
double z = 0;
mapLogPoint(1, 1, 1, &w1.x, &w1.y, &z);
renderer->windowToPixel(w1, p);
}
bool
CQGnuPlotGroup::
inside(const CGnuPlotMouseEvent &mouseEvent) const
{
double xr = CGnuPlotUtil::map(mouseEvent.pixel().x, 0, qwindow()->pixelWidth () - 1, 0, 1);
double yr = CGnuPlotUtil::map(mouseEvent.pixel().y, 0, qwindow()->pixelHeight() - 1, 1, 0);
return region().inside(CPoint2D(xr, yr));
}
void
CQGnuPlotGroup::
fitSlot()
{
CGnuPlotGroup::fit();
window_->redraw();
}
| 20.445122 | 93 | 0.663784 | [
"vector"
] |
bb1c931016702488459d01dd96ca839427851e51 | 13,054 | hh | C++ | include/benchmark/all_libraries/pcl_test.hh | mlawsonca/benchmarking_suite_range_searching_libraries | 85f2e6be47633836e56684636851eeb393c46d7d | [
"MIT"
] | 1 | 2021-10-07T18:46:56.000Z | 2021-10-07T18:46:56.000Z | include/benchmark/all_libraries/pcl_test.hh | mlawsonca/benchmarking_suite_range_searching_libraries | 85f2e6be47633836e56684636851eeb393c46d7d | [
"MIT"
] | null | null | null | include/benchmark/all_libraries/pcl_test.hh | mlawsonca/benchmarking_suite_range_searching_libraries | 85f2e6be47633836e56684636851eeb393c46d7d | [
"MIT"
] | null | null | null | #ifndef PCL_TEST_HH
#define PCL_TEST_HH
#include <math.h> /* cbrt, round */
#include <pcl/point_cloud.h>
#include <pcl/octree/octree_search.h>
#include <pcl/kdtree/kdtree_flann.h>
#ifdef USE_GPU
#include <pcl/gpu/octree/octree.hpp>
#include <pcl/gpu/containers/impl/device_array.hpp>
#include <pcl/memory.h>
#include <pcl/point_types.h>
#include <set>
#endif
#ifndef NUM_ELEMS_PER_NODE
#error Your need to define NUM_ELEMS_PER_NODE in a common header file
#endif
using namespace std;
namespace TestPCL {
class Octree : public BboxIntersectionTest {
private:
pcl::octree::OctreePointCloudSearch<pcl::PointXYZ> *tree;
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud;
public:
bool intersections_exact() { return true ;} //get_intersections is exact, but get radius (a bonus function we won't need to use) isn't
Octree() {}
~Octree() {
cloud->points.clear ();
tree->deleteTree();
delete tree;
// delete cloud;
}
void build_tree(const std::vector<point> &pts, const std::vector<size_t> &indices, double leaf_volume, size_t bucket_size=0) {
if(leaf_volume <= 0) {
cerr << "TestPCL::Octree.build_tree error. leaf_volume must be a positive number" << endl;
exit(-1);
}
cloud = pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>());
//indicates there will be no infinite or NaN values
cloud->is_dense = true;
for(const point &pt : pts) {
cloud->push_back(pcl::PointXYZ(pt[0],pt[1],pt[2]));
}
cloud ->push_back(pcl::PointXYZ(0,0,0));
tree = new pcl::octree::OctreePointCloudSearch<pcl::PointXYZ>(std::round(std::cbrt(leaf_volume)));
tree->setInputCloud(cloud);
if(bucket_size != 0) {
//throws an error when trying to use that the developers could not explain on git
// tree->defineBoundingBox ();
tree->enableDynamicDepth(bucket_size);
}
tree->addPointsFromInputCloud();
}
void build_tree(const std::vector<point> &pts, const std::vector<size_t> &indices) {
build_tree(pts, indices, NUM_ELEMS_PER_NODE);
}
void get_intersections(const bbox &my_bbox, std::vector<size_t> &intersections_indices) {
Eigen::Vector3f bbox_min = Eigen::Vector3f (my_bbox.first[0], my_bbox.first[1], my_bbox.first[2]);
Eigen::Vector3f bbox_max = Eigen::Vector3f (my_bbox.second[0], my_bbox.second[1], my_bbox.second[2]);
//has to be ints not size_t
std::vector<int> indices;
tree->boxSearch (bbox_min, bbox_max, indices);
std::copy(indices.begin(), indices.end(), std::back_inserter(intersections_indices));
}
void get_radius(const bbox &my_bbox, std::vector<size_t> &intersections_indices) {
pcl::PointXYZ searchPoint;
point mid_pt;
double radius_search_bound = 0;
//uses radius not squared radius
get_max_radius(my_bbox, mid_pt, radius_search_bound);
//needs slight tolerance to find points exactly on the edge
radius_search_bound += DEFAULT_TOLERANCE;
searchPoint.x = mid_pt[0];
searchPoint.y = mid_pt[1];
searchPoint.z = mid_pt[2];
//has to be ints and floats, not size_t and doubles
std::vector<int> indices;
std::vector<float> distances;
tree->radiusSearch (searchPoint, radius_search_bound, indices, distances);
std::copy(indices.begin(), indices.end(), std::back_inserter(intersections_indices));
}
};
//is just a thin wrapper around FLANN. no reason to think it'll be better
class KDTree : public BboxIntersectionTest {
private:
pcl::KdTreeFLANN<pcl::PointXYZ> *tree;
public:
bool intersections_exact() { return false ;} //circular radius with tolerance is not exact
KDTree() {}
~KDTree() {
delete tree;
}
//library doesn't support setting a leaf size
void build_tree(const std::vector<point> &pts, const std::vector<size_t> &indices) {
bool sort = false;
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);
//indicates there will be no infinite or NaN values
cloud->is_dense = true;
for(const point &pt : pts) {
cloud->push_back(pcl::PointXYZ(pt[0],pt[1],pt[2]));
}
tree = new pcl::KdTreeFLANN<pcl::PointXYZ>(sort);
tree->setInputCloud(cloud);
}
void get_intersections(const bbox &my_bbox, std::vector<size_t> &intersections_indices) {
pcl::PointXYZ searchPoint;
point mid_pt;
double radius_search_bound = 0;
//uses radius not squared radius
get_max_radius(my_bbox, mid_pt, radius_search_bound);
//needs slight tolerance to find points exactly on the edge
radius_search_bound += DEFAULT_TOLERANCE;
searchPoint.x = mid_pt[0];
searchPoint.y = mid_pt[1];
searchPoint.z = mid_pt[2];
//has to be ints and floats, not size_t and doubles
std::vector<int> indices;
std::vector<float> distances;
tree->radiusSearch (searchPoint, radius_search_bound, indices, distances);
std::copy(indices.begin(), indices.end(), std::back_inserter(intersections_indices));
}
};
#ifdef USE_GPU
class OctreeGPU : public BboxIntersectionTest {
private:
pcl::octree::OctreePointCloudSearch<pcl::PointXYZ> *tree;
pcl::gpu::Octree *octree_device;
size_t tree_size;
public:
bool intersections_exact() { return false ;} //circular radius with tolerance is not exact
OctreeGPU() {}
~OctreeGPU() {
delete tree;
delete octree_device;
}
//doesn't allow you to set the leaf size when using a gpu
void build_tree(const std::vector<point> &pts, const std::vector<size_t> &indices) {
tree_size = pts.size();
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);
//indicates there will be no infinite or NaN values
cloud->is_dense = true;
for(const point &pt : pts) {
cloud->push_back(pcl::PointXYZ(pt[0],pt[1],pt[2]));
}
pcl::gpu::Octree::PointCloud cloud_device;
cloud_device.upload(cloud->points);
octree_device = new pcl::gpu::Octree();
octree_device->setCloud(cloud_device);
octree_device->build();
}
//note - gpu octre doesn't support box search like the non-gpu variant does
//by default we won't do query domain decomposition
void get_intersections(const bbox &my_bbox, std::vector<size_t> &intersections_indices,
size_t num_sub_queries, size_t x_queries, size_t y_queries, size_t z_queries) {
if(x_queries*y_queries*z_queries != num_sub_queries) {
std::cerr << "error. you have provided a query domain decompoistion where x_queries*y_queries*z_queries != total_queries" << std::endl;
return;
}
std::vector<pcl::PointXYZ> query_host;
query_host.resize (num_sub_queries);
vector<double> subquery_bbox_len = {
(my_bbox.second[0]-my_bbox.first[0])/x_queries,
(my_bbox.second[1]-my_bbox.first[1])/y_queries,
(my_bbox.second[2]-my_bbox.first[2])/z_queries
};
for(size_t i = 0; i < num_sub_queries; i++) {
size_t x_pos = i % x_queries;
size_t y_pos = (i / x_queries) % y_queries;
size_t z_pos = ((i / (x_queries * y_queries)) % z_queries);
double x_offset = x_pos * subquery_bbox_len[0] + my_bbox.first[0];
double y_offset = y_pos * subquery_bbox_len[1] + my_bbox.first[1];
double z_offset = z_pos * subquery_bbox_len[2] + my_bbox.first[2];
//want the midpoints
query_host[i].x = x_offset + subquery_bbox_len[0]*.5;
query_host[i].y = y_offset + subquery_bbox_len[1]*.5;
query_host[i].z = z_offset + subquery_bbox_len[2]*.5;
}
pcl::gpu::Octree::Queries queries_device;
queries_device.upload(query_host);
point mid_pt;
double radius_search_bound = 0;
bbox sub_bbox = bbox(my_bbox.first,
point({
my_bbox.first[0]+subquery_bbox_len[0],
my_bbox.first[1]+subquery_bbox_len[1],
my_bbox.first[2]+subquery_bbox_len[2]
})
);
//uses radius not squared radius
get_max_radius(sub_bbox, mid_pt, radius_search_bound);
radius_search_bound += DEFAULT_TOLERANCE;
std::vector<float> radius;
for(int i = 0; i < num_sub_queries; i++) {
radius.push_back(radius_search_bound);
}
pcl::gpu::Octree::Radiuses radiuses_device;
radiuses_device.upload(radius);
//every point could conceivably match
const int max_answers = tree_size;
// Output buffer on the device
pcl::gpu::NeighborIndices result_device(queries_device.size(), max_answers);
// Do the actual search
octree_device->radiusSearch(queries_device, radiuses_device, max_answers, result_device);
std::vector<int> sizes, data;
result_device.sizes.download(sizes);
result_device.data.download(data);
if(num_sub_queries > 1) {
//use a set since there could be duplicates when performing multuple sub-queries in parallel
std::set<size_t> result_indices;
for (std::size_t i = 0; i < sizes.size (); ++i) {
for (std::size_t j = 0; j < sizes[i]; ++j) {
//have to use a set since there could be overlap in the results
result_indices.insert(data[j+ i * max_answers]);
}
}
std::copy(result_indices.begin(), result_indices.end(), std::back_inserter(intersections_indices));
}
else {
for (std::size_t i = 0; i < sizes.size (); ++i) {
for (std::size_t j = 0; j < sizes[i]; ++j) {
intersections_indices.push_back(data[j+ i * max_answers]);
}
}
}
}
void get_intersections(const bbox &my_bbox, std::vector<size_t> &intersections_indices) {
size_t num_sub_queries=1, x_queries=1, y_queries=1, z_queries=1;
get_intersections(my_bbox, intersections_indices, num_sub_queries, x_queries, y_queries, z_queries);
}
};
#endif
}
#endif //PCL_TEST_HH
| 45.16955 | 159 | 0.506358 | [
"vector"
] |
bb20bdbdec082c8677053820d51512a629b2dc4a | 14,103 | hpp | C++ | include/util.hpp | Razdeep/autocomplete | fbe73627d58805e137bef2ebb10945cd845c5928 | [
"MIT"
] | 26 | 2020-05-12T10:55:48.000Z | 2022-03-07T10:57:37.000Z | include/util.hpp | Razdeep/autocomplete | fbe73627d58805e137bef2ebb10945cd845c5928 | [
"MIT"
] | 3 | 2021-08-04T18:27:03.000Z | 2022-02-08T11:22:53.000Z | include/util.hpp | Razdeep/autocomplete | fbe73627d58805e137bef2ebb10945cd845c5928 | [
"MIT"
] | 3 | 2020-05-24T08:07:29.000Z | 2021-07-19T09:59:56.000Z | #pragma once
#pragma once
#include <string.h>
#include <sys/time.h>
#include <cassert>
#include <ctime>
#include <iostream>
#include <locale>
#include <vector>
#include <smmintrin.h>
#include <xmmintrin.h>
#include "../external/essentials/include/essentials.hpp"
#define LIKELY(x) __builtin_expect(!!(x), 1)
#define UNLIKELY(x) __builtin_expect(!!(x), 0)
#define NOINLINE __attribute__((noinline))
#define ALWAYSINLINE __attribute__((always_inline))
namespace autocomplete {
// NOTE: assume 32 bits are enough to store
// both a term_id and a doc_id
typedef uint32_t id_type;
namespace global {
static const id_type invalid_term_id = id_type(-1);
static const id_type terminator = 0;
static const uint64_t not_found = uint64_t(-1);
static const uint64_t linear_scan_threshold = 8;
} // namespace global
namespace util {
template <typename S>
uint64_t find(S const& sequence, uint64_t id, uint64_t lo, uint64_t hi) {
while (lo <= hi) {
if (hi - lo <= global::linear_scan_threshold) {
auto it = sequence.at(lo);
for (uint64_t pos = lo; pos != hi; ++pos, ++it) {
if (*it == id) {
return pos;
}
}
}
uint64_t pos = lo + ((hi - lo) >> 1);
uint64_t val = sequence.access(pos);
if (val == id) {
return pos;
} else if (val > id) {
hi = pos - 1;
} else {
lo = pos + 1;
}
}
return global::not_found;
}
template <typename S>
uint64_t next_geq(S const& sequence, uint64_t lower_bound, uint64_t lo,
uint64_t hi) {
while (lo <= hi) {
if (hi - lo <= global::linear_scan_threshold) {
auto it = sequence.at(lo);
for (uint64_t pos = lo; pos <= hi; ++pos, ++it) {
if (*it >= lower_bound) {
return pos;
}
}
break;
}
uint64_t pos = (lo + hi) / 2;
uint64_t val = sequence.access(pos);
if (val > lower_bound) {
hi = pos != 0 ? pos - 1 : 0;
if (lower_bound > sequence.access(hi)) {
return pos;
}
} else if (val < lower_bound) {
lo = pos + 1;
} else {
return pos;
}
}
return global::not_found;
}
} // namespace util
namespace tables {
const uint8_t select_in_byte[2048] = {
8, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0,
1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1,
0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0,
2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2,
0, 1, 0, 7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0,
1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1,
0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 6, 0, 1, 0, 2, 0, 1, 0,
3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0,
1, 0, 2, 0, 1, 0, 8, 8, 8, 1, 8, 2, 2, 1, 8, 3, 3, 1, 3, 2, 2, 1, 8, 4, 4,
1, 4, 2, 2, 1, 4, 3, 3, 1, 3, 2, 2, 1, 8, 5, 5, 1, 5, 2, 2, 1, 5, 3, 3, 1,
3, 2, 2, 1, 5, 4, 4, 1, 4, 2, 2, 1, 4, 3, 3, 1, 3, 2, 2, 1, 8, 6, 6, 1, 6,
2, 2, 1, 6, 3, 3, 1, 3, 2, 2, 1, 6, 4, 4, 1, 4, 2, 2, 1, 4, 3, 3, 1, 3, 2,
2, 1, 6, 5, 5, 1, 5, 2, 2, 1, 5, 3, 3, 1, 3, 2, 2, 1, 5, 4, 4, 1, 4, 2, 2,
1, 4, 3, 3, 1, 3, 2, 2, 1, 8, 7, 7, 1, 7, 2, 2, 1, 7, 3, 3, 1, 3, 2, 2, 1,
7, 4, 4, 1, 4, 2, 2, 1, 4, 3, 3, 1, 3, 2, 2, 1, 7, 5, 5, 1, 5, 2, 2, 1, 5,
3, 3, 1, 3, 2, 2, 1, 5, 4, 4, 1, 4, 2, 2, 1, 4, 3, 3, 1, 3, 2, 2, 1, 7, 6,
6, 1, 6, 2, 2, 1, 6, 3, 3, 1, 3, 2, 2, 1, 6, 4, 4, 1, 4, 2, 2, 1, 4, 3, 3,
1, 3, 2, 2, 1, 6, 5, 5, 1, 5, 2, 2, 1, 5, 3, 3, 1, 3, 2, 2, 1, 5, 4, 4, 1,
4, 2, 2, 1, 4, 3, 3, 1, 3, 2, 2, 1, 8, 8, 8, 8, 8, 8, 8, 2, 8, 8, 8, 3, 8,
3, 3, 2, 8, 8, 8, 4, 8, 4, 4, 2, 8, 4, 4, 3, 4, 3, 3, 2, 8, 8, 8, 5, 8, 5,
5, 2, 8, 5, 5, 3, 5, 3, 3, 2, 8, 5, 5, 4, 5, 4, 4, 2, 5, 4, 4, 3, 4, 3, 3,
2, 8, 8, 8, 6, 8, 6, 6, 2, 8, 6, 6, 3, 6, 3, 3, 2, 8, 6, 6, 4, 6, 4, 4, 2,
6, 4, 4, 3, 4, 3, 3, 2, 8, 6, 6, 5, 6, 5, 5, 2, 6, 5, 5, 3, 5, 3, 3, 2, 6,
5, 5, 4, 5, 4, 4, 2, 5, 4, 4, 3, 4, 3, 3, 2, 8, 8, 8, 7, 8, 7, 7, 2, 8, 7,
7, 3, 7, 3, 3, 2, 8, 7, 7, 4, 7, 4, 4, 2, 7, 4, 4, 3, 4, 3, 3, 2, 8, 7, 7,
5, 7, 5, 5, 2, 7, 5, 5, 3, 5, 3, 3, 2, 7, 5, 5, 4, 5, 4, 4, 2, 5, 4, 4, 3,
4, 3, 3, 2, 8, 7, 7, 6, 7, 6, 6, 2, 7, 6, 6, 3, 6, 3, 3, 2, 7, 6, 6, 4, 6,
4, 4, 2, 6, 4, 4, 3, 4, 3, 3, 2, 7, 6, 6, 5, 6, 5, 5, 2, 6, 5, 5, 3, 5, 3,
3, 2, 6, 5, 5, 4, 5, 4, 4, 2, 5, 4, 4, 3, 4, 3, 3, 2, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 3, 8, 8, 8, 8, 8, 8, 8, 4, 8, 8, 8, 4, 8, 4, 4, 3,
8, 8, 8, 8, 8, 8, 8, 5, 8, 8, 8, 5, 8, 5, 5, 3, 8, 8, 8, 5, 8, 5, 5, 4, 8,
5, 5, 4, 5, 4, 4, 3, 8, 8, 8, 8, 8, 8, 8, 6, 8, 8, 8, 6, 8, 6, 6, 3, 8, 8,
8, 6, 8, 6, 6, 4, 8, 6, 6, 4, 6, 4, 4, 3, 8, 8, 8, 6, 8, 6, 6, 5, 8, 6, 6,
5, 6, 5, 5, 3, 8, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3, 8, 8, 8, 8,
8, 8, 8, 7, 8, 8, 8, 7, 8, 7, 7, 3, 8, 8, 8, 7, 8, 7, 7, 4, 8, 7, 7, 4, 7,
4, 4, 3, 8, 8, 8, 7, 8, 7, 7, 5, 8, 7, 7, 5, 7, 5, 5, 3, 8, 7, 7, 5, 7, 5,
5, 4, 7, 5, 5, 4, 5, 4, 4, 3, 8, 8, 8, 7, 8, 7, 7, 6, 8, 7, 7, 6, 7, 6, 6,
3, 8, 7, 7, 6, 7, 6, 6, 4, 7, 6, 6, 4, 6, 4, 4, 3, 8, 7, 7, 6, 7, 6, 6, 5,
7, 6, 6, 5, 6, 5, 5, 3, 7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 4, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 8, 8, 8,
8, 8, 8, 8, 5, 8, 8, 8, 5, 8, 5, 5, 4, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 6, 8, 8, 8, 8, 8, 8, 8, 6, 8, 8, 8, 6, 8, 6, 6, 4, 8, 8, 8, 8, 8,
8, 8, 6, 8, 8, 8, 6, 8, 6, 6, 5, 8, 8, 8, 6, 8, 6, 6, 5, 8, 6, 6, 5, 6, 5,
5, 4, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
7, 8, 8, 8, 7, 8, 7, 7, 4, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 7, 8, 7, 7, 5,
8, 8, 8, 7, 8, 7, 7, 5, 8, 7, 7, 5, 7, 5, 5, 4, 8, 8, 8, 8, 8, 8, 8, 7, 8,
8, 8, 7, 8, 7, 7, 6, 8, 8, 8, 7, 8, 7, 7, 6, 8, 7, 7, 6, 7, 6, 6, 4, 8, 8,
8, 7, 8, 7, 7, 6, 8, 7, 7, 6, 7, 6, 6, 5, 8, 7, 7, 6, 7, 6, 6, 5, 7, 6, 6,
5, 6, 5, 5, 4, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 6, 8, 8, 8, 8, 8, 8, 8, 6,
8, 8, 8, 6, 8, 6, 6, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 7, 8, 7, 7, 5, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 7,
8, 7, 7, 6, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 7, 8, 7, 7, 6, 8, 8, 8, 7, 8,
7, 7, 6, 8, 7, 7, 6, 7, 6, 6, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
7, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 7, 8, 7, 7, 6, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7};
}
namespace util {
template <typename T>
inline void prefetch(T const* ptr) {
_mm_prefetch(reinterpret_cast<const char*>(ptr), _MM_HINT_T0);
}
inline uint8_t msb(uint64_t x) {
assert(x);
unsigned long ret = -1U;
if (x) {
ret = (unsigned long)(63 - __builtin_clzll(x));
}
return (uint8_t)ret;
}
inline bool bsr64(unsigned long* const index, const uint64_t mask) {
if (mask) {
*index = (unsigned long)(63 - __builtin_clzll(mask));
return true;
} else {
return false;
}
}
inline uint8_t msb(uint64_t x, unsigned long& ret) {
return bsr64(&ret, x);
}
inline uint8_t lsb(uint64_t x, unsigned long& ret) {
if (x) {
ret = (unsigned long)__builtin_ctzll(x);
return true;
}
return false;
}
inline uint8_t lsb(uint64_t x) {
assert(x);
unsigned long ret = -1U;
lsb(x, ret);
return (uint8_t)ret;
}
inline uint64_t ceil_log2(const uint64_t x) {
return (x > 1) ? msb(x - 1) + 1 : 0;
}
inline uint64_t floor_log2(const uint64_t x) {
return (x > 1) ? msb(x) : 0;
}
static const uint64_t ones_step_4 = 0x1111111111111111ULL;
static const uint64_t ones_step_8 = 0x0101010101010101ULL;
static const uint64_t ones_step_9 = 1ULL << 0 | 1ULL << 9 | 1ULL << 18 |
1ULL << 27 | 1ULL << 36 | 1ULL << 45 |
1ULL << 54;
static const uint64_t msbs_step_8 = 0x80ULL * ones_step_8;
static const uint64_t msbs_step_9 = 0x100ULL * ones_step_9;
static const uint64_t incr_step_8 =
0x80ULL << 56 | 0x40ULL << 48 | 0x20ULL << 40 | 0x10ULL << 32 |
0x8ULL << 24 | 0x4ULL << 16 | 0x2ULL << 8 | 0x1;
static const uint64_t inv_count_step_9 = 1ULL << 54 | 2ULL << 45 | 3ULL << 36 |
4ULL << 27 | 5ULL << 18 | 6ULL << 9 |
7ULL;
static const uint64_t magic_mask_1 = 0x5555555555555555ULL;
static const uint64_t magic_mask_2 = 0x3333333333333333ULL;
static const uint64_t magic_mask_3 = 0x0F0F0F0F0F0F0F0FULL;
static const uint64_t magic_mask_4 = 0x00FF00FF00FF00FFULL;
static const uint64_t magic_mask_5 = 0x0000FFFF0000FFFFULL;
static const uint64_t magic_mask_6 = 0x00000000FFFFFFFFULL;
inline uint64_t leq_step_8(uint64_t x, uint64_t y) {
return ((((y | msbs_step_8) - (x & ~msbs_step_8)) ^ (x ^ y)) &
msbs_step_8) >>
7;
}
inline uint64_t uleq_step_9(uint64_t x, uint64_t y) {
return (((((y | msbs_step_9) - (x & ~msbs_step_9)) | (x ^ y)) ^ (x & ~y)) &
msbs_step_9) >>
8;
}
inline uint64_t byte_counts(uint64_t x) {
x = x - ((x & 0xa * ones_step_4) >> 1);
x = (x & 3 * ones_step_4) + ((x >> 2) & 3 * ones_step_4);
x = (x + (x >> 4)) & 0x0f * ones_step_8;
return x;
}
inline uint64_t bytes_sum(uint64_t x) {
return x * ones_step_8 >> 56;
}
inline uint64_t byteswap64(uint64_t value) {
#if defined(__GNUC__) || defined(__clang__)
return __builtin_bswap64(value);
#else
#error Unsupported platform
#endif
}
inline uint64_t reverse_bytes(uint64_t x) {
#if USE_INTRINSICS
return byteswap64(x);
#else
x = ((x >> 8) & magic_mask_4) | ((x & magic_mask_4) << 8);
x = ((x >> 16) & magic_mask_5) | ((x & magic_mask_5) << 16);
x = ((x >> 32)) | ((x) << 32);
return x;
#endif
}
inline uint64_t reverse_bits(uint64_t x) {
x = ((x >> 1) & magic_mask_1) | ((x & magic_mask_1) << 1);
x = ((x >> 2) & magic_mask_2) | ((x & magic_mask_2) << 2);
x = ((x >> 4) & magic_mask_3) | ((x & magic_mask_3) << 4);
return reverse_bytes(x);
}
inline uint64_t popcount(uint64_t x) {
#if USE_INTRINSICS
return uint64_t(_mm_popcnt_u64(x));
#else
return bytes_sum(byte_counts(x));
#endif
}
// NOTE: this is the select-in-word algorithm presented in
// "A Fast x86 Implementation of Select" by
// P. Pandey, M. A. Bender, and R. Johnson
// the algorithm uses only four x86 machine instructions,
// two of which were introduced in Intel’s Haswell CPUs in 2013
// source: https://github.com/splatlab/rankselect/blob/master/popcount.h
inline uint64_t select64_pdep_tzcnt(uint64_t x, const uint64_t k) {
uint64_t i = 1ULL << k;
asm("pdep %[x], %[mask], %[x]" : [ x ] "+r"(x) : [ mask ] "r"(i));
asm("tzcnt %[bit], %[index]" : [ index ] "=r"(i) : [ bit ] "g"(x) : "cc");
return i;
}
inline uint64_t select_in_word(const uint64_t x, const uint64_t k) {
assert(k < popcount(x));
#if USE_PDEP
return select64_pdep_tzcnt(x, k);
#else
uint64_t byte_sums = byte_counts(x) * ones_step_8;
const uint64_t k_step_8 = k * ones_step_8;
const uint64_t geq_k_step_8 =
(((k_step_8 | msbs_step_8) - byte_sums) & msbs_step_8);
const uint64_t place = popcount(geq_k_step_8) * 8;
const uint64_t byte_rank =
k - (((byte_sums << 8) >> place) & uint64_t(0xFF));
return place +
tables::select_in_byte[((x >> place) & 0xFF) | (byte_rank << 8)];
#endif
}
template <typename IntType1, typename IntType2>
inline IntType1 ceil_div(IntType1 dividend, IntType2 divisor) {
IntType1 d = IntType1(divisor);
return IntType1(dividend + d - 1) / d;
}
} // namespace util
} // namespace autocomplete | 40.409742 | 79 | 0.469049 | [
"vector"
] |
bb21557145b5481b4a41f0f68ad2ea7571a21b61 | 7,313 | cpp | C++ | apriltags-cpp/src/quadtest.cpp | jacknlliu/apriltags_ros | 403e5a2e6bdd23b846d3c9a9ffea83e49bca8978 | [
"MIT"
] | 10 | 2018-04-25T10:48:20.000Z | 2020-03-26T13:01:57.000Z | apriltags-cpp/src/quadtest.cpp | jacknlliu/apriltags_ros | 403e5a2e6bdd23b846d3c9a9ffea83e49bca8978 | [
"MIT"
] | 1 | 2018-07-11T01:47:50.000Z | 2018-09-04T22:49:24.000Z | apriltags-cpp/src/quadtest.cpp | jacknlliu/apriltags_ros | 403e5a2e6bdd23b846d3c9a9ffea83e49bca8978 | [
"MIT"
] | 3 | 2018-11-15T14:30:06.000Z | 2019-11-18T01:17:07.000Z | /*********************************************************************
* This file is distributed as part of the C++ port of the APRIL tags
* library. The code is licensed under GPLv2.
*
* Original author: Edwin Olson <ebolson@umich.edu>
* C++ port and modifications: Matt Zucker <mzucker1@swarthmore.edu>
********************************************************************/
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <vector>
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#include "Geometry.h"
#include "TagDetector.h"
#include "Refine.h"
enum {
test_img_w = 30,
test_img_h = 30,
test_img_tagsz = 12,
test_img_scl = 8
};
cv::Mat shrink(const cv::Mat& image, int scl) {
cv::Mat small;
cv::resize(image, small, cv::Size(image.cols/scl, image.rows/scl), 0, 0,
CV_INTER_AREA);
return small;
}
cv::Mat addNoise(const cv::Mat& src, cv::RNG& rng, double stddev) {
cv::Mat input;
if (src.depth() != at::REAL_IMAGE_TYPE) {
src.convertTo(input, CV_MAKETYPE(at::REAL_IMAGE_TYPE, src.channels()));
} else {
input = src.clone();
}
std::vector<cv::Mat> chans;
cv::split(input, chans);
for (size_t c=0; c<chans.size(); ++c) {
at::Mat m = chans[c];
for (int y=0; y<m.rows; ++y) {
for (int x=0; x<m.cols; ++x) {
m(y,x) += rng.gaussian(stddev);
}
}
}
cv::merge(chans, input);
cv::Mat output;
if (input.depth() != src.depth()) {
input.convertTo(output, CV_MAKETYPE(src.depth(), src.channels()));
} else {
output = input;
}
return output;
}
size_t fakeDetectionImage(const TagFamily& tagFamily,
cv::RNG& rng,
at::Point p[4],
cv::Mat& small) {
const int dx[4] = { -1, 1, 1, -1 };
const int dy[4] = { 1, 1, -1, -1 };
at::real theta = rng.uniform(-1.0,1.0) * M_PI / 4;
at::real ct = cos(theta);
at::real st = sin(theta);
at::Point b1(ct, st);
at::Point b2(-st, ct);
for (int i=0; i<4; ++i) {
p[i] = at::Point(dx[i]*test_img_tagsz*0.5, dy[i]*test_img_tagsz*0.5);
p[i] = at::Point(b1.dot(p[i]), b2.dot(p[i]));
p[i].x += test_img_tagsz*rng.uniform(-1.0, 1.0) / 10 + test_img_w/2;
p[i].y += test_img_tagsz*rng.uniform(-1.0, 1.0) / 10 + test_img_h/2;
p[i] *= test_img_scl;
}
int id = rng.uniform(0, int(tagFamily.codes.size()-1));
at::Point opticalCenter(0.5*test_img_w*test_img_scl, 0.5*test_img_h*test_img_scl);
Quad quad(p, opticalCenter, 4*test_img_scl*test_img_tagsz);
TagDetection d;
tagFamily.decode(d, tagFamily.codes[id]);
for (int i = 0; i < 4; i++) {
d.p[i] = quad.p[i] * (1.0/test_img_scl);
}
// compute the homography (and rotate it appropriately)
d.homography = quad.H;
d.hxy = quad.opticalCenter;
at::real c = cos(d.rotation*M_PI/2.0);
at::real s = sin(d.rotation*M_PI/2.0);
at::real R[9] = {
c, -s, 0,
s, c, 0,
0, 0, 1
};
at::Mat Rmat(3, 3, R);
d.homography = d.homography * Rmat;
d.cxy = quad.interpolate01(.5, .5);
d.observedPerimeter = quad.observedPerimeter;
cv::Mat big = tagFamily.detectionImage(d,
cv::Size(test_img_scl*test_img_w,
test_img_scl*test_img_h),
CV_8UC3, CV_RGB(255,255,255));
small = addNoise(shrink(big, test_img_scl), rng, 10);
for (int i=0; i<4; ++i) {
p[i] *= (1.0/test_img_scl);
}
return id;
}
int main(int argc, char** argv) {
bool debug = false;
if (argc > 1 && argv[1] == std::string("-d")) {
debug = true;
}
cv::RNG rng(12345);
TagFamily tagFamily("Tag36h11");
int dd = tagFamily.d + 2 * tagFamily.blackBorder;
TPointArray tpoints;
for (int i=-1; i<=dd; ++i) {
at::real fi = at::real(i+0.5) / dd;
for (int j=-1; j<=dd; ++j) {
at::real fj = at::real(j+0.5) / dd;
at::real t = -1;
if (i == -1 || j == -1 || i == dd || j == dd) {
t = 255;
} else if (i == 0 || j == 0 || i+1 == dd || j+1 == dd) {
t = 0;
}
if (t >= 0) {
tpoints.push_back(TPoint(fi, fj, t));
}
}
}
int ntrials = 100;
double total_time = 0;
double total_err1 = 0;
double total_err2 = 0;
for (int trial=0; trial<ntrials; ++trial) {
TagDetection d;
at::Point p[4];
cv::Mat small;
fakeDetectionImage(tagFamily, rng, p, small);
cv::Mat_<unsigned char> gsmall;
cv::cvtColor(small, gsmall, CV_RGB2GRAY);
at::Mat gx = at::Mat::zeros(gsmall.size());
at::Mat gy = at::Mat::zeros(gsmall.size());
/*
for (int y=1; y<gsmall.rows-1; ++y) {
for (int x=1; x<gsmall.cols-1; ++x) {
gx(y,x) = gsmall(y,x+1) - gsmall(y,x-1);
gy(y,x) = gsmall(y+1,x) - gsmall(y-1,x);
}
}
*/
cv::Sobel( gsmall, gx, at::REAL_IMAGE_TYPE, 1, 0 );
cv::Sobel( gsmall, gy, at::REAL_IMAGE_TYPE, 0, 1 );
gx *= 0.25;
gy *= 0.25;
at::Point badp[4];
at::real err1 = 0;
for (int i=0; i<4; ++i) {
at::Point ei = at::Point( rng.uniform(-1.0,1.0),
rng.uniform(-1.0,1.0) ) * (test_img_tagsz / 8.0);
badp[i] = p[i] + ei;
err1 += sqrt(ei.dot(ei));
}
total_err1 += err1;
clock_t begin = clock();
int iter = refineQuad(gsmall, gx, gy, badp, tpoints, debug, 10, 5e-3);
clock_t end = clock();
total_time += double(end-begin)/CLOCKS_PER_SEC;
at::real err2 = 0;
for (int i=0; i<4; ++i) {
at::Point ei = p[i] - badp[i];
err2 += sqrt(ei.dot(ei));
}
total_err2 += err2;
std::cout << "err before: " << std::setw(10) << err1
<< ", after: " << std::setw(10) << err2
<< ", improvement: " << std::setw(10) << err1/err2
<< " after " << iter << " iterations.\n";
}
std::cout << "refined " << ntrials << " quads in "
<< total_time << " sec (" << (total_time/ntrials) << " per trial)\n";
std::cout << "average improvement was " << total_err1 / total_err2 << "\n";
return 0;
}
/*
ucMat img = tagFamily.makeImage(id);
int b = tagFamily.whiteBorder + tagFamily.blackBorder;
int errors = 0;
TagFamily::code_t tagCode = 0;
for (int iy = tagFamily.d-1; iy >= 0; iy--) {
for (int ix = 0; ix < tagFamily.d; ix++) {
at::real y = (tagFamily.blackBorder + iy + .5) / dd;
at::real x = (tagFamily.blackBorder + ix + .5) / dd;
at::Point uv(x, y);
at::Point pi = interpolate(badp, uv);
cv::Point ii = pi + at::Point(0.5, 0.5);
int tagbit = img(tagFamily.d-iy-1+b, ix+b) ? 1 : 0;
int imgbit = gbig(ii) > 127;
tagCode = tagCode << TagFamily::code_t(1);
if (imgbit) {
tagCode |= TagFamily::code_t(1);
}
errors += (tagbit != imgbit);
cv::Scalar tc = tagbit ? CV_RGB(255,0,0) : CV_RGB(0,0,255);
cv::Scalar dc = imgbit ? CV_RGB(255,0,0) : CV_RGB(0,0,255);
drawPoint(big, pi, tc, 5, CV_FILLED);
drawPoint(big, pi, dc, 5, 2);
}
}
*/
| 24.959044 | 84 | 0.515384 | [
"geometry",
"vector"
] |
bb23cfc1d8a8876f106dfbee1bc395c2c81bee9b | 6,997 | cpp | C++ | genetic_code/SQP/MINL2/TINL2.cpp | umbax/HyGP | d6a38b624f531638a78f7a69b8a5f89538e128c8 | [
"Apache-2.0"
] | 3 | 2017-07-08T21:53:12.000Z | 2022-02-09T08:16:48.000Z | genetic_code/SQP/MINL2/TINL2.cpp | umbax/HyGP | d6a38b624f531638a78f7a69b8a5f89538e128c8 | [
"Apache-2.0"
] | null | null | null | genetic_code/SQP/MINL2/TINL2.cpp | umbax/HyGP | d6a38b624f531638a78f7a69b8a5f89538e128c8 | [
"Apache-2.0"
] | 1 | 2017-07-08T21:53:02.000Z | 2017-07-08T21:53:02.000Z | /* TINL2.F -- translated by f2c (version 20050501).
You must link the resulting object file with libf2c:
on Microsoft Windows system, link with libf2c.lib;
on Linux or Unix systems, link with .../path/to/libf2c.a -lm
or, if you install libf2c.a in a standard place, with -lf2c -lm
-- in that order, at the end of the command line, as in
cc *.o -lf2c -lm
Source for libf2c is in /netlib/f2c/libf2c.zip, e.g.,
http://www.netlib.org/f2c/libf2c.zip
*/
#include <iostream> // basic i/o commands
using namespace std;
#ifdef __cplusplus
extern "C" {
#endif
#include "f2c.h"
/* Table of constant values */
static integer c__0 = 0;
static integer c__1 = 1;
static integer n = 2; // n: number of unknowns (parameters) c__2
static integer m = 3; // m: number of functions (terms of the sum) c__3
static integer c__195 = 195;
/* TEST OF MINL2 21.11.1991 */
int MAIN__() //<----refers to the master.cpp!
{
extern /* Subroutine */ int opti_(integer *);
//opti_(&c__0); // to check the gradient
opti_(&c__1); // to perform optimization
cout << "\nDone...\n";
return 0;
}
int opti_(integer *method)
{
/* Format strings */
static char fmt_10[] = "(\002 INPUT ERROR. PARAMETER NUMBER \002,i1,\002 IS OUTSIDE ITS RANGE.\002)";
static char fmt_21[] = "(\002 TEST OF GRADIENTS \002//\002 MAXIMUM FORWA\
RD DIFFERENCE: \002,d8.2,\002 AT FUNCTION NO \002,i1,\002 AND VARIABLE NO\
\002,i1/\002 MAXIMUM BACKWARD DIFFERENCE: \002,d8.2,\002 AT FUNCTION NO \
\002,i1,\002 AND VARIABLE NO \002,i1/\002 MAXIMUM CENTRAL DIFFERENCE: \002,\
d8.2,\002 AT FUNCTION NO \002,i1,\002 AND VARIABLE NO \002,i1)";
static char fmt_22[] = "(//\002 MAXIMUM ELEMENT IN DF: \002,d8.2)";
static char fmt_30[] = "(\002 UPPER LIMIT FOR FUNCTION EVALUATIONS EXCEEDED.\002/)";
static char fmt_31[] = "(23x,\002 SOLUTION: \002,d18.10/d52.10//\002 NUM\
BER OF CALLS OF FDF: \002,i4//\002 FUNCTION VALUES AT THE SOLUTION: \002,d18.10,2(/d52.10))";
/* System generated locals */
integer i__1;
/* Builtin functions */
integer s_wsfe(cilist *), do_fio(integer *, char *, ftnlen), e_wsfe();
/* Local variables */
static integer i__, j, k;
static doublereal w[195]; // size of the workspace: don't touch it!
static doublereal x[2]; // size of the parameters vector: get it as input
static doublereal dx; //<----------------------------------------------------
extern /* Subroutine */ int fdf_(...); //
static doublereal eps;
extern /* Subroutine */ int minl2_(U_fp, integer *, integer *, doublereal
*, doublereal *, doublereal *, integer *, doublereal *, integer *,
integer *);
static integer index[8] /* was [4][2] */; //?????
static logical optim;
static integer icontr, maxfun;
/* Fortran I/O blocks */
static cilist io___8 = { 0, 6, 0, fmt_10, 0 };
static cilist io___11 = { 0, 6, 0, fmt_21, 0 };
static cilist io___12 = { 0, 6, 0, fmt_22, 0 };
static cilist io___13 = { 0, 6, 0, fmt_30, 0 };
static cilist io___14 = { 0, 6, 0, fmt_31, 0 };
/* SET PAPAMETERS */
eps = 1e-10;
maxfun = 25;
/* SET INITIAL GUESS */
x[0] = 1.; //initial guess of x1
x[1] = 1.; //initial guess of x2
icontr = *method; // <---------------------------------------------------------
optim = icontr > 0;
if (! optim) {
dx = .001;
}
minl2_( (U_fp)fdf_,
&n, //n : no. of unknown parameters - dimension of x
&m, // m : no. of functions, terms of the sum
x, // x : initial guess of the parameters
&dx, // dx : damping factor (10E-4 if initial guess close to solution, otherwise 1)
&eps, // eps : accuracy
&maxfun,// maxfun : max no. of calls to the function
w, // workspace
&c__195,// dimension of the workspace: don't touch it
&icontr); // icontr : used to control the function
if (icontr < 0) {
goto L100;
}
if (! optim) {
goto L200;
}
goto L300;
/* PARAMETER OUTSIDE RANGE */
L100:
s_wsfe(&io___8);
i__1 = -icontr;
do_fio(&c__1, (char *)&i__1, (ftnlen)sizeof(integer));
e_wsfe();
goto L400;
/* RESULTS FROM GRADIENT TEST */
L200:
for (k = 2; k <= 4; ++k) {
index[k - 1] = (integer) w[k * 2];
index[k + 3] = (integer) w[(k << 1) + 1];
/* L20: */
}
s_wsfe(&io___11);
for (k = 2; k <= 4; ++k) {
do_fio(&c__1, (char *)&w[k - 1], (ftnlen)sizeof(doublereal));
do_fio(&c__1, (char *)&index[k - 1], (ftnlen)sizeof(integer));
do_fio(&c__1, (char *)&index[k + 3], (ftnlen)sizeof(integer));
}
e_wsfe();
s_wsfe(&io___12);
do_fio(&c__1, (char *)&w[0], (ftnlen)sizeof(doublereal));
e_wsfe();
goto L400;
/* RESULTS FROM OPTIMIZATION */
L300:
if (icontr == 2) {
s_wsfe(&io___13);
e_wsfe();
}
// only this part is executed if icontr =1
s_wsfe(&io___14);
// this cycle controls the independent variables x
for (i__ = 1; i__ <= 2; ++i__) { //2 is the number of independent variables
do_fio(&c__1, (char *)&x[i__ - 1], (ftnlen)sizeof(doublereal));
}
do_fio(&c__1, (char *)&maxfun, (ftnlen)sizeof(integer));
// this cycle controls the dependent functions f
for (j = 1; j <= 3; ++j) { //3 is the number of functions the F sum is made of
do_fio(&c__1, (char *)&w[j - 1], (ftnlen)sizeof(doublereal));
}
e_wsfe(); //this function prints "SOLUTION"
L400:
printf ("\nSolution: %f %f Solution size n: %i", x[0], x[1], sizeof(x));
printf ("\nValues of the single f : %E %E %E", w[0], w[1], w[2] );
return 0;
}
// Subroutine fdf : this has to be defined by the user
// n : no. of unknown parameters - dimension of x (in)
// m : no. of functions, terms of the sum (in)
// x : initial guess of the parameters (in)
// df : vector containing the values of the derivatives in x (out)
// f : vector containing the values of the functions in x (out)
int fdf_(integer *n, integer *m, doublereal *x, doublereal *df, doublereal *f)
{
/* System generated locals */
int df_dim1, df_offset;
double d__1;
/* Parameter adjustments */
--x;
--f;
df_dim1 = *m;
df_offset = 1 + df_dim1;
df -= df_offset;
/* Function Body */
// functions
f[1] = 1.5 - x[1] * (1. - x[2]); //F1
f[2] = 2.25 - x[1] * (1. - x[2] * x[2]); //F2
f[3] = 2.625 - x[1] * (1. - x[2] * (x[2] * x[2])); //F3
// derivatives
df[df_dim1 + 1] = x[2] - 1.; // dF1/dx1
df[(df_dim1 << 1) + 1] = x[1]; // dF1/dx2 << = shift left?
df[df_dim1 + 2] = x[2] * x[2] - 1.; // dF2/dx1
df[(df_dim1 << 1) + 2] = x[1] * 2. * x[2]; // dF2/dx2
df[df_dim1 + 3] = x[2] * (x[2] * x[2]) - 1.; // dF3/dx1
df[(df_dim1 << 1) + 3] = x[1] * 3. * (x[2] * x[2]); // dF3/dx2
return 0;
}
#ifdef __cplusplus
}
#endif
| 32.393519 | 106 | 0.561955 | [
"object",
"vector"
] |
bb2b1fd79bb6e41dbbf697abc34ba0b078ab4548 | 3,969 | cpp | C++ | src/classwork/05_assign/sequence.cpp | acc-cosc-1337-spring-2022/acc-cosc-1337-spring-2022-delaneyld | 62c66c4f5c51f65300d07fe6d16a8887a30d913d | [
"MIT"
] | 1 | 2022-02-04T02:24:34.000Z | 2022-02-04T02:24:34.000Z | src/classwork/05_assign/sequence.cpp | acc-cosc-1337-spring-2022/acc-cosc-1337-spring-2022-delaneyld | 62c66c4f5c51f65300d07fe6d16a8887a30d913d | [
"MIT"
] | null | null | null | src/classwork/05_assign/sequence.cpp | acc-cosc-1337-spring-2022/acc-cosc-1337-spring-2022-delaneyld | 62c66c4f5c51f65300d07fe6d16a8887a30d913d | [
"MIT"
] | null | null | null | //write include statements
#include <string>
#include <iostream>
#include <cctype>
#include "sequence.h"
using std::cout, std::string, std::cin;
//function get_gc_content
//returns decimal percent of G and C from a given constant dna string
double get_gc_content(const std::string& dna)
{
double percent_gc, size_s, count;
count = 0;
size_s = dna.size();
for (auto& ch: dna)
{
//convert ch to uppercase, doesn't work because ch is constant
//ch = toupper(ch);
if (ch == 'G' || ch == 'C')
{
++count;
}
}
percent_gc = count / size_s;
return percent_gc;
}
//function get_dna_complement
//returns the reverse complement from a given dna string value
//calls reverse_string to get reverse dna string
//then finds the complement
string get_dna_complement(string dna)
{
int count = 0;
string dna_new = reverse_string(dna);
for (auto ch: dna_new)
{
if (ch == 'A')
{
ch = 'T';
dna_new[count] = ch;
}
else if (ch == 'T')
{
ch = 'A';
dna_new[count] = ch;
}
else if (ch == 'G')
{
ch = 'C';
dna_new[count] = ch;
}
else if (ch == 'C')
{
ch = 'G';
dna_new[count] = ch;
}
++count;
}
return dna_new;
}
//function reverse_string
//returns the reverse string from a given dna string value
string reverse_string(string dna)
{
int size_s, count_for;
size_s = dna.size();
string new_string=dna;
count_for=0;
for(int count_back = size_s - 1; count_back >= 0; --count_back)
{
new_string[count_for] = dna[count_back];
++count_for;
}
return new_string;
}
//function user_menu
void user_menu()
{
cout<< "\nMAIN MENU\n\n";
cout<< "1 - Get GC Content\n";
cout<< "2 - Get DNA Complement\n";
cout<< "3 - Exit\n\n";
}
//function to run user menu
int run_user_menu()
{
int choice;
cout<<"Please enter your menu choice number: ";
cin>>choice;
return choice;
}
//function for user menu conditions
void user_menu_conditions(int choice)
{
string dna_test, result_string;
double result_doub;
// switch loop to handle menu choices
switch(choice)
{
//GC Content
case 1:
cout<<"Please enter a DNA string: ";
cin>>dna_test;
result_doub = get_gc_content(dna_test);
cout<<"The decimal percent of GC is: "<< result_doub << "\n";
break;
//Get DNA Complement
case 2:
cout<<"Please enter a DNA string: ";
cin>>dna_test;
result_string = get_dna_complement(dna_test);
cout<<"The DNA complement is: "<< result_string << "\n";
break;
//exit with user confirm
case 3:
break;
default:
cout<<"Menu number choice entered was not valid.\n";
}
}
//function user_confirm_check
char user_confirm_check()
{
char user_confirm;
cout << "Are you sure that you want to exit? (y/n): ";
cin >> user_confirm;
return user_confirm;
}
// Helping to test code from the discussion board of this HW
// //function test
// string test_reverse(string dna)
// {
// string temp_st;
// for (int i = dna.length()-1; i>=0; i--)
// {
// temp_st += dna[i];
// }
// return temp_st;
// }
/*
Write code for void function display_vector that accepts parameter const reference vector of strings.
The function will iterate through the vector and display a string per line.
*/
/*
Write code for void function update_vector_element that accepts parameter reference vector of strings,
a string vector search_value, and a string replace_value.
The function will iterate through the vector and search for the search_value and if found will
replace the vector element with the replace_value.
*/
| 20.353846 | 102 | 0.593852 | [
"vector"
] |
bb2fe8a6a96c249ce8d748d81598913441656a28 | 3,109 | hpp | C++ | RobWorkSim/src/rwsim/util/PlanarSupportPoseGenerator.hpp | ZLW07/RobWork | e713881f809d866b9a0749eeb15f6763e64044b3 | [
"Apache-2.0"
] | 1 | 2021-12-29T14:16:27.000Z | 2021-12-29T14:16:27.000Z | RobWorkSim/src/rwsim/util/PlanarSupportPoseGenerator.hpp | ZLW07/RobWork | e713881f809d866b9a0749eeb15f6763e64044b3 | [
"Apache-2.0"
] | null | null | null | RobWorkSim/src/rwsim/util/PlanarSupportPoseGenerator.hpp | ZLW07/RobWork | e713881f809d866b9a0749eeb15f6763e64044b3 | [
"Apache-2.0"
] | null | null | null | /*
* PlanarSupportPoseGenerator.hpp
*
* Created on: 19/08/2010
* Author: jimali
*/
#ifndef RWSIM_UTIL_PLANARSUPPORTPOSEGENERATOR_HPP_
#define RWSIM_UTIL_PLANARSUPPORTPOSEGENERATOR_HPP_
#include "SupportPose.hpp"
#include <rw/core/Ptr.hpp>
#include <rw/geometry/Plane.hpp>
#include <vector>
namespace rw { namespace geometry {
class ConvexHull3D;
}} // namespace rw::geometry
namespace rw { namespace geometry {
class Geometry;
}} // namespace rw::geometry
namespace rw { namespace geometry {
class TriMesh;
}} // namespace rw::geometry
namespace rw { namespace kinematics {
class Frame;
}} // namespace rw::kinematics
namespace rw { namespace kinematics {
class State;
}} // namespace rw::kinematics
namespace rwsim { namespace util {
/**
* @brief calculates the stable poses of an object when the support structure is
* planar.
*
* This support pose generator implementation calculates the convex hull of an object
* and projects the center of mass of the object onto all polygons of the convex hull.
* If the projection is inside the polygon then the polygon is considered as a stable
* support pose. Only projections that are within some threshold of the border of
* a support polygon is used to further generate support poses.
*/
class PlanarSupportPoseGenerator
{
public:
/**
* @brief constructor
* @return
*/
PlanarSupportPoseGenerator ();
/**
* @brief constructor - a convex hull generator can be supplied
* @param hullGenerator
* @return
*/
PlanarSupportPoseGenerator (rw::core::Ptr< rw::geometry::ConvexHull3D > hullGenerator);
/**
* @brief calculates the hull and the support poses.
* @param mesh
*/
void analyze (const rw::geometry::TriMesh& mesh);
void analyze (const std::vector< rw::core::Ptr< rw::geometry::Geometry > >& bodies,
rw::kinematics::Frame* ref, const rw::kinematics::State& state);
void calculateDistribution (int i, std::vector< rw::math::Transform3D<> >& poses,
std::vector< rw::math::Transform3D<> >& posesMises);
/**
* @brief gets the previously calculated support poses.
* @return
*/
std::vector< SupportPose > getSupportPoses ();
private:
void doAnalysis ();
bool isInside (const rw::math::Vector3D<>& v, size_t i);
void cleanup ()
{
_supportTriangles.clear ();
_supportPoses.clear ();
_supportPlanes.clear ();
}
private:
rw::core::Ptr< rw::geometry::ConvexHull3D > _hullGenerator;
std::vector< SupportPose > _supportPoses;
std::vector< rw::geometry::Plane > _supportPlanes;
std::vector< std::vector< rw::geometry::TriangleN1<double> > > _supportTriangles;
rw::math::Vector3D<> _com;
};
}} // namespace rwsim::util
#endif /* PLANARSUPPORTPOSEGENERATOR_HPP_ */
| 30.480392 | 95 | 0.624317 | [
"mesh",
"geometry",
"object",
"vector"
] |
bb34bf39f2201e02a3e146ae55df0d544b351d21 | 1,288 | cpp | C++ | Codeforces/713C/dp.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2018-02-14T01:59:31.000Z | 2018-03-28T03:30:45.000Z | Codeforces/713C/dp.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | null | null | null | Codeforces/713C/dp.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2017-12-30T02:46:35.000Z | 2018-03-28T03:30:49.000Z | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <string>
#include <cstring>
#include <iomanip>
#include <climits>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <functional>
#include <iterator>
#define SIZE 3010
using namespace std;
long long int arr[SIZE], valArr[SIZE];
long long int dp[SIZE][SIZE];
int main()
{
ios::sync_with_stdio(false);
int len;
cin >> len;
for (int i = 0; i < len; i++)
{
cin >> arr[i];
arr[i] -= i;
valArr[i] = arr[i];
}
if (len == 1)
{
cout << 0 << endl;
return 0;
}
long long int ans = LLONG_MAX;
sort(valArr + 0, valArr + len);
int valLen = unique(valArr, valArr + len) - valArr;
for (int j = 0; j < valLen; j++)
{
dp[0][j] = abs(arr[0] - valArr[j]);
}
for (int i = 1; i < len; i++)
{
long long int prevMinVal = LLONG_MAX;
for (int j = 0; j < valLen; j++)
{
prevMinVal = min(prevMinVal, dp[i - 1][j]);
dp[i][j] = prevMinVal + abs(arr[i] - valArr[j]);
if (i == len - 1)
{
ans = min(ans, dp[i][j]);
}
}
}
cout << ans << endl;
return 0;
} | 19.815385 | 60 | 0.501553 | [
"vector"
] |
7d6d5386a5b486f749c3857fa8a4065d1335d93a | 38,503 | cpp | C++ | wall.cpp | Czerwony-Kapturek/wallpaper-changer | e316d1d0eaa71defdcf623a7e4a92a376c4ce28c | [
"MIT"
] | 1 | 2020-11-03T09:21:55.000Z | 2020-11-03T09:21:55.000Z | wall.cpp | Czerwony-Kapturek/wallpaper-changer | e316d1d0eaa71defdcf623a7e4a92a376c4ce28c | [
"MIT"
] | null | null | null | wall.cpp | Czerwony-Kapturek/wallpaper-changer | e316d1d0eaa71defdcf623a7e4a92a376c4ce28c | [
"MIT"
] | null | null | null | //////////////////////////////
// Wallpaper Changer
//////////////////////////////
// Some magic needed for LoadIconMetric not to throw error while linking app
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
// COM definitions - for Wallpaper management object
#include "shobjidl.h"
// shell objects - needed for common directories in Windows
#include <Shlobj.h>
// GDI stuff for JPEG reading
#include <Gdiplus.h>
using namespace Gdiplus;
// std stuff
#include <fstream>
#include <string>
#include <map>
#include <set>
#include <vector>
using namespace std;
// Needed for logging timestamps
#include <time.h>
// Resources
#include "resource.h"
// Who we are...
const wchar_t* APP_NAME = L"Wallpaper Changer";
// Constant for converting minutes to miliseconds
#define ONE_MINUTE_MILLIS 60000
// Delay of the wallpaper update when display or HW configuration is discovered
// ...to aggregate multiple events OS fires quickly one after another
#define SET_WALLPAPER_TIMER_DELAY 3000
// ID of timer triggered after HW change
#define EVENT_SET_WALLPAPER_HW_CHANGE 0x5109
// ID of timer for periodic wallpaper updates
#define EVENT_SET_WALLPAPER_SCHEDULED 0x510A
// Message from our tray icon
#define MY_TRAY_MESSAGE WM_USER + 1
#define MY_MSG_FOLDER_CHANGED WM_USER + 2
// Try icon menu IDs
#define MENU_ID_EXIT 1
#define MENU_ID_SETTINGS 2
#define MENU_ID_SET_WALLPAPER 3
// Forward declarations for functions that do the actual job
void readWallpapers();
bool setWallpapers(bool change = 0);
unsigned long manageFolderWatcher(HWND window, bool start = true);
#pragma region "DEBUG LOGGER"
// A slow, primitive, always flushing, non thread safe file logger
class Logger
{
public:
Logger(const WCHAR* name, bool enable = true) : enabled(enable) {
PWSTR logDir;
SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, NULL, &logDir);
file = logDir;
CoTaskMemFree(logDir);
file += L"\\";
file += name;
file += L".log";
}
const Logger& operator<< (const WCHAR* msg) const {
if (!enabled)
return *this;
WCHAR buffer[80];
formatTimestamp(buffer);
wofstream f(file, wofstream::app);
f << buffer << msg << L"\n";
f.close();
return *this;
}
const Logger& operator<< (const int num) const {
if (!enabled)
return *this;
WCHAR buffer[80];
formatTimestamp(buffer);
wofstream f(file, wofstream::app);
f << buffer << to_wstring(num).c_str() << L"\n";
f.close();
return *this;
}
void enable(bool enable = true) {
enabled = enable;
}
private:
void formatTimestamp(wchar_t* buff) const {
time_t rawtime;
struct tm timeinfo;
time(&rawtime);
localtime_s(&timeinfo, &rawtime);
wcsftime(buff, 80, L"%F %T ", &timeinfo);
}
bool enabled;
wstring file;
} LOG(APP_NAME, true);
#pragma endregion
#pragma region "GENERIC SETTINGS UTILITIES"
// Class representing a single configurable value: integer, boolean or text.
// I think I liked the version that was storing values simply as strings better - was much much shorter.
class Value
{
public:
typedef enum { String, Int, Bool /*, Enum*/ } Type;
Value(bool default) : type(Type::Bool), boolVal(default) {}
Value(int default) : type(Type::Int), intVal(default) {}
Value(const wchar_t* default) : type(Type::String), strVal(new wstring(default)) {}
Value() { throw std::runtime_error("never to be used"); }
~Value() { if (type == Type::String && strVal != nullptr) delete strVal; }
// Get rid of the asignment operator and copy constructor
Value & operator=(const Value&) = delete;
Value(const Value& org) = delete;
// Move constructor - needed since we store settings in tuple and don't want copy
Value(Value&& org) {
type = org.type;
strVal = org.strVal;
org.strVal = nullptr;
}
public:
operator bool() const {
validateType(Type::Bool);
//return value == L"true";
return boolVal;
}
operator int() const {
validateType(Type::Int);
//return std::stoi(value);
return intVal;
}
operator const wchar_t*() const {
validateType(Type::String);
//return value.c_str();
return strVal->c_str();
}
void setVal(bool val) {
validateType(Type::Bool);
boolVal = val;
}
void setVal(int val) {
validateType(Type::Int);
intVal = val;
}
void setVal(const wchar_t* val) {
validateType(Type::String);
*strVal = val;
}
void fromString(const wchar_t* str) {
switch (type) {
case Type::Bool:
boolVal = wcscmp(str, L"true") == 0;
break;
case Type::Int:
intVal = std::stoi(str);
break;
case Type::String:
*strVal = str;
break;
}
}
void toString(wstring& outStr) const {
switch (type) {
case Type::Bool:
outStr = boolVal ? L"true" : L"false";
break;
case Type::Int:
outStr = std::to_wstring(intVal);
break;
case Type::String:
outStr = *strVal;
break;
}
}
private:
void validateType(Type t) const {
if (type != t) throw std::runtime_error("incorrect type of the settings variable");
}
Type type;
union {
bool boolVal;
int intVal;
wstring* strVal;
};
};
template<typename T>
class Settings
{
public:
Settings(tuple<T, const wchar_t*, Value>* tuples, int count, const wchar_t* fileName)
{
for (int i = 0; i < count; i++) {
this->key2setting.insert(make_pair(std::get<0>(tuples[i]), &std::get<2>(tuples[i])));
this->name2key.insert(make_pair(std::get<1>(tuples[i]), std::get<0>(tuples[i])));
}
PWSTR settingsDir;
SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, NULL, &settingsDir);
file = settingsDir;
CoTaskMemFree(settingsDir);
file += L"\\";
file += fileName;
file += L".ini";
load();
save();
}
Value& get(T key) {
return *key2setting[key];
}
void save() {
wstring val;
wofstream f(file);
for (auto const& s : name2key) {
key2setting[s.second]->toString(val);
f << s.first << L"=" << val << std::endl;
}
f.close();
}
private:
void load() {
wstring line;
wstring name;
wstring value;
wifstream f(file);
while (std::getline(f, line))
{
// Split the ini file line
size_t pos = line.find(L"=");
if (pos == wstring::npos) {
// Exactly two tokens should be there
continue;
}
name = line.substr(0, pos);
value = line.substr(pos + 1);
try {
T key = name2key.at(name.c_str());
Value* s = key2setting[key];
s->fromString(value.c_str());
}
catch (...) {
// Ignore setting not recognized
}
}
f.close();
}
private:
map<T, Value*> key2setting;
map<wstring, T> name2key;
wstring file;
};
#pragma endregion
#pragma region "APPLICATION SPECIFIC SETTINGS + CONFIG DIALOG"
typedef enum {
ImageDirectory,
AllowUpscaling,
AutoChangeImage,
AutoChangeInterval,
AllowedAspectRatioMismatch,
DisplayMode,
MultiMonPolicy,
EnableDebugLog
} WallSettings;
typedef enum {
Different = 0,
Same,
Whatever
} MultiMonImage;
// Some settings that are needed for this application
Settings<WallSettings>& getSettings()
{
PWSTR picturesDir;
SHGetKnownFolderPath(FOLDERID_Pictures, 0, NULL, &picturesDir);
static wstring picturesDirStr(picturesDir);
CoTaskMemFree(picturesDir);
static tuple<WallSettings, const wchar_t*, Value> mySettings[] = {
make_tuple(WallSettings::ImageDirectory, L"ImageDirectory", Value(picturesDirStr.c_str())),
make_tuple(WallSettings::AllowUpscaling, L"AllowUpscaling", Value(false)),
make_tuple(WallSettings::AutoChangeImage, L"AutoChangeImage", Value(false)),
make_tuple(WallSettings::AutoChangeInterval, L"AutoChangeInterval", Value(10)),
make_tuple(WallSettings::AllowedAspectRatioMismatch, L"AllowedAspectRatioMismatch", Value(1)),
make_tuple(WallSettings::DisplayMode, L"DisplayMode", Value(DWPOS_FILL)),
make_tuple(WallSettings::MultiMonPolicy, L"MultiMonPolicy", Value(0)),
make_tuple(WallSettings::EnableDebugLog, L"EnableDebugLog", Value(false)),
};
static Settings<WallSettings> theSettingsObj(mySettings, sizeof(mySettings) / sizeof(mySettings[0]), APP_NAME);
return theSettingsObj;
}
Settings<WallSettings>& SETTINGS = getSettings();
void enableAutoStart(bool ena) {
HKEY key = NULL;
RegCreateKey(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", &key);
if (ena) {
wchar_t exePath[MAX_PATH + 1];
GetModuleFileName(NULL, exePath, MAX_PATH + 1);
RegSetValueEx(key, APP_NAME, 0, REG_SZ, (BYTE*)exePath, (DWORD)(wcslen(exePath) + 1) * 2);
}
else {
RegDeleteValue(key, APP_NAME);
}
}
bool isAutoStartEnabled() {
HKEY key = NULL;
int err = RegOpenKeyEx(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_READ, &key);
if (err == ERROR_SUCCESS) {
DWORD type;
err = RegQueryValueEx(key, APP_NAME, NULL, &type, NULL, NULL);
if (err == ERROR_SUCCESS && type == REG_SZ) {
return true;
}
}
return false;
}
void initDlgAndLoadSettings(HWND window)
{
// Most settings are accessed via SETTINGS global, autostart goes directly to/from registry
SetDlgItemText(window, IDC_DIRECTORY, SETTINGS.get(WallSettings::ImageDirectory));
// No DWPOS_SPAN or DWPOS_TILE since the program installs separate wallpapers on every screen
const wchar_t* modesNames[] = {
L"Fill", // - cover entire screen, preserve aspect ratio, image may be clipped"
L"Fit", // - preserve aspect ratio, do not clip image - black bands possible around",
L"Stretch", // - scale to entire screen, no clipping, don't care about aspect ratio",
L"Center", // - don't scale, center of image at center of the screen",
};
DESKTOP_WALLPAPER_POSITION modeCodes[] = { DWPOS_FILL, DWPOS_FIT, DWPOS_STRETCH, DWPOS_CENTER };
HWND comboDisplayMode = GetDlgItem(window, IDC_DISPLAY_MODE);
int sel = 0;
for (int i = sizeof(modesNames) / sizeof(modesNames[0]) - 1; i >= 0; i--) {
SendMessage(comboDisplayMode, CB_INSERTSTRING, 0, (LPARAM)modesNames[i]);
SendMessage(comboDisplayMode, CB_SETITEMDATA, 0, modeCodes[i]);
if ((int)SETTINGS.get(WallSettings::DisplayMode) == modeCodes[i]) {
sel = i;
}
}
SendMessage(comboDisplayMode, CB_SETCURSEL, sel, 0);
CheckDlgButton(window, IDC_AUTO_START, isAutoStartEnabled() ? BST_CHECKED : BST_UNCHECKED);
CheckDlgButton(window, IDC_AUTO_CHANGE, (bool)SETTINGS.get(WallSettings::AutoChangeImage) ? BST_CHECKED : BST_UNCHECKED);
SendMessage(GetDlgItem(window, IDC_AUTO_CHANGE_SPIN), UDM_SETRANGE32, 0, MAXINT32);
// Setting buddy makes the editbox too narrow
//SendMessage(GetDlgItem(window, IDC_AUTO_CHANGE_SPIN), UDM_SETBUDDY, (int)GetDlgItem(window, IDC_AUTO_CHANGE_INTERVAL), 0);
SetDlgItemInt(window, IDC_AUTO_CHANGE_INTERVAL, (int)SETTINGS.get(WallSettings::AutoChangeInterval), false);
CheckDlgButton(window, IDC_ALLOW_UPSCALLING, (bool)SETTINGS.get(WallSettings::AllowUpscaling) ? BST_CHECKED : BST_UNCHECKED);
const wchar_t* multimonNames[] = { L"different images", L"the same image", L"(no preference)" };
MultiMonImage multiMonPolicy = MultiMonImage::Whatever;
HWND comboMultiMon = GetDlgItem(window, IDC_MULTIPLE_MONITORS);
for (int i = sizeof(multimonNames) / sizeof(multimonNames[0]) - 1; i >= 0; i--) {
SendMessage(comboMultiMon, CB_INSERTSTRING, 0, (LPARAM)multimonNames[i]);
SendMessage(comboMultiMon, CB_SETITEMDATA, 0, multiMonPolicy);
if ((int)SETTINGS.get(WallSettings::MultiMonPolicy) == multiMonPolicy) {
sel = i;
}
((int&)multiMonPolicy)--;
}
SendMessage(comboMultiMon, CB_SETCURSEL, sel, 0);
HWND aspect = GetDlgItem(window, IDC_ASPECT_RATIO_MISMATCH);
SendMessage(aspect, TBM_SETRANGE, true, MAKELONG(0, 1000)); // min. & max. positions
SendMessage(aspect, TBM_SETPOS, true, (int)SETTINGS.get(WallSettings::AllowedAspectRatioMismatch));
CheckDlgButton(window, IDC_DEBUG_LOG, (bool)SETTINGS.get(WallSettings::EnableDebugLog) ? BST_CHECKED : BST_UNCHECKED);
}
bool saveSettingsFromDlg(HWND window)
{
wchar_t directory[MAX_PATH + 1];
GetDlgItemText(window, IDC_DIRECTORY, directory, sizeof(directory));
DWORD dwAttrib = GetFileAttributes(directory);
if ((dwAttrib == INVALID_FILE_ATTRIBUTES) || (dwAttrib & FILE_ATTRIBUTE_DIRECTORY) == 0) {
// No such directory
MessageBox(window, L"The directory does not exist", L"Wrong value", MB_OK | MB_ICONEXCLAMATION);
return false;
}
int displayPos = (int)SendMessage(GetDlgItem(window, IDC_DISPLAY_MODE), CB_GETCURSEL, 0, 0);
int displayMode = (int)SendMessage(GetDlgItem(window, IDC_DISPLAY_MODE), CB_GETITEMDATA, displayPos, 0);
bool autoStart = IsDlgButtonChecked(window, IDC_AUTO_START);
bool autoChange = IsDlgButtonChecked(window, IDC_AUTO_CHANGE);
BOOL autoChangeIntervalOk;
int autoChangeInterval = GetDlgItemInt(window, IDC_AUTO_CHANGE_INTERVAL, &autoChangeIntervalOk, false);
if (!autoChangeIntervalOk) {
if (autoChange) {
// Valid integer required, notify that we have a problem
MessageBox(window, L"Image change interval must be a number grater than 0", L"Wrong value", MB_OK | MB_ICONEXCLAMATION);
return false;
}
}
bool allowUpscalling = IsDlgButtonChecked(window, IDC_ALLOW_UPSCALLING);
int multiMonPos = (int)SendMessage(GetDlgItem(window, IDC_MULTIPLE_MONITORS), CB_GETCURSEL, 0, 0);
int multiMonMode = (int)SendMessage(GetDlgItem(window, IDC_MULTIPLE_MONITORS), CB_GETITEMDATA, multiMonPos, 0);
HWND aspect = GetDlgItem(window, IDC_ASPECT_RATIO_MISMATCH);
int aspectMismatch = (int)SendMessage(aspect, TBM_GETPOS, 0, 0);
bool debug = IsDlgButtonChecked(window, IDC_DEBUG_LOG);
// All data ok, save the settings
SETTINGS.get(WallSettings::ImageDirectory).setVal(directory);
SETTINGS.get(WallSettings::DisplayMode).setVal(displayMode);
enableAutoStart(autoStart);
SETTINGS.get(WallSettings::AutoChangeImage).setVal(autoChange);
SETTINGS.get(WallSettings::AutoChangeInterval).setVal(autoChangeIntervalOk ? autoChangeInterval : 10);
SETTINGS.get(WallSettings::AllowUpscaling).setVal(allowUpscalling);
SETTINGS.get(WallSettings::MultiMonPolicy).setVal(multiMonMode);
SETTINGS.get(WallSettings::AllowedAspectRatioMismatch).setVal(aspectMismatch);
SETTINGS.get(WallSettings::EnableDebugLog).setVal(debug);
// In case of debug log configure the logging object
LOG.enable(debug);
SETTINGS.save();
return true;
}
// Reccomended way to use OS built-in folder selection dialog (copied from MSDN).
// They don't distinguish between good and evil anymore.
bool selectDirectory(wstring& dir)
{
HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
if (SUCCEEDED(hr))
{
IFileOpenDialog *pFileOpen;
// Create the FileOpenDialog object.
hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_ALL,
IID_IFileOpenDialog, reinterpret_cast<void**>(&pFileOpen));
if (SUCCEEDED(hr))
{
DWORD dwOptions;
if (SUCCEEDED(pFileOpen->GetOptions(&dwOptions)))
{
pFileOpen->SetOptions(dwOptions | FOS_PICKFOLDERS);
// Show the Open dialog box.
hr = pFileOpen->Show(NULL);
// Get the file name from the dialog box.
if (SUCCEEDED(hr))
{
IShellItem *pItem;
hr = pFileOpen->GetResult(&pItem);
if (SUCCEEDED(hr))
{
PWSTR pszFilePath;
hr = pItem->GetDisplayName(SIGDN_FILESYSPATH, &pszFilePath);
// Display the file name to the user.
if (SUCCEEDED(hr))
{
//MessageBox(NULL, pszFilePath, L"File Path", MB_OK);
dir = pszFilePath;
CoTaskMemFree(pszFilePath);
}
pItem->Release();
}
}
}
pFileOpen->Release();
}
CoUninitialize();
}
return SUCCEEDED(hr);
}
INT_PTR CALLBACK DialogProc(HWND window, unsigned int msg, WPARAM wp, LPARAM lp)
{
switch (msg)
{
case WM_INITDIALOG:
initDlgAndLoadSettings(window);
return TRUE;
case WM_CLOSE:
DestroyWindow(window);
return TRUE;
case WM_DESTROY:
return TRUE;
case WM_KEYDOWN:
if (VK_CANCEL == wp) {
EndDialog(window, IDCANCEL);
return TRUE;
}
return FALSE;
case WM_COMMAND:
switch (LOWORD(wp))
{
case IDCANCEL:
EndDialog(window, IDCANCEL);
return TRUE;
case IDOK:
if (saveSettingsFromDlg(window)) {
EndDialog(window, IDOK);
}
return TRUE;
case IDC_SELECT_DIR:
{
wstring dir;
if (selectDirectory(dir)) {
SetDlgItemText(window, IDC_DIRECTORY, dir.c_str());
}
}
}
break;
case WM_NOTIFY:
{
int code = ((LPNMHDR)lp)->code;
switch (code)
{
case UDN_DELTAPOS:
{
LPNMUPDOWN ud = (LPNMUPDOWN)lp;
BOOL autoChangeIntervalOk;
int autoChangeInterval = GetDlgItemInt(window, IDC_AUTO_CHANGE_INTERVAL, &autoChangeIntervalOk, false);
if (autoChangeIntervalOk) {
SetDlgItemInt(window, IDC_AUTO_CHANGE_INTERVAL, autoChangeInterval + ud->iDelta, false);
}
break;
}
}
}
}
return FALSE;
}
void showConfig(HWND window)
{
static bool showing = false;
if (showing) {
}
else {
// poorman's synchronization
showing = true;
wstring oldDir(SETTINGS.get(WallSettings::ImageDirectory));
INT_PTR res = DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_SETTINGS), window, DialogProc);
if (res == IDOK) {
readWallpapers();
// Set the wallpaper - if directory changed force changing the image
bool imageDirChanged = oldDir != (const wchar_t*)SETTINGS.get(WallSettings::ImageDirectory);
setWallpapers(imageDirChanged);
if (imageDirChanged) {
manageFolderWatcher(window);
}
if ((bool)SETTINGS.get(WallSettings::AutoChangeImage)) {
SetTimer(window, EVENT_SET_WALLPAPER_SCHEDULED, ONE_MINUTE_MILLIS * (int)SETTINGS.get(WallSettings::AutoChangeInterval), NULL);
}
else {
KillTimer(window, EVENT_SET_WALLPAPER_SCHEDULED);
}
}
showing = false;
}
}
#pragma endregion
#pragma region "MONITORING FOLDER WITH IMAGES"
typedef struct {
HANDLE mutex;
const wchar_t* folder;
HWND window;
} WatcherData;
unsigned long WINAPI folderWatcherThreadProc(void* data)
{
unsigned long waitStatus;
HANDLE changeHandle;
WatcherData watcherData = *(WatcherData*)data;
changeHandle = FindFirstChangeNotification(
watcherData.folder, // directory to watch
FALSE, // do not watch subtree
FILE_NOTIFY_CHANGE_FILE_NAME); // watch file name changes
HANDLE waitHandles[] = { changeHandle , watcherData.mutex};
while (true)
{
LOG << L"Watching folder " << watcherData.folder;
waitStatus = WaitForMultipleObjects(2, waitHandles, FALSE, INFINITE);
switch (waitStatus)
{
case WAIT_OBJECT_0:
LOG << L"Change in observed folder";
// Notify App window about the change
SendMessage(watcherData.window, MY_MSG_FOLDER_CHANGED, 0, 0);
if (FindNextChangeNotification(changeHandle) == FALSE) {
return 0;
}
break;
case WAIT_OBJECT_0 + 1:
LOG << L"Thread asked to terminate";
CloseHandle(watcherData.mutex);
FindCloseChangeNotification(changeHandle);
return 0;
default:
LOG << L"Unexpected notification";
FindCloseChangeNotification(changeHandle);
return 0;
}
}
}
unsigned long manageFolderWatcher(HWND window, bool start)
{
static WatcherData data = { 0 };
// If thread is already working ask it politely to terminate
if (data.mutex != NULL) {
ReleaseMutex(data.mutex);
data.mutex = 0;
}
if (!start) {
return NULL;
}
// The thread will not use the data anymore - use the structure again
data.mutex = CreateMutex(NULL, TRUE, L"");
if (data.mutex == NULL) {
LOG << L"Creating mutex for folder watcher syncyng failed";
return NULL;
}
data.window = window;
data.folder = SETTINGS.get(WallSettings::ImageDirectory);
unsigned long threadId;
HANDLE thread = CreateThread(
NULL, // default security attributes
0, // use default stack size
folderWatcherThreadProc, // thread function name
&data, // argument to thread function
0, // use default creation flags
&threadId); // returns the thread identifier
if (threadId == NULL)
{
LOG << L"Creating thread for watching folder changes";
}
LOG << L"Folder Watcher thread created";
return threadId;
}
#pragma endregion
#pragma region "WALLPAPER IMAGES HANDLING"
// Global:
// List of known images and their dimensions
map<wstring, int> file2dimensions;
// Read all images in the configured wallpapers directory and prapare
// map of picture name to their dimentions ratio
void readWallpapers()
{
file2dimensions.clear();
// For reading image properties GDI library will be used - it must by initialized first
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
WIN32_FIND_DATA ffd;
HANDLE hFind = INVALID_HANDLE_VALUE;
const wchar_t* imageDir = SETTINGS.get(WallSettings::ImageDirectory);
// Find the first file in the directory.
wstring searchTemplate(imageDir);
searchTemplate += L"\\*.jpg";
hFind = FindFirstFile(searchTemplate.c_str(), &ffd);
if (INVALID_HANDLE_VALUE == hFind)
{
// No files in this directory or no access
return;
}
// List all the files in the directory with some info about them.
do
{
wstring filePath(imageDir);
filePath += L"\\";
filePath += ffd.cFileName;
Image* img = Image::FromFile(filePath.c_str());
if (img == nullptr) {
continue;
}
UINT dimensions = (img->GetWidth() << 16) + img->GetHeight();
file2dimensions.insert(std::make_pair(filePath, dimensions));
delete img;
} while (FindNextFile(hFind, &ffd) != 0);
// De-initialize GDI
GdiplusShutdown(gdiplusToken);
}
// Set best wallpapers for currently attached monitors
// If change parameter is true the function will try not to use currently set wallpapers
bool setWallpapers(bool change)
{
LOG << L"setWallpapers()";
bool allowUpscaling = SETTINGS.get(WallSettings::AllowUpscaling);
int allowedMismatch = SETTINGS.get(WallSettings::AllowedAspectRatioMismatch);
MultiMonImage multiMonMode = (MultiMonImage)(int)SETTINGS.get(WallSettings::MultiMonPolicy);
HRESULT hr;
CoInitializeEx(nullptr, COINIT_MULTITHREADED);
IDesktopWallpaper* pWall = nullptr;
hr = CoCreateInstance(__uuidof(DesktopWallpaper), nullptr, CLSCTX_ALL, __uuidof(IDesktopWallpaper), reinterpret_cast<LPVOID *>(&pWall));
if (FAILED(hr) || pWall == nullptr) {
return false;
}
set<const wchar_t*> used;
UINT nMonitors = 0;
pWall->GetMonitorDevicePathCount(&nMonitors);
for (UINT monitor = 0; monitor < nMonitors; monitor++)
{
LPWSTR pId;
hr = pWall->GetMonitorDevicePathAt(monitor, &pId);
if (!FAILED(hr)) {
RECT rect;
hr = pWall->GetMonitorRECT(pId, &rect);
if (!FAILED(hr)) {
int ratio = 1000 * (rect.right - rect.left) / (rect.bottom - rect.top);
bool allowUpscalling = SETTINGS.get(WallSettings::AllowUpscaling);
set<const WCHAR*> properImages;
for (auto const& f2d : file2dimensions)
{
int w = f2d.second >> 16;
int h = f2d.second & 0xFFFF;
if (!allowUpscaling) {
if ((w < rect.right - rect.left) || (h < rect.bottom - rect.top)) {
continue;
}
}
int fileRatio = 1000 * w / h;
int mismatch = 1000 * (fileRatio - ratio) / ratio;
if (mismatch < 0) {
mismatch = -mismatch;
}
if (mismatch < allowedMismatch) {
properImages.insert(f2d.first.c_str());
}
}
if (properImages.size() == 1) {
// Only one good image found - just set it
const wchar_t* image = *properImages.begin();
hr = pWall->SetWallpaper(pId, image);
used.insert(image);
}
else if (properImages.size() > 1) {
// More than one matching options, choose right image depending on 'change' parameter
LPWSTR current;
pWall->GetWallpaper(pId, ¤t);
bool currentFound = false;
auto it = properImages.begin();
do {
if (wcscmp(current, *it) == 0) {
currentFound = true;
properImages.erase(it);
break;
}
} while (++it != properImages.end());
if (!change && currentFound) {
// The function was requested not to change Wallpaper and we found out, that
// curently set wallpaper is present in the images set - no action required
}
else {
// Multiple matching images available
if (multiMonMode == MultiMonImage::Different) {
// If prefference is to use different images on each
// screen remove from the pool already used ones
for (const auto & img : used) {
properImages.erase(img);
}
// ...but make sure something has left
if (properImages.size() == 0) {
properImages = used;
}
}
else if (multiMonMode == MultiMonImage::Same) {
// If prefference is to use the same image check if there is an intersection
// in sets of proper images and already used ones
set<const wchar_t*> usedAndProper;
for (const auto & img : used) {
if (properImages.find(img) != properImages.end()) {
usedAndProper.insert(img);
}
}
if (usedAndProper.size() > 0) {
// Some of the used images are proper - so use them
properImages = usedAndProper;
}
}
// Choose random image from available pool
int r = rand() % properImages.size();
it = properImages.begin();
advance(it, r);
hr = pWall->SetWallpaper(pId, *it);
used.insert(*it);
}
}
else {
// No suitable images for this screen - log error
}
}
}
}
pWall->SetPosition((DESKTOP_WALLPAPER_POSITION)(int)SETTINGS.get(WallSettings::DisplayMode));
pWall->Release();
CoUninitialize();
return true;
}
#pragma endregion
#pragma region "WINDOWS APPLICATION + GUI"
bool createNotificationIcon(HWND window, const WCHAR* tip)
{
LOG << L"Creating notification icon";
HICON icon = 0;
LoadIconMetric(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_WALL), LIM_SMALL, &icon);
NOTIFYICONDATA nid = {};
nid.cbSize = sizeof(NOTIFYICONDATA);
nid.uVersion = NOTIFYICON_VERSION_4;
// System uses window handle and ID to identify the icon - we just have one so ID == 0
nid.hWnd = window;
nid.uID = 0;
nid.hIcon = icon;
// Following message will be sent to our main window when user interacts with the tray icon
nid.uCallbackMessage = MY_TRAY_MESSAGE;
wcscpy_s(nid.szTip, tip);
// Add the icon with tooltip and sending messagess to the parent window
nid.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE;
return Shell_NotifyIcon(NIM_ADD, &nid);
// Set the version
Shell_NotifyIcon(NIM_SETVERSION, &nid);
}
// Get rid of the icon in tray
bool deleteNotificationIcon(HWND window)
{
LOG << L"Deleting notification icon";
// System uses window handle and ID to identify the icon
NOTIFYICONDATA nid = {};
nid.hWnd = window;
nid.uID = 0;
// Delete the icon
return Shell_NotifyIcon(NIM_DELETE, &nid);
}
// Show context menu for the tray icon
void showContextMenu(HWND window)
{
// They say it is needed...
SetForegroundWindow(window);
// Point at which to display the menu - not very carelully choosen..
POINT point;
GetCursorPos(&point);
HMENU menu = CreatePopupMenu();
AppendMenu(menu, MF_STRING, MENU_ID_SET_WALLPAPER, L"Set wallpaper");
AppendMenu(menu, MF_STRING, MENU_ID_SETTINGS, L"Settings...");
AppendMenu(menu, MF_STRING, MENU_ID_EXIT, L"Exit");
TrackPopupMenu(menu, TPM_CENTERALIGN | TPM_VCENTERALIGN | TPM_LEFTBUTTON, point.x, point.y, 0, window, NULL);
DestroyMenu(menu);
}
LRESULT __stdcall WndProc(HWND window, unsigned int msg, WPARAM wp, LPARAM lp)
{
// Windows Explorer (not Windows OS!) message - needed to handle case Explorer is restarted
const static UINT WM_TASKBARCREATED = ::RegisterWindowMessage(L"TaskbarCreated");
switch (msg)
{
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_KILLFOCUS:
ShowWindow(window, SW_HIDE);
return 0;
case WM_TIMER:
LOG << L"WM_TIMER";
if (wp == EVENT_SET_WALLPAPER_HW_CHANGE || wp == EVENT_SET_WALLPAPER_SCHEDULED) {
// If the timer was caused by HW change kill it - it is one time only event
KillTimer(window, EVENT_SET_WALLPAPER_HW_CHANGE);
setWallpapers(wp == EVENT_SET_WALLPAPER_SCHEDULED);
}
return 0;
case WM_COMMAND:
if (HIWORD(wp) == 0) {
switch (LOWORD(wp)) {
case MENU_ID_EXIT:
PostQuitMessage(0);
break;
case MENU_ID_SETTINGS:
//ShowWindow(window, SW_SHOW);
showConfig(window);
break;
case MENU_ID_SET_WALLPAPER:
setWallpapers(true);
// If periodic change of wallpapers is configured schedule the next update
if (SETTINGS.get(WallSettings::AutoChangeImage)) {
SetTimer(window, EVENT_SET_WALLPAPER_SCHEDULED, ONE_MINUTE_MILLIS * (int)SETTINGS.get(WallSettings::AutoChangeInterval), NULL);
}
break;
}
}
return 0;
case MY_TRAY_MESSAGE:
switch (lp)
{
case WM_LBUTTONDBLCLK:
setWallpapers(true);
// If periodic change of wallpapers is configured schedule (postpone) the next update
if (SETTINGS.get(WallSettings::AutoChangeImage)) {
SetTimer(window, EVENT_SET_WALLPAPER_SCHEDULED, ONE_MINUTE_MILLIS * (int)SETTINGS.get(WallSettings::AutoChangeInterval), NULL);
}
break;
case WM_RBUTTONDOWN:
case WM_CONTEXTMENU:
showContextMenu(window);
break;
}
return 0;
case MY_MSG_FOLDER_CHANGED:
readWallpapers();
setWallpapers();
return 0;
case WM_DISPLAYCHANGE:
case WM_DEVICECHANGE:
// Event that may require the wallpaper update happened - so let's do it!
LOG << ((msg == WM_DEVICECHANGE) ? L"WM_DEVICECHANGE" : L"WM_DISPLAYCHANGE");
SetTimer(window, EVENT_SET_WALLPAPER_HW_CHANGE, SET_WALLPAPER_TIMER_DELAY, NULL);
return 0;
case WM_SETTINGCHANGE:
if (wp == SPI_SETDESKWALLPAPER) {
// Event that may require the wallpaper update happened - so let's do it!
LOG << L"WM_SETTINGCHANGE ";
SetTimer(window, EVENT_SET_WALLPAPER_HW_CHANGE, SET_WALLPAPER_TIMER_DELAY, NULL);
return 0;
}
}
// Dynamically obtained message ID - cannot use in switch above
if (msg == WM_TASKBARCREATED) {
// Explorer was restarted - create the icon again (just in case delete it first)
deleteNotificationIcon(window);
createNotificationIcon(window, L"Double-click to set desktop wallpaper");
return 0;
}
return DefWindowProc(window, msg, wp, lp);
}
// Register window class and create main application window
HWND createWindow(const WCHAR* name, WNDPROC wndProc)
{
WNDCLASSEX wndclass = { sizeof(WNDCLASSEX), CS_DBLCLKS, wndProc,
0, 0, GetModuleHandle(0), LoadIcon(0,IDI_APPLICATION),
LoadCursor(0,IDC_ARROW), HBRUSH(COLOR_WINDOW + 1),
0, name, LoadIcon(0,IDI_APPLICATION) };
if (RegisterClassEx(&wndclass))
{
UINT flags = WS_OVERLAPPED | WS_CAPTION | WS_THICKFRAME;
HWND window = CreateWindowEx(0, name, name,
flags & ~WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT,
200, 200, 0, 0, GetModuleHandle(0), 0);
return window;
}
return NULL;
}
int __stdcall WinMain(_In_ HINSTANCE hInstance,
_In_ HINSTANCE hPrevInstance,
_In_ LPSTR lpCmdLine,
_In_ int nCmdShow)
{
LOG.enable(SETTINGS.get(WallSettings::EnableDebugLog));
LOG << L"Begin";
// Allow only single instance of the application
HWND oldWindow = FindWindow(APP_NAME, APP_NAME);
if (oldWindow != NULL) {
LOG << L"Activate previous instance and exit";
PostMessage(oldWindow, WM_COMMAND, MENU_ID_SET_WALLPAPER, 0);
return 0;
}
// Read list of images and apply wallpapers
readWallpapers();
setWallpapers(false);
// Create main window for message handling and tray icon
HWND window = createWindow(APP_NAME, WndProc);
// Create tray icon - the only way to interact with the program
createNotificationIcon(window, L"Double-click to set desktop wallpaper");
// Watch for changes in the directory with images
manageFolderWatcher(window);
// If configured schedule periodic wallpaper updates
if (SETTINGS.get(WallSettings::AutoChangeImage)) {
SetTimer(window, EVENT_SET_WALLPAPER_SCHEDULED, ONE_MINUTE_MILLIS * (int)SETTINGS.get(WallSettings::AutoChangeInterval), NULL);
}
// Main program loop
MSG msg;
while (GetMessage(&msg, 0, 0, 0)) DispatchMessage(&msg);
// Terminate folder watcher thread
manageFolderWatcher(window, false);
// Remove icon from tray
deleteNotificationIcon(window);
return 0;
}
#pragma endregion | 32.464587 | 194 | 0.587175 | [
"object",
"vector"
] |
7d731a134ecd682362020b4e019acfece24d52e3 | 5,141 | hpp | C++ | ChangeJournal/VolumeOptions.hpp | ambray/Ntfs | c610315b007d0d0d1666d878e4f9c955deb86077 | [
"MIT"
] | 20 | 2016-02-04T12:23:39.000Z | 2021-12-30T04:17:49.000Z | ChangeJournal/VolumeOptions.hpp | c3358/Ntfs | c610315b007d0d0d1666d878e4f9c955deb86077 | [
"MIT"
] | null | null | null | ChangeJournal/VolumeOptions.hpp | c3358/Ntfs | c610315b007d0d0d1666d878e4f9c955deb86077 | [
"MIT"
] | 6 | 2015-07-15T04:29:07.000Z | 2020-12-21T22:35:17.000Z | #pragma once
/********************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2015, Aaron M. Bray, aaron.m.bray@gmail.com
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*********************************************************************************/
#include <Windows.h>
#include <memory>
#include <string>
#include <stdint.h>
#include <vector>
#include <tuple>
#include <codecvt>
#include <functional>
#include "ntfs_defs.h"
#define EXTRACT_ATTRIBUTE(base, type)\
((base->NonResident) ? (type*)((unsigned char*)base + ((ntfs::NTFS_NONRESIDENT_ATTRIBUTE*)base)->RunArrayOffset) :\
(type*)((unsigned char*)base + ((ntfs::NTFS_RESIDENT_ATTRIBUTE*)base)->Offset))
#define VOL_API_INTERACTION_ERROR(msg, err)\
std::runtime_error(("[VolOps] " msg + std::to_string(__LINE__) + " " + std::to_string(err)))
#define VOL_API_INTERACTION_LASTERROR(msg)\
VOL_API_INTERACTION_ERROR(msg, GetLastError())
namespace ntfs {
constexpr uint32_t vol_data_size = sizeof(NTFS_VOLUME_DATA_BUFFER) + sizeof(NTFS_EXTENDED_VOLUME_DATA);
class VolOps {
public:
VolOps(std::shared_ptr<void> volHandle);
VolOps() = default;
~VolOps() = default;
VolOps(const VolOps&) = default;
VolOps(VolOps&&) = default;
VolOps& operator=(const VolOps&) = default;
VolOps& operator=(VolOps&&) = default;
/**
* Setter method for the HANDLE the class is currently operating on
*
* @param a shared_ptr containing the HANDLE (e.g., std::shared_ptr<void>(HANDLE, CloseHandle))
*/
void setVolHandle(std::shared_ptr<void> vh);
/**
* Gets a shared pointer containing the HANDLE the class instance is currently operating on
*
* @return a shared_ptr containing the HANDLE (e.g., std::shared_ptr<void>(HANDLE, CloseHandle))
*/
std::shared_ptr<void> getVolHandle();
/**
* Returns useful information about the current volume.
*
* @throws std::runtime_error if the operation fails fatally (e.g., bad handle)
* @return std::tuple containing (in order): the volume name, the filesystem name,
* and the max component length.
*/
std::tuple<std::string, std::string, unsigned long> getVolInfo();
/**
* Gets the volume data for the current volume.
*
* @throws std::runtime_error if the operation fails to complete
* @return a unique_ptr containing the NTFS_VOLUME_DATA_BUFFER, and is vol_data_size bytes in size.
*/
std::unique_ptr<NTFS_VOLUME_DATA_BUFFER> getVolData();
/**
* Returns the drive type of the current volume (See: MSDN documentation for GetDriveType())
*
* @throws std::runtime_error if getVolInfo fails
* @return unsigned long indicating the drive type
*/
unsigned long getDriveType();
/**
* Returns the file count on the current volume.
*
* @throws std::runtime_error if the operation is unable to complete.
* @return a uint64_t containing the total number of files on the volume.
*/
uint64_t getFileCount();
/**
* Gets a Master File Table record given its number
*
* @throws std::runtime_error if the operation is unable to complete
* @param recNum The file being requested
* @return A vector containing the MFT record.
*/
std::vector<uint8_t> getMftRecord(uint64_t recNum);
/**
* Retrieves an MFT record by number, maps callable func across all of its attributes, and returns the
* retrieved record back in a std::vector.
*
* @param recNum The record to retrieve
* @param func The function which will be provided each attribute
* @return the retrieved MFT record, after processing is complete (including changes made during by func)
*/
std::vector<uint8_t> processMftAttributes(uint64_t recNum, std::function<void(NTFS_ATTRIBUTE*)> func);
/**
* Maps func across the attributes contained within record.
*
* @param record A retrieved MFT record, stored within a vector.
* @param func The callable that will be mapped against all attributes contained in record.
* @return None
*/
void processMftAttributes(std::vector<uint8_t>& record, std::function<void(NTFS_ATTRIBUTE*)> func);
private:
std::shared_ptr<void> vhandle;
};
} | 36.460993 | 116 | 0.706672 | [
"vector"
] |
7d7685e894e056ed667dffcbd84deb6ac1d5f89f | 3,861 | hpp | C++ | apps/opencs/model/world/regionmap.hpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | apps/opencs/model/world/regionmap.hpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | apps/opencs/model/world/regionmap.hpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | #ifndef CSM_WOLRD_REGIONMAP_H
#define CSM_WOLRD_REGIONMAP_H
#include <map>
#include <string>
#include <vector>
#include <QAbstractTableModel>
#include "record.hpp"
#include "cell.hpp"
#include "cellcoordinates.hpp"
namespace CSMWorld
{
class Data;
/// \brief Model for the region map
///
/// This class does not holds any record data (other than for the purpose of buffering).
class RegionMap : public QAbstractTableModel
{
Q_OBJECT
public:
enum Role
{
Role_Region = Qt::UserRole,
Role_CellId = Qt::UserRole+1
};
private:
struct CellDescription
{
bool mDeleted;
std::string mRegion;
std::string mName;
CellDescription();
CellDescription (const Record<Cell>& cell);
};
Data& mData;
std::map<CellCoordinates, CellDescription> mMap;
CellCoordinates mMin; ///< inclusive
CellCoordinates mMax; ///< exclusive
std::map<std::string, unsigned int> mColours; ///< region ID, colour (RGBA)
CellCoordinates getIndex (const QModelIndex& index) const;
///< Translates a Qt model index into a cell index (which can contain negative components)
QModelIndex getIndex (const CellCoordinates& index) const;
CellCoordinates getIndex (const Cell& cell) const;
void buildRegions();
void buildMap();
void addCell (const CellCoordinates& index, const CellDescription& description);
///< May be called on a cell that is already in the map (in which case an update is
// performed)
void addCells (int start, int end);
void removeCell (const CellCoordinates& index);
///< May be called on a cell that is not in the map (in which case the call is ignored)
void addRegion (const std::string& region, unsigned int colour);
///< May be called on a region that is already listed (in which case an update is
/// performed)
///
/// \note This function does not update the region map.
void removeRegion (const std::string& region);
///< May be called on a region that is not listed (in which case the call is ignored)
///
/// \note This function does not update the region map.
void updateRegions (const std::vector<std::string>& regions);
///< Update cells affected by the listed regions
void updateSize();
std::pair<CellCoordinates, CellCoordinates> getSize() const;
public:
RegionMap (Data& data);
virtual int rowCount (const QModelIndex& parent = QModelIndex()) const;
virtual int columnCount (const QModelIndex& parent = QModelIndex()) const;
virtual QVariant data (const QModelIndex& index, int role = Qt::DisplayRole) const;
///< \note Calling this function with role==Role_CellId may return the ID of a cell
/// that does not exist.
virtual Qt::ItemFlags flags (const QModelIndex& index) const;
private slots:
void regionsAboutToBeRemoved (const QModelIndex& parent, int start, int end);
void regionsInserted (const QModelIndex& parent, int start, int end);
void regionsChanged (const QModelIndex& topLeft, const QModelIndex& bottomRight);
void cellsAboutToBeRemoved (const QModelIndex& parent, int start, int end);
void cellsInserted (const QModelIndex& parent, int start, int end);
void cellsChanged (const QModelIndex& topLeft, const QModelIndex& bottomRight);
};
}
#endif
| 31.909091 | 102 | 0.603212 | [
"vector",
"model"
] |
7d770bc571e7912a00299f39d93d1fb99a5a7acc | 3,715 | cpp | C++ | src/align/lmk_scan_rigid_pipe.cpp | ycjungSubhuman/Kinect-Face | b582bd8572e998617b5a0d197b4ac9bd4a9b42be | [
"CNRI-Python"
] | 7 | 2018-08-12T22:05:26.000Z | 2021-05-14T08:39:32.000Z | src/align/lmk_scan_rigid_pipe.cpp | ycjungSubhuman/Kinect-Face | b582bd8572e998617b5a0d197b4ac9bd4a9b42be | [
"CNRI-Python"
] | null | null | null | src/align/lmk_scan_rigid_pipe.cpp | ycjungSubhuman/Kinect-Face | b582bd8572e998617b5a0d197b4ac9bd4a9b42be | [
"CNRI-Python"
] | 2 | 2019-02-14T08:29:16.000Z | 2019-03-01T07:11:17.000Z | #include <iostream>
#include <pcl/common/copy_point.h>
#include <pcl/registration/transformation_estimation_svd_scale.h>
#include "align/rigid_pipe.h"
using namespace std;
using namespace telef::feature;
using namespace telef::types;
using namespace telef::face;
namespace telef::align {
LmkToScanRigidFittingPipe::LmkToScanRigidFittingPipe()
: BaseT(), transformation(Eigen::Matrix4f::Identity(4, 4)),
landmark3d(new pcl::PointCloud<pcl::PointXYZRGBA>()) {}
boost::shared_ptr<FittingSuite>
LmkToScanRigidFittingPipe::_processData(FeatureDetectSuite::Ptr in) {
// Only update transform and landmarks if features were found
auto feature = in->feature;
std::vector<int> rawCloudLmkIdx;
auto badlmks = std::vector<int>();
if (feature->points.size() > 0) {
// Find Correspondences between Image(Feature points) and Scan
// & Determine valid and invalid lmks
auto rawCloud = in->deviceInput->rawCloud;
auto mapping = in->deviceInput->img2cloudMapping;
auto prnetCorr = boost::make_shared<CloudT>();
auto scanCorr = boost::make_shared<CloudT>();
std::vector<int> rigidCorr;
int validLmkCount = 0;
for (long i = 0; i < feature->points.cols(); i++) {
try {
auto pointInd = mapping->getMappedPointId(
feature->points(0, i), feature->points(1, i));
auto scanPoint = rawCloud->at(pointInd);
scanCorr->push_back(scanPoint);
rawCloudLmkIdx.push_back(pointInd);
pcl::PointXYZRGBA lmkPoint;
pcl::copyPoint(scanPoint, lmkPoint);
lmkPoint.x = feature->points(0, i);
lmkPoint.y = feature->points(1, i);
lmkPoint.z = feature->points(2, i);
prnetCorr->push_back(lmkPoint);
// Only do rigid fitting on most rigid landmarks (exclude chin for scan
// alignment)
if (i > 16) {
rigidCorr.push_back(validLmkCount);
}
validLmkCount++;
} catch (std::out_of_range &e) {
badlmks.push_back(i);
}
}
// Align Lmks to Scan
Eigen::Matrix4f currentTransform;
// Fill correspondance list with range 0, ..., n valid landmarks.
pcl::registration::
TransformationEstimationSVDScale<pcl::PointXYZRGBA, pcl::PointXYZRGBA>
svd;
svd.estimateRigidTransformation(
*prnetCorr, rigidCorr, *scanCorr, rigidCorr, currentTransform);
// Return Aligned 3D Landmarks via PointCloud
auto transformed_lmks = boost::make_shared<CloudT>();
// You can either apply transform_1 or transform_2; they are the same
pcl::transformPointCloud(*prnetCorr, *transformed_lmks, currentTransform);
transformation = currentTransform;
Eigen::MatrixXf finalTransformedLmks =
transformation * (in->feature->points.colwise().homogeneous().matrix());
CloudPtrT lmk3d = boost::make_shared<CloudT>();
lmk3d->resize(static_cast<size_t>(finalTransformedLmks.cols()));
for (int i = 0; i < finalTransformedLmks.cols(); i++) {
lmk3d->points[i].x = finalTransformedLmks(0, i);
lmk3d->points[i].y = finalTransformedLmks(1, i);
lmk3d->points[i].z = finalTransformedLmks(2, i);
}
landmark3d.swap(lmk3d);
} else {
std::cout << "No Landmarks detected, using previous frames...\n";
};
boost::shared_ptr<FittingSuite> output = boost::make_shared<FittingSuite>();
output->landmark3d = landmark3d;
output->landmark2d.swap(feature);
output->invalid3dLandmarks = badlmks;
output->rawCloudLmkIdx = rawCloudLmkIdx;
output->rawImage.swap(in->deviceInput->rawImage);
output->rawCloud = in->deviceInput->rawCloud;
output->fx = in->deviceInput->fx;
output->fy = in->deviceInput->fy;
return output;
}
} // namespace telef::align | 35.721154 | 80 | 0.680215 | [
"vector",
"transform",
"3d"
] |
7d7917997ad54e60fc4140af2043e0c9e77a08d2 | 7,463 | cc | C++ | websocket/server.cc | hanoi404/websocket | 7f0ff5315d8c74d1ea82b2714ecd92f9b3ea0ba9 | [
"MIT"
] | 1 | 2021-04-08T00:48:44.000Z | 2021-04-08T00:48:44.000Z | websocket/server.cc | hanoi404/websocket | 7f0ff5315d8c74d1ea82b2714ecd92f9b3ea0ba9 | [
"MIT"
] | null | null | null | websocket/server.cc | hanoi404/websocket | 7f0ff5315d8c74d1ea82b2714ecd92f9b3ea0ba9 | [
"MIT"
] | 1 | 2021-11-22T08:50:21.000Z | 2021-11-22T08:50:21.000Z | // Copyright(c) 2019, 2020
// Yuming Meng <mengyuming@hotmail.com>.
// All rights reserved.
//
// Author: Yuming Meng
// Date: 2020-01-07 16:49
// Description: No.
#include "server.h"
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#if defined(__linux__)
#include <arpa/inet.h>
#include <netinet/in.h>
#include <fcntl.h>
#endif
#include <algorithm>
#include <chrono>
#include <memory>
#include <thread> // NOLINT.
#include <vector>
#include "socket_util.h"
#include "websocket.h"
namespace libwebsocket {
namespace {
constexpr int kMaxBufferLength = 4096;
} // namespace
// 重要参数初始化.
void WebSocketServer::Init(void) {
callback_ = [] (Socket const&, char const*, int const&) { return; };
deep_callback_ = [] (Socket const&, char const*, int const&) { return; };
is_ready_.store(false);
waiting_is_running_.store(false);
service_is_running_.store(false);
}
// 创建一个套接字, 并绑定到指定IP和端口上.
int WebSocketServer::InitServer(void) {
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(static_cast<uint16_t>(server_port_));
#if defined(__linux__)
addr.sin_addr.s_addr = inet_addr(server_ip_.c_str());
listen_socket_= socket(AF_INET, SOCK_STREAM, 0);
if (listen_socket_ == -1) {
printf("%s[%d]: Create socket failed!!!\n", __FUNCTION__, __LINE__);
return -1;
}
#elif defined(_WIN32)
WSADATA ws_data;
if (WSAStartup(MAKEWORD(2,2), &ws_data) != 0) {
return -1;
}
listen_socket_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listen_socket_ == INVALID_SOCKET) {
printf("%s[%d]: Create socket failed!!!\n", __FUNCTION__, __LINE__);
WSACleanup();
return -1;
}
addr.sin_addr.S_un.S_addr = inet_addr(server_ip_.c_str());
#endif
if (Bind(listen_socket_, reinterpret_cast<struct sockaddr *>(&addr),
sizeof(addr)) == -1) {
printf("%s[%d]: Connect to remote server failed!!!\n",
__FUNCTION__, __LINE__);
Close(listen_socket_);
#if defined(_WIN32)
WSACleanup();
#endif
return -1;
}
is_ready_.store(true);
return 0;
}
// 开启等待客户端连接和与客户端通信线程.
bool WebSocketServer::Run(void) {
if (!is_ready_) return false;
service_thread_ = std::thread(&WebSocketServer::ServiceHandler, this);
service_thread_.detach();
waiting_thread_ = std::thread(&WebSocketServer::WaitHandler, this);
waiting_thread_.detach();
return true;
}
// 停止服务线程, 关闭并清空所有已连接的套接字.
void WebSocketServer::Stop(void) {
if (listen_socket_ > 0) {
service_is_running_.store(false);
waiting_is_running_.store(false);
std::this_thread::sleep_for(std::chrono::seconds(3));
for (auto& socket : valid_sockets_) {
Close(socket);
}
valid_sockets_.clear();
Close(listen_socket_);
listen_socket_ = 0;
#if defined(_WIN32)
WSACleanup();
#endif
is_ready_.store(false);
}
}
int WebSocketServer::SendToOne(Socket const& socket,
char const* buffer, int const& size) {
for (auto client : valid_sockets_) {
if (socket == client) {
return Send(socket, buffer, size, 0);
}
}
return -1;
}
int WebSocketServer::SendToAll(char const* buffer, int const& size) {
for (auto socket : valid_sockets_) {
Send(socket, buffer, size, 0);
}
return 0;
}
// 等待客户端连接线程处理函数.
// 若有客户端进行连接, 先进行握手操作, 认证成功后
// 将转到主服务线程中进行数据交换.
void WebSocketServer::WaitHandler(void) {
waiting_is_running_.store(true);
if (Listen(listen_socket_, 10) < 0) {
waiting_is_running_.store(false);
Stop();
return;
}
struct sockaddr_in addr;
int len = sizeof(addr);
std::vector<uint8_t> msg;
std::string request;
std::string respond;
int ret = -1;
int timeout_ms = 3*10; // 超时时间, 100ms.
auto tp = std::chrono::steady_clock::now();
std::unique_ptr<char[]> buffer(
new char[kMaxBufferLength], std::default_delete<char[]>());
while(waiting_is_running_) {
// 等待新的连接.
Socket socket = Accept(listen_socket_,
reinterpret_cast<struct sockaddr *>(&addr), &len);
if (socket <= 0) {
printf("%s[%d]: Invalid socket!!!\n", __FUNCTION__, __LINE__);
break;
}
tp = std::chrono::steady_clock::now();
while (1) {
if ((ret = Recv(socket, buffer.get(), kMaxBufferLength, 0)) > 0) {
msg.assign(buffer.get(), buffer.get()+ret);
break;
} else if (ret == 0) {
printf("%s[%d]: Disconnect !!!\n", __FUNCTION__, __LINE__);
break;
} else {
#if defined(__linux__)
if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) {
continue;
}
#elif defined(_WIN32)
auto wsa_errno = WSAGetLastError();
if (wsa_errno == WSAEINTR || wsa_errno == WSAEWOULDBLOCK) continue;
#endif
printf("%s[%d]: Disconnect !!!\n", __FUNCTION__, __LINE__);
break;
}
// 检测超时退出.
if (std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now()-tp).count() >= timeout_ms) {
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
if (msg.empty()) {
Close(socket);
continue;
}
request.assign(msg.begin(), msg.end());
if (!IsHandShake(request)) {
Close(socket);
continue;
}
HandShake(request, &respond);
if (Send(socket, respond.c_str(), respond.size(), 0) < 0) {
Close(socket);
continue;
}
// 设置非阻塞模式.
#if defined(__linux__)
int flags = fcntl(socket, F_GETFL, 0);
fcntl(socket, F_SETFL, flags | O_NONBLOCK);
#elif defined(_WIN32)
unsigned long ul = 1;
if (ioctlsocket(socket, FIONBIO, (unsigned long *)&ul) == SOCKET_ERROR) {
printf("%s[%d]: Set socket nonblock failed !!!\n",
__FUNCTION__, __LINE__);
Close(socket);
continue;
}
#endif
// 保存已通过认证的socket.
valid_sockets_.push_back(socket);
}
waiting_is_running_.store(false);
Stop();
}
void WebSocketServer::ServiceHandler(void) {
service_is_running_.store(true);
int ret = -1;
bool alive = false;
std::unique_ptr<char[]> buffer(
new char[kMaxBufferLength], std::default_delete<char[]>());
std::vector<char> msg;
WebSocketMsg websocket_msg {};
while(service_is_running_) {
for (auto it = valid_sockets_.begin(); it != valid_sockets_.end(); ++it) {
if ((ret = Recv(*it, buffer.get(), kMaxBufferLength, 0)) > 0) {
if (!alive) alive = true;
deep_callback_(*it, buffer.get(), ret);
msg.assign(buffer.get(), buffer.get() + ret);
if (WebSocketFrameParse(msg, &websocket_msg) == 0) {
callback_(*it, websocket_msg.payload_content.data(),
websocket_msg.payload_content.size());
}
continue;
} else if (ret <= 0) {
if (ret < 0) {
#if defined(__linux__)
if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) {
continue;
}
#elif defined(_WIN32)
auto wsa_errno = WSAGetLastError();
if (wsa_errno == WSAEINTR || wsa_errno == WSAEWOULDBLOCK) continue;
#endif
}
printf("%s[%d]: Disconnect !!!\n", __FUNCTION__, __LINE__);
valid_sockets_.erase(it);
Close(*it);
if (!alive) alive = true;
break; // 删除连接时不再继续遍历, 而是重新开始遍历.
}
}
if (!alive) {
std::this_thread::sleep_for(std::chrono:: milliseconds(10));
}
alive = false;
}
service_is_running_.store(false);
Stop();
}
} // namespace libwebsocket
| 27.743494 | 78 | 0.626826 | [
"vector"
] |
7d8b2b7140443aa453131d2e7dcd579965b2fdcf | 9,814 | cpp | C++ | Sandbox/src/SandboxApp.cpp | Zheap/RabbitEngine | 42bf6c651f36180340434bf23b045d813c5d5e73 | [
"Apache-2.0"
] | null | null | null | Sandbox/src/SandboxApp.cpp | Zheap/RabbitEngine | 42bf6c651f36180340434bf23b045d813c5d5e73 | [
"Apache-2.0"
] | null | null | null | Sandbox/src/SandboxApp.cpp | Zheap/RabbitEngine | 42bf6c651f36180340434bf23b045d813c5d5e73 | [
"Apache-2.0"
] | null | null | null | #include <Rabbit.h>
#include "Platform/OpenGL/OpenGLShader.h"
#include "imgui/imgui.h"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
class ExampleLayer : public Rabbit::Layer
{
public:
ExampleLayer()
: Layer("Example"), m_Camera(-1.6f, 1.6f, -0.9f, 0.9f), m_CameraPosition(0.0f), m_SquarePosition(0.0f)
{
m_VertexArray.reset(Rabbit::VertexArray::Create());
float vertices[3 * 7] = {
-0.5f, -0.5f, 0.0f, 0.8f, 0.2f, 0.8f, 1.0f,
0.5f, -0.5f, 0.0f, 0.2f, 0.3f, 0.8f, 1.0f,
0.0f, 0.5f, 0.0f, 0.8f, 0.8f, 0.2f, 1.0f
};
// VertexBuffer
Rabbit::Ref<Rabbit::VertexBuffer> vertexBuffer;
vertexBuffer.reset(Rabbit::VertexBuffer::Create(vertices, sizeof(vertices)));
Rabbit::BufferLayout layout = {
{ Rabbit::ShaderDataType::Float3, "a_Position" },
{ Rabbit::ShaderDataType::Float4, "a_Color" }
};
vertexBuffer->SetLayout(layout);
m_VertexArray->AddVertexBuffer(vertexBuffer);
// IndexBuffer
uint32_t indices[3] = { 0, 1, 2 };
Rabbit::Ref<Rabbit::IndexBuffer> indexBuffer;
indexBuffer.reset(Rabbit::IndexBuffer::Create(indices, sizeof(indices) / sizeof(uint32_t)));
m_VertexArray->SetIndexBuffer(indexBuffer);
float squareVertices[5 * 4] = {
-0.5f, -0.5f, 0.0f, 0.0f, 0.0f,
0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.0f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
};
m_SquareVA.reset(Rabbit::VertexArray::Create());
Rabbit::Ref<Rabbit::VertexBuffer> squareVB;
squareVB.reset(Rabbit::VertexBuffer::Create(squareVertices, sizeof(squareVertices)));
squareVB->SetLayout({
{ Rabbit::ShaderDataType::Float3, "a_Position" },
{ Rabbit::ShaderDataType::Float2, "a_TexCoord" }
});
m_SquareVA->AddVertexBuffer(squareVB);
uint32_t squareIndices[6] = { 0, 1, 2, 2, 3, 0 };
Rabbit::Ref<Rabbit::IndexBuffer> squareIB;
squareIB.reset(Rabbit::IndexBuffer::Create(squareIndices, sizeof(squareIndices) / sizeof(uint32_t)));
m_SquareVA->SetIndexBuffer(squareIB);
std::string vertexSrc = R"(
#version 330 core
layout(location = 0) in vec3 a_Position;
layout(location = 1) in vec4 a_Color;
uniform mat4 u_ViewProjection;
uniform mat4 u_Transform;
out vec3 v_Position;
out vec4 v_Color;
void main()
{
v_Position = a_Position;
v_Color = a_Color;
gl_Position = u_ViewProjection * u_Transform * vec4(a_Position, 1.0);
}
)";
std::string fragmentSrc = R"(
#version 330 core
layout(location = 0) out vec4 color;
in vec3 v_Position;
in vec4 v_Color;
void main()
{
color = vec4(v_Position * 0.5 + 0.5, 1.0);
color = v_Color;
}
)";
m_Shader.reset(Rabbit::Shader::Create(vertexSrc, fragmentSrc));
std::string FlatColorShaderVertexSrc = R"(
#version 330 core
layout(location = 0) in vec3 a_Position;
uniform mat4 u_ViewProjection;
uniform mat4 u_Transform;
out vec3 v_Position;
void main()
{
v_Position = a_Position;
gl_Position = u_ViewProjection * u_Transform * vec4(a_Position, 1.0);
}
)";
std::string FlatColorShaderFragmentSrc = R"(
#version 330 core
layout(location = 0) out vec4 color;
in vec3 v_Position;
uniform vec3 u_Color;
void main()
{
color = vec4(u_Color, 1.0f);
}
)";
m_FlatColorShader.reset(Rabbit::Shader::Create(FlatColorShaderVertexSrc, FlatColorShaderFragmentSrc));
std::string textureShaderVertexSrc = R"(
#version 330 core
layout(location = 0) in vec3 a_Position;
layout(location = 1) in vec2 a_TexCoord;
uniform mat4 u_ViewProjection;
uniform mat4 u_Transform;
out vec2 v_TexCoord;
void main()
{
v_TexCoord = a_TexCoord;
gl_Position = u_ViewProjection * u_Transform * vec4(a_Position, 1.0);
}
)";
std::string textureShaderFragmentSrc = R"(
#version 330 core
layout(location = 0) out vec4 color;
in vec2 v_TexCoord;
uniform sampler2D u_Texture;
void main()
{
color = texture(u_Texture, v_TexCoord);
}
)";
m_TextureShader.reset(Rabbit::Shader::Create(textureShaderVertexSrc, textureShaderFragmentSrc));
// 我理解texture的本质是:把纹理(图片)的数据缓存到GPU中,配合着texCoord,将数据送给Fragment Shader里的color成员,绘制color即绘制纹理(图片)
m_Texture = Rabbit::Texture2D::Create("assets/textures/Checkerboard.png");
std::dynamic_pointer_cast<Rabbit::OpenGLShader>(m_TextureShader)->Bind();
std::dynamic_pointer_cast<Rabbit::OpenGLShader>(m_TextureShader)->UploadUniformInt("u_Texture", 0); // texture slot
}
void OnUpdate(Rabbit::Timestep ts) override
{
RB_TRACE("Delta time: {0}s ({1}ms)", ts.GetSeconds(), ts.GetMilliseconds());
if (Rabbit::Input::IsKeyPressed(RB_KEY_LEFT))
m_CameraPosition.x -= m_CameraMoveSpeed * ts;
else if (Rabbit::Input::IsKeyPressed(RB_KEY_RIGHT))
m_CameraPosition.x += m_CameraMoveSpeed * ts;
if (Rabbit::Input::IsKeyPressed(RB_KEY_UP))
m_CameraPosition.y += m_CameraMoveSpeed * ts;
else if (Rabbit::Input::IsKeyPressed(RB_KEY_DOWN))
m_CameraPosition.y -= m_CameraMoveSpeed * ts;
if (Rabbit::Input::IsKeyPressed(RB_KEY_A))
m_CameraRotation += m_CameraRotationSpeed * ts;
if (Rabbit::Input::IsKeyPressed(RB_KEY_D))
m_CameraRotation -= m_CameraRotationSpeed * ts;
//if (Rabbit::Input::IsKeyPressed(RB_KEY_J))
// m_SquarePosition.x -= m_SquareMoveSpeed * ts;
//else if (Rabbit::Input::IsKeyPressed(RB_KEY_L))
// m_SquarePosition.x += m_SquareMoveSpeed * ts;
//if (Rabbit::Input::IsKeyPressed(RB_KEY_I))
// m_SquarePosition.y += m_SquareMoveSpeed * ts;
//else if (Rabbit::Input::IsKeyPressed(RB_KEY_K))
// m_SquarePosition.y -= m_SquareMoveSpeed * ts;
Rabbit::RenderCommand::SetClearColor({ 0.1f, 0.1f, 0.1f, 1.0f });
Rabbit::RenderCommand::Clear();
m_Camera.SetPosition(m_CameraPosition);
m_Camera.SetRotation(m_CameraRotation);
Rabbit::Renderer::BeginScene(m_Camera);
glm::mat4 scale = glm::scale(glm::mat4(1.0f), glm::vec3(0.1f));
std::dynamic_pointer_cast<Rabbit::OpenGLShader>(m_FlatColorShader)->Bind();
std::dynamic_pointer_cast<Rabbit::OpenGLShader>(m_FlatColorShader)->UploadUniformFloat3("u_Color", m_SquareColor);
for (int y = 0; y < 20; y++)
{
for (int x = 0; x < 20; x++)
{
glm::vec3 pos(x * 0.11f, y * 0.11f, 0.0f);
glm::mat4 transform = glm::translate(glm::mat4(1.0f), pos) * scale;
Rabbit::Renderer::Submit(m_FlatColorShader, m_SquareVA, transform);
}
}
// Fragment里面的uniform sampler2D u_Texture; 会默认在buffer里面对应的slot = 0 位置查找texture data,所以即使上面m_TextureShader没有uploadUniformInt(u_Texture),图片也能正常绘制
m_Texture->Bind();
Rabbit::Renderer::Submit(m_TextureShader, m_SquareVA, glm::scale(glm::mat4(1.0f), glm::vec3(1.5f)));
// Triangle
// Rabbit::Renderer::Submit(m_Shader, m_VertexArray);
Rabbit::Renderer::EndScene();
}
void OnImGuiRender() override
{
ImGui::Begin("Settings");
ImGui::ColorEdit3("Square Color", glm::value_ptr(m_SquareColor));
ImGui::End();
}
void OnEvent(Rabbit::Event& event) override
{
//Rabbit::EventDispatcher dispatcher(event);
//dispatcher.Dispatch<Rabbit::KeyPressedEvent>(RB_BIND_EVENT_FN(ExampleLayer::OnKeyPressedEvent));
}
bool OnKeyPressedEvent(Rabbit::KeyPressedEvent& event)
{
// chunky movement on event system
//if (event.GetKeyCode() == RB_KEY_LEFT)
// m_CameraPosition.x -= m_CameraSpeed;
//if (event.GetKeyCode() == RB_KEY_RIGHT)
// m_CameraPosition.x += m_CameraSpeed;
//if (event.GetKeyCode() == RB_KEY_DOWN)
// m_CameraPosition.y -= m_CameraSpeed;
//if (event.GetKeyCode() == RB_KEY_UP)
// m_CameraPosition.y += m_CameraSpeed;
return false;
}
private:
Rabbit::Ref<Rabbit::Shader> m_Shader;
Rabbit::Ref<Rabbit::VertexArray> m_VertexArray;
Rabbit::Ref<Rabbit::Shader> m_FlatColorShader, m_TextureShader;
Rabbit::Ref<Rabbit::VertexArray> m_SquareVA;
Rabbit::Ref<Rabbit::Texture> m_Texture;
Rabbit::OrthographicCamera m_Camera;
glm::vec3 m_CameraPosition;
float m_CameraMoveSpeed = 5.0f;
float m_CameraRotation = 0.0f;
float m_CameraRotationSpeed = 180.0f;
glm::vec3 m_SquarePosition;
float m_SquareMoveSpeed = 5.0f;
glm::vec3 m_SquareColor = { 0.2f, 0.3f, 0.8f };
};
class Sandbox : public Rabbit::Application
{
public:
Sandbox()
{
PushLayer(new ExampleLayer());
}
~Sandbox() {}
};
Rabbit::Application* Rabbit::CreateApplication()
{
return new Sandbox();
} | 31.967427 | 151 | 0.587324 | [
"transform"
] |
7d8ca2f1191b1ddb20f19a0dd89d836b2cb459dd | 631 | hpp | C++ | surround360_camera_ctl_ui/source/CameraListView.hpp | DarwinSenior/Surround360 | 2031b7ca8aa5cc00dc23285cfdde2570842dc617 | [
"BSD-3-Clause"
] | 2,326 | 2016-07-26T17:05:59.000Z | 2021-08-14T11:37:25.000Z | surround360_camera_ctl_ui/source/CameraListView.hpp | wkMvg/Surround360 | 5a8eabd4acdef749bd49be57cad1078a2bf5189c | [
"BSD-3-Clause"
] | 273 | 2016-07-26T18:53:12.000Z | 2020-07-31T06:03:42.000Z | surround360_camera_ctl_ui/source/CameraListView.hpp | wkMvg/Surround360 | 5a8eabd4acdef749bd49be57cad1078a2bf5189c | [
"BSD-3-Clause"
] | 674 | 2016-07-26T17:16:56.000Z | 2021-07-19T08:33:36.000Z | /**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE_camera_ctl_ui file in the root directory of this subproject.
*/
#pragma once
#include <vector>
#include <tuple>
#include <set>
#include <gtkmm.h>
#include "CameraListModel.hpp"
#include "PointGrey.hpp"
namespace surround360 {
class CameraListView : public Gtk::TreeView {
private:
void getCameraSerialNumbers(SerialIndexVector& v);
public:
CameraListView();
void discoverCameras();
CameraListModel m_model;
Glib::RefPtr<Gtk::ListStore> m_store;
};
}
| 19.71875 | 70 | 0.722662 | [
"vector"
] |
7d9d547f75aa241892848f27656d1d84980fa838 | 1,788 | hpp | C++ | libs/opencl/include/sge/opencl/program/build_parameters.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/opencl/include/sge/opencl/program/build_parameters.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/opencl/include/sge/opencl/program/build_parameters.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_OPENCL_PROGRAM_BUILD_PARAMETERS_HPP_INCLUDED
#define SGE_OPENCL_PROGRAM_BUILD_PARAMETERS_HPP_INCLUDED
#include <sge/opencl/detail/symbol.hpp>
#include <sge/opencl/device/object_ref_sequence.hpp>
#include <sge/opencl/program/build_options.hpp>
#include <sge/opencl/program/notification_callback.hpp>
#include <sge/opencl/program/optional_notification_callback.hpp>
#include <fcppt/optional/object_impl.hpp>
namespace sge::opencl::program
{
class build_parameters
{
public:
SGE_OPENCL_DETAIL_SYMBOL
build_parameters();
[[nodiscard]] SGE_OPENCL_DETAIL_SYMBOL build_parameters
devices(sge::opencl::device::object_ref_sequence &&) &&;
[[nodiscard]] SGE_OPENCL_DETAIL_SYMBOL build_parameters
options(sge::opencl::program::build_options &&) &&;
[[nodiscard]] SGE_OPENCL_DETAIL_SYMBOL build_parameters
notification_callback(sge::opencl::program::notification_callback &&) &&;
using optional_object_ref_sequence =
fcppt::optional::object<sge::opencl::device::object_ref_sequence>;
[[nodiscard]] SGE_OPENCL_DETAIL_SYMBOL optional_object_ref_sequence const &devices() const;
[[nodiscard]] SGE_OPENCL_DETAIL_SYMBOL sge::opencl::program::build_options const &
build_options() const;
[[nodiscard]] SGE_OPENCL_DETAIL_SYMBOL
sge::opencl::program::optional_notification_callback const &
notification_callback() const;
private:
optional_object_ref_sequence devices_;
sge::opencl::program::build_options build_options_;
sge::opencl::program::optional_notification_callback notification_callback_;
};
}
#endif
| 31.368421 | 93 | 0.782998 | [
"object"
] |
7db0e4321cf91869ceceb16aaa5c7ec6fb4f7b4f | 69,134 | cc | C++ | tensorflow/core/example/example_parser_configuration.pb.cc | 1250281649/tensorflow | fc6f4ec813c3514fc4a4c6a078f3f492b3ff325c | [
"Apache-2.0"
] | null | null | null | tensorflow/core/example/example_parser_configuration.pb.cc | 1250281649/tensorflow | fc6f4ec813c3514fc4a4c6a078f3f492b3ff325c | [
"Apache-2.0"
] | 2 | 2021-08-25T15:57:35.000Z | 2022-02-10T01:09:32.000Z | tensorflow/core/example/example_parser_configuration.pb.cc | 1250281649/tensorflow | fc6f4ec813c3514fc4a4c6a078f3f492b3ff325c | [
"Apache-2.0"
] | null | null | null | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: tensorflow/core/example/example_parser_configuration.proto
#include "tensorflow/core/example/example_parser_configuration.pb.h"
#include <algorithm>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
extern PROTOBUF_INTERNAL_EXPORT_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_ExampleParserConfiguration_FeatureMapEntry_DoNotUse_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<2> scc_info_FeatureConfiguration_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<2> scc_info_FixedLenFeatureProto_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_tensorflow_2fcore_2fframework_2ftensor_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<2> scc_info_TensorProto_tensorflow_2fcore_2fframework_2ftensor_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_tensorflow_2fcore_2fframework_2ftensor_5fshape_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_TensorShapeProto_tensorflow_2fcore_2fframework_2ftensor_5fshape_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_VarLenFeatureProto_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto;
namespace tensorflow {
class VarLenFeatureProtoDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<VarLenFeatureProto> _instance;
} _VarLenFeatureProto_default_instance_;
class FixedLenFeatureProtoDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<FixedLenFeatureProto> _instance;
} _FixedLenFeatureProto_default_instance_;
class FeatureConfigurationDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<FeatureConfiguration> _instance;
const ::tensorflow::FixedLenFeatureProto* fixed_len_feature_;
const ::tensorflow::VarLenFeatureProto* var_len_feature_;
} _FeatureConfiguration_default_instance_;
class ExampleParserConfiguration_FeatureMapEntry_DoNotUseDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<ExampleParserConfiguration_FeatureMapEntry_DoNotUse> _instance;
} _ExampleParserConfiguration_FeatureMapEntry_DoNotUse_default_instance_;
class ExampleParserConfigurationDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<ExampleParserConfiguration> _instance;
} _ExampleParserConfiguration_default_instance_;
} // namespace tensorflow
static void InitDefaultsscc_info_ExampleParserConfiguration_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::tensorflow::_ExampleParserConfiguration_default_instance_;
new (ptr) ::tensorflow::ExampleParserConfiguration();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::tensorflow::ExampleParserConfiguration::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_ExampleParserConfiguration_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, 0, InitDefaultsscc_info_ExampleParserConfiguration_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto}, {
&scc_info_ExampleParserConfiguration_FeatureMapEntry_DoNotUse_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto.base,}};
static void InitDefaultsscc_info_ExampleParserConfiguration_FeatureMapEntry_DoNotUse_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::tensorflow::_ExampleParserConfiguration_FeatureMapEntry_DoNotUse_default_instance_;
new (ptr) ::tensorflow::ExampleParserConfiguration_FeatureMapEntry_DoNotUse();
}
::tensorflow::ExampleParserConfiguration_FeatureMapEntry_DoNotUse::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_ExampleParserConfiguration_FeatureMapEntry_DoNotUse_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, 0, InitDefaultsscc_info_ExampleParserConfiguration_FeatureMapEntry_DoNotUse_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto}, {
&scc_info_FeatureConfiguration_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto.base,}};
static void InitDefaultsscc_info_FeatureConfiguration_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::tensorflow::_FeatureConfiguration_default_instance_;
new (ptr) ::tensorflow::FeatureConfiguration();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::tensorflow::FeatureConfiguration::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<2> scc_info_FeatureConfiguration_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 2, 0, InitDefaultsscc_info_FeatureConfiguration_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto}, {
&scc_info_FixedLenFeatureProto_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto.base,
&scc_info_VarLenFeatureProto_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto.base,}};
static void InitDefaultsscc_info_FixedLenFeatureProto_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::tensorflow::_FixedLenFeatureProto_default_instance_;
new (ptr) ::tensorflow::FixedLenFeatureProto();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::tensorflow::FixedLenFeatureProto::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<2> scc_info_FixedLenFeatureProto_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 2, 0, InitDefaultsscc_info_FixedLenFeatureProto_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto}, {
&scc_info_TensorShapeProto_tensorflow_2fcore_2fframework_2ftensor_5fshape_2eproto.base,
&scc_info_TensorProto_tensorflow_2fcore_2fframework_2ftensor_2eproto.base,}};
static void InitDefaultsscc_info_VarLenFeatureProto_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::tensorflow::_VarLenFeatureProto_default_instance_;
new (ptr) ::tensorflow::VarLenFeatureProto();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::tensorflow::VarLenFeatureProto::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_VarLenFeatureProto_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_VarLenFeatureProto_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto}, {}};
static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto[5];
static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto = nullptr;
static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto = nullptr;
const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::tensorflow::VarLenFeatureProto, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::tensorflow::VarLenFeatureProto, dtype_),
PROTOBUF_FIELD_OFFSET(::tensorflow::VarLenFeatureProto, values_output_tensor_name_),
PROTOBUF_FIELD_OFFSET(::tensorflow::VarLenFeatureProto, indices_output_tensor_name_),
PROTOBUF_FIELD_OFFSET(::tensorflow::VarLenFeatureProto, shapes_output_tensor_name_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::tensorflow::FixedLenFeatureProto, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::tensorflow::FixedLenFeatureProto, dtype_),
PROTOBUF_FIELD_OFFSET(::tensorflow::FixedLenFeatureProto, shape_),
PROTOBUF_FIELD_OFFSET(::tensorflow::FixedLenFeatureProto, default_value_),
PROTOBUF_FIELD_OFFSET(::tensorflow::FixedLenFeatureProto, values_output_tensor_name_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::tensorflow::FeatureConfiguration, _internal_metadata_),
~0u, // no _extensions_
PROTOBUF_FIELD_OFFSET(::tensorflow::FeatureConfiguration, _oneof_case_[0]),
~0u, // no _weak_field_map_
offsetof(::tensorflow::FeatureConfigurationDefaultTypeInternal, fixed_len_feature_),
offsetof(::tensorflow::FeatureConfigurationDefaultTypeInternal, var_len_feature_),
PROTOBUF_FIELD_OFFSET(::tensorflow::FeatureConfiguration, config_),
PROTOBUF_FIELD_OFFSET(::tensorflow::ExampleParserConfiguration_FeatureMapEntry_DoNotUse, _has_bits_),
PROTOBUF_FIELD_OFFSET(::tensorflow::ExampleParserConfiguration_FeatureMapEntry_DoNotUse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::tensorflow::ExampleParserConfiguration_FeatureMapEntry_DoNotUse, key_),
PROTOBUF_FIELD_OFFSET(::tensorflow::ExampleParserConfiguration_FeatureMapEntry_DoNotUse, value_),
0,
1,
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::tensorflow::ExampleParserConfiguration, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::tensorflow::ExampleParserConfiguration, feature_map_),
};
static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::tensorflow::VarLenFeatureProto)},
{ 9, -1, sizeof(::tensorflow::FixedLenFeatureProto)},
{ 18, -1, sizeof(::tensorflow::FeatureConfiguration)},
{ 26, 33, sizeof(::tensorflow::ExampleParserConfiguration_FeatureMapEntry_DoNotUse)},
{ 35, -1, sizeof(::tensorflow::ExampleParserConfiguration)},
};
static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = {
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::tensorflow::_VarLenFeatureProto_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::tensorflow::_FixedLenFeatureProto_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::tensorflow::_FeatureConfiguration_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::tensorflow::_ExampleParserConfiguration_FeatureMapEntry_DoNotUse_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::tensorflow::_ExampleParserConfiguration_default_instance_),
};
const char descriptor_table_protodef_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) =
"\n:tensorflow/core/example/example_parser"
"_configuration.proto\022\ntensorflow\032,tensor"
"flow/core/framework/tensor_shape.proto\032&"
"tensorflow/core/framework/tensor.proto\032%"
"tensorflow/core/framework/types.proto\"\243\001"
"\n\022VarLenFeatureProto\022#\n\005dtype\030\001 \001(\0162\024.te"
"nsorflow.DataType\022!\n\031values_output_tenso"
"r_name\030\002 \001(\t\022\"\n\032indices_output_tensor_na"
"me\030\003 \001(\t\022!\n\031shapes_output_tensor_name\030\004 "
"\001(\t\"\273\001\n\024FixedLenFeatureProto\022#\n\005dtype\030\001 "
"\001(\0162\024.tensorflow.DataType\022+\n\005shape\030\002 \001(\013"
"2\034.tensorflow.TensorShapeProto\022.\n\rdefaul"
"t_value\030\003 \001(\0132\027.tensorflow.TensorProto\022!"
"\n\031values_output_tensor_name\030\004 \001(\t\"\232\001\n\024Fe"
"atureConfiguration\022=\n\021fixed_len_feature\030"
"\001 \001(\0132 .tensorflow.FixedLenFeatureProtoH"
"\000\0229\n\017var_len_feature\030\002 \001(\0132\036.tensorflow."
"VarLenFeatureProtoH\000B\010\n\006config\"\276\001\n\032Examp"
"leParserConfiguration\022K\n\013feature_map\030\001 \003"
"(\01326.tensorflow.ExampleParserConfigurati"
"on.FeatureMapEntry\032S\n\017FeatureMapEntry\022\013\n"
"\003key\030\001 \001(\t\022/\n\005value\030\002 \001(\0132 .tensorflow.F"
"eatureConfiguration:\0028\001B|\n\026org.tensorflo"
"w.exampleB ExampleParserConfigurationPro"
"tosP\001Z;github.com/tensorflow/tensorflow/"
"tensorflow/go/core/example\370\001\001b\006proto3"
;
static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto_deps[3] = {
&::descriptor_table_tensorflow_2fcore_2fframework_2ftensor_2eproto,
&::descriptor_table_tensorflow_2fcore_2fframework_2ftensor_5fshape_2eproto,
&::descriptor_table_tensorflow_2fcore_2fframework_2ftypes_2eproto,
};
static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto_sccs[5] = {
&scc_info_ExampleParserConfiguration_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto.base,
&scc_info_ExampleParserConfiguration_FeatureMapEntry_DoNotUse_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto.base,
&scc_info_FeatureConfiguration_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto.base,
&scc_info_FixedLenFeatureProto_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto.base,
&scc_info_VarLenFeatureProto_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto.base,
};
static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto_once;
static bool descriptor_table_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto_initialized = false;
const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto = {
&descriptor_table_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto_initialized, descriptor_table_protodef_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto, "tensorflow/core/example/example_parser_configuration.proto", 1037,
&descriptor_table_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto_once, descriptor_table_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto_sccs, descriptor_table_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto_deps, 5, 3,
schemas, file_default_instances, TableStruct_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto::offsets,
file_level_metadata_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto, 5, file_level_enum_descriptors_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto, file_level_service_descriptors_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto,
};
// Force running AddDescriptors() at dynamic initialization time.
static bool dynamic_init_dummy_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto), true);
namespace tensorflow {
// ===================================================================
void VarLenFeatureProto::InitAsDefaultInstance() {
}
class VarLenFeatureProto::_Internal {
public:
};
VarLenFeatureProto::VarLenFeatureProto()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:tensorflow.VarLenFeatureProto)
}
VarLenFeatureProto::VarLenFeatureProto(::PROTOBUF_NAMESPACE_ID::Arena* arena)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:tensorflow.VarLenFeatureProto)
}
VarLenFeatureProto::VarLenFeatureProto(const VarLenFeatureProto& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
values_output_tensor_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (!from._internal_values_output_tensor_name().empty()) {
values_output_tensor_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_values_output_tensor_name(),
GetArenaNoVirtual());
}
indices_output_tensor_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (!from._internal_indices_output_tensor_name().empty()) {
indices_output_tensor_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_indices_output_tensor_name(),
GetArenaNoVirtual());
}
shapes_output_tensor_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (!from._internal_shapes_output_tensor_name().empty()) {
shapes_output_tensor_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_shapes_output_tensor_name(),
GetArenaNoVirtual());
}
dtype_ = from.dtype_;
// @@protoc_insertion_point(copy_constructor:tensorflow.VarLenFeatureProto)
}
void VarLenFeatureProto::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_VarLenFeatureProto_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto.base);
values_output_tensor_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
indices_output_tensor_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
shapes_output_tensor_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
dtype_ = 0;
}
VarLenFeatureProto::~VarLenFeatureProto() {
// @@protoc_insertion_point(destructor:tensorflow.VarLenFeatureProto)
SharedDtor();
}
void VarLenFeatureProto::SharedDtor() {
GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
values_output_tensor_name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
indices_output_tensor_name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
shapes_output_tensor_name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
void VarLenFeatureProto::ArenaDtor(void* object) {
VarLenFeatureProto* _this = reinterpret_cast< VarLenFeatureProto* >(object);
(void)_this;
}
void VarLenFeatureProto::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
}
void VarLenFeatureProto::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const VarLenFeatureProto& VarLenFeatureProto::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_VarLenFeatureProto_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto.base);
return *internal_default_instance();
}
void VarLenFeatureProto::Clear() {
// @@protoc_insertion_point(message_clear_start:tensorflow.VarLenFeatureProto)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
values_output_tensor_name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
indices_output_tensor_name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
shapes_output_tensor_name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
dtype_ = 0;
_internal_metadata_.Clear();
}
const char* VarLenFeatureProto::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// .tensorflow.DataType dtype = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
_internal_set_dtype(static_cast<::tensorflow::DataType>(val));
} else goto handle_unusual;
continue;
// string values_output_tensor_name = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) {
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8(_internal_mutable_values_output_tensor_name(), ptr, ctx, "tensorflow.VarLenFeatureProto.values_output_tensor_name");
CHK_(ptr);
} else goto handle_unusual;
continue;
// string indices_output_tensor_name = 3;
case 3:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) {
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8(_internal_mutable_indices_output_tensor_name(), ptr, ctx, "tensorflow.VarLenFeatureProto.indices_output_tensor_name");
CHK_(ptr);
} else goto handle_unusual;
continue;
// string shapes_output_tensor_name = 4;
case 4:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) {
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8(_internal_mutable_shapes_output_tensor_name(), ptr, ctx, "tensorflow.VarLenFeatureProto.shapes_output_tensor_name");
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
::PROTOBUF_NAMESPACE_ID::uint8* VarLenFeatureProto::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:tensorflow.VarLenFeatureProto)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .tensorflow.DataType dtype = 1;
if (this->dtype() != 0) {
stream->EnsureSpace(&target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray(
1, this->_internal_dtype(), target);
}
// string values_output_tensor_name = 2;
if (this->values_output_tensor_name().size() > 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->_internal_values_output_tensor_name().data(), static_cast<int>(this->_internal_values_output_tensor_name().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE,
"tensorflow.VarLenFeatureProto.values_output_tensor_name");
target = stream->WriteStringMaybeAliased(
2, this->_internal_values_output_tensor_name(), target);
}
// string indices_output_tensor_name = 3;
if (this->indices_output_tensor_name().size() > 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->_internal_indices_output_tensor_name().data(), static_cast<int>(this->_internal_indices_output_tensor_name().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE,
"tensorflow.VarLenFeatureProto.indices_output_tensor_name");
target = stream->WriteStringMaybeAliased(
3, this->_internal_indices_output_tensor_name(), target);
}
// string shapes_output_tensor_name = 4;
if (this->shapes_output_tensor_name().size() > 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->_internal_shapes_output_tensor_name().data(), static_cast<int>(this->_internal_shapes_output_tensor_name().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE,
"tensorflow.VarLenFeatureProto.shapes_output_tensor_name");
target = stream->WriteStringMaybeAliased(
4, this->_internal_shapes_output_tensor_name(), target);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:tensorflow.VarLenFeatureProto)
return target;
}
size_t VarLenFeatureProto::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:tensorflow.VarLenFeatureProto)
size_t total_size = 0;
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// string values_output_tensor_name = 2;
if (this->values_output_tensor_name().size() > 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->_internal_values_output_tensor_name());
}
// string indices_output_tensor_name = 3;
if (this->indices_output_tensor_name().size() > 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->_internal_indices_output_tensor_name());
}
// string shapes_output_tensor_name = 4;
if (this->shapes_output_tensor_name().size() > 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->_internal_shapes_output_tensor_name());
}
// .tensorflow.DataType dtype = 1;
if (this->dtype() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->_internal_dtype());
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize(
_internal_metadata_, total_size, &_cached_size_);
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void VarLenFeatureProto::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:tensorflow.VarLenFeatureProto)
GOOGLE_DCHECK_NE(&from, this);
const VarLenFeatureProto* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<VarLenFeatureProto>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:tensorflow.VarLenFeatureProto)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:tensorflow.VarLenFeatureProto)
MergeFrom(*source);
}
}
void VarLenFeatureProto::MergeFrom(const VarLenFeatureProto& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:tensorflow.VarLenFeatureProto)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.values_output_tensor_name().size() > 0) {
_internal_set_values_output_tensor_name(from._internal_values_output_tensor_name());
}
if (from.indices_output_tensor_name().size() > 0) {
_internal_set_indices_output_tensor_name(from._internal_indices_output_tensor_name());
}
if (from.shapes_output_tensor_name().size() > 0) {
_internal_set_shapes_output_tensor_name(from._internal_shapes_output_tensor_name());
}
if (from.dtype() != 0) {
_internal_set_dtype(from._internal_dtype());
}
}
void VarLenFeatureProto::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:tensorflow.VarLenFeatureProto)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void VarLenFeatureProto::CopyFrom(const VarLenFeatureProto& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:tensorflow.VarLenFeatureProto)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool VarLenFeatureProto::IsInitialized() const {
return true;
}
void VarLenFeatureProto::InternalSwap(VarLenFeatureProto* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
values_output_tensor_name_.Swap(&other->values_output_tensor_name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
indices_output_tensor_name_.Swap(&other->indices_output_tensor_name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
shapes_output_tensor_name_.Swap(&other->shapes_output_tensor_name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
swap(dtype_, other->dtype_);
}
::PROTOBUF_NAMESPACE_ID::Metadata VarLenFeatureProto::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void FixedLenFeatureProto::InitAsDefaultInstance() {
::tensorflow::_FixedLenFeatureProto_default_instance_._instance.get_mutable()->shape_ = const_cast< ::tensorflow::TensorShapeProto*>(
::tensorflow::TensorShapeProto::internal_default_instance());
::tensorflow::_FixedLenFeatureProto_default_instance_._instance.get_mutable()->default_value_ = const_cast< ::tensorflow::TensorProto*>(
::tensorflow::TensorProto::internal_default_instance());
}
class FixedLenFeatureProto::_Internal {
public:
static const ::tensorflow::TensorShapeProto& shape(const FixedLenFeatureProto* msg);
static const ::tensorflow::TensorProto& default_value(const FixedLenFeatureProto* msg);
};
const ::tensorflow::TensorShapeProto&
FixedLenFeatureProto::_Internal::shape(const FixedLenFeatureProto* msg) {
return *msg->shape_;
}
const ::tensorflow::TensorProto&
FixedLenFeatureProto::_Internal::default_value(const FixedLenFeatureProto* msg) {
return *msg->default_value_;
}
void FixedLenFeatureProto::unsafe_arena_set_allocated_shape(
::tensorflow::TensorShapeProto* shape) {
if (GetArenaNoVirtual() == nullptr) {
delete shape_;
}
shape_ = shape;
if (shape) {
} else {
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.FixedLenFeatureProto.shape)
}
void FixedLenFeatureProto::clear_shape() {
if (GetArenaNoVirtual() == nullptr && shape_ != nullptr) {
delete shape_;
}
shape_ = nullptr;
}
void FixedLenFeatureProto::unsafe_arena_set_allocated_default_value(
::tensorflow::TensorProto* default_value) {
if (GetArenaNoVirtual() == nullptr) {
delete default_value_;
}
default_value_ = default_value;
if (default_value) {
} else {
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.FixedLenFeatureProto.default_value)
}
void FixedLenFeatureProto::clear_default_value() {
if (GetArenaNoVirtual() == nullptr && default_value_ != nullptr) {
delete default_value_;
}
default_value_ = nullptr;
}
FixedLenFeatureProto::FixedLenFeatureProto()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:tensorflow.FixedLenFeatureProto)
}
FixedLenFeatureProto::FixedLenFeatureProto(::PROTOBUF_NAMESPACE_ID::Arena* arena)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:tensorflow.FixedLenFeatureProto)
}
FixedLenFeatureProto::FixedLenFeatureProto(const FixedLenFeatureProto& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
values_output_tensor_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (!from._internal_values_output_tensor_name().empty()) {
values_output_tensor_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_values_output_tensor_name(),
GetArenaNoVirtual());
}
if (from._internal_has_shape()) {
shape_ = new ::tensorflow::TensorShapeProto(*from.shape_);
} else {
shape_ = nullptr;
}
if (from._internal_has_default_value()) {
default_value_ = new ::tensorflow::TensorProto(*from.default_value_);
} else {
default_value_ = nullptr;
}
dtype_ = from.dtype_;
// @@protoc_insertion_point(copy_constructor:tensorflow.FixedLenFeatureProto)
}
void FixedLenFeatureProto::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_FixedLenFeatureProto_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto.base);
values_output_tensor_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
::memset(&shape_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&dtype_) -
reinterpret_cast<char*>(&shape_)) + sizeof(dtype_));
}
FixedLenFeatureProto::~FixedLenFeatureProto() {
// @@protoc_insertion_point(destructor:tensorflow.FixedLenFeatureProto)
SharedDtor();
}
void FixedLenFeatureProto::SharedDtor() {
GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
values_output_tensor_name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (this != internal_default_instance()) delete shape_;
if (this != internal_default_instance()) delete default_value_;
}
void FixedLenFeatureProto::ArenaDtor(void* object) {
FixedLenFeatureProto* _this = reinterpret_cast< FixedLenFeatureProto* >(object);
(void)_this;
}
void FixedLenFeatureProto::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
}
void FixedLenFeatureProto::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const FixedLenFeatureProto& FixedLenFeatureProto::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_FixedLenFeatureProto_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto.base);
return *internal_default_instance();
}
void FixedLenFeatureProto::Clear() {
// @@protoc_insertion_point(message_clear_start:tensorflow.FixedLenFeatureProto)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
values_output_tensor_name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
if (GetArenaNoVirtual() == nullptr && shape_ != nullptr) {
delete shape_;
}
shape_ = nullptr;
if (GetArenaNoVirtual() == nullptr && default_value_ != nullptr) {
delete default_value_;
}
default_value_ = nullptr;
dtype_ = 0;
_internal_metadata_.Clear();
}
const char* FixedLenFeatureProto::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// .tensorflow.DataType dtype = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
_internal_set_dtype(static_cast<::tensorflow::DataType>(val));
} else goto handle_unusual;
continue;
// .tensorflow.TensorShapeProto shape = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) {
ptr = ctx->ParseMessage(_internal_mutable_shape(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .tensorflow.TensorProto default_value = 3;
case 3:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) {
ptr = ctx->ParseMessage(_internal_mutable_default_value(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// string values_output_tensor_name = 4;
case 4:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) {
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8(_internal_mutable_values_output_tensor_name(), ptr, ctx, "tensorflow.FixedLenFeatureProto.values_output_tensor_name");
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
::PROTOBUF_NAMESPACE_ID::uint8* FixedLenFeatureProto::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:tensorflow.FixedLenFeatureProto)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .tensorflow.DataType dtype = 1;
if (this->dtype() != 0) {
stream->EnsureSpace(&target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray(
1, this->_internal_dtype(), target);
}
// .tensorflow.TensorShapeProto shape = 2;
if (this->has_shape()) {
stream->EnsureSpace(&target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
2, _Internal::shape(this), target, stream);
}
// .tensorflow.TensorProto default_value = 3;
if (this->has_default_value()) {
stream->EnsureSpace(&target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
3, _Internal::default_value(this), target, stream);
}
// string values_output_tensor_name = 4;
if (this->values_output_tensor_name().size() > 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->_internal_values_output_tensor_name().data(), static_cast<int>(this->_internal_values_output_tensor_name().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE,
"tensorflow.FixedLenFeatureProto.values_output_tensor_name");
target = stream->WriteStringMaybeAliased(
4, this->_internal_values_output_tensor_name(), target);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:tensorflow.FixedLenFeatureProto)
return target;
}
size_t FixedLenFeatureProto::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:tensorflow.FixedLenFeatureProto)
size_t total_size = 0;
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// string values_output_tensor_name = 4;
if (this->values_output_tensor_name().size() > 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->_internal_values_output_tensor_name());
}
// .tensorflow.TensorShapeProto shape = 2;
if (this->has_shape()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*shape_);
}
// .tensorflow.TensorProto default_value = 3;
if (this->has_default_value()) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*default_value_);
}
// .tensorflow.DataType dtype = 1;
if (this->dtype() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->_internal_dtype());
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize(
_internal_metadata_, total_size, &_cached_size_);
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void FixedLenFeatureProto::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:tensorflow.FixedLenFeatureProto)
GOOGLE_DCHECK_NE(&from, this);
const FixedLenFeatureProto* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<FixedLenFeatureProto>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:tensorflow.FixedLenFeatureProto)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:tensorflow.FixedLenFeatureProto)
MergeFrom(*source);
}
}
void FixedLenFeatureProto::MergeFrom(const FixedLenFeatureProto& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:tensorflow.FixedLenFeatureProto)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.values_output_tensor_name().size() > 0) {
_internal_set_values_output_tensor_name(from._internal_values_output_tensor_name());
}
if (from.has_shape()) {
_internal_mutable_shape()->::tensorflow::TensorShapeProto::MergeFrom(from._internal_shape());
}
if (from.has_default_value()) {
_internal_mutable_default_value()->::tensorflow::TensorProto::MergeFrom(from._internal_default_value());
}
if (from.dtype() != 0) {
_internal_set_dtype(from._internal_dtype());
}
}
void FixedLenFeatureProto::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:tensorflow.FixedLenFeatureProto)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void FixedLenFeatureProto::CopyFrom(const FixedLenFeatureProto& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:tensorflow.FixedLenFeatureProto)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool FixedLenFeatureProto::IsInitialized() const {
return true;
}
void FixedLenFeatureProto::InternalSwap(FixedLenFeatureProto* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
values_output_tensor_name_.Swap(&other->values_output_tensor_name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
swap(shape_, other->shape_);
swap(default_value_, other->default_value_);
swap(dtype_, other->dtype_);
}
::PROTOBUF_NAMESPACE_ID::Metadata FixedLenFeatureProto::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void FeatureConfiguration::InitAsDefaultInstance() {
::tensorflow::_FeatureConfiguration_default_instance_.fixed_len_feature_ = const_cast< ::tensorflow::FixedLenFeatureProto*>(
::tensorflow::FixedLenFeatureProto::internal_default_instance());
::tensorflow::_FeatureConfiguration_default_instance_.var_len_feature_ = const_cast< ::tensorflow::VarLenFeatureProto*>(
::tensorflow::VarLenFeatureProto::internal_default_instance());
}
class FeatureConfiguration::_Internal {
public:
static const ::tensorflow::FixedLenFeatureProto& fixed_len_feature(const FeatureConfiguration* msg);
static const ::tensorflow::VarLenFeatureProto& var_len_feature(const FeatureConfiguration* msg);
};
const ::tensorflow::FixedLenFeatureProto&
FeatureConfiguration::_Internal::fixed_len_feature(const FeatureConfiguration* msg) {
return *msg->config_.fixed_len_feature_;
}
const ::tensorflow::VarLenFeatureProto&
FeatureConfiguration::_Internal::var_len_feature(const FeatureConfiguration* msg) {
return *msg->config_.var_len_feature_;
}
void FeatureConfiguration::set_allocated_fixed_len_feature(::tensorflow::FixedLenFeatureProto* fixed_len_feature) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual();
clear_config();
if (fixed_len_feature) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
::PROTOBUF_NAMESPACE_ID::Arena::GetArena(fixed_len_feature);
if (message_arena != submessage_arena) {
fixed_len_feature = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, fixed_len_feature, submessage_arena);
}
set_has_fixed_len_feature();
config_.fixed_len_feature_ = fixed_len_feature;
}
// @@protoc_insertion_point(field_set_allocated:tensorflow.FeatureConfiguration.fixed_len_feature)
}
void FeatureConfiguration::set_allocated_var_len_feature(::tensorflow::VarLenFeatureProto* var_len_feature) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual();
clear_config();
if (var_len_feature) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
::PROTOBUF_NAMESPACE_ID::Arena::GetArena(var_len_feature);
if (message_arena != submessage_arena) {
var_len_feature = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, var_len_feature, submessage_arena);
}
set_has_var_len_feature();
config_.var_len_feature_ = var_len_feature;
}
// @@protoc_insertion_point(field_set_allocated:tensorflow.FeatureConfiguration.var_len_feature)
}
FeatureConfiguration::FeatureConfiguration()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:tensorflow.FeatureConfiguration)
}
FeatureConfiguration::FeatureConfiguration(::PROTOBUF_NAMESPACE_ID::Arena* arena)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:tensorflow.FeatureConfiguration)
}
FeatureConfiguration::FeatureConfiguration(const FeatureConfiguration& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
clear_has_config();
switch (from.config_case()) {
case kFixedLenFeature: {
_internal_mutable_fixed_len_feature()->::tensorflow::FixedLenFeatureProto::MergeFrom(from._internal_fixed_len_feature());
break;
}
case kVarLenFeature: {
_internal_mutable_var_len_feature()->::tensorflow::VarLenFeatureProto::MergeFrom(from._internal_var_len_feature());
break;
}
case CONFIG_NOT_SET: {
break;
}
}
// @@protoc_insertion_point(copy_constructor:tensorflow.FeatureConfiguration)
}
void FeatureConfiguration::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_FeatureConfiguration_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto.base);
clear_has_config();
}
FeatureConfiguration::~FeatureConfiguration() {
// @@protoc_insertion_point(destructor:tensorflow.FeatureConfiguration)
SharedDtor();
}
void FeatureConfiguration::SharedDtor() {
GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
if (has_config()) {
clear_config();
}
}
void FeatureConfiguration::ArenaDtor(void* object) {
FeatureConfiguration* _this = reinterpret_cast< FeatureConfiguration* >(object);
(void)_this;
}
void FeatureConfiguration::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
}
void FeatureConfiguration::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const FeatureConfiguration& FeatureConfiguration::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_FeatureConfiguration_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto.base);
return *internal_default_instance();
}
void FeatureConfiguration::clear_config() {
// @@protoc_insertion_point(one_of_clear_start:tensorflow.FeatureConfiguration)
switch (config_case()) {
case kFixedLenFeature: {
if (GetArenaNoVirtual() == nullptr) {
delete config_.fixed_len_feature_;
}
break;
}
case kVarLenFeature: {
if (GetArenaNoVirtual() == nullptr) {
delete config_.var_len_feature_;
}
break;
}
case CONFIG_NOT_SET: {
break;
}
}
_oneof_case_[0] = CONFIG_NOT_SET;
}
void FeatureConfiguration::Clear() {
// @@protoc_insertion_point(message_clear_start:tensorflow.FeatureConfiguration)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
clear_config();
_internal_metadata_.Clear();
}
const char* FeatureConfiguration::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// .tensorflow.FixedLenFeatureProto fixed_len_feature = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) {
ptr = ctx->ParseMessage(_internal_mutable_fixed_len_feature(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .tensorflow.VarLenFeatureProto var_len_feature = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) {
ptr = ctx->ParseMessage(_internal_mutable_var_len_feature(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
::PROTOBUF_NAMESPACE_ID::uint8* FeatureConfiguration::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:tensorflow.FeatureConfiguration)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .tensorflow.FixedLenFeatureProto fixed_len_feature = 1;
if (_internal_has_fixed_len_feature()) {
stream->EnsureSpace(&target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
1, _Internal::fixed_len_feature(this), target, stream);
}
// .tensorflow.VarLenFeatureProto var_len_feature = 2;
if (_internal_has_var_len_feature()) {
stream->EnsureSpace(&target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(
2, _Internal::var_len_feature(this), target, stream);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:tensorflow.FeatureConfiguration)
return target;
}
size_t FeatureConfiguration::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:tensorflow.FeatureConfiguration)
size_t total_size = 0;
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
switch (config_case()) {
// .tensorflow.FixedLenFeatureProto fixed_len_feature = 1;
case kFixedLenFeature: {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*config_.fixed_len_feature_);
break;
}
// .tensorflow.VarLenFeatureProto var_len_feature = 2;
case kVarLenFeature: {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*config_.var_len_feature_);
break;
}
case CONFIG_NOT_SET: {
break;
}
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize(
_internal_metadata_, total_size, &_cached_size_);
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void FeatureConfiguration::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:tensorflow.FeatureConfiguration)
GOOGLE_DCHECK_NE(&from, this);
const FeatureConfiguration* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<FeatureConfiguration>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:tensorflow.FeatureConfiguration)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:tensorflow.FeatureConfiguration)
MergeFrom(*source);
}
}
void FeatureConfiguration::MergeFrom(const FeatureConfiguration& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:tensorflow.FeatureConfiguration)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
switch (from.config_case()) {
case kFixedLenFeature: {
_internal_mutable_fixed_len_feature()->::tensorflow::FixedLenFeatureProto::MergeFrom(from._internal_fixed_len_feature());
break;
}
case kVarLenFeature: {
_internal_mutable_var_len_feature()->::tensorflow::VarLenFeatureProto::MergeFrom(from._internal_var_len_feature());
break;
}
case CONFIG_NOT_SET: {
break;
}
}
}
void FeatureConfiguration::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:tensorflow.FeatureConfiguration)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void FeatureConfiguration::CopyFrom(const FeatureConfiguration& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:tensorflow.FeatureConfiguration)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool FeatureConfiguration::IsInitialized() const {
return true;
}
void FeatureConfiguration::InternalSwap(FeatureConfiguration* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(config_, other->config_);
swap(_oneof_case_[0], other->_oneof_case_[0]);
}
::PROTOBUF_NAMESPACE_ID::Metadata FeatureConfiguration::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
ExampleParserConfiguration_FeatureMapEntry_DoNotUse::ExampleParserConfiguration_FeatureMapEntry_DoNotUse() {}
ExampleParserConfiguration_FeatureMapEntry_DoNotUse::ExampleParserConfiguration_FeatureMapEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena)
: SuperType(arena) {}
void ExampleParserConfiguration_FeatureMapEntry_DoNotUse::MergeFrom(const ExampleParserConfiguration_FeatureMapEntry_DoNotUse& other) {
MergeFromInternal(other);
}
::PROTOBUF_NAMESPACE_ID::Metadata ExampleParserConfiguration_FeatureMapEntry_DoNotUse::GetMetadata() const {
return GetMetadataStatic();
}
void ExampleParserConfiguration_FeatureMapEntry_DoNotUse::MergeFrom(
const ::PROTOBUF_NAMESPACE_ID::Message& other) {
::PROTOBUF_NAMESPACE_ID::Message::MergeFrom(other);
}
// ===================================================================
void ExampleParserConfiguration::InitAsDefaultInstance() {
}
class ExampleParserConfiguration::_Internal {
public:
};
ExampleParserConfiguration::ExampleParserConfiguration()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:tensorflow.ExampleParserConfiguration)
}
ExampleParserConfiguration::ExampleParserConfiguration(::PROTOBUF_NAMESPACE_ID::Arena* arena)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(arena),
feature_map_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:tensorflow.ExampleParserConfiguration)
}
ExampleParserConfiguration::ExampleParserConfiguration(const ExampleParserConfiguration& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
feature_map_.MergeFrom(from.feature_map_);
// @@protoc_insertion_point(copy_constructor:tensorflow.ExampleParserConfiguration)
}
void ExampleParserConfiguration::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_ExampleParserConfiguration_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto.base);
}
ExampleParserConfiguration::~ExampleParserConfiguration() {
// @@protoc_insertion_point(destructor:tensorflow.ExampleParserConfiguration)
SharedDtor();
}
void ExampleParserConfiguration::SharedDtor() {
GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
}
void ExampleParserConfiguration::ArenaDtor(void* object) {
ExampleParserConfiguration* _this = reinterpret_cast< ExampleParserConfiguration* >(object);
(void)_this;
}
void ExampleParserConfiguration::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
}
void ExampleParserConfiguration::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const ExampleParserConfiguration& ExampleParserConfiguration::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_ExampleParserConfiguration_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto.base);
return *internal_default_instance();
}
void ExampleParserConfiguration::Clear() {
// @@protoc_insertion_point(message_clear_start:tensorflow.ExampleParserConfiguration)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
feature_map_.Clear();
_internal_metadata_.Clear();
}
const char* ExampleParserConfiguration::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// map<string, .tensorflow.FeatureConfiguration> feature_map = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) {
ptr -= 1;
do {
ptr += 1;
ptr = ctx->ParseMessage(&feature_map_, ptr);
CHK_(ptr);
if (!ctx->DataAvailable(ptr)) break;
} while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<10>(ptr));
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
::PROTOBUF_NAMESPACE_ID::uint8* ExampleParserConfiguration::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:tensorflow.ExampleParserConfiguration)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// map<string, .tensorflow.FeatureConfiguration> feature_map = 1;
if (!this->_internal_feature_map().empty()) {
typedef ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::FeatureConfiguration >::const_pointer
ConstPtr;
typedef ConstPtr SortItem;
typedef ::PROTOBUF_NAMESPACE_ID::internal::CompareByDerefFirst<SortItem> Less;
struct Utf8Check {
static void Check(ConstPtr p) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
p->first.data(), static_cast<int>(p->first.length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE,
"tensorflow.ExampleParserConfiguration.FeatureMapEntry.key");
}
};
if (stream->IsSerializationDeterministic() &&
this->_internal_feature_map().size() > 1) {
::std::unique_ptr<SortItem[]> items(
new SortItem[this->_internal_feature_map().size()]);
typedef ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::FeatureConfiguration >::size_type size_type;
size_type n = 0;
for (::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::FeatureConfiguration >::const_iterator
it = this->_internal_feature_map().begin();
it != this->_internal_feature_map().end(); ++it, ++n) {
items[static_cast<ptrdiff_t>(n)] = SortItem(&*it);
}
::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less());
for (size_type i = 0; i < n; i++) {
target = ExampleParserConfiguration_FeatureMapEntry_DoNotUse::Funcs::InternalSerialize(1, items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second, target, stream);
Utf8Check::Check(&(*items[static_cast<ptrdiff_t>(i)]));
}
} else {
for (::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::FeatureConfiguration >::const_iterator
it = this->_internal_feature_map().begin();
it != this->_internal_feature_map().end(); ++it) {
target = ExampleParserConfiguration_FeatureMapEntry_DoNotUse::Funcs::InternalSerialize(1, it->first, it->second, target, stream);
Utf8Check::Check(&(*it));
}
}
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:tensorflow.ExampleParserConfiguration)
return target;
}
size_t ExampleParserConfiguration::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:tensorflow.ExampleParserConfiguration)
size_t total_size = 0;
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// map<string, .tensorflow.FeatureConfiguration> feature_map = 1;
total_size += 1 *
::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(this->_internal_feature_map_size());
for (::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::FeatureConfiguration >::const_iterator
it = this->_internal_feature_map().begin();
it != this->_internal_feature_map().end(); ++it) {
total_size += ExampleParserConfiguration_FeatureMapEntry_DoNotUse::Funcs::ByteSizeLong(it->first, it->second);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize(
_internal_metadata_, total_size, &_cached_size_);
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void ExampleParserConfiguration::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:tensorflow.ExampleParserConfiguration)
GOOGLE_DCHECK_NE(&from, this);
const ExampleParserConfiguration* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<ExampleParserConfiguration>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:tensorflow.ExampleParserConfiguration)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:tensorflow.ExampleParserConfiguration)
MergeFrom(*source);
}
}
void ExampleParserConfiguration::MergeFrom(const ExampleParserConfiguration& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:tensorflow.ExampleParserConfiguration)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
feature_map_.MergeFrom(from.feature_map_);
}
void ExampleParserConfiguration::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:tensorflow.ExampleParserConfiguration)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void ExampleParserConfiguration::CopyFrom(const ExampleParserConfiguration& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:tensorflow.ExampleParserConfiguration)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool ExampleParserConfiguration::IsInitialized() const {
return true;
}
void ExampleParserConfiguration::InternalSwap(ExampleParserConfiguration* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
feature_map_.Swap(&other->feature_map_);
}
::PROTOBUF_NAMESPACE_ID::Metadata ExampleParserConfiguration::GetMetadata() const {
return GetMetadataStatic();
}
// @@protoc_insertion_point(namespace_scope)
} // namespace tensorflow
PROTOBUF_NAMESPACE_OPEN
template<> PROTOBUF_NOINLINE ::tensorflow::VarLenFeatureProto* Arena::CreateMaybeMessage< ::tensorflow::VarLenFeatureProto >(Arena* arena) {
return Arena::CreateMessageInternal< ::tensorflow::VarLenFeatureProto >(arena);
}
template<> PROTOBUF_NOINLINE ::tensorflow::FixedLenFeatureProto* Arena::CreateMaybeMessage< ::tensorflow::FixedLenFeatureProto >(Arena* arena) {
return Arena::CreateMessageInternal< ::tensorflow::FixedLenFeatureProto >(arena);
}
template<> PROTOBUF_NOINLINE ::tensorflow::FeatureConfiguration* Arena::CreateMaybeMessage< ::tensorflow::FeatureConfiguration >(Arena* arena) {
return Arena::CreateMessageInternal< ::tensorflow::FeatureConfiguration >(arena);
}
template<> PROTOBUF_NOINLINE ::tensorflow::ExampleParserConfiguration_FeatureMapEntry_DoNotUse* Arena::CreateMaybeMessage< ::tensorflow::ExampleParserConfiguration_FeatureMapEntry_DoNotUse >(Arena* arena) {
return Arena::CreateMessageInternal< ::tensorflow::ExampleParserConfiguration_FeatureMapEntry_DoNotUse >(arena);
}
template<> PROTOBUF_NOINLINE ::tensorflow::ExampleParserConfiguration* Arena::CreateMaybeMessage< ::tensorflow::ExampleParserConfiguration >(Arena* arena) {
return Arena::CreateMessageInternal< ::tensorflow::ExampleParserConfiguration >(arena);
}
PROTOBUF_NAMESPACE_CLOSE
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
| 45.363517 | 299 | 0.775769 | [
"object",
"shape"
] |
7db7c132c25d3c119cce69757955940f854433c1 | 27,169 | cpp | C++ | ToolKit/Markup/XTPMarkupInline.cpp | 11Zero/DemoBCG | 8f41d5243899cf1c82990ca9863fb1cb9f76491c | [
"MIT"
] | 2 | 2018-03-30T06:40:08.000Z | 2022-02-23T12:40:13.000Z | ToolKit/Markup/XTPMarkupInline.cpp | 11Zero/DemoBCG | 8f41d5243899cf1c82990ca9863fb1cb9f76491c | [
"MIT"
] | null | null | null | ToolKit/Markup/XTPMarkupInline.cpp | 11Zero/DemoBCG | 8f41d5243899cf1c82990ca9863fb1cb9f76491c | [
"MIT"
] | 1 | 2020-08-11T05:48:02.000Z | 2020-08-11T05:48:02.000Z | // XTPMarkupInline.cpp: implementation of the CXTPMarkupInline class.
//
// This file is a part of the XTREME TOOLKIT PRO MFC class library.
// (c)1998-2011 Codejock Software, All Rights Reserved.
//
// THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE
// RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN
// CONSENT OF CODEJOCK SOFTWARE.
//
// THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED
// IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO
// YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A
// SINGLE COMPUTER.
//
// CONTACT INFORMATION:
// support@codejock.com
// http://www.codejock.com
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Common/XTPSystemHelpers.h"
#include "Common/XTPResourceManager.h"
#include "Common/resource.h"
#include "XTPMarkupResourceDictionary.h"
#include "XTPMarkupInline.h"
#include "XTPMarkupDrawingContext.h"
#include "XTPMarkupBuilder.h"
#include "XTPMarkupTextBlock.h"
#include "XTPMarkupContext.h"
#include "XTPMarkupButton.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////////
// CXTPMarkupFrameworkContentElement
CXTPMarkupDependencyProperty* CXTPMarkupFrameworkContentElement::m_pTagProperty = NULL;
IMPLEMENT_MARKUPCLASS(L"FrameworkContentElement", CXTPMarkupFrameworkContentElement, CXTPMarkupInputElement);
void CXTPMarkupFrameworkContentElement::RegisterMarkupClass()
{
CXTPMarkupFrameworkElement::RegisterType();
m_pTagProperty = CXTPMarkupFrameworkElement::m_pTagProperty->AddOwner(MARKUP_TYPE(CXTPMarkupFrameworkContentElement));
}
CXTPMarkupFrameworkContentElement::CXTPMarkupFrameworkContentElement()
{
}
void CXTPMarkupFrameworkContentElement::OnPropertyChanged(CXTPMarkupDependencyProperty* pProperty, CXTPMarkupObject* pOldValue, CXTPMarkupObject* pNewValue)
{
CXTPMarkupInputElement::OnPropertyChanged(pProperty, pOldValue, pNewValue);
FireTriggers(pProperty, pNewValue);
if (pProperty->GetFlags() & CXTPMarkupPropertyMetadata::flagAffectsMeasure)
{
CXTPMarkupFrameworkElement* pParent = GetParent();
if (pParent) pParent->InvalidateMeasure();
}
if (pProperty->GetFlags() & CXTPMarkupPropertyMetadata::flagAffectsArrange)
{
CXTPMarkupFrameworkElement* pParent = GetParent();
if (pParent) pParent->InvalidateArrange();
}
if (pProperty->GetFlags() & CXTPMarkupPropertyMetadata::flagAffectsRender)
{
CXTPMarkupFrameworkElement* pParent = GetParent();
if (pParent) pParent->InvalidateVisual();
}
}
CXTPMarkupFrameworkElement* CXTPMarkupFrameworkContentElement::GetParent() const
{
CXTPMarkupObject* pParent = m_pLogicalParent;
while (pParent)
{
if (pParent->IsKindOf(MARKUP_TYPE(CXTPMarkupFrameworkElement)))
return (CXTPMarkupFrameworkElement*)pParent;
pParent = pParent->GetLogicalParent();
}
return NULL;
}
//////////////////////////////////////////////////////////////////////////
//
CXTPMarkupDependencyProperty* CXTPMarkupTextElement::m_pBackgroundProperty = NULL;
CXTPMarkupDependencyProperty* CXTPMarkupTextElement::m_pForegroundProperty = NULL;
CXTPMarkupDependencyProperty* CXTPMarkupTextElement::m_pFontSizeProperty = NULL;
CXTPMarkupDependencyProperty* CXTPMarkupTextElement::m_pFontWeightProperty = NULL;
CXTPMarkupDependencyProperty* CXTPMarkupTextElement::m_pFontFamilyProperty = NULL;
CXTPMarkupDependencyProperty* CXTPMarkupTextElement::m_pFontStyleProperty = NULL;
CXTPMarkupDependencyProperty* CXTPMarkupTextElement::m_pTextDecorationsProperty = NULL;
CXTPMarkupDependencyProperty* CXTPMarkupTextElement::m_pFontQualityProperty = NULL;
CXTPMarkupDependencyProperty* CXTPMarkupTextElement::m_pFontCharsetProperty = NULL;
//////////////////////////////////////////////////////////////////////////
// CXTPMarkupTextElement
IMPLEMENT_MARKUPCLASS(L"TextElement", CXTPMarkupTextElement, CXTPMarkupFrameworkContentElement);
void CXTPMarkupTextElement::RegisterMarkupClass()
{
m_pBackgroundProperty = CXTPMarkupDependencyProperty::RegisterAttached(L"Background", MARKUP_TYPE(CXTPMarkupBrush), MARKUP_TYPE(CXTPMarkupTextElement),
new CXTPMarkupPropertyMetadata(NULL, CXTPMarkupPropertyMetadata::flagInherited | CXTPMarkupPropertyMetadata::flagAffectsRender));
m_pForegroundProperty = CXTPMarkupDependencyProperty::RegisterAttached(L"Foreground", MARKUP_TYPE(CXTPMarkupBrush), MARKUP_TYPE(CXTPMarkupTextElement),
new CXTPMarkupPropertyMetadata(NULL, CXTPMarkupPropertyMetadata::flagInherited | CXTPMarkupPropertyMetadata::flagAffectsRender));
m_pFontSizeProperty = CXTPMarkupDependencyProperty::RegisterAttached(L"FontSize", MARKUP_TYPE(CXTPMarkupInt), MARKUP_TYPE(CXTPMarkupTextElement),
new CXTPMarkupPropertyMetadata(NULL, &CXTPMarkupBuilder::ConvertLength, CXTPMarkupPropertyMetadata::flagInherited | CXTPMarkupPropertyMetadata::flagAffectsMeasure));
m_pFontWeightProperty = CXTPMarkupDependencyProperty::RegisterAttached(L"FontWeight", MARKUP_TYPE(CXTPMarkupEnum), MARKUP_TYPE(CXTPMarkupTextElement),
new CXTPMarkupPropertyMetadata(NULL, &CXTPMarkupBuilder::ConvertFontWeight, CXTPMarkupPropertyMetadata::flagInherited | CXTPMarkupPropertyMetadata::flagAffectsMeasure));
m_pFontFamilyProperty = CXTPMarkupDependencyProperty::RegisterAttached(L"FontFamily", MARKUP_TYPE(CXTPMarkupString), MARKUP_TYPE(CXTPMarkupTextElement),
new CXTPMarkupPropertyMetadata(NULL, CXTPMarkupPropertyMetadata::flagInherited | CXTPMarkupPropertyMetadata::flagAffectsMeasure));
m_pFontStyleProperty = CXTPMarkupDependencyProperty::RegisterAttached(L"FontStyle", MARKUP_TYPE(CXTPMarkupEnum), MARKUP_TYPE(CXTPMarkupTextElement),
new CXTPMarkupPropertyMetadata(NULL, &CXTPMarkupBuilder::ConvertFontStyle, CXTPMarkupPropertyMetadata::flagInherited | CXTPMarkupPropertyMetadata::flagAffectsMeasure));
m_pTextDecorationsProperty = CXTPMarkupDependencyProperty::RegisterAttached(L"TextDecorations", MARKUP_TYPE(CXTPMarkupEnum), MARKUP_TYPE(CXTPMarkupTextElement),
new CXTPMarkupPropertyMetadata(NULL, &CXTPMarkupBuilder::ConvertTextDecorations, CXTPMarkupPropertyMetadata::flagInherited | CXTPMarkupPropertyMetadata::flagAffectsRender));
m_pFontQualityProperty = CXTPMarkupDependencyProperty::RegisterAttached(L"FontQuality", MARKUP_TYPE(CXTPMarkupEnum), MARKUP_TYPE(CXTPMarkupTextElement),
new CXTPMarkupPropertyMetadata(NULL, &CXTPMarkupBuilder::ConvertFontQuality, CXTPMarkupPropertyMetadata::flagInherited | CXTPMarkupPropertyMetadata::flagAffectsRender));
m_pFontCharsetProperty = CXTPMarkupDependencyProperty::RegisterAttached(L"FontCharset", MARKUP_TYPE(CXTPMarkupInt), MARKUP_TYPE(CXTPMarkupTextElement),
new CXTPMarkupPropertyMetadata(NULL, CXTPMarkupPropertyMetadata::flagInherited | CXTPMarkupPropertyMetadata::flagAffectsRender));
}
CXTPMarkupTextElement::CXTPMarkupTextElement()
{
}
CXTPMarkupTextElement::~CXTPMarkupTextElement()
{
}
void CXTPMarkupTextElement::SetBackground(CXTPMarkupBrush* pBrush)
{
SetValue(m_pBackgroundProperty, pBrush);
}
void CXTPMarkupTextElement::SetBackground(COLORREF clr)
{
SetValue(m_pBackgroundProperty, new CXTPMarkupSolidColorBrush(clr));
}
void CXTPMarkupTextElement::SetBackground(CXTPMarkupObject* pObject, CXTPMarkupBrush* pBrush)
{
pObject->SetValue(m_pBackgroundProperty, pBrush);
}
CXTPMarkupBrush* CXTPMarkupTextElement::GetBackground() const
{
return MARKUP_STATICCAST(CXTPMarkupBrush, GetValue(m_pBackgroundProperty));
}
void CXTPMarkupTextElement::SetForeground(CXTPMarkupBrush* pBrush)
{
SetValue(m_pForegroundProperty, pBrush);
}
void CXTPMarkupTextElement::SetForeground(COLORREF clr)
{
SetValue(m_pForegroundProperty, new CXTPMarkupSolidColorBrush(clr));
}
void CXTPMarkupTextElement::SetForeground(CXTPMarkupObject* pObject, CXTPMarkupBrush* pBrush)
{
pObject->SetValue(m_pForegroundProperty, pBrush);
}
CXTPMarkupBrush* CXTPMarkupTextElement::GetForeground() const
{
return MARKUP_STATICCAST(CXTPMarkupBrush, GetValue(m_pForegroundProperty));
}
void CXTPMarkupTextElement::SetFontSize(int nFontSize)
{
SetValue(m_pFontSizeProperty, new CXTPMarkupInt(nFontSize));
}
int CXTPMarkupTextElement::GetFontSize() const
{
CXTPMarkupInt* pFontSize = MARKUP_STATICCAST(CXTPMarkupInt, GetValue(m_pFontSizeProperty));
if (!pFontSize)
return -12;
return *pFontSize;
}
void CXTPMarkupTextElement::SetFontWeight(int nFontWeight)
{
SetValue(m_pFontWeightProperty, CXTPMarkupEnum::CreateValue(nFontWeight));
}
int CXTPMarkupTextElement::GetFontWeight() const
{
CXTPMarkupEnum* pFontWeigh = MARKUP_STATICCAST(CXTPMarkupEnum, GetValue(m_pFontWeightProperty));
if (!pFontWeigh)
return FW_NORMAL;
return *pFontWeigh;
}
void CXTPMarkupTextElement::SetFontStyle(int nFontStyle)
{
SetValue(m_pFontStyleProperty, CXTPMarkupEnum::CreateValue(nFontStyle));
}
int CXTPMarkupTextElement::GetFontStyle() const
{
CXTPMarkupEnum* pFontStyle = MARKUP_STATICCAST(CXTPMarkupEnum, GetValue(m_pFontStyleProperty));
if (!pFontStyle)
return 0;
return *pFontStyle;
}
void CXTPMarkupTextElement::SetTextDecorations(int nTextDecorations)
{
SetValue(m_pTextDecorationsProperty, CXTPMarkupEnum::CreateValue(nTextDecorations));
}
int CXTPMarkupTextElement::GetTextDecorations() const
{
CXTPMarkupEnum* pTextDecorations = MARKUP_STATICCAST(CXTPMarkupEnum, GetValue(m_pTextDecorationsProperty));
if (!pTextDecorations)
return 0;
return *pTextDecorations;
}
void CXTPMarkupTextElement::SetFontFamily(LPCWSTR lpszFontFamily)
{
SetValue(m_pFontFamilyProperty, CXTPMarkupString::CreateValue(lpszFontFamily));
}
LPCWSTR CXTPMarkupTextElement::GetFontFamily() const
{
CXTPMarkupString* pFontFamily = MARKUP_STATICCAST(CXTPMarkupString, GetValue(m_pFontFamilyProperty));
if (!pFontFamily)
return NULL;
return *pFontFamily;
}
CXTPMarkupInputElement* CXTPMarkupFrameworkContentElement::InputHitTest(CPoint /*point*/) const
{
return (CXTPMarkupInputElement*)this;
}
CRect CXTPMarkupFrameworkContentElement::GetBoundRect() const
{
return GetParent()->GetBoundRect();
}
//////////////////////////////////////////////////////////////////////////
// CXTPMarkupInline
CXTPMarkupDependencyProperty* CXTPMarkupInline::m_pBaselineAlignmentProperty = NULL;
IMPLEMENT_MARKUPCLASS(NULL, CXTPMarkupInline, CXTPMarkupTextElement);
void CXTPMarkupInline::RegisterMarkupClass()
{
m_pBaselineAlignmentProperty = CXTPMarkupDependencyProperty::Register(L"BaselineAlignment", MARKUP_TYPE(CXTPMarkupEnum), MARKUP_TYPE(CXTPMarkupInline),
new CXTPMarkupPropertyMetadata(NULL, &CXTPMarkupBuilder::ConvertBaselineAlignment, CXTPMarkupPropertyMetadata::flagAffectsArrange));
}
CXTPMarkupInline::CXTPMarkupInline()
{
m_nIndex = -1;
}
CXTPMarkupInline::~CXTPMarkupInline()
{
}
POSITION CXTPMarkupInline::GetContentStartPosition() const
{
return MARKUP_POSITION_EOF;
};
void CXTPMarkupInline::GetContentNextPosition(POSITION& pos) const
{
pos = NULL;
}
BOOL CXTPMarkupInline::IsWordBreakPosition(POSITION /*pos*/) const
{
return FALSE;
}
BOOL CXTPMarkupInline::IsLineBreakPosition(POSITION /*pos*/) const
{
return FALSE;
}
BOOL CXTPMarkupInline::IsCaretReturnPosition(POSITION /*pos*/) const
{
return FALSE;
}
BOOL CXTPMarkupInline::IsWhiteSpacePosition(POSITION /*pos*/) const
{
return FALSE;
}
void CXTPMarkupInline::PrepareMeasure(CXTPMarkupDrawingContext* /*pDC*/)
{
}
CSize CXTPMarkupInline::Measure(CXTPMarkupDrawingContext* /*pDC*/, POSITION /*posStart*/, POSITION /*posEnd*/)
{
return CSize(0, 0);
}
int CXTPMarkupInline::GetBaseline() const
{
return 0;
}
void CXTPMarkupInline::Arrange(CRect /*rcFinalRect*/, POSITION /*posStart*/, POSITION /*posEnd*/)
{
}
void CXTPMarkupInline::Render(CXTPMarkupDrawingContext* /*pDC*/, CRect /*rc*/, POSITION /*posStart*/, POSITION /*posEnd*/)
{
}
CXTPMarkupInline* CXTPMarkupInline::GetFirstInline() const
{
return (CXTPMarkupInline*)this;
}
CXTPMarkupInline* CXTPMarkupInline::GetNextInline() const
{
CXTPMarkupInlineCollection* pOwner = MARKUP_DYNAMICCAST(CXTPMarkupInlineCollection, m_pLogicalParent);
if (!pOwner)
return NULL;
if (pOwner->GetCount() > m_nIndex + 1)
return pOwner->GetInline(m_nIndex + 1)->GetFirstInline();
if (MARKUP_DYNAMICCAST(CXTPMarkupSpan, pOwner->GetLogicalParent()))
return ((CXTPMarkupSpan*)(pOwner->GetLogicalParent()))->GetNextInline();
return NULL;
}
CXTPMarkupTextBlock* CXTPMarkupInline::GetTextBlock() const
{
return MARKUP_STATICCAST(CXTPMarkupTextBlock, GetParent());
}
//////////////////////////////////////////////////////////////////////////
// CXTPMarkupRun
CXTPMarkupDependencyProperty* CXTPMarkupRun::m_pTextProperty = NULL;
IMPLEMENT_MARKUPCLASS(L"Run", CXTPMarkupRun, CXTPMarkupInline);
void CXTPMarkupRun::RegisterMarkupClass()
{
m_pTextProperty = CXTPMarkupDependencyProperty::Register(L"Text", MARKUP_TYPE(CXTPMarkupString), MARKUP_TYPE(CXTPMarkupRun),
new CXTPMarkupPropertyMetadata(NULL, CXTPMarkupPropertyMetadata::flagAffectsMeasure));
}
CXTPMarkupRun::CXTPMarkupRun()
{
m_nBaseline = 0;
m_pFont = NULL;
}
CXTPMarkupRun::~CXTPMarkupRun()
{
MARKUP_RELEASE(m_pFont);
}
void CXTPMarkupRun::OnFinalRelease()
{
MARKUP_RELEASE(m_pFont);
CXTPMarkupInline::OnFinalRelease();
}
void CXTPMarkupRun::SetContentObject(CXTPMarkupBuilder* pBuilder, CXTPMarkupObject* pContent)
{
if (IsStringObject(pContent))
{
SetValue(m_pTextProperty, pContent);
}
else
{
CXTPMarkupInline::SetContentObject(pBuilder, pContent);
}
}
BOOL CXTPMarkupRun::HasContentObject() const
{
return GetValue(m_pTextProperty) != NULL;
}
int CXTPMarkupRun::GetBaseline() const
{
return m_nBaseline;
}
CString CXTPMarkupRun::GetText() const
{
CXTPMarkupString* pString = MARKUP_STATICCAST(CXTPMarkupString, GetValue(m_pTextProperty));
if (!pString)
return _T("");
return CString((LPCWSTR)*pString);
}
LPCWSTR CXTPMarkupRun::GetTextW() const
{
CXTPMarkupString* pString = MARKUP_STATICCAST(CXTPMarkupString, GetValue(m_pTextProperty));
if (!pString)
return L"";
return (LPCWSTR)*pString;
}
void CXTPMarkupRun::SetText(LPCWSTR lpszText)
{
SetValue(m_pTextProperty, CXTPMarkupString::CreateValue(lpszText));
}
void CXTPMarkupRun::SetText(CXTPMarkupString* pText)
{
SetValue(m_pTextProperty, pText);
}
POSITION CXTPMarkupRun::GetContentStartPosition() const
{
CXTPMarkupString* pString = MARKUP_STATICCAST(CXTPMarkupString, GetValue(m_pTextProperty));
if (!pString)
return MARKUP_POSITION_EOF;
LPCWSTR lpszText = (LPCWSTR)(*pString);
if ((!lpszText) || (*lpszText == '\0'))
return MARKUP_POSITION_EOF;
return (POSITION)lpszText;
}
void CXTPMarkupRun::GetContentNextPosition(POSITION& pos) const
{
if (!pos || pos == MARKUP_POSITION_EOF)
return;
LPCWSTR lpszText = (LPCWSTR)pos;
if (*lpszText == '\0')
{
pos = MARKUP_POSITION_EOF;
}
else
{
lpszText++;
pos = (POSITION)lpszText;
}
}
BOOL CXTPMarkupRun::IsWordBreakPosition(POSITION pos) const
{
if (!pos)
return FALSE;
LPCWSTR lpszText = (LPCWSTR)pos;
return *lpszText == _T(' ') || *lpszText == _T('\t') || *lpszText == _T('\n');
}
BOOL CXTPMarkupRun::IsWhiteSpacePosition(POSITION pos) const
{
if (!pos)
return FALSE;
LPCWSTR lpszText = (LPCWSTR)pos;
return *lpszText == _T(' ') || *lpszText == _T('\t');
}
BOOL CXTPMarkupRun::IsLineBreakPosition(POSITION pos) const
{
if (!pos)
return FALSE;
LPCWSTR lpszText = (LPCWSTR)pos;
return *lpszText == _T('\n');
}
BOOL CXTPMarkupRun::IsCaretReturnPosition(POSITION pos) const
{
if (!pos)
return FALSE;
LPCWSTR lpszText = (LPCWSTR)pos;
return *lpszText == _T('\r');
}
void CXTPMarkupRun::GetLogFont(LOGFONT* pLogFont) const
{
memcpy(pLogFont, GetMarkupContext()->GetDefaultLogFont(), sizeof(LOGFONT));
CXTPMarkupInt* pFontSize = MARKUP_STATICCAST(CXTPMarkupInt, GetValue(m_pFontSizeProperty));
if (pFontSize)
{
pLogFont->lfHeight = - *pFontSize;
}
CXTPMarkupEnum* pFontWeight = MARKUP_STATICCAST(CXTPMarkupEnum, GetValue(m_pFontWeightProperty));
if (pFontWeight)
{
pLogFont->lfWeight = *pFontWeight;
}
CXTPMarkupEnum* pFontStyle = MARKUP_STATICCAST(CXTPMarkupEnum, GetValue(m_pFontStyleProperty));
if (pFontStyle)
{
pLogFont->lfItalic = *pFontStyle ? (BYTE)1 : (BYTE)0;
}
CXTPMarkupEnum* pFontQuality = MARKUP_STATICCAST(CXTPMarkupEnum, GetValue(m_pFontQualityProperty));
if (pFontQuality && XTPSystemVersion()->IsClearTypeTextQualitySupported())
{
pLogFont->lfQuality = (BYTE)*pFontQuality;
}
CXTPMarkupInt* pFontCharset = MARKUP_STATICCAST(CXTPMarkupInt, GetValue(m_pFontCharsetProperty));
if (pFontCharset)
{
pLogFont->lfCharSet = (BYTE)*pFontCharset;
}
CXTPMarkupString* pFontFamily = MARKUP_STATICCAST(CXTPMarkupString, GetValue(m_pFontFamilyProperty));
if (pFontFamily)
{
LPCWSTR lpszFaceName = *pFontFamily;
LPTSTR lpszLogFontFaceName = pLogFont->lfFaceName;
while ((*lpszLogFontFaceName++ = (TCHAR)*(lpszFaceName++)) != 0);
}
}
void CXTPMarkupRun::PrepareMeasure(CXTPMarkupDrawingContext* pDC)
{
LOGFONT lf;
GetLogFont(&lf);
if (m_pFont == NULL || !CXTPMarkupContext::CompareFont(&m_pFont->m_lf, &lf))
{
CXTPMarkupFont* pFont = GetMarkupContext()->GetFont(&lf);
MARKUP_RELEASE(m_pFont);
m_pFont = pFont;
}
pDC->SetFont(m_pFont);
TEXTMETRIC tm;
HDC hDC = pDC->GetDC();
GetTextMetrics(hDC, &tm);
pDC->ReleaseDC(hDC);
m_nBaseline = tm.tmDescent;
}
CSize CXTPMarkupRun::Measure(CXTPMarkupDrawingContext* pDC, POSITION posStart, POSITION posEnd)
{
if (posStart == NULL || posEnd == NULL || posEnd == MARKUP_POSITION_EOF)
return CSize(0, 0);
pDC->SetFont(m_pFont);
if (posEnd == posStart)
{
SIZE sz = pDC->GetTextExtent(L" ", 1);
return CSize(0, sz.cy);
}
LPCWSTR lpszText = (LPCWSTR)posStart;
int nCount = int(posEnd - posStart) / sizeof(WCHAR);
SIZE sz = pDC->GetTextExtent(lpszText, nCount);
return sz;
}
void CXTPMarkupRun::Render(CXTPMarkupDrawingContext* pDC, CRect rc, POSITION posStart, POSITION posEnd)
{
if (posStart == NULL || posEnd == NULL || posEnd == posStart || posEnd == MARKUP_POSITION_EOF)
return;
LPCWSTR lpszText = (LPCWSTR)posStart;
UINT nCount = UINT(posEnd - posStart) / sizeof(WCHAR);
pDC->SetFont(m_pFont);
pDC->DrawTextLine(lpszText, nCount, rc);
}
//////////////////////////////////////////////////////////////////////////
// CXTPMarkupLineBreak
IMPLEMENT_MARKUPCLASS(L"LineBreak", CXTPMarkupLineBreak, CXTPMarkupRun);
void CXTPMarkupLineBreak::RegisterMarkupClass()
{
}
CXTPMarkupLineBreak::CXTPMarkupLineBreak()
{
SetText(L"\n");
}
//////////////////////////////////////////////////////////////////////////
// CXTPMarkupInlineCollection
IMPLEMENT_MARKUPCLASS(NULL, CXTPMarkupInlineCollection, CXTPMarkupCollection);
void CXTPMarkupInlineCollection::RegisterMarkupClass()
{
}
CXTPMarkupInlineCollection::CXTPMarkupInlineCollection()
{
m_pElementType = MARKUP_TYPE(CXTPMarkupInline);
}
CXTPMarkupInlineCollection::~CXTPMarkupInlineCollection()
{
}
void CXTPMarkupInlineCollection::OnItemAdded(CXTPMarkupObject* pItem, int nIndex)
{
((CXTPMarkupInline*)pItem)->m_nIndex = nIndex;
}
void CXTPMarkupInlineCollection::SetContentObject(CXTPMarkupBuilder* pBuilder, CXTPMarkupObject* pContent)
{
CXTPMarkupInputElement* pParent = MARKUP_DYNAMICCAST(CXTPMarkupInputElement, m_pLogicalParent);
ASSERT(pParent);
if (!pParent)
{
pBuilder->ThrowBuilderException(CXTPMarkupBuilder::FormatString(_T("'%ls' object cannot be added to '%ls'. Object cannot be converted to type 'CXTPMarkupInline'"),
(LPCTSTR)pContent->GetType()->m_lpszClassName, (LPCTSTR)GetType()->m_lpszClassName));
}
if (IsStringObject(pContent))
{
CXTPMarkupRun* pRun = MARKUP_CREATE(CXTPMarkupRun, pParent->GetMarkupContext());
pRun->SetText((CXTPMarkupString*)pContent);
Add(pRun);
}
else if (pContent->IsKindOf(MARKUP_TYPE(CXTPMarkupInline)))
{
Add((CXTPMarkupInline*)pContent);
}
else if (pContent->IsKindOf(MARKUP_TYPE(CXTPMarkupUIElement)))
{
CXTPMarkupInlineUIContainer* pInlineUIContainer = MARKUP_CREATE(CXTPMarkupInlineUIContainer, pParent->GetMarkupContext());
pInlineUIContainer->SetChild((CXTPMarkupUIElement*)pContent);
Add(pInlineUIContainer);
}
else
{
pBuilder->ThrowBuilderException(CXTPMarkupBuilder::FormatString(_T("'%ls' object cannot be added to '%ls'. Object cannot be converted to type 'CXTPMarkupInline'"),
(LPCTSTR)pContent->GetType()->m_lpszClassName, (LPCTSTR)GetType()->m_lpszClassName));
}
}
//////////////////////////////////////////////////////////////////////////
// CXTPMarkupSpan
IMPLEMENT_MARKUPCLASS(L"Span", CXTPMarkupSpan, CXTPMarkupInline);
void CXTPMarkupSpan::RegisterMarkupClass()
{
}
CXTPMarkupSpan::CXTPMarkupSpan()
{
m_pInlines = new CXTPMarkupInlineCollection();
m_pInlines->SetLogicalParent(this);
}
CXTPMarkupSpan::~CXTPMarkupSpan()
{
if (m_pInlines)
{
m_pInlines->SetLogicalParent(NULL);
m_pInlines->Release();
}
}
void CXTPMarkupSpan::SetContentObject(CXTPMarkupBuilder* pBuilder, CXTPMarkupObject* pContent)
{
m_pInlines->SetContentObject(pBuilder, pContent);
}
BOOL CXTPMarkupSpan::HasContentObject() const
{
return m_pInlines->HasContentObject();
}
BOOL CXTPMarkupSpan::AllowWhiteSpaceContent() const
{
return TRUE;
}
CXTPMarkupInline* CXTPMarkupSpan::GetFirstInline() const
{
return m_pInlines->GetCount() > 0 ? m_pInlines->GetInline(0)->GetFirstInline() : (CXTPMarkupInline*)this;
}
//////////////////////////////////////////////////////////////////////////
// CXTPMarkupBold
IMPLEMENT_MARKUPCLASS(L"Bold", CXTPMarkupBold, CXTPMarkupSpan);
void CXTPMarkupBold::RegisterMarkupClass()
{
}
CXTPMarkupBold::CXTPMarkupBold()
{
SetFontWeight(FW_BOLD);
}
//////////////////////////////////////////////////////////////////////////
// CXTPMarkupHyperlink
CXTPMarkupRoutedEvent* CXTPMarkupHyperlink::m_pClickEvent = NULL;
IMPLEMENT_MARKUPCLASS(L"Hyperlink", CXTPMarkupHyperlink, CXTPMarkupSpan);
void CXTPMarkupHyperlink::RegisterMarkupClass()
{
CXTPMarkupStyle::RegisterType();
CXTPMarkupButtonBase::RegisterType();
CXTPMarkupSolidColorBrush::RegisterType();
CXTPMarkupHyperlink::RegisterType();
CXTPMarkupType* pType = MARKUP_TYPE(CXTPMarkupHyperlink);
CXTPMarkupStyle* pStyle = new CXTPMarkupStyle();
pStyle->GetSetters()->Add(new CXTPMarkupSetter(CXTPMarkupHyperlink::m_pTextDecorationsProperty, CXTPMarkupEnum::CreateValue(1)));
pStyle->GetSetters()->Add(new CXTPMarkupSetter(CXTPMarkupHyperlink::m_pForegroundProperty, new CXTPMarkupSolidColorBrush(RGB(0, 0, 255))));
pStyle->GetSetters()->Add(new CXTPMarkupSetter(CXTPMarkupHyperlink::m_pCursorProperty, new CXTPMarkupInt(32649)));
CXTPMarkupTriggerCollection* pTriggers = new CXTPMarkupTriggerCollection();
CXTPMarkupTrigger* pTrigger = new CXTPMarkupTrigger(CXTPMarkupHyperlink::m_pIsMouseOverProperty, CXTPMarkupBool::CreateTrueValue());
CXTPMarkupSetterColection* pSetters = new CXTPMarkupSetterColection();
pSetters->Add(new CXTPMarkupSetter(CXTPMarkupHyperlink::m_pForegroundProperty, new CXTPMarkupSolidColorBrush(RGB(255, 0, 0))));
pTrigger->SetSetters(pSetters);
pTriggers->Add(pTrigger);
pStyle->SetTriggers(pTriggers);
pType->SetTypeStyle(pStyle);
m_pClickEvent = (CXTPMarkupRoutedEvent*)CXTPMarkupButtonBase::m_pClickEvent->AddOwner(MARKUP_TYPE(CXTPMarkupHyperlink));
}
CXTPMarkupHyperlink::CXTPMarkupHyperlink()
{
m_bPressed = FALSE;
}
void CXTPMarkupHyperlink::OnMouseLeftButtonUp(CXTPMarkupMouseButtonEventArgs* e)
{
if (m_bPressed)
{
m_bPressed = FALSE;
OnClick();
e->SetHandled();
}
}
void CXTPMarkupHyperlink::OnMouseLeftButtonDown(CXTPMarkupMouseButtonEventArgs* e)
{
m_bPressed = TRUE;
e->SetHandled();
}
void CXTPMarkupHyperlink::OnClick()
{
CXTPMarkupRoutedEventArgs* e = new CXTPMarkupRoutedEventArgs(m_pClickEvent, this);
RaiseEvent(e);
e->Release();
}
//////////////////////////////////////////////////////////////////////////
// CXTPMarkupItalic
IMPLEMENT_MARKUPCLASS(L"Italic", CXTPMarkupItalic, CXTPMarkupSpan);
void CXTPMarkupItalic::RegisterMarkupClass()
{
}
CXTPMarkupItalic::CXTPMarkupItalic()
{
SetFontStyle(1);
}
//////////////////////////////////////////////////////////////////////////
// CXTPMarkupUnderline
IMPLEMENT_MARKUPCLASS(L"Underline", CXTPMarkupUnderline, CXTPMarkupSpan);
void CXTPMarkupUnderline::RegisterMarkupClass()
{
}
CXTPMarkupUnderline::CXTPMarkupUnderline()
{
SetTextDecorations(1);
}
//////////////////////////////////////////////////////////////////////////
// CXTPMarkupInlineUIContainer
IMPLEMENT_MARKUPCLASS(L"InlineUIContainer", CXTPMarkupInlineUIContainer, CXTPMarkupInline);
void CXTPMarkupInlineUIContainer::RegisterMarkupClass()
{
}
CXTPMarkupInlineUIContainer::CXTPMarkupInlineUIContainer()
{
m_pChild = NULL;
}
CXTPMarkupInlineUIContainer::CXTPMarkupInlineUIContainer(CXTPMarkupUIElement* pElement)
{
m_pChild = NULL;
SetChild(pElement);
}
CXTPMarkupInlineUIContainer::~CXTPMarkupInlineUIContainer()
{
MARKUP_RELEASE(m_pChild);
}
CXTPMarkupUIElement* CXTPMarkupInlineUIContainer::GetChild() const
{
return m_pChild;
}
void CXTPMarkupInlineUIContainer::SetChild(CXTPMarkupUIElement* pChild)
{
if (m_pChild)
{
m_pChild->SetLogicalParent(NULL);
MARKUP_RELEASE(m_pChild);
}
m_pChild = pChild;
if (m_pChild)
{
m_pChild->SetLogicalParent(this);
}
}
void CXTPMarkupInlineUIContainer::SetContentObject(CXTPMarkupBuilder* pBuilder, CXTPMarkupObject* pContent)
{
if (!pContent->IsKindOf(MARKUP_TYPE(CXTPMarkupUIElement)))
{
pBuilder->ThrowBuilderException(CXTPMarkupBuilder::FormatString(_T("'%ls' object cannot be added to '%ls'. Object cannot be converted to type 'CXTPMarkupUIElement'"),
(LPCTSTR)pContent->GetType()->m_lpszClassName, (LPCTSTR)GetType()->m_lpszClassName));
}
SetChild((CXTPMarkupUIElement*)pContent);
}
BOOL CXTPMarkupInlineUIContainer::HasContentObject() const
{
return m_pChild != NULL;
}
POSITION CXTPMarkupInlineUIContainer::GetContentStartPosition() const
{
return m_pChild ? MARKUP_POSITION_START : MARKUP_POSITION_EOF;
};
void CXTPMarkupInlineUIContainer::GetContentNextPosition(POSITION& pos) const
{
pos = (pos == MARKUP_POSITION_START ? MARKUP_POSITION_END : MARKUP_POSITION_EOF);
}
BOOL CXTPMarkupInlineUIContainer::IsWordBreakPosition(POSITION pos) const
{
return pos == MARKUP_POSITION_START || pos == MARKUP_POSITION_END;
}
CSize CXTPMarkupInlineUIContainer::Measure(CXTPMarkupDrawingContext* pDC, POSITION posStart, POSITION /*posEnd*/)
{
if (!m_pChild || posStart != MARKUP_POSITION_START)
return CSize(0, 0);
m_pChild->Measure(pDC, CSize(32000, 32000));
return m_pChild->GetDesiredSize();
}
void CXTPMarkupInlineUIContainer::Arrange(CRect rcFinalRect, POSITION posStart, POSITION /*posEnd*/)
{
if (!m_pChild || posStart != MARKUP_POSITION_START)
return;
m_pChild->Arrange(rcFinalRect);
}
void CXTPMarkupInlineUIContainer::Render(CXTPMarkupDrawingContext* pDC, CRect /*rc*/, POSITION posStart, POSITION /*posEnd*/)
{
if (!m_pChild || posStart != MARKUP_POSITION_START)
return;
m_pChild->Render(pDC);
}
CXTPMarkupInputElement* CXTPMarkupInlineUIContainer::InputHitTest(CPoint point) const
{
CXTPMarkupInputElement* pObject = m_pChild ? m_pChild->InputHitTest(point) : (CXTPMarkupInputElement*)this;
if (pObject)
return pObject;
return (CXTPMarkupInputElement*)this;
}
| 27.723469 | 175 | 0.763407 | [
"render",
"object"
] |
7dbbfcd25b0cc158cf3052eac3f2c3230523d77b | 10,366 | cpp | C++ | kinectGrab.cpp | buq2/matlab_multiview_toolbox | 2ded59134119ba41f88332dd2e31e7fff71433f5 | [
"BSD-2-Clause-FreeBSD"
] | 2 | 2019-01-04T09:01:37.000Z | 2021-11-10T09:12:21.000Z | kinectGrab.cpp | buq2/matlab_multiview_toolbox | 2ded59134119ba41f88332dd2e31e7fff71433f5 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | kinectGrab.cpp | buq2/matlab_multiview_toolbox | 2ded59134119ba41f88332dd2e31e7fff71433f5 | [
"BSD-2-Clause-FreeBSD"
] | 3 | 2019-01-04T09:01:57.000Z | 2021-11-10T09:12:23.000Z | #include "mex.h"
#include "libfreenect.h"
#include <vector>
#include <cmath>
#include <limits> //NaN
#include <pthread.h>
void usage()
{
mexPrintf(
"Returns depth and RGB data from Kinect using libfreenect\n"
"\n"
"Inputs:\n"
" numFrames - Number of frames to grab (double)\n"
"\n"
"Outputs:\n"
" depth - Depth data\n"
" rgb - RGB data\n"
" accel - Raw accelaration data for each frame\n"
);
}
//Kinect device (physical device)
freenect_device *kinectDevice = NULL;
//Freenect library context
freenect_context *freenectContext = NULL;
//Number of rgb frames captured
int framesCapturedRgb = 0;
//Number of depth frames captured
int framesCapturedDepth = 0;
//Number of frames to be captured
int framesToBeCaptured = 0;
//Pointers to MATLAB output data
double *data_depth = NULL;
uint8_t *data_rgb = NULL;
double *data_accel = NULL;
//Video constants
const int width = 640;
const int height = 480;
const int channels = 3;
//Have we received valid vide/depth?
bool validDepthReceived = false;
bool validRgbReceived = false;
//Simple check to make sure that depth buffer contains actual data
bool isValidDepthBuffer(void* depthBuf)
{
uint16_t* depth = static_cast<uint16_t*>(depthBuf);
size_t numElem = width*height;
for(size_t ii = 0 ; ii < numElem ; ++ii) {
if (depth[ii] != 0) {
return true;
}
}
return false;
}
//Simple check to make sure that rgb buffer contains actual data
bool isValidRgbBuffer(void* rgbBuf)
{
uint8_t* rgb = static_cast<uint8_t*>(rgbBuf);
size_t layer = width*height;
size_t numElems = layer*3;
for(size_t ii = 0 ; ii < numElems ; ++ii) {
if (rgb[ii] != 0) {
return true;
}
}
return false;
}
// Do not call directly even in child
void VideoCallback(freenect_device *kinectDeviceCaller, void* rgbBuf, uint32_t timestamp)
{
//Have we already received valid rgb data?
if (!validRgbReceived) {
validRgbReceived = isValidRgbBuffer(rgbBuf);
if (!validRgbReceived) {
return; //Rgb data not yet valid. Wait for next buffer
}
}
//We also must wait for valid depth
if (!validDepthReceived) {
return; //Wait till depth is ready
}
//Do not try to capture more frames than needed
if (framesCapturedRgb >= framesToBeCaptured) {
return;
}
uint8_t* rgb = static_cast<uint8_t*>(rgbBuf);
//size_t numBytes = freenect_get_current_depth_mode(device).bytes;
//size_t numElems = numBytes;
size_t layer = width*height;
size_t numElems = layer*3;
for (size_t ii = 0; ii < numElems; ++ii) {
data_rgb[numElems*framesCapturedRgb + ii/3 + ii%3*layer] = rgb[ii];
}
++framesCapturedRgb;
};
// Do not call directly even in child
void DepthCallback(freenect_device *kinectDeviceCaller, void* depthBuf, uint32_t timestamp)
{
//Have we already received valid rgb data?
if (!validDepthReceived) {
validDepthReceived = isValidDepthBuffer(depthBuf);
return; //RGB must be captured first
//if (!validDepthReceived) {
// return; //Rgb data not yet valid. Wait for next buffer
//}
}
//We also must wait for valid depth
if (framesCapturedRgb==0) {
return; //Wait till depth is ready
}
//Do not try to capture more frames than needed
if (framesCapturedDepth >= framesToBeCaptured) {
return;
}
//Get the acceleration state
double *datacol = &data_accel[3*framesCapturedDepth];
freenect_raw_tilt_state *tiltstateptr = freenect_get_tilt_state(kinectDeviceCaller);
freenect_get_mks_accel(tiltstateptr, datacol, datacol+1, datacol+2);
//Get depth data
uint16_t* depth = static_cast<uint16_t*>(depthBuf);
size_t numElem = width*height;
for(size_t ii = 0 ; ii < numElem ; ++ii) {
data_depth[numElem*framesCapturedDepth + ii] = depth[ii];
}
++framesCapturedDepth;
}
//Returns how many frames have been captured
int capturedFrames()
{
return std::min(framesCapturedRgb,framesCapturedDepth);
}
//Additional processing (update acceleration values)
void *process(void *data)
{
int currentFrame = 0;
//While images need to be captured
while ((currentFrame = capturedFrames()) < framesToBeCaptured) {
//Send blocking request to update tilt state
if(freenect_update_tilt_state(kinectDevice) != 0) {
//We might be trying to update too often
}
}
//Terminate thread
thread_exit:
pthread_exit(NULL);
}
void mexFunction(int nlhs, /*(NumLeftHandSide) Number of arguments in left side of '=' (number of output arguments)*/
mxArray *plhs[], /*(PointerLeftHandSide) Pointers to output data*/
int nrhs, /*(NumRightHandSide) Number of input arguments*/
const mxArray *prhs[]) /*(PointerRightHandSide) Pointers to input data*/
{
//Initialize globals
freenectContext = NULL;
kinectDevice = NULL;
framesCapturedRgb = 0;
framesCapturedDepth = 0;
framesToBeCaptured = 0;
data_depth = NULL;
data_rgb = NULL;
data_accel = NULL;
validDepthReceived = false;
validRgbReceived = false;
//Error checking for inputs and outputs
if (nrhs < 1) {
//Not enough inputs
usage();
mexErrMsgTxt("Not enough input parameters.\n");
}
if (mxGetClassID(prhs[0]) != mxDOUBLE_CLASS) {
usage();
mexErrMsgTxt("Number of frames to grap (argument 1) must be double precision scalar.\n");
}
if (mxGetNumberOfElements(prhs[0]) != 1) {
usage();
mexErrMsgTxt("Number of frames must be scalar\n");
}
//Get number of frames to be captured
framesToBeCaptured = *((double*)mxGetData(prhs[0]));
if (nlhs != 3) {
usage();
mexPrintf("There must be three outputs\n");
}
//Create output arrays
mwSize dims_out_depth[3] = {width,height,framesToBeCaptured};
mwSize dims_out_rgb[4] = {width,height,3,framesToBeCaptured};
mwSize dims_out_accel[2] = {3,framesToBeCaptured};
mxArray *out_rgb = mxCreateNumericArray(4, dims_out_rgb, mxUINT8_CLASS, mxREAL);
mxArray *out_depth = mxCreateNumericArray(3, dims_out_depth, mxDOUBLE_CLASS, mxREAL);
mxArray *out_accel = mxCreateNumericArray(2, dims_out_accel, mxDOUBLE_CLASS, mxREAL);
plhs[0] = out_depth;
plhs[1] = out_rgb;
plhs[2] = out_accel;
data_rgb = (uint8_t*)mxGetData(out_rgb);
data_depth = (double*)mxGetData(out_depth);
data_accel = (double*)mxGetData(out_accel);
//Initialize freenect library
if (freenect_init(&freenectContext, NULL) < 0) {
mexErrMsgTxt("Cannot initialize freenect library");
}
//We claim both the motor and camera devices, since this class exposes both.
//It does not support audio, so we do not claim it.
freenect_select_subdevices(freenectContext, static_cast<freenect_device_flags>(FREENECT_DEVICE_MOTOR | FREENECT_DEVICE_CAMERA));
//Try to open device
//Open device 0
if(freenect_open_device(freenectContext, &kinectDevice, 0) < 0) {
mexErrMsgTxt("Cannot open Kinect");
}
//We would like to use these video output formats
freenect_video_format requested_format_rgb(FREENECT_VIDEO_RGB);
freenect_depth_format requested_format_depth(FREENECT_DEPTH_11BIT);
//Set video modes and callbacks
freenect_set_video_mode(kinectDevice, freenect_find_video_mode(FREENECT_RESOLUTION_MEDIUM, requested_format_rgb));
freenect_set_depth_mode(kinectDevice, freenect_find_depth_mode(FREENECT_RESOLUTION_MEDIUM, requested_format_depth));
freenect_set_depth_callback(kinectDevice, DepthCallback);
freenect_set_video_callback(kinectDevice, VideoCallback);
//Open video and depth capturing
if(freenect_start_video(kinectDevice) < 0) {
mexErrMsgTxt("Cannot start RGB video");
}
if(freenect_start_depth(kinectDevice) < 0) {
mexErrMsgTxt("Cannot start depth");
}
//Two processing threads, one at "process" updating acceleration
//and one here (main thread) processing events
pthread_t thread;
int rc = pthread_create(&thread, NULL, process, (void*)&thread);
if (rc) {
mexErrMsgTxt("problem with return code from pthread_create()");
}
int currentFrame = 0;
//While still some images need to be captured
while ((currentFrame = capturedFrames()) < framesToBeCaptured) {
//Process USB events and images
if(freenect_process_events(freenectContext) < 0) {
mexPrintf("Cannot process freenect events\n");
}
}
//Wait till acceleration updating thread stops
void *status;
pthread_join(thread, &status);
//Stop video and depth capturing
if(freenect_stop_video(kinectDevice) < 0) {
mexErrMsgTxt("Cannot stop RGB callback");
}
if(freenect_stop_depth(kinectDevice) < 0) {
mexErrMsgTxt("Cannot stop depth callback");
}
//Close USB device
if(freenect_close_device(kinectDevice) < 0) {
mexErrMsgTxt("Closing of the Kinect failed");
}
//Uninit freenect
if(freenect_shutdown < 0) {
mexErrMsgTxt("Freenect shutdown failed");
}
//Permute outputs (otherwise images seem to be trasposed)
mwSize permute1_vec_size[1] = {3};
mxArray *permute1_in_params[2] = {out_depth,mxCreateNumericArray(1, permute1_vec_size, mxDOUBLE_CLASS, mxREAL)};
double *data_permute1_vec = (double*)mxGetData(permute1_in_params[1]);
data_permute1_vec[0] = 2;
data_permute1_vec[1] = 1;
data_permute1_vec[2] = 3;
mexCallMATLAB(1, &plhs[0], 2, permute1_in_params, "permute");
mwSize permute2_vec_size[1] = {4};
mxArray *permute2_in_params[2] = {out_rgb,mxCreateNumericArray(1, permute2_vec_size, mxDOUBLE_CLASS, mxREAL)};
double *data_permute2_vec = (double*)mxGetData(permute2_in_params[1]);
data_permute2_vec[0] = 2;
data_permute2_vec[1] = 1;
data_permute2_vec[2] = 3;
data_permute2_vec[3] = 4;
mexCallMATLAB(1, &plhs[1], 2, permute2_in_params, "permute");
//pthread_exit should never be called from main thread when using MATLAB
//as it causes MATLAB to exit ("crash")
//pthread_exit(NULL);
}
| 32.292835 | 132 | 0.671233 | [
"vector"
] |
7dbf320e1b36d8abf5bcea4b3ca4c1f4a93aa7cf | 9,188 | cpp | C++ | qtxmlpatterns/src/xmlpatterns/expr/qorderby.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | 1 | 2020-04-30T15:47:35.000Z | 2020-04-30T15:47:35.000Z | qtxmlpatterns/src/xmlpatterns/expr/qorderby.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | qtxmlpatterns/src/xmlpatterns/expr/qorderby.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtXmlPatterns module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtAlgorithms>
#include "qcommonsequencetypes_p.h"
#include "qnodebuilder_p.h"
#include "qschemanumeric_p.h"
#include "qpatternistlocale_p.h"
#include "qreturnorderby_p.h"
#include "qsorttuple_p.h"
#include "qsequencemappingiterator_p.h"
#include "qorderby_p.h"
#include <algorithm>
#include <functional>
QT_BEGIN_NAMESPACE
using namespace QPatternist;
OrderBy::OrderBy(const Stability stability,
const OrderSpec::Vector &aOrderSpecs,
const Expression::Ptr &op,
ReturnOrderBy *const returnOrderBy) : SingleContainer(op)
, m_stability(stability)
, m_orderSpecs(aOrderSpecs)
, m_returnOrderBy(returnOrderBy)
{
Q_ASSERT(m_returnOrderBy);
}
void OrderBy::OrderSpec::prepare(const Expression::Ptr &source,
const StaticContext::Ptr &context)
{
m_expr = source;
const ItemType::Ptr t(source->staticType()->itemType());
prepareComparison(fetchComparator(t, t, context));
}
/**
* @short Functor used by Qt's qSort() and qStableSort(). Used for FLWOR's
* <tt>order by</tt> expression.
*
* This must be in the std namespace, since it is specializing std::less(), which
* is in the std namespace. Hence it can't be in QPatternist.
*/
QT_END_NAMESPACE
QT_USE_NAMESPACE
namespace std {
template<>
struct less<Item::List>
{
private:
static inline bool isNaN(const Item &i)
{
return BuiltinTypes::xsDouble->xdtTypeMatches(i.type()) &&
i.as<Numeric>()->isNaN();
}
public:
inline less(const OrderBy::OrderSpec::Vector &orderspecs,
const DynamicContext::Ptr &context) : m_orderSpecs(orderspecs)
, m_context(context)
{
Q_ASSERT(!m_orderSpecs.isEmpty());
Q_ASSERT(context);
}
inline bool operator()(const Item &item1, const Item &item2) const
{
const SortTuple *const s1 = item1.as<SortTuple>();
const SortTuple *const s2 = item2.as<SortTuple>();
const Item::Vector &sortKeys1 = s1->sortKeys();
const Item::Vector &sortKeys2 = s2->sortKeys();
const int len = sortKeys1.count();
Q_ASSERT(sortKeys1.count() == sortKeys2.count());
for(int i = 0; i < len; ++i)
{
const Item &i1 = sortKeys1.at(i);
const Item &i2 = sortKeys2.at(i);
const OrderBy::OrderSpec &orderSpec = m_orderSpecs.at(i);
if(!i1)
{
if(i2 && !isNaN(i2))
{
/* We got ((), item()). */
return orderSpec.orderingEmptySequence == StaticContext::Least ? orderSpec.direction == OrderBy::OrderSpec::Ascending
: orderSpec.direction != OrderBy::OrderSpec::Ascending;
}
else
return false;
}
if(!i2)
{
if(i1 && !isNaN(i1))
/* We got (item(), ()). */
return orderSpec.orderingEmptySequence == StaticContext::Greatest ? orderSpec.direction == OrderBy::OrderSpec::Ascending
: orderSpec.direction != OrderBy::OrderSpec::Ascending;
else
return false;
}
Q_ASSERT(orderSpec.direction == OrderBy::OrderSpec::Ascending ||
orderSpec.direction == OrderBy::OrderSpec::Descending);
const AtomicComparator::ComparisonResult result = orderSpec.detailedFlexibleCompare(i1, i2, m_context);
switch(result)
{
case AtomicComparator::LessThan:
return orderSpec.direction == OrderBy::OrderSpec::Ascending;
case AtomicComparator::GreaterThan:
return orderSpec.direction != OrderBy::OrderSpec::Ascending;
case AtomicComparator::Equal:
continue;
case AtomicComparator::Incomparable:
Q_ASSERT_X(false, Q_FUNC_INFO, "This code path assume values are always comparable.");
}
}
return false;
}
private:
/* Yes, we store references here. */
const OrderBy::OrderSpec::Vector & m_orderSpecs;
const DynamicContext::Ptr & m_context;
};
} // namespace std
QT_BEGIN_NAMESPACE
Item::Iterator::Ptr OrderBy::mapToSequence(const Item &i,
const DynamicContext::Ptr &) const
{
return i.as<SortTuple>()->value();
}
Item::Iterator::Ptr OrderBy::evaluateSequence(const DynamicContext::Ptr &context) const
{
Item::List tuples(m_operand->evaluateSequence(context)->toList());
const std::less<Item::List> sorter(m_orderSpecs, context);
Q_ASSERT(m_stability == StableOrder || m_stability == UnstableOrder);
/* On one hand we could just disregard stability and always use qStableSort(), but maybe qSort()
* is a bit faster? */
if(m_stability == StableOrder)
std::stable_sort(tuples.begin(), tuples.end(), sorter);
else
{
Q_ASSERT(m_stability == UnstableOrder);
std::sort(tuples.begin(), tuples.end(), sorter);
}
return makeSequenceMappingIterator<Item>(ConstPtr(this),
makeListIterator(tuples),
context);
}
Expression::Ptr OrderBy::typeCheck(const StaticContext::Ptr &context,
const SequenceType::Ptr &reqType)
{
m_returnOrderBy->setStay(true);
/* It's important we do the typeCheck() before calling OrderSpec::prepare(), since
* atomizers must first be inserted. */
const Expression::Ptr me(SingleContainer::typeCheck(context, reqType));
const Expression::List ops(m_returnOrderBy->operands());
const int len = ops.count();
Q_ASSERT(ops.count() > 1);
Q_ASSERT(m_orderSpecs.count() == ops.count() - 1);
for(int i = 1; i < len; ++i)
m_orderSpecs[i - 1].prepare(ops.at(i), context);
return me;
/* It's not meaningful to sort a single item or less, so rewrite ourselves
* away if that is the case. This is an optimization. */
/* TODO: How do we remove ReturnOrderBy?
if(Cardinality::zeroOrOne().isMatch(m_operand->staticType()->cardinality()))
return m_operand->typeCheck(context, reqType);
else
return SingleContainer::typeCheck(context, reqType);
*/
}
Expression::Properties OrderBy::properties() const
{
return m_operand->properties() & DisableElimination;
}
Expression::Ptr OrderBy::compress(const StaticContext::Ptr &context)
{
/* If we only will produce one item, there's no point in sorting. */
if(m_operand->staticType()->cardinality().allowsMany())
return SingleContainer::compress(context);
else
{
m_returnOrderBy->setStay(false);
return m_operand->compress(context);
}
}
SequenceType::Ptr OrderBy::staticType() const
{
return m_operand->staticType();
}
SequenceType::List OrderBy::expectedOperandTypes() const
{
SequenceType::List result;
result.append(CommonSequenceTypes::ZeroOrMoreItems);
return result;
}
ExpressionVisitorResult::Ptr
OrderBy::accept(const ExpressionVisitor::Ptr &visitor) const
{
return visitor->visit(this);
}
QT_END_NAMESPACE
| 34.541353 | 141 | 0.608293 | [
"vector"
] |
7dbfe24d3c4f5ff1add55f3ed3242168afae1f96 | 15,526 | cpp | C++ | hackathon/zhi/reconstruction_evaluation/reco_eval_plugin.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2021-12-27T19:14:03.000Z | 2021-12-27T19:14:03.000Z | hackathon/zhi/reconstruction_evaluation/reco_eval_plugin.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | hackathon/zhi/reconstruction_evaluation/reco_eval_plugin.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | /* reco_eval_plugin.cpp
* This is a test plugin, you can use it as a demo.
* 2019-2-4 : by Zhi Zhou
*/
#include "v3d_message.h"
#include <vector>
#include "reco_eval_plugin.h"
#include "../../../released_plugins/v3d_plugins/swc_to_maskimage/filter_dialog.h"
#include "../AllenNeuron_postprocessing/sort_swc_IVSCC.h"
#include "volimg_proc.h"
#include <algorithm>
using namespace std;
#define NTDIS(a,b) (sqrt(((a).x-(b).x)*((a).x-(b).x)+((a).y-(b).y)*((a).y-(b).y)+((a).z-(b).z)*((a).z-(b).z)))
Q_EXPORT_PLUGIN2(reco_eval, TestPlugin);
QStringList TestPlugin::menulist() const
{
return QStringList()
<<tr("menu1")
<<tr("menu2")
<<tr("about");
}
QStringList TestPlugin::funclist() const
{
return QStringList()
<<tr("func1")
<<tr("func2")
<<tr("help");
}
double distTwoSegs(NeuronTree nt, QList<MyMarker>& seg);
void TestPlugin::domenu(const QString &menu_name, V3DPluginCallback2 &callback, QWidget *parent)
{
if (menu_name == tr("menu1"))
{
v3d_msg("To be implemented.");
}
else if (menu_name == tr("menu2"))
{
v3d_msg("To be implemented.");
}
else
{
v3d_msg(tr("This is a test plugin, you can use it as a demo.. "
"Developed by Zhi Zhou, 2019-2-4"));
}
}
bool TestPlugin::dofunc(const QString & func_name, const V3DPluginArgList & input, V3DPluginArgList & output, V3DPluginCallback2 & callback, QWidget * parent)
{
vector<char*> infiles, inparas, outfiles;
if(input.size() >= 1) infiles = *((vector<char*> *)input.at(0).p);
if(input.size() >= 2) inparas = *((vector<char*> *)input.at(1).p);
if(output.size() >= 1) outfiles = *((vector<char*> *)output.at(0).p);
if (func_name == tr("generative_model"))
{
vector<char*> * pinfiles = (input.size() >= 1) ? (vector<char*> *) input[0].p : 0;
vector<char*> * poutfiles = (output.size() >= 1) ? (vector<char*> *) output[0].p : 0;
vector<char*> * pparas = (input.size() >= 2) ? (vector<char*> *) input[1].p : 0;
vector<char*> infiles = (pinfiles != 0) ? * pinfiles : vector<char*>();
vector<char*> outfiles = (poutfiles != 0) ? * poutfiles : vector<char*>();
vector<char*> paras = (pparas != 0) ? * pparas : vector<char*>();
QString inimg_file = infiles[0];
QString output_folder = outfiles[0];
int k=0;
QString swc_name = paras.empty() ? "" : paras[k]; if(swc_name == "NULL") swc_name = ""; k++;
NeuronTree nt = readSWC_file(swc_name);
QVector<QVector<V3DLONG> > childs;
V3DLONG neuronNum = nt.listNeuron.size();
childs = QVector< QVector<V3DLONG> >(neuronNum, QVector<V3DLONG>() );
for (V3DLONG i=0;i<neuronNum;i++)
{
V3DLONG par = nt.listNeuron[i].pn;
if (par<0) continue;
childs[nt.hashNeuron.value(par)].push_back(i);
}
int Wx = 32;
int Wy = 32;
int Wz = 32;
QList<NeuronSWC> list = nt.listNeuron;
double corr = 0;
int cnt = 0;
for (V3DLONG i=0;i<list.size();i++)
{
if (childs[i].size()==0)
{
cnt++;
V3DLONG tmpx = nt.listNeuron.at(i).x;
V3DLONG tmpy = nt.listNeuron.at(i).y;
V3DLONG tmpz = nt.listNeuron.at(i).z;
V3DLONG xb = tmpx-Wx;
V3DLONG xe = tmpx+Wx;
V3DLONG yb = tmpy-Wy;
V3DLONG ye = tmpy+Wy;
V3DLONG zb = tmpz-Wz;
V3DLONG ze = tmpz+Wz;
QString outimg_file;
outimg_file = output_folder + QString("/x%1_y%2_z%3.tif").arg(tmpx).arg(tmpy).arg(tmpz);
unsigned char * data1d = 0;
data1d = callback.getSubVolumeTeraFly(inimg_file.toStdString(),xb,xe+1,yb,ye+1,zb,ze+1);
V3DLONG im_cropped_sz[4];
im_cropped_sz[0] = xe - xb + 1;
im_cropped_sz[1] = ye - yb + 1;
im_cropped_sz[2] = ze - zb + 1;
im_cropped_sz[3] = 1;
simple_saveimage_wrapper(callback,outimg_file.toStdString().c_str(),data1d,im_cropped_sz,1);
V3DLONG stacksz = im_cropped_sz[0] * im_cropped_sz[1] * im_cropped_sz[2];
vector<pair<V3DLONG,MyMarker> > vp;
vp.reserve(stacksz);
V3DLONG N = im_cropped_sz[0];
V3DLONG M = im_cropped_sz[1];
V3DLONG P = im_cropped_sz[2];
for(V3DLONG iz = 0; iz < P; iz++)
{
V3DLONG offsetk = iz*M*N;
for(V3DLONG iy = 0; iy < M; iy++)
{
V3DLONG offsetj = iy*N;
for(V3DLONG ix = 0; ix < N; ix++)
{
MyMarker t;
t.x = ix;
t.y = iy;
t.z = iz;
V3DLONG I_t = data1d[offsetk + offsetj + ix];
vp.push_back(make_pair(I_t, t));
}
}
}
sort(vp.begin(), vp.end());
QList<MyMarker> file_inmarkers;
file_inmarkers.push_back(vp.back().second);
for (size_t i = vp.size()-2 ; i >=0; i--)
{
bool flag =false;
for(int j = 0; j < file_inmarkers.size();j++)
{
if(NTDIS(file_inmarkers.at(j),vp[i].second) < N/15)
{
flag = true;
break;
}
}
if(!flag)
{
file_inmarkers.push_back(vp[i].second);
}
if(file_inmarkers.size()>20)
break;
}
vp.clear();
QString outmarker_file = output_folder + QString("/x%1_y%2_z%3.marker").arg(tmpx).arg(tmpy).arg(tmpz);
QList<ImageMarker> marker_tmp;
for(int i=0; i<file_inmarkers.size();i++)
{
ImageMarker t;
t.x = file_inmarkers.at(i).x+1;
t.y = file_inmarkers.at(i).y+1;
t.z = file_inmarkers.at(i).z+1;
marker_tmp.push_back(t);
}
writeMarker_file(outmarker_file,marker_tmp);
NeuronTree nt_tps;
QList <NeuronSWC> & listNeuron = nt_tps.listNeuron;
for(V3DLONG j =0; j < list.size();j++)
{
NeuronSWC t;
t = list.at(j);
t.x = list[j].x - xb;
t.y = list[j].y - yb;
t.z = list[j].z - zb;
if(t.x >= 0 && t.x < im_cropped_sz[0] && t.y >= 0 && t.y < im_cropped_sz[1] && t.z >= 0 && t.z < im_cropped_sz[2])
{
listNeuron << t;
}
}
nt_tps = SortSWC_pipeline(nt_tps.listNeuron,VOID,0);
QString outimg_swc = output_folder + QString("/x%1_y%2_z%3.swc").arg(tmpx).arg(tmpy).arg(tmpz);
writeSWC_file(outimg_swc,nt_tps);
unsigned char *data1d_mask = new unsigned char [stacksz];
memset(data1d_mask,0,stacksz*sizeof(unsigned char));
double margin=0;
ComputemaskImage(nt_tps, data1d_mask, im_cropped_sz[0], im_cropped_sz[1], im_cropped_sz[2], margin);
listNeuron.clear();
for(V3DLONG i=0; i<stacksz; i++)
data1d_mask[i] = data1d_mask[i]==255?data1d[i]:0;
outimg_file = output_folder + QString("/x%1_y%2_z%3_v2.tif").arg(tmpx).arg(tmpy).arg(tmpz);
simple_saveimage_wrapper(callback,outimg_file.toStdString().c_str(),data1d_mask,im_cropped_sz,1);
corr += calCorrelation(data1d,data1d_mask,stacksz)*NTDIS(list.at(0),list.at(i));
if(data1d_mask) { delete []data1d_mask; data1d_mask = 0;}
if(data1d) { delete []data1d; data1d = 0;}
v3d_msg(QString("%1").arg(corr));
}
}
double corr_total = corr/cnt;
if (output.size() == 1)
{
char *outimg_file = ((vector<char*> *)(output.at(0).p))->at(0);
ofstream myfile;
myfile.open (outimg_file,ios::out | ios::app );
myfile << swc_name.toStdString()<<"\t"<<corr_total <<endl;
myfile.close();
}
return true;
}
else if (func_name == tr("compressive_sensing"))
{
vector<char*> * pinfiles = (input.size() >= 1) ? (vector<char*> *) input[0].p : 0;
vector<char*> * poutfiles = (output.size() >= 1) ? (vector<char*> *) output[0].p : 0;
vector<char*> * pparas = (input.size() >= 2) ? (vector<char*> *) input[1].p : 0;
vector<char*> infiles = (pinfiles != 0) ? * pinfiles : vector<char*>();
vector<char*> outfiles = (poutfiles != 0) ? * poutfiles : vector<char*>();
vector<char*> paras = (pparas != 0) ? * pparas : vector<char*>();
QString inimg_file = infiles[0];
// QString output_folder = outfiles[0];
int k=0;
QString swc_name = paras.empty() ? "" : paras[k]; if(swc_name == "NULL") swc_name = ""; k++;
NeuronTree nt = readSWC_file(swc_name);
QVector<QVector<V3DLONG> > childs;
V3DLONG neuronNum = nt.listNeuron.size();
childs = QVector< QVector<V3DLONG> >(neuronNum, QVector<V3DLONG>() );
for (V3DLONG i=0;i<neuronNum;i++)
{
V3DLONG par = nt.listNeuron[i].pn;
if (par<0) continue;
childs[nt.hashNeuron.value(par)].push_back(i);
}
int Wx = 32;
int Wy = 32;
int Wz = 32;
QList<NeuronSWC> list = nt.listNeuron;
double dist = 0;
int cnt = 0;
for (V3DLONG i=0;i<list.size();i++)
{
if (childs[i].size()==0)
{
cnt++;
V3DLONG tmpx = nt.listNeuron.at(i).x;
V3DLONG tmpy = nt.listNeuron.at(i).y;
V3DLONG tmpz = nt.listNeuron.at(i).z;
V3DLONG xb = tmpx-Wx;
V3DLONG xe = tmpx+Wx;
V3DLONG yb = tmpy-Wy;
V3DLONG ye = tmpy+Wy;
V3DLONG zb = tmpz-Wz;
V3DLONG ze = tmpz+Wz;
// QString outimg_file;
// outimg_file = output_folder + QString("/x%1_y%2_z%3.tif").arg(tmpx).arg(tmpy).arg(tmpz);
unsigned char * data1d = 0;
data1d = callback.getSubVolumeTeraFly(inimg_file.toStdString(),xb,xe+1,yb,ye+1,zb,ze+1);
V3DLONG im_cropped_sz[4];
im_cropped_sz[0] = xe - xb + 1;
im_cropped_sz[1] = ye - yb + 1;
im_cropped_sz[2] = ze - zb + 1;
im_cropped_sz[3] = 1;
// simple_saveimage_wrapper(callback,outimg_file.toStdString().c_str(),data1d,im_cropped_sz,1);
V3DLONG stacksz = im_cropped_sz[0] * im_cropped_sz[1] * im_cropped_sz[2];
vector<pair<V3DLONG,MyMarker> > vp;
vp.reserve(stacksz);
V3DLONG N = im_cropped_sz[0];
V3DLONG M = im_cropped_sz[1];
V3DLONG P = im_cropped_sz[2];
for(V3DLONG iz = 0; iz < P; iz++)
{
V3DLONG offsetk = iz*M*N;
for(V3DLONG iy = 0; iy < M; iy++)
{
V3DLONG offsetj = iy*N;
for(V3DLONG ix = 0; ix < N; ix++)
{
MyMarker t;
t.x = ix;
t.y = iy;
t.z = iz;
V3DLONG I_t = data1d[offsetk + offsetj + ix];
vp.push_back(make_pair(I_t, t));
}
}
}
sort(vp.begin(), vp.end());
QList<MyMarker> file_inmarkers;
file_inmarkers.push_back(vp.back().second);
for (size_t i = vp.size()-2 ; i >=0; i--)
{
bool flag =false;
for(int j = 0; j < file_inmarkers.size();j++)
{
if(NTDIS(file_inmarkers.at(j),vp[i].second) < N/15)
{
flag = true;
break;
}
}
if(!flag)
{
file_inmarkers.push_back(vp[i].second);
}
if(file_inmarkers.size()>20)
break;
}
vp.clear();
// QString outmarker_file = output_folder + QString("/x%1_y%2_z%3.marker").arg(tmpx).arg(tmpy).arg(tmpz);
// writeMarker_file(outmarker_file,file_inmarkers);
NeuronTree nt_tps;
QList <NeuronSWC> & listNeuron = nt_tps.listNeuron;
for(V3DLONG j =0; j < list.size();j++)
{
NeuronSWC t;
t = list.at(j);
t.x = list[j].x - xb;
t.y = list[j].y - yb;
t.z = list[j].z - zb;
if(t.x >= 0 && t.x < im_cropped_sz[0] && t.y >= 0 && t.y < im_cropped_sz[1] && t.z >= 0 && t.z < im_cropped_sz[2])
{
listNeuron << t;
}
}
nt_tps = SortSWC_pipeline(nt_tps.listNeuron,VOID,0);
// QString outimg_swc = output_folder + QString("/x%1_y%2_z%3.swc").arg(tmpx).arg(tmpy).arg(tmpz);
// writeSWC_file(outimg_swc,nt_tps);
dist += NTDIS(list.at(0),list.at(i))/distTwoSegs(nt_tps,file_inmarkers);
if(data1d) { delete []data1d; data1d = 0;}
// v3d_msg(QString("dist is %1").arg(dist));
}
}
double dist_total = dist/cnt;
if (output.size() == 1)
{
char *outimg_file = ((vector<char*> *)(output.at(0).p))->at(0);
ofstream myfile;
myfile.open (outimg_file,ios::out | ios::app );
myfile << swc_name.toStdString()<<"\t"<<dist_total <<endl;
myfile.close();
}
return true;
}
else if (func_name == tr("help"))
{
v3d_msg("To be implemented.");
}
else return false;
return true;
}
double distTwoSegs(NeuronTree nt, QList<MyMarker>& seg)
{
double dis1=0, dis2=0;
for(int i=0;i<nt.listNeuron.size();i++)
{
double tmp = 1000000;
for(int j=0; j<seg.size();j++)
{
if(NTDIS(nt.listNeuron.at(i),seg.at(j))<tmp)
tmp = NTDIS(nt.listNeuron.at(i),seg.at(j));
}
dis1 += tmp;
}
for(int i=0;i<seg.size();i++)
{
double tmp = 1000000;
for(int j=0;j<nt.listNeuron.size();j++)
{
if(NTDIS(nt.listNeuron.at(j),seg.at(i))<tmp)
tmp = NTDIS(nt.listNeuron.at(j),seg.at(i));
}
dis2 += tmp;
}
double res = 0.5*(dis1/nt.listNeuron.size() + dis2/seg.size());
return res;
}
| 39.01005 | 159 | 0.470952 | [
"vector"
] |
7dc4346b9635e8aac157fe24cbf58b1620b51589 | 640 | cpp | C++ | BOJ_CPP/25053.cpp | tnsgh9603/BOJ_CPP | 432b1350f6c67cce83aec3e723e30a3c6b5dbfda | [
"MIT"
] | null | null | null | BOJ_CPP/25053.cpp | tnsgh9603/BOJ_CPP | 432b1350f6c67cce83aec3e723e30a3c6b5dbfda | [
"MIT"
] | null | null | null | BOJ_CPP/25053.cpp | tnsgh9603/BOJ_CPP | 432b1350f6c67cce83aec3e723e30a3c6b5dbfda | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define fastio ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
using namespace std;
int main() {
fastio;
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> diff2beauty(11, -1000);
for (int i = 0; i < n; ++i) {
int b, d;
cin >> b >> d;
diff2beauty[d] = max(diff2beauty[d], b);
}
int total_beauty = 0;
for (int d = 1; d <= 10; ++d) {
total_beauty += diff2beauty[d];
}
cout << (total_beauty < 0 ? "MOREPROBLEMS" : to_string(total_beauty)) << "\n";
}
return 0;
}
| 23.703704 | 86 | 0.467188 | [
"vector"
] |
7dd6b8bb81176b03c6234793d7223024af0b9a1a | 1,329 | cpp | C++ | 2021/Day 1/Day 1 - CPP/Program.cpp | edgorman/Advent-of-Code | 7c354dfdfd0c072c59b15bcac265c19e6a088440 | [
"MIT"
] | null | null | null | 2021/Day 1/Day 1 - CPP/Program.cpp | edgorman/Advent-of-Code | 7c354dfdfd0c072c59b15bcac265c19e6a088440 | [
"MIT"
] | null | null | null | 2021/Day 1/Day 1 - CPP/Program.cpp | edgorman/Advent-of-Code | 7c354dfdfd0c072c59b15bcac265c19e6a088440 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <numeric>
std::string PartOne(std::vector<int> input)
{
uint32_t numberOfIncreases = 0;
for (int i = 1; i < input.size(); i++)
{
if (input[i] > input[i - 1])
{
numberOfIncreases++;
}
}
return std::to_string(numberOfIncreases);
}
std::string PartTwo(std::vector<int> input)
{
uint32_t numberOfIncreases = 0;
for (int i = 1; i < input.size() - 2; i++)
{
uint32_t prevWindow = std::accumulate(input.begin() + i - 1, input.begin() + i - 1 + 3, 0);
uint32_t nextWindow = std::accumulate(input.begin() + i, input.begin() + i + 3, 0);
if (nextWindow > prevWindow)
{
numberOfIncreases++;
}
}
return std::to_string(numberOfIncreases);
}
int main()
{
// Get input from txt file
std::string line;
std::vector<std::string> lines;
std::ifstream file("input.txt");
while (std::getline(file, line))
{
lines.push_back(line);
}
// Clean input
std::vector<int> input;
for (int i = 0; i < lines.size(); i++)
{
input.push_back(stoi(lines[i]));
}
// Part 1
std::cout << PartOne(input) << "\n";
// Part 2
std::cout << PartTwo(input) << "\n";
}
| 20.765625 | 99 | 0.545523 | [
"vector"
] |
8fc044fa85cfc2c36b7a51e1a0a4d8307f0d0ce0 | 17,269 | cpp | C++ | src/embeddings/tools/glove.cpp | Lolik111/meta | c7019401185cdfa15e1193aad821894c35a83e3f | [
"MIT"
] | 615 | 2015-01-31T17:14:03.000Z | 2022-03-27T03:03:02.000Z | src/embeddings/tools/glove.cpp | Lolik111/meta | c7019401185cdfa15e1193aad821894c35a83e3f | [
"MIT"
] | 167 | 2015-01-20T17:48:16.000Z | 2021-12-20T00:15:29.000Z | src/embeddings/tools/glove.cpp | Lolik111/meta | c7019401185cdfa15e1193aad821894c35a83e3f | [
"MIT"
] | 264 | 2015-01-30T00:08:01.000Z | 2022-03-02T17:19:11.000Z | /**
* @file glove.cpp
* @author Chase Geigle
*
* This tool builds word embedding vectors from a weighted cooccurrence
* matrix using the GloVe model.
*
* @see http://nlp.stanford.edu/projects/glove/
*/
#include <thread>
#include "cpptoml.h"
#include "meta/embeddings/cooccur_iterator.h"
#include "meta/io/filesystem.h"
#include "meta/io/packed.h"
#include "meta/logging/logger.h"
#include "meta/parallel/thread_pool.h"
#include "meta/util/aligned_allocator.h"
#include "meta/util/array_view.h"
#include "meta/util/printing.h"
#include "meta/util/progress.h"
#include "meta/util/random.h"
#include "meta/util/time.h"
using namespace meta;
std::size_t shuffle_partition(const std::string& prefix, std::size_t max_ram,
std::size_t num_partitions)
{
using namespace embeddings;
using vec_type = std::vector<cooccur_record>;
using diff_type = vec_type::iterator::difference_type;
std::mt19937 engine{std::random_device{}()};
vec_type records(max_ram / sizeof(cooccur_record));
// read in RAM sized chunks and shuffle in memory and write out to disk
std::vector<uint64_t> chunk_sizes;
std::size_t total_records = 0;
cooccur_iterator input{prefix + "/cooccur.bin"};
auto elapsed = common::time([&]() {
printing::progress progress{" > Shuffling (pass 1): ",
input.total_bytes()};
while (input != cooccur_iterator{})
{
std::size_t i = 0;
for (; i < records.size() && input != cooccur_iterator{};
++i, ++input)
{
progress(input.bytes_read());
records[i] = *input;
}
std::shuffle(records.begin(),
records.begin() + static_cast<diff_type>(i), engine);
std::ofstream output{prefix + "/cooccur-shuf."
+ std::to_string(chunk_sizes.size())
+ ".tmp",
std::ios::binary};
total_records += i;
chunk_sizes.push_back(i);
for (std::size_t j = 0; j < i; ++j)
io::packed::write(output, records[j]);
}
});
LOG(info) << "Shuffling pass 1 took " << elapsed.count() / 1000.0
<< " seconds" << ENDLG;
std::vector<cooccur_iterator> chunks;
chunks.reserve(chunk_sizes.size());
for (std::size_t i = 0; i < chunk_sizes.size(); ++i)
{
chunks.emplace_back(prefix + "/cooccur-shuf." + std::to_string(i)
+ ".tmp");
}
std::vector<std::ofstream> outputs(num_partitions);
for (std::size_t i = 0; i < outputs.size(); ++i)
{
outputs[i].open(prefix + "/cooccur-shuf." + std::to_string(i) + ".bin",
std::ios::binary);
}
{
printing::progress progress{" > Shuffling (pass 2): ", total_records};
uint64_t num_read = 0;
while (true)
{
// read in records from each chunk on disk. Records are taken from
// chunks with probability proportional to their total size (in
// records).
std::size_t i = 0;
for (std::size_t j = 0; j < chunk_sizes.size(); ++j)
{
auto to_write = std::max<std::size_t>(
static_cast<std::size_t>(static_cast<double>(chunk_sizes[j])
/ total_records * records.size()),
1);
for (std::size_t n = 0; n < to_write; ++n)
{
if (chunks[j] == cooccur_iterator{} || i == records.size())
break;
records[i] = *chunks[j];
++chunks[j];
++i;
progress(++num_read);
}
}
if (i == 0)
break;
// partition the records into the output files randomly
for (std::size_t j = 0; j < i; ++j)
{
auto idx = random::bounded_rand(engine, outputs.size());
io::packed::write(outputs[idx], records[j]);
}
}
}
// delete temporary files
for (std::size_t i = 0; i < chunk_sizes.size(); ++i)
{
filesystem::delete_file(prefix + "/cooccur-shuf." + std::to_string(i)
+ ".tmp");
}
return total_records;
}
class glove_exception : public std::runtime_error
{
public:
using std::runtime_error::runtime_error;
};
class glove_trainer
{
public:
glove_trainer(const cpptoml::table& embed_cfg)
{
// extract building parameters
auto prefix = *embed_cfg.get_as<std::string>("prefix");
auto max_ram = embed_cfg.get_as<std::size_t>("max-ram").value_or(4096)
* 1024 * 1024;
vector_size_
= embed_cfg.get_as<std::size_t>("vector-size").value_or(50);
auto num_threads
= embed_cfg.get_as<std::size_t>("num-threads")
.value_or(std::max(1u, std::thread::hardware_concurrency()));
auto iters = embed_cfg.get_as<std::size_t>("max-iter").value_or(25);
learning_rate_
= embed_cfg.get_as<double>("learning-rate").value_or(0.05);
xmax_ = embed_cfg.get_as<double>("xmax").value_or(100.0);
scale_ = embed_cfg.get_as<double>("scale").value_or(0.75);
auto num_rare = embed_cfg.get_as<uint64_t>("unk-num-avg").value_or(100);
if (!filesystem::file_exists(prefix + "/vocab.bin"))
{
LOG(fatal) << "Vocabulary has not yet been generated, please "
"do this before learning word embeddings"
<< ENDLG;
throw glove_exception{"no vocabulary file found in " + prefix};
}
if (!filesystem::file_exists(prefix + "/cooccur.bin"))
{
LOG(fatal)
<< "Cooccurrence matrix has not yet been generated, please "
"do this before learning word embeddings"
<< ENDLG;
throw glove_exception{"no cooccurrence matrix found in " + prefix};
}
// shuffle the data and partition it into equal parts for each
// thread
auto total_records = shuffle_partition(prefix, max_ram, num_threads);
std::size_t num_words = 0;
{
std::ifstream vocab{prefix + "/vocab.bin", std::ios::binary};
io::packed::read(vocab, num_words);
}
// two vectors for each word (target and context vectors)
// each has vector_size number of features, plus one bias weight
auto size = num_words * 2 * (vector_size_ + 1);
weights_.resize(size);
grad_squared_.resize(size, 1.0);
// randomly initialize the word embeddings and biases
{
std::mt19937 engine{std::random_device{}()};
std::generate(weights_.begin(), weights_.end(), [&]() {
// use the word2vec style initialization
// I'm not entirely sure why, but this seems
// to do better than initializing the vectors
// to lie in the unit cube. Maybe scaling?
auto rnd = random::bounded_rand(engine, 65536);
return (rnd / 65536.0 - 0.5) / (vector_size_ + 1);
});
}
// train using the specified number of threads
train(prefix, num_threads, iters, total_records);
// delete the temporary shuffled cooccurrence files
for (std::size_t i = 0; i < num_threads; ++i)
filesystem::delete_file(prefix + "/cooccur-shuf."
+ std::to_string(i) + ".bin");
// save the target and context word embeddings
save(prefix, num_words, num_rare);
}
util::array_view<double> target_vector(uint64_t term)
{
return {weights_.data() + (term * 2 * (vector_size_ + 1)),
vector_size_};
}
util::array_view<const double> target_vector(uint64_t term) const
{
return {weights_.data() + (term * 2 * (vector_size_ + 1)),
vector_size_};
}
double& target_bias(uint64_t term)
{
return weights_[term * 2 * (vector_size_ + 1) + vector_size_];
}
double target_bias(uint64_t term) const
{
return weights_[term * 2 * (vector_size_ + 1) + vector_size_];
}
util::array_view<double> context_vector(uint64_t term)
{
return {weights_.data() + (term * 2 + 1) * (vector_size_ + 1),
vector_size_};
}
util::array_view<const double> context_vector(uint64_t term) const
{
return {weights_.data() + (term * 2 + 1) * (vector_size_ + 1),
vector_size_};
}
double& context_bias(uint64_t term)
{
return weights_[(term * 2 + 1) * (vector_size_ + 1) + vector_size_];
}
double context_bias(uint64_t term) const
{
return weights_[(term * 2 + 1) * (vector_size_ + 1) + vector_size_];
}
double score(uint64_t target, uint64_t context) const
{
auto tv = target_vector(target);
auto cv = context_vector(context);
return std::inner_product(tv.begin(), tv.end(), cv.begin(), 0.0)
+ target_bias(target) + context_bias(context);
}
private:
util::array_view<double> target_gradsq(uint64_t term)
{
return {grad_squared_.data() + (term * 2 * (vector_size_ + 1)),
vector_size_};
}
double& target_bias_gradsq(uint64_t term)
{
return grad_squared_[term * 2 * (vector_size_ + 1) + vector_size_];
}
util::array_view<double> context_gradsq(uint64_t term)
{
return {grad_squared_.data() + (term * 2 + 1) * (vector_size_ + 1),
vector_size_};
}
double& context_bias_gradsq(uint64_t term)
{
return grad_squared_[(term * 2 + 1) * (vector_size_ + 1)
+ vector_size_];
}
void train(const std::string& prefix, std::size_t num_threads,
std::size_t iters, std::size_t total_records)
{
parallel::thread_pool pool{num_threads};
for (std::size_t i = 1; i <= iters; ++i)
{
printing::progress progress{" > Iteration: ", total_records};
std::atomic_size_t records{0};
std::vector<std::future<double>> futures;
futures.reserve(num_threads);
for (std::size_t t = 0; t < num_threads; ++t)
{
futures.emplace_back(pool.submit_task([&, t]() {
return train_thread(prefix, t, progress, records);
}));
}
double total_cost = 0.0;
auto elapsed = common::time([&]() {
for (auto& fut : futures)
total_cost += fut.get();
});
progress.end();
LOG(progress) << "> Iteration " << i << "/" << iters
<< ": avg cost = " << total_cost / total_records
<< ", " << elapsed.count() / 1000.0 << " seconds\n"
<< ENDLG;
}
}
double cost_weight(double cooccur) const
{
return (cooccur < xmax_) ? std::pow(cooccur / xmax_, scale_) : 1.0;
}
void update_weight(double* weight, double* gradsq, double grad)
{
// adaptive gradient update
*weight -= grad / std::sqrt(*gradsq);
*gradsq += grad * grad;
}
double train_thread(const std::string& prefix, std::size_t thread_id,
printing::progress& progress,
std::atomic_size_t& records)
{
using namespace embeddings;
cooccur_iterator iter{prefix + "/cooccur-shuf."
+ std::to_string(thread_id) + ".bin"};
double cost = 0.0;
for (; iter != cooccur_iterator{}; ++iter)
{
progress(records++);
auto record = *iter;
auto diff = score(record.target, record.context)
- std::log(record.weight);
auto weighted_diff = cost_weight(record.weight) * diff;
// cost is weighted squared difference
cost += 0.5 * weighted_diff * diff;
auto delta = weighted_diff * learning_rate_;
auto target = target_vector(record.target);
auto targ_gradsq = target_gradsq(record.target);
auto context = context_vector(record.context);
auto ctx_gradsq = context_gradsq(record.context);
auto target_it = target.begin();
auto target_grad_it = targ_gradsq.begin();
auto context_it = context.begin();
auto context_grad_it = ctx_gradsq.begin();
auto target_end = target.end();
// update the embedding vectors
while (target_it != target_end)
{
auto target_grad = delta * *context_it;
auto context_grad = delta * *target_it;
update_weight(target_it, target_grad_it, target_grad);
update_weight(context_it, context_grad_it, context_grad);
++target_it;
++target_grad_it;
++context_it;
++context_grad_it;
}
// update the bias terms
update_weight(&target_bias(record.target),
&target_bias_gradsq(record.target), delta);
update_weight(&context_bias(record.context),
&context_bias_gradsq(record.context), delta);
}
return cost;
}
void save(const std::string& prefix, uint64_t num_words,
uint64_t num_rare) const
{
// target embeddings
{
std::ofstream output{prefix + "/embeddings.target.bin",
std::ios::binary};
printing::progress progress{" > Saving target embeddings: ",
num_words};
io::packed::write(output, vector_size_);
save_embeddings(output, num_words, num_rare, progress,
[&](uint64_t term) { return target_vector(term); });
}
// context embeddings
{
std::ofstream output{prefix + "/embeddings.context.bin",
std::ios::binary};
printing::progress progress{" > Saving context embeddings: ",
num_words};
io::packed::write(output, vector_size_);
save_embeddings(
output, num_words, num_rare, progress,
[&](uint64_t term) { return context_vector(term); });
}
}
template <class VectorFetcher>
void save_embeddings(std::ofstream& output, uint64_t num_words,
uint64_t num_rare, printing::progress& progress,
VectorFetcher&& vf) const
{
for (uint64_t tid = 0; tid < num_words; ++tid)
{
progress(tid);
const auto& vec = vf(tid);
write_normalized(vec.begin(), vec.end(), output);
}
util::aligned_vector<double> unk_vec(vector_size_, 0.0);
auto num_to_average = std::min(num_rare, num_words);
for (uint64_t tid = num_words - num_rare; tid < num_words; ++tid)
{
const auto& vec = vf(tid);
std::transform(unk_vec.begin(), unk_vec.end(), vec.begin(),
unk_vec.begin(),
[=](double unkweight, double vecweight) {
return unkweight + vecweight / num_to_average;
});
}
write_normalized(unk_vec.begin(), unk_vec.end(), output);
}
template <class ForwardIterator>
void write_normalized(ForwardIterator begin, ForwardIterator end,
std::ofstream& output) const
{
auto len = std::sqrt(
std::accumulate(begin, end, 0.0, [](double accum, double weight) {
return accum + weight * weight;
}));
std::for_each(begin, end, [&](double weight) {
io::packed::write(output, weight / len);
});
}
util::aligned_vector<double> weights_;
util::aligned_vector<double> grad_squared_;
std::size_t vector_size_;
double xmax_;
double scale_;
double learning_rate_;
};
int main(int argc, char** argv)
{
if (argc < 2)
{
std::cerr << "Usage: " << argv[0] << " config.toml" << std::endl;
return 1;
}
logging::set_cerr_logging();
auto config = cpptoml::parse_file(argv[1]);
auto embed_cfg = config->get_table("embeddings");
if (!embed_cfg)
{
std::cerr << "Missing [embeddings] configuration in " << argv[1]
<< std::endl;
return 1;
}
try
{
glove_trainer trainer{*embed_cfg};
}
catch (const glove_exception& ex)
{
LOG(fatal) << ex.what() << ENDLG;
return 1;
}
return 0;
}
| 33.662768 | 80 | 0.534484 | [
"vector",
"model",
"transform"
] |
8fcae12135f7f94f80f34970dec0497d38f97742 | 807 | cc | C++ | test/replace.cc | fcharlie/BelaUtils | 3d3f8e48a5e73a7427c951ff048f267e0360b5ae | [
"Apache-2.0"
] | 28 | 2020-07-19T11:15:36.000Z | 2022-03-18T02:52:39.000Z | test/replace.cc | fcharlie/BelaUtils | 3d3f8e48a5e73a7427c951ff048f267e0360b5ae | [
"Apache-2.0"
] | null | null | null | test/replace.cc | fcharlie/BelaUtils | 3d3f8e48a5e73a7427c951ff048f267e0360b5ae | [
"Apache-2.0"
] | null | null | null | #include <vector>
#include <string>
#include <string_view>
#include <cstdio>
std::string ReplaceAll(std::string_view str, std::string_view rep,
std::string_view to) {
std::string s;
s.reserve(str.size());
while (!str.empty()) {
auto pos = str.find(rep);
if (pos == std::string::npos) {
s.append(str);
break;
}
s.append(str.substr(0, pos)).append(to);
str.remove_prefix(pos + rep.size());
}
return s;
}
int main() {
constexpr std::string_view svs[] = {"dewdhedewewdeAB", "dewdewdewdewqdewdB",
"vvvvvvv", "ABABABABABABAB",
"ZZAHHBABBDDBAAB"};
for (auto s : svs) {
fprintf(stderr, "%s -> [%s]\n", s.data(), ReplaceAll(s, "AB", "B").data());
}
return 0;
}
| 26.032258 | 79 | 0.537794 | [
"vector"
] |
8fd0b1bf992359dd08c85a9be316fa2f001dc5e8 | 1,635 | cpp | C++ | Entity.cpp | EWBiv/graphics-project | 7343d467c0184a2b23d2ca5c8c9d9ef0c22d4088 | [
"MIT"
] | null | null | null | Entity.cpp | EWBiv/graphics-project | 7343d467c0184a2b23d2ca5c8c9d9ef0c22d4088 | [
"MIT"
] | null | null | null | Entity.cpp | EWBiv/graphics-project | 7343d467c0184a2b23d2ca5c8c9d9ef0c22d4088 | [
"MIT"
] | null | null | null | #include "Entity.h"
#include <d3d11.h>
using namespace DirectX;
Entity::Entity(Mesh* mesh, Material* mat, bool draw)
{
mesh_ = mesh;
material_ = mat;
shouldDraw = draw;
}
Entity::~Entity()
{
}
Mesh* Entity::GetMesh()
{
return mesh_;
}
Transform* Entity::GetTransform()
{
return &transform_;
}
Material* Entity::GetMaterial()
{
return material_;
}
void Entity::SetDrawState(bool draw)
{
shouldDraw = draw;
}
bool Entity::GetDrawState()
{
return shouldDraw;
}
void Entity::Draw(Microsoft::WRL::ComPtr<ID3D11DeviceContext> cntxt,Camera* c,float totalTime)
{
//Used to have to do VS or PS SetShader from the context before added simple shader
material_->GetVertexShader()->SetShader();
material_->GetPixelShader()->SetShader();
SimpleVertexShader* vs = material_->GetVertexShader();
vs->SetMatrix4x4("world", transform_.GetWorldMatrix()); //Get world matrix from entities transform
vs->SetMatrix4x4("view", c->GetView()); //Get View matrix from passed in camera
vs->SetMatrix4x4("projection", c->GetProjection()); //Get Projection matrix from passed in camera
vs->SetMatrix4x4("worldInvTranspose", transform_.GetWorldInverseTranspose());
vs->CopyAllBufferData();
//Used to have to manually copy it over using memcpy, but now uses simple shader call to copy the buffer
SimplePixelShader* ps = material_->GetPixelShader();
ps->SetFloat4("colorTint", material_->GetColorTint()); //Get color tint from the material
ps->SetFloat3("cameraPosition", c->GetTransform()->GetPosition()); //Needs to be adjusted when >1 camera is in scene - needs current camera
ps->CopyAllBufferData();
mesh_->Draw();
}
| 24.772727 | 140 | 0.73211 | [
"mesh",
"transform"
] |
8fd3ff5dec83a8683693a239ae24f8c73fdb5685 | 4,349 | cpp | C++ | GIDI/Src/GIDI_array3d.cpp | Mathnerd314/gidiplus | ed4c48ab399a964fe782f73d0a065849b00090bb | [
"MIT-0",
"MIT"
] | null | null | null | GIDI/Src/GIDI_array3d.cpp | Mathnerd314/gidiplus | ed4c48ab399a964fe782f73d0a065849b00090bb | [
"MIT-0",
"MIT"
] | null | null | null | GIDI/Src/GIDI_array3d.cpp | Mathnerd314/gidiplus | ed4c48ab399a964fe782f73d0a065849b00090bb | [
"MIT-0",
"MIT"
] | null | null | null | /*
# <<BEGIN-copyright>>
# Copyright 2019, Lawrence Livermore National Security, LLC.
# See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: MIT
# <<END-copyright>>
*/
#include <stdlib.h>
#include <algorithm>
#include "GIDI.hpp"
#include <HAPI.hpp>
namespace GIDI {
/*! \class Array3d
* Class to store a 3d array.
*/
/* *********************************************************************************************************//**
*
* @param a_node [in] The **HAPI::Node** to be parsed and used to construct the Array3d.
* @param a_setupInfo [in] Information create my the Protare constructor to help in parsing.
* @param a_useSystem_strtod [in] Flag passed to the function nfu_stringToListOfDoubles.
***********************************************************************************************************/
Array3d::Array3d( HAPI::Node const &a_node, SetupInfo &a_setupInfo, int a_useSystem_strtod ) :
Form( a_node, a_setupInfo, FormType::array3d ),
m_array( a_node, a_setupInfo, 3, a_useSystem_strtod ) {
}
/* *********************************************************************************************************//**
***********************************************************************************************************/
Array3d::~Array3d( ) {
}
/* *********************************************************************************************************//**
* Only for internal use. Called by ProtareTNSL instance to zero the lower energy multi-group data covered by the ProtareSingle that
* contains the TNSL data covers the lower energy multi-group data.
*
* @param a_maxTNSL_index [in] All elements up to "row" *a_maxTNSL_index* exclusive are zero-ed.
***********************************************************************************************************/
void Array3d::modifiedMultiGroupElasticForTNSL( int a_maxTNSL_index ) {
std::vector<int> const &m_shape = m_array.shape( );
int maxFlatIndex = a_maxTNSL_index * m_shape[1] * m_shape[2];
m_array.setToValueInFlatRange( 0, maxFlatIndex, 0.0 );
}
/* *********************************************************************************************************//**
* Returns the matrix that represents the specified 3rd dimension. That is the matrix M[i][j] for all i, j of A2d[i][j][*a_index*].
* This is mainly used for multi-group, Legendre expanded transfer matrices where a specific Legendre order is requested. This is,
* the matrix represent the *energy_in* as rows and the *energy_outp* as columns for a specific Legendre order.
*
* @param a_index [in] The requested *index* for the 3rd dimension.
***********************************************************************************************************/
Matrix Array3d::matrix( std::size_t a_index ) const {
if( size( ) <= a_index ) {
Matrix matrix( 0, 0 );
return( matrix );
}
std::size_t numberOfOrders = m_array.m_shape[2], rows = m_array.m_shape[0], columns = m_array.m_shape[1];
Matrix matrix( rows, columns );
std::size_t lengthSum = 0;
for( std::size_t i1 = 0; i1 < m_array.m_numberOfStarts; ++i1 ) {
std::size_t start = m_array.m_starts[i1];
std::size_t length = m_array.m_lengths[i1];
std::size_t energyInIndex = start / ( numberOfOrders * columns );
std::size_t energyOutIndex = start % ( numberOfOrders * columns );
std::size_t orderIndex = energyOutIndex % numberOfOrders;
energyOutIndex /= numberOfOrders;
std::size_t step = a_index - orderIndex;
if( orderIndex > a_index ) {
++energyOutIndex;
if( energyOutIndex >= columns ) {
energyOutIndex = 0;
++energyInIndex;
}
step += numberOfOrders;
}
std::size_t dataIndex = lengthSum + step;
for( ; step < length; step += numberOfOrders ) {
matrix.set( energyInIndex, energyOutIndex, m_array.m_dValues[dataIndex] );
++energyOutIndex;
if( energyOutIndex >= columns ) {
energyOutIndex = 0;
++energyInIndex;
}
dataIndex += numberOfOrders;
}
lengthSum += length;
}
return( matrix );
}
}
| 38.830357 | 132 | 0.509772 | [
"shape",
"vector",
"3d"
] |
8fd4fdfaf7940de69cc14f6666e09ece85cd3322 | 4,475 | cpp | C++ | Doodle Jump/source/player/Player.cpp | AlexTemnyakov/Doodle-Jump | 9d6809d3180b88e962fdc3557682c64599cfcfaf | [
"MIT"
] | 1 | 2019-08-27T15:17:23.000Z | 2019-08-27T15:17:23.000Z | Doodle Jump/source/player/Player.cpp | AlexTemnyakov/Doodle-Jump | 9d6809d3180b88e962fdc3557682c64599cfcfaf | [
"MIT"
] | null | null | null | Doodle Jump/source/player/Player.cpp | AlexTemnyakov/Doodle-Jump | 9d6809d3180b88e962fdc3557682c64599cfcfaf | [
"MIT"
] | null | null | null | #include "Player.h"
#include <thread>
Rectangle* collisions(Player* p, set<Block*> blocks);
Rectangle* hasGround(Player* p, set<Block*> blocks);
Player::Player(const char* texturePath, int w, int h, int _x, int _y, SDL_Renderer* renderer)
{
Utils u;
textureLeft = new Texture(u.playersTextureLeftPath, w, h, renderer);
textureRight = new Texture(u.playersTextureRightPath, w, h, renderer);
width = w;
height = h;
x = _x;
y = _y;
dir = true;
totalDistCurrent = 0;
totalDistMax = 0;
}
Player::~Player()
{
textureLeft->~Texture();
textureRight->~Texture();
}
void Player::render(SDL_Renderer* renderer)
{
if (dir)
textureRight->render(renderer, x, y);
else
textureLeft->render(renderer, x, y);
}
void Player::move(int moveX, int moveY, set<Block*> blocks)
{
if (moveX > 0) // move to the right
{
dir = true;
if (x + width + moveX < u.W_WIDTH)
{
x += moveX;
Rectangle* c = collisions(this, blocks);
if (c != NULL)
{
//printf("Collision moveX > 0\n");
//x = c.x - width - 1;
x -= moveX;
return;
}
}
else
{
x = u.W_WIDTH - width;
}
}
else if (moveX < 0) // move to the left
{
dir = false;
if (x + moveX > 0)
{
x += moveX;
Rectangle* c = collisions(this, blocks);
if (c != NULL)
{
//printf("Collision moveX < 0\n");
x -= moveX;
return;
}
}
else
{
x = 0;
}
}
/*if (moveY < 0)
{
if (y + moveY > 0)
{
y += moveY;
Rectangle c = collisions(this, blocks);
if (c.x != -1)
{
printf("Collision moveY < 0\n");
y = c.y + c.height + 1;
return;
}
}
else
y = 0;
}
else
{
y += moveY;
Rectangle c = collisions(this, blocks);
if (c.x != -1)
{
printf("Collision moveY > 0\n");
y = c.y - height - 1;
return;
}
}*/
}
void Player::update(set<Block*> blocks)
{
int yPrev = y;
int shift = 0;
if (jumping)
{
//printf("Jumping... Distance %d\n", jumpDist);
if (jumpTimer == 0)
{
jumpTimer = t.milliseconds();
}
else
{
jumpTotalTime = t.milliseconds() - jumpTimer;
jumpTimer = t.milliseconds();
}
// because of shifting the world if the player is above than 1/3 part of the window,
// we need to avoid extension of the jump
shift = (y < u.W_HEIGHT / 3) ? 8 : 0;
// how long the player has jumped
int jumpRange = 0;
if (jumpDist < 80)
{
y -= 10;
jumpDist += 10 + shift;
jumpRange = 10;
}
else if (jumpDist < 220)
{
y -= 8;
jumpDist += 8 + shift;
jumpRange = 8;
}
else if (jumpDist < 280)
{
y -= 5;
jumpDist += 5 + shift;
jumpRange = 5;
}
else
{
//printf("End of jumping\n");
jumping = false;
jumpDist = 0;
jumpTimer = 0;
jumpTotalTime = 0;
jumpRange = 0;
return;
}
// if there is a collision, move the player back
if (collisions(this, blocks) != NULL)
{
y += jumpRange;
jumpDist = 0;
jumping = false;
jumpTotalTime = 0;
jumpTimer = 0;
jumpRange = 0;
}
}
else
{
jump(blocks);
// free fall
if (hasGround(this, blocks) == NULL)
{
y += 15;
Rectangle* r = hasGround(this, blocks);
if (r != NULL)
{
y = r->y - height - 1;
}
}
}
int dist = yPrev - (y - shift);
totalDistCurrent += dist;
if (totalDistCurrent > totalDistMax)
totalDistMax = totalDistCurrent;
}
void Player::jump(set<Block*> blocks)
{
if (hasGround(this, blocks) != NULL && jumpDist == 0 && jumpTimer == 0)
{
jumping = true;
}
}
Rectangle Player::getRectangle()
{
Rectangle r = { x, y, width, height };
return r;
}
int Player::getY()
{
return y;
}
int Player::getX()
{
return x;
}
int Player::getWidth()
{
return width;
}
int Player::getHeight()
{
return height;
}
int Player::getTotalDistance()
{
return totalDistMax;
}
Rectangle* collisions(Player* p, set<Block*> blocks)
{
for (auto b : blocks)
{
if (rectOverlap(p->getRectangle(), b->getRectangle()))
{
Rectangle* r = &b->getRectangle();
return r;
}
}
return NULL;
}
Rectangle* hasGround(Player* p, set<Block*> blocks)
{
for (auto b : blocks)
{
bool yInRange = (p->getY() + p->getHeight() + 1 >= b->getY()) && (p->getY() + p->getHeight() + 1 <= b->getY() + b->getHeight());
bool xInRange = ((p->getX() >= b->getX()) && (p->getX() <= b->getX() + b->getWidth())) || ((p->getX() + p->getWidth() >= b->getX()) && (p->getX() + p->getWidth() <= b->getX() + b->getWidth()));
if (xInRange && yInRange)
{
Rectangle r = b->getRectangle();
b->setTouched();
return &r;
}
}
return NULL;
}
| 17.54902 | 195 | 0.57162 | [
"render"
] |
8fdd4a27690d26e70587a556ef7cdc34026f0d25 | 9,619 | hpp | C++ | ridge_detection/rd/utils/assessment_quality.hpp | play7046118/RidgeDetection | 701b55948fff23fd516d8ba3929b03edb0c9b4c5 | [
"MIT"
] | 10 | 2016-10-24T16:38:45.000Z | 2021-09-23T13:53:54.000Z | ridge_detection/rd/utils/assessment_quality.hpp | play7046118/RidgeDetection | 701b55948fff23fd516d8ba3929b03edb0c9b4c5 | [
"MIT"
] | null | null | null | ridge_detection/rd/utils/assessment_quality.hpp | play7046118/RidgeDetection | 701b55948fff23fd516d8ba3929b03edb0c9b4c5 | [
"MIT"
] | 5 | 2020-02-22T23:30:02.000Z | 2021-09-23T12:57:42.000Z | /**
* @file assessment_quality.hpp
* @author Adam Rogowiec
*
* This file is an integral part of the master thesis entitled:
* "Elaboration and implementation in CUDA technology parallel version of
* estimation of multidimensional random variable density function ridge
* detection algorithm."
* , which is conducted under the supervision of prof. dr hab. inż. Marka
* Nałęcza.
*
* Institute of Control and Computation Engineering Faculty of Electronics and
* Information Technology Warsaw University of Technology 2016
*/
#pragma once
#include "rd/cpu/samples_generator.hpp"
#include <vector>
#include <stdexcept>
#include <limits>
#include <algorithm>
#include <cmath>
#ifdef RD_USE_OPENMP
#include <omp.h>
#endif
namespace rd
{
template <typename T>
class RDAssessmentQuality
{
protected:
size_t pointCnt;
size_t dim;
public:
RDAssessmentQuality(
size_t dim)
:
pointCnt(0),
dim(dim)
{}
RDAssessmentQuality(
size_t pointCnt,
size_t dim)
:
pointCnt(pointCnt),
dim(dim)
{
idealPattern.resize(pointCnt * dim);
}
virtual ~RDAssessmentQuality() {};
void clean() {
idealPattern.clear();
}
virtual void genIdealPattern(
size_t pointCnt_,
size_t dim_)
{
pointCnt = pointCnt_;
dim = dim_;
clean();
idealPattern.resize(pointCnt * dim);
}
virtual void genIdealPattern(
size_t dim_)
{
pointCnt = 0;
dim = dim_;
clean();
}
/**
* @brief Calculates Hausdorff metric from idealPattern.
*
* @param testSet Set for which we want to calculate Hausdorff metric.
*
* @return Hausdorff distance from idealPattern.
*/
virtual T hausdorffDistance(
std::vector<T> const & testSet) const
{
if (testSet.empty())
{
#ifdef RD_DEBUG
std::cout << ">>>>> hausdorffDistance on empty set!! <<<<<<<" << std::endl;
#endif
return -1;
}
T distAB = setDistance(testSet, idealPattern);
T distBA = setDistance(idealPattern, testSet);
#ifdef RD_DEBUG
std::cout << ">>>>>>>>> dist(set, ideal): " << distAB << ", dist(ideal, set): " << distBA << "<<<<<<<<<<<\n";
#endif
// return std::max(setDistance(testSet, idealPattern),
// setDistance(idealPattern, testSet));
return std::max(distAB, distBA);
}
/**
* @brief Calculates range of @p srcSet distance form idealPattern statistics
*
* @param srcSet Set to examine.
* @param medianDist
* @param avgDist
* @param minDist
* @param maxDist
*/
void setDistanceStats(
std::vector<T> const & srcSet,
T & medianDist,
T & avgDist,
T & minDist,
T & maxDist) const
{
std::vector<T>&& distances = calcDistances(srcSet, idealPattern);
std::sort(distances.begin(), distances.end());
minDist = distances.front();
maxDist = distances.back();
medianDist = distances[distances.size() / 2];
T avg = 0;
for (T const &d : distances)
{
avg += d;
}
avgDist = avg /= distances.size();
}
protected:
std::vector<T> idealPattern;
/**
* @brief Calculates distance from nearest point from @p set to @srcPoint
*
* @param srcPoint Pointer to reference point coordinates
* @param[in] set Vector containing points to search.
*
* @return Distance from nearest point from @p set to @srcPoint
*/
virtual T distance(
T const * srcPoint,
std::vector<T> const & set) const
{
T nearestDist = std::numeric_limits<T>::max();
T const * data = set.data();
#ifdef RD_USE_OPENMP
#pragma omp parallel for schedule(static) reduction(min:nearestDist)
#endif
for (size_t k = 0; k < set.size(); k += dim)
{
T dist = squareEuclideanDistance(srcPoint, data + k, dim);
if (dist < nearestDist)
{
nearestDist = dist;
}
}
return std::sqrt(nearestDist);
}
/**
* @brief Calculate distance from each @p setA point to @p setB
*
* @param setA Point set for which points we calculate distances
* @param setB Point set from which we calculate distances
*
* @return Vector containing distances from each @p setA point to @p setB
*/
std::vector<T> calcDistances(
std::vector<T> const & setA,
std::vector<T> const & setB) const
{
std::vector<T> distances;
T const * srcPoints = setA.data();
for (size_t k = 0; k < setA.size(); k += dim)
{
distances.push_back(distance(srcPoints + k, setB));
}
return distances;
}
/**
* @brief Calculate distance from @p setA to @p setB
*
* @param setA
* @param setB
*
* @return distance
*/
T setDistance(
std::vector<T> const & setA,
std::vector<T> const & setB) const
{
std::vector<T>&& distances = calcDistances(setA, setB);
std::sort(distances.begin(), distances.end());
return distances.back();
}
/**
* @brief Calculate square euclidean distance
*
* @param p1 First point
* @param p2 Second point
*
* @return square euclidean distance
*/
T squareEuclideanDistance(T const * p1, T const * p2, size_t pDim) const
{
T dist = 0, t;
while(pDim-- > 0) {
t = *(p1++) - *(p2++);
dist += t*t;
}
return dist;
}
};
template <typename T>
class RDSpiralAssessmentQuality : public RDAssessmentQuality<T>
{
typedef RDAssessmentQuality<T> BaseT;
public:
using BaseT::genIdealPattern;
RDSpiralAssessmentQuality(
size_t pointCnt,
size_t dim,
T length,
T step)
:
BaseT(pointCnt, dim)
{
if (dim < 2 || dim > 3)
{
throw std::logic_error("Unsupported spiral dimension !");
}
if (dim == 2)
{
genSpiral2D(pointCnt, length, step, T(0), this->idealPattern.data());
}
else
{
genSpiral3D(pointCnt, length, step, T(0), this->idealPattern.data());
}
}
void genIdealPattern(
size_t pointCnt,
size_t dim,
T length,
T step)
{
BaseT::genIdealPattern(pointCnt, dim);
if (dim < 2 || dim > 3)
{
throw std::logic_error("Unsupported spiral dimension !");
}
if (dim == 2)
{
genSpiral2D(pointCnt, length, step, T(0), this->idealPattern.data());
}
else
{
genSpiral3D(pointCnt, length, step, T(0), this->idealPattern.data());
}
}
virtual ~RDSpiralAssessmentQuality() {};
};
template <typename T>
class RDSegmentAssessmentQuality : public RDAssessmentQuality<T>
{
typedef RDAssessmentQuality<T> BaseT;
public:
using BaseT::genIdealPattern;
/**
* The ideal pattern for segment is a segment with all but first coordinates set to zero.
*/
RDSegmentAssessmentQuality(
size_t pointCnt,
size_t dim)
:
BaseT(pointCnt, dim)
{
}
virtual void genIdealPattern(
size_t pointCnt,
size_t dim) override
{
BaseT::genIdealPattern(pointCnt, dim);
}
virtual ~RDSegmentAssessmentQuality() {};
/**
* @brief Calculates Hausdorff metric from idealPattern.
*
* @param testSet Set for which we want to calculate Hausdorff metric.
*
* @return Hausdorff distance from idealPattern.
*/
virtual T hausdorffDistance(
std::vector<T> const & testSet) const
{
if (testSet.empty())
{
#ifdef RD_DEBUG
std::cout << ">>>>> hausdorffDistance on empty set!! <<<<<<<" << std::endl;
#endif
return -1;
}
T distAB = this->setDistance(testSet, this->idealPattern);
#ifdef RD_DEBUG
std::cout << ">>>>>>>>> dist(set, ideal): " << distAB << "<<<<<<<<<<<\n";
#endif
return distAB;
}
protected:
/**
* @brief Calculates distance from nearest point from @p set to @srcPoint
*
* @param srcPoint Pointer to reference point coordinates
* @param[in] set Vector containing points to search.
*
* @return Distance from nearest point from @p set to @srcPoint
*/
virtual T distance(
T const * srcPoint,
std::vector<T> const & set) const
{
set.empty(); // suppress warnings
/**
* The ideal pattern for segment is a segment with all but first coordinates set to zero
*/
T nearestDist = 0;
for (size_t k = 1; k < this->dim; ++k)
{
nearestDist += srcPoint[k] * srcPoint[k];
}
return (nearestDist > 0) ? std::sqrt(nearestDist) : 0;
}
};
} // end namespace rd
| 25.313158 | 117 | 0.535399 | [
"vector"
] |
8fdd4f3f87cd130caaf865c04a93058705f1ced5 | 1,198 | cpp | C++ | components/physics/bullet_driver/sources/bullet_utils.cpp | untgames/funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 7 | 2016-03-30T17:00:39.000Z | 2017-03-27T16:04:04.000Z | components/physics/bullet_driver/sources/bullet_utils.cpp | untgames/Funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 4 | 2017-11-21T11:25:49.000Z | 2018-09-20T17:59:27.000Z | components/physics/bullet_driver/sources/bullet_utils.cpp | untgames/Funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 4 | 2016-11-29T15:18:40.000Z | 2017-03-27T16:04:08.000Z | #include "shared.h"
namespace physics
{
namespace low_level
{
namespace bullet
{
//преобразование векторов
void vector_from_bullet_vector (const btVector3& bullet_vector, math::vec3f& target_vector)
{
target_vector.x = bullet_vector.x ();
target_vector.y = bullet_vector.y ();
target_vector.z = bullet_vector.z ();
}
void bullet_vector_from_vector (const math::vec3f& vector, btVector3& target_vector)
{
target_vector.setX (vector.x);
target_vector.setY (vector.y);
target_vector.setZ (vector.z);
}
//преобразование кватернионов
void quaternion_from_bullet_quaternion (const btQuaternion& bullet_quaternion, math::quatf& target_quaternion)
{
target_quaternion.x = bullet_quaternion.getX ();
target_quaternion.y = bullet_quaternion.getY ();
target_quaternion.z = bullet_quaternion.getZ ();
target_quaternion.w = bullet_quaternion.getW ();
}
void bullet_quaternion_from_quaternion (const math::quatf& quaternion, btQuaternion& target_quaternion)
{
target_quaternion.setX (quaternion.x);
target_quaternion.setY (quaternion.y);
target_quaternion.setZ (quaternion.z);
target_quaternion.setW (quaternion.w);
}
}
}
}
| 23.96 | 111 | 0.740401 | [
"vector"
] |
8fe35f397ab11aa53743c58639d60c8dae28a6f9 | 4,030 | cpp | C++ | examples/WifiCam/handlers.cpp | RobAxt/esp32cam | 211f7d2a628e3cb71002ee9b76430a8c208c2b15 | [
"ISC"
] | null | null | null | examples/WifiCam/handlers.cpp | RobAxt/esp32cam | 211f7d2a628e3cb71002ee9b76430a8c208c2b15 | [
"ISC"
] | null | null | null | examples/WifiCam/handlers.cpp | RobAxt/esp32cam | 211f7d2a628e3cb71002ee9b76430a8c208c2b15 | [
"ISC"
] | null | null | null | #include "WifiCam.hpp"
#include <StreamString.h>
#include <uri/UriBraces.h>
static const char FRONTPAGE[] = R"EOT(
<!doctype html>
<title>esp32cam WifiCam example</title>
<style>
table,th,td { border: solid 1px #000000; border-collapse: collapse; }
th,td { padding: 0.4rem; }
a { text-decoration: none; }
footer { margin-top: 1rem; }
</style>
<body>
<h1>esp32cam WifiCam example</h1>
<table>
<thead>
<tr><th>BMP<th>JPG<th>MJPEG
<tbody id="resolutions">
<tr><td colspan="3">loading
</table>
<footer>Powered by <a href="https://esp32cam.yoursunny.dev/">esp32cam</a></footer>
<script type="module">
async function fetchText(uri, init) {
const response = await fetch(uri, init);
if (!response.ok) {
throw new Error(await response.text());
}
return (await response.text()).trim().replaceAll("\r\n", "\n");
}
try {
const list = (await fetchText("/resolutions.csv")).split("\n");
document.querySelector("#resolutions").innerHTML = list.map((r) => `<tr>${
["bmp", "jpg", "mjpeg"].map((fmt) => `<td><a href="/${r}.${fmt}">${r}</a>`).join("")
}`).join("");
} catch (err) {
document.querySelector("#resolutions td").textContent = err.toString();
}
</script>
)EOT";
static void
serveStill(bool wantBmp)
{
auto frame = esp32cam::capture();
if (frame == nullptr) {
Serial.println("capture() failure");
server.send(500, "text/plain", "still capture error\n");
return;
}
Serial.printf("capture() success: %dx%d %zub\n", frame->getWidth(), frame->getHeight(),
frame->size());
if (wantBmp) {
if (!frame->toBmp()) {
Serial.println("toBmp() failure");
server.send(500, "text/plain", "convert to BMP error\n");
return;
}
Serial.printf("toBmp() success: %dx%d %zub\n", frame->getWidth(), frame->getHeight(),
frame->size());
}
server.setContentLength(frame->size());
server.send(200, wantBmp ? "image/bmp" : "image/jpeg");
WiFiClient client = server.client();
frame->writeTo(client);
}
static void
serveMjpeg()
{
Serial.println("MJPEG streaming begin");
WiFiClient client = server.client();
auto startTime = millis();
int nFrames = esp32cam::Camera.streamMjpeg(client);
auto duration = millis() - startTime;
Serial.printf("MJPEG streaming end: %dfrm %0.2ffps\n", nFrames, 1000.0 * nFrames / duration);
}
void
addRequestHandlers()
{
server.on("/", HTTP_GET, [] {
server.setContentLength(sizeof(FRONTPAGE));
server.send(200, "text/html");
server.sendContent(FRONTPAGE, sizeof(FRONTPAGE));
});
server.on("/robots.txt", HTTP_GET,
[] { server.send(200, "text/html", "User-Agent: *\nDisallow: /\n"); });
server.on("/resolutions.csv", HTTP_GET, [] {
StreamString b;
for (const auto& r : esp32cam::Camera.listResolutions()) {
b.println(r);
}
server.send(200, "text/csv", b);
});
server.on(UriBraces("/{}x{}.{}"), HTTP_GET, [] {
long width = server.pathArg(0).toInt();
long height = server.pathArg(1).toInt();
String format = server.pathArg(2);
if (width == 0 || height == 0 || !(format == "bmp" || format == "jpg" || format == "mjpeg")) {
server.send(404);
return;
}
auto r = esp32cam::Camera.listResolutions().find(width, height);
if (!r.isValid()) {
server.send(404, "text/plain", "non-existent resolution\n");
return;
}
if (r.getWidth() != width || r.getHeight() != height) {
server.sendHeader("Location",
String("/") + r.getWidth() + "x" + r.getHeight() + "." + format);
server.send(302);
return;
}
if (!esp32cam::Camera.changeResolution(r)) {
Serial.printf("changeResolution(%ld,%ld) failure\n", width, height);
server.send(500, "text/plain", "changeResolution error\n");
}
Serial.printf("changeResolution(%ld,%ld) success\n", width, height);
if (format == "bmp") {
serveStill(true);
} else if (format == "jpg") {
serveStill(false);
} else if (format == "mjpeg") {
serveMjpeg();
}
});
}
| 29.202899 | 98 | 0.608685 | [
"solid"
] |
8ff1f0356253cccb53ccf0c5404beea8a618c9ad | 2,345 | cpp | C++ | src/net/HttpServer.cpp | Maltliquor/HttpServer | b05825752d96e5a7331be30db7587478db9b3124 | [
"MIT"
] | null | null | null | src/net/HttpServer.cpp | Maltliquor/HttpServer | b05825752d96e5a7331be30db7587478db9b3124 | [
"MIT"
] | null | null | null | src/net/HttpServer.cpp | Maltliquor/HttpServer | b05825752d96e5a7331be30db7587478db9b3124 | [
"MIT"
] | null | null | null | #include "src/net/HttpServer.h"
#include "src/net/HttpRequest.h"
#include "src/net/HttpResponse.h"
using namespace serverlib;
namespace serverlib
{
namespace detail
{
void defaultHttpCallback(const HttpRequest&, HttpResponse* resp){
resp->setStatusCode(HttpResponse::NotFound404);
resp->setContentType("text/html");
resp->addHeader("Server", "Serverlib");
resp->setCloseConnection(true);
resp->setBody("<html><head><title>Web Blog</title></head>"
"<body><h1>404 Not Found</h1>"
"</body></html>");
}
} // namespace detail
} // namespace serverlib
HttpServer::HttpServer(EventLoop* loop,
const InetAddress& listenAddr,
const string& name,
TcpServer::Option option)
: _server(loop, listenAddr, name, option),
_http_callback(detail::defaultHttpCallback)
{
_server.setConnectionCallback(
std::bind(&HttpServer::onConnection, this, _1)); //接受新的Http连接时执行的函数
_server.setMessageCallback(
std::bind(&HttpServer::onMessage, this, _1, _2, _3)); //接受到消息时执行的函数,主要进行url分析
}
void HttpServer::start(){
_server.start();
}
void HttpServer::onConnection(const TcpConnectionPtr& conn){
if (conn->connected()) {
conn->setContext(HttpRequest());
}
}
void HttpServer::onMessage(const TcpConnectionPtr& conn,
std::vector<char> &buf, int len){
printf("In HttpServer::onMessage()\n");
HttpRequest* req = conn->getMutableContext();
if (!req->parseRequest(buf, len)) { //如果请求分析的过程中出现错误
conn->send("HTTP/1.1 400 Bad Request\r\n\r\n");
conn->shutdown();
}
if (req->isGotAll()) { //如果请求分析完毕
printf("In req->isGotAll()\n");
onRequest(conn, *req);
req->reset();
}
}
void HttpServer::onRequest(const TcpConnectionPtr& conn, const HttpRequest& req){
printf("In HttpServer::onRequest()\n");
const string& connection = req.getHeader("Connection");
bool client_close = (connection == "close" ||
(req.getVersion() == HttpRequest::vHttp10 && connection != "Keep-Alive"));
HttpResponse response(client_close);
//调用用户自定义的callback函数
_http_callback(req, &response);
std::string msg;
response.getResponseMsg(msg); //把response里面的信息组装成string,存放到msg内
conn->send(msg);
if (client_close){
conn->shutdown();
}
}
| 27.588235 | 87 | 0.652026 | [
"vector"
] |
8ff4cc2534aba8bb43d96406e4e074c8a34ffb35 | 4,578 | cpp | C++ | annotation_tools/mpii_annotator/ThreeDGroundTruthLabeler/ThreeDGroundTruthLabeler/common/UtilityWin/ConsoleHelper.cpp | strawberryfg/NAPA-NST-HPE | a11a63aaa1ebdc2836dad0b9640dffb951ab7e50 | [
"MIT"
] | 4 | 2020-12-16T12:53:48.000Z | 2021-04-20T04:11:11.000Z | annotation_tools/mpii_annotator/ThreeDGroundTruthLabeler/ThreeDGroundTruthLabeler/common/UtilityWin/ConsoleHelper.cpp | strawberryfg/NAPA-NST-HPE | a11a63aaa1ebdc2836dad0b9640dffb951ab7e50 | [
"MIT"
] | null | null | null | annotation_tools/mpii_annotator/ThreeDGroundTruthLabeler/ThreeDGroundTruthLabeler/common/UtilityWin/ConsoleHelper.cpp | strawberryfg/NAPA-NST-HPE | a11a63aaa1ebdc2836dad0b9640dffb951ab7e50 | [
"MIT"
] | 1 | 2021-01-03T01:00:58.000Z | 2021-01-03T01:00:58.000Z | /*************************************************************************\
Microsoft Research Asia
Copyright(c) 2003 Microsoft Corporation
Module Name:
Helper, to display a console window for debug
Usage:
1. Adding this CPP file into project will automatically
raise a console window with the application executed.
2. To toggle the console window in application as following
void ToggleConsole()
{
extern BOOL HasConsole();
extern void ShowConsole(BOOL);
ShowConsole(!HasConsole());
}
History:
Created on 2003 Aug. 16 by oliver_liyin
\*************************************************************************/
#include <io.h>
#include <tchar.h>
#include <conio.h>
#include <fcntl.h>
#include <stdio.h>
#include <iostream>
#include <memory>
#include <Windows.h>
/// External functions to contorl Consoles
/// Use ShowConsole to display or hide console window
extern void ShowConsole(BOOL);
/// Use HasConsole to query the state of the console window
extern BOOL HasConsole();
namespace helper
{
/// Helper to display console window and redirect IO streams
class ConsoleHelper
{
void friend ::ShowConsole(BOOL);
BOOL friend ::HasConsole();
private:
static ConsoleHelper& Instance()
{
/// Mayer's singlton pattern
static ConsoleHelper theConsole;
return theConsole;
}
ConsoleHelper() : m_hasConsole(FALSE)
{
}
~ConsoleHelper()
{
ShowConsole(FALSE);
}
void RedirectIOToConsole(const TCHAR* szTitle);
void RedirectOneStream(FILE* pStream, LPCTSTR szMode, DWORD nStdHandle);
static BOOL CtrlHandler(DWORD fdwCtrlType);
private:
BOOL m_hasConsole;
};
/// Display console window, by simply add this CPP file in project
/// It's a static object to display console when Exe is loaded
class ConsoleLoader
{
public:
ConsoleLoader()
{
::ShowConsole(TRUE);
}
~ConsoleLoader()
{
::ShowConsole(FALSE);
}
static ConsoleLoader consoleLoader;
};
#ifndef DISABLE_VTL_TRACE
/// The static instance to load console with application
ConsoleLoader consoleLoader;
#endif
void ConsoleHelper::RedirectIOToConsole(const TCHAR* szTitle)
{
FreeConsole();
AllocConsole();
SetConsoleTitle(szTitle);
// redirect three major c-lib stream to console
RedirectOneStream(stdin , _T("r"), STD_INPUT_HANDLE);
RedirectOneStream(stdout, _T("w"), STD_OUTPUT_HANDLE);
RedirectOneStream(stderr, _T("w"), STD_ERROR_HANDLE);
/// redirect std::ios streams to console
std::ios_base::sync_with_stdio();
/// hook console handler to properly exit process
SetConsoleCtrlHandler( (PHANDLER_ROUTINE) ConsoleHelper::CtrlHandler, TRUE);
}
void ConsoleHelper::RedirectOneStream(FILE* pStream, LPCTSTR szMode, DWORD nStdHandle)
{
HANDLE lStdHandle = GetStdHandle(nStdHandle);
if(lStdHandle != NULL)
{
int hConHandle = _open_osfhandle(intptr_t(lStdHandle), _O_TEXT);
if(hConHandle != -1)
{
FILE *fp = _tfdopen(hConHandle, szMode);
if (fp != NULL)
{
*pStream = *fp;
setvbuf(pStream, NULL, _IONBF, 0);
}
}
}
}
BOOL ConsoleHelper::CtrlHandler(DWORD fdwCtrlType)
{
if (fdwCtrlType == CTRL_SHUTDOWN_EVENT ||
fdwCtrlType == CTRL_LOGOFF_EVENT ||
fdwCtrlType == CTRL_CLOSE_EVENT)
{
/// if return false, the main window will be killed
/// , and therefore cause resource leak.
/// if return true, console will be locked until main process ends.
return TRUE;
}
return TRUE;
}
} /// namespace helper
void ShowConsole(BOOL show = TRUE)
{
using namespace helper;
if(show && !ConsoleHelper::Instance().m_hasConsole)
{
ConsoleHelper::Instance().RedirectIOToConsole(GetCommandLine());
ConsoleHelper::Instance().m_hasConsole = TRUE;
}
else if(!show && ConsoleHelper::Instance().m_hasConsole)
{
ConsoleHelper::Instance().m_hasConsole = FALSE;
::FreeConsole();
}
}
BOOL HasConsole()
{
using namespace helper;
return ConsoleHelper::Instance().m_hasConsole;
}
| 26.16 | 90 | 0.591525 | [
"object"
] |
8ffc31428035a5b3cd306210d1291c409125f44a | 10,489 | cpp | C++ | emitter/ppc/ppcruntime_printer.cpp | nandor/genm-opt | b3347d508fff707837d1dc8232487ebfe157fe2a | [
"MIT"
] | 13 | 2020-06-25T18:26:54.000Z | 2021-02-16T03:14:38.000Z | emitter/ppc/ppcruntime_printer.cpp | nandor/genm-opt | b3347d508fff707837d1dc8232487ebfe157fe2a | [
"MIT"
] | 3 | 2020-07-01T01:39:47.000Z | 2022-01-24T23:47:12.000Z | emitter/ppc/ppcruntime_printer.cpp | nandor/genm-opt | b3347d508fff707837d1dc8232487ebfe157fe2a | [
"MIT"
] | 2 | 2021-03-11T05:08:09.000Z | 2021-07-17T23:36:17.000Z | // This file if part of the llir-opt project.
// Licensing information can be found in the LICENSE file.
// (C) 2018 Nandor Licker. All rights reserved.
#include <llvm/BinaryFormat/ELF.h>
#include <llvm/CodeGen/MachineModuleInfo.h>
#include <llvm/IR/Mangler.h>
#include <llvm/MC/MCSectionELF.h>
#include <llvm/MC/MCInstBuilder.h>
#include <llvm/Target/PowerPC/PPCInstrInfo.h>
#include <llvm/Target/PowerPC/PPCTargetStreamer.h>
#include <llvm/Target/PowerPC/MCTargetDesc/PPCMCExpr.h>
#include "core/cast.h"
#include "core/data.h"
#include "core/prog.h"
#include "core/block.h"
#include "core/func.h"
#include "emitter/ppc/ppcruntime_printer.h"
using MCSymbol = llvm::MCSymbol;
using MCInst = llvm::MCInst;
using MCOperand = llvm::MCOperand;
using MCInstBuilder = llvm::MCInstBuilder;
using MCSymbolRefExpr = llvm::MCSymbolRefExpr;
using MCBinaryExpr = llvm::MCBinaryExpr;
using PPCMCExpr = llvm::PPCMCExpr;
namespace PPC = llvm::PPC;
// -----------------------------------------------------------------------------
char PPCRuntimePrinter::ID;
// -----------------------------------------------------------------------------
PPCRuntimePrinter::PPCRuntimePrinter(
const Prog &prog,
const llvm::TargetMachine &tm,
llvm::MCContext &ctx,
llvm::MCStreamer &os,
const llvm::MCObjectFileInfo &objInfo,
bool shared)
: RuntimePrinter(ID, prog, tm, ctx, os, objInfo, shared)
{
}
// -----------------------------------------------------------------------------
llvm::StringRef PPCRuntimePrinter::getPassName() const
{
return "LLIR PPC Data Section Printer";
}
// -----------------------------------------------------------------------------
static std::vector<llvm::Register> kXRegs =
{
PPC::X3, PPC::X4, PPC::X5, PPC::X6, PPC::X7,
PPC::X8, PPC::X9, PPC::X10, PPC::X11, PPC::X12,
PPC::X13, PPC::X14, PPC::X15, PPC::X16, PPC::X17,
PPC::X18, PPC::X19, PPC::X20, PPC::X21, PPC::X22,
PPC::X23, PPC::X24, PPC::X25, PPC::X26, PPC::X27,
};
// -----------------------------------------------------------------------------
static std::vector<llvm::Register> kFRegs =
{
PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6,
PPC::F7, PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12,
PPC::F13, PPC::F14, PPC::F15, PPC::F16, PPC::F17, PPC::F18,
PPC::F19, PPC::F20, PPC::F21, PPC::F22, PPC::F23, PPC::F24,
PPC::F25, PPC::F26, PPC::F27, PPC::F28, PPC::F29, PPC::F30,
PPC::F31,
};
// -----------------------------------------------------------------------------
void PPCRuntimePrinter::EmitCamlCallGc(llvm::Function &F)
{
auto &sti = tm_.getSubtarget<llvm::PPCSubtarget>(F);
EmitFunctionStart("caml_call_gc", sti);
// mflr 0
os_.emitInstruction(MCInstBuilder(PPC::MFLR8).addReg(PPC::X0), sti);
StoreState(PPC::X28, PPC::X0, "last_return_address", sti);
StoreState(PPC::X28, PPC::X1, "bottom_of_stack", sti);
StoreState(PPC::X28, PPC::X29, "young_ptr", sti);
StoreState(PPC::X28, PPC::X30, "young_limit", sti);
StoreState(PPC::X28, PPC::X31, "exception_pointer", sti);
// stdu 1, (32 + 200 + 248)
os_.emitInstruction(MCInstBuilder(PPC::STDU)
.addReg(PPC::X1)
.addReg(PPC::X1)
.addImm(-(32 + 200 + 248))
.addReg(PPC::X1),
sti
);
// add 0, 1, 32
os_.emitInstruction(MCInstBuilder(PPC::ADDI)
.addReg(PPC::X0)
.addReg(PPC::X1)
.addImm(32),
sti
);
StoreState(PPC::X28, PPC::X0, "gc_regs", sti);
// std xi, (32 + 8 * i)(1)
for (unsigned i = 0, n = kXRegs.size(); i < n; ++i) {
os_.emitInstruction(MCInstBuilder(PPC::STD)
.addReg(kXRegs[i])
.addImm(32 + 8 * i)
.addReg(PPC::X1),
sti
);
}
// stf xi, (32 + 200 + 8 * i)(1)
for (unsigned i = 0, n = kFRegs.size(); i < n; ++i) {
os_.emitInstruction(MCInstBuilder(PPC::STFD)
.addReg(kFRegs[i])
.addImm(232 + 8 * i)
.addReg(PPC::X1),
sti
);
}
// bl caml_garbage_collection
// nop
os_.emitInstruction(
MCInstBuilder(PPC::BL8_NOP)
.addExpr(MCSymbolRefExpr::create(
LowerSymbol("caml_garbage_collection"),
MCSymbolRefExpr::VK_None,
ctx_
)),
sti
);
LoadCamlState(PPC::X28, sti);
LoadState(PPC::X28, PPC::X29, "young_ptr", sti);
LoadState(PPC::X28, PPC::X30, "young_limit", sti);
LoadState(PPC::X28, PPC::X31, "exception_pointer", sti);
LoadState(PPC::X28, PPC::X0, "last_return_address", sti);
// mflr 11
os_.emitInstruction(MCInstBuilder(PPC::MTLR8).addReg(PPC::X0), sti);
// ld xi, (32 + 8 * i)(1)
for (unsigned i = 0, n = kXRegs.size(); i < n; ++i) {
os_.emitInstruction(MCInstBuilder(PPC::LD)
.addReg(kXRegs[i])
.addImm(32 + 8 * i)
.addReg(PPC::X1),
sti
);
}
// lf xi, (32 + 200 + 8 * i)(1)
for (unsigned i = 0, n = kFRegs.size(); i < n; ++i) {
os_.emitInstruction(MCInstBuilder(PPC::LFD)
.addReg(kFRegs[i])
.addImm(232 + 8 * i)
.addReg(PPC::X1),
sti
);
}
// addi 1, 1, 32 + 200 + 248
os_.emitInstruction(MCInstBuilder(PPC::ADDI)
.addReg(PPC::X1)
.addReg(PPC::X1)
.addImm(32 + 200 + 248),
sti
);
// blr
os_.emitInstruction(MCInstBuilder(PPC::BLR), sti);
}
// -----------------------------------------------------------------------------
static const std::unordered_map<std::string, unsigned> kOffsets =
{
#define FIELD(name, index) { #name, index },
#include "core/state.h"
#undef FIELD
};
// -----------------------------------------------------------------------------
static unsigned GetOffset(const char *name)
{
auto it = kOffsets.find(name);
assert(it != kOffsets.end() && "missing offset");
return it->second;
}
// -----------------------------------------------------------------------------
void PPCRuntimePrinter::EmitCamlCCall(llvm::Function &F)
{
auto &sti = tm_.getSubtarget<llvm::PPCSubtarget>(F);
EmitFunctionStart("caml_c_call", sti);
// mflr x28
os_.emitInstruction(MCInstBuilder(PPC::MFLR8).addReg(PPC::X28), sti);
LoadCamlState(PPC::X27, sti);
StoreState(PPC::X27, PPC::X1, "bottom_of_stack", sti);
StoreState(PPC::X27, PPC::X28, "last_return_address", sti);
// mtctr 25
os_.emitInstruction(MCInstBuilder(PPC::MTCTR8).addReg(PPC::X25), sti);
// mr 12, 25
os_.emitInstruction(MCInstBuilder(PPC::OR8)
.addReg(PPC::X12)
.addReg(PPC::X25)
.addReg(PPC::X25),
sti
);
// mr 27, 2
os_.emitInstruction(MCInstBuilder(PPC::OR8)
.addReg(PPC::X27)
.addReg(PPC::X2)
.addReg(PPC::X2),
sti
);
// bctrl
os_.emitInstruction(MCInstBuilder(PPC::BCTRL8), sti);
// mr 2, 27
os_.emitInstruction(MCInstBuilder(PPC::OR8)
.addReg(PPC::X2)
.addReg(PPC::X27)
.addReg(PPC::X27),
sti
);
// mtlr 28
os_.emitInstruction(MCInstBuilder(PPC::MTLR8).addReg(PPC::X28), sti);
// blr
os_.emitInstruction(MCInstBuilder(PPC::BLR8), sti);
}
// -----------------------------------------------------------------------------
void PPCRuntimePrinter::EmitFunctionStart(
const char *name,
const llvm::PPCSubtarget &sti)
{
auto *sym = LowerSymbol(name);
auto *symRef = MCSymbolRefExpr::create(sym, ctx_);
os_.SwitchSection(objInfo_.getTextSection());
os_.emitCodeAlignment(16);
os_.emitSymbolAttribute(sym, llvm::MCSA_Global);
os_.emitLabel(sym);
auto *globalEntry = ctx_.getOrCreateSymbol(
layout_.getPrivateGlobalPrefix() +
"func_gep_" +
llvm::Twine(name)
);
os_.emitLabel(globalEntry);
auto *globalEntryRef = MCSymbolRefExpr::create(globalEntry, ctx_);
MCSymbol *tocSymbol = ctx_.getOrCreateSymbol(".TOC.");
auto *tocDeltaExpr = MCBinaryExpr::createSub(
MCSymbolRefExpr::create(tocSymbol, ctx_),
globalEntryRef,
ctx_
);
auto *tocDeltaHi = PPCMCExpr::createHa(tocDeltaExpr, ctx_);
os_.emitInstruction(
MCInstBuilder(PPC::ADDIS)
.addReg(PPC::X2)
.addReg(PPC::X12)
.addExpr(tocDeltaHi),
sti
);
auto *tocDeltaLo = PPCMCExpr::createLo(tocDeltaExpr, ctx_);
os_.emitInstruction(
MCInstBuilder(PPC::ADDI)
.addReg(PPC::X2)
.addReg(PPC::X2)
.addExpr(tocDeltaLo),
sti
);
auto *localEntry = ctx_.getOrCreateSymbol(
layout_.getPrivateGlobalPrefix() +
"func_lep_" +
llvm::Twine(name)
);
os_.emitLabel(localEntry);
auto *localEntryRef = MCSymbolRefExpr::create(localEntry, ctx_);
auto *localOffset = MCBinaryExpr::createSub(
localEntryRef,
globalEntryRef,
ctx_
);
if (auto *ts = static_cast<llvm::PPCTargetStreamer *>(os_.getTargetStreamer())) {
ts->emitLocalEntry(llvm::cast<llvm::MCSymbolELF>(sym), localOffset);
}
}
// -----------------------------------------------------------------------------
MCSymbol *PPCRuntimePrinter::LowerSymbol(const char *name)
{
llvm::SmallString<128> sym;
llvm::Mangler::getNameWithPrefix(sym, name, layout_);
return ctx_.getOrCreateSymbol(sym);
}
// -----------------------------------------------------------------------------
void PPCRuntimePrinter::LoadCamlState(
llvm::Register state,
const llvm::PPCSubtarget &sti)
{
auto *sym = LowerSymbol("Caml_state");
auto *symHI = MCSymbolRefExpr::create(sym, MCSymbolRefExpr::VK_PPC_TOC_HA, ctx_);
os_.emitInstruction(
MCInstBuilder(PPC::ADDIS)
.addReg(state)
.addReg(PPC::X2)
.addExpr(symHI),
sti
);
auto *symLO = MCSymbolRefExpr::create(sym, MCSymbolRefExpr::VK_PPC_TOC_LO, ctx_);
os_.emitInstruction(
MCInstBuilder(PPC::LD)
.addReg(state)
.addExpr(symLO)
.addReg(state),
sti
);
}
// -----------------------------------------------------------------------------
void PPCRuntimePrinter::StoreState(
llvm::Register state,
llvm::Register val,
const char *name,
const llvm::PPCSubtarget &sti)
{
// std val, offset(state)
os_.emitInstruction(MCInstBuilder(PPC::STD)
.addReg(val)
.addImm(GetOffset(name) * 8)
.addReg(state),
sti
);
}
// -----------------------------------------------------------------------------
void PPCRuntimePrinter::LoadState(
llvm::Register state,
llvm::Register val,
const char *name,
const llvm::PPCSubtarget &sti)
{
// ld val, offset(state)
os_.emitInstruction(MCInstBuilder(PPC::LD)
.addReg(val)
.addImm(GetOffset(name) * 8)
.addReg(state),
sti
);
}
| 28.425474 | 83 | 0.567356 | [
"vector"
] |
8ffff573c010bdb9343423f9b7ed7ccab6815a4a | 8,679 | cc | C++ | test/performance/ExpectData.cc | diegoferigo/ign-physics | 8f0d8ce3229f53fbf4e05cb0273530169e6d9fef | [
"ECL-2.0",
"Apache-2.0"
] | 39 | 2020-04-15T16:56:50.000Z | 2022-03-23T19:53:01.000Z | test/performance/ExpectData.cc | diegoferigo/ign-physics | 8f0d8ce3229f53fbf4e05cb0273530169e6d9fef | [
"ECL-2.0",
"Apache-2.0"
] | 265 | 2020-04-17T22:46:45.000Z | 2022-03-30T21:34:29.000Z | test/performance/ExpectData.cc | diegoferigo/ign-physics | 8f0d8ce3229f53fbf4e05cb0273530169e6d9fef | [
"ECL-2.0",
"Apache-2.0"
] | 26 | 2020-04-16T08:08:56.000Z | 2022-01-12T07:47:34.000Z | /*
* Copyright (C) 2017 Open Source Robotics Foundation
*
* 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 <gtest/gtest.h>
#include <chrono>
#include <iomanip>
#include <cmath>
#include "utils/TestDataTypes.hh"
std::size_t gNumTests = 100000;
struct SomeData1 { };
struct SomeData2 { };
struct SomeData3 { };
struct SomeData4 { };
struct SomeData5 { };
struct SomeData6 { };
struct SomeData7 { };
struct SomeData8 { };
struct SomeData9 { };
struct SomeData10 { };
struct SomeData11 { };
struct SomeData12 { };
struct SomeData13 { };
struct SomeData14 { };
struct SomeData15 { };
struct SomeData16 { };
struct SomeData17 { };
struct SomeData18 { };
struct SomeData19 { };
// Expect only 1 type
using ExpectString = ignition::physics::ExpectData<StringData>;
// Expect 3 different types, and put the type we care about first in the list
using Expect3Types_Leading =
ignition::physics::ExpectData<StringData, BoolData, CharData>;
// Expect 3 different types, and put the type we care about last in the list
using Expect3Types_Trailing =
ignition::physics::ExpectData<CharData, BoolData, StringData>;
// Expect 10 different types, and put the type we care about first in the list
using Expect10Types_Leading =
ignition::physics::ExpectData<
StringData,
SomeData1, SomeData2, SomeData3, SomeData4, SomeData5,
SomeData6, SomeData7, SomeData8, SomeData9>;
// Expect 10 different types, and put the type we care about last in the list
using Expect10Types_Trailing =
ignition::physics::ExpectData<
SomeData1, SomeData2, SomeData3, SomeData4, SomeData5,
SomeData6, SomeData7, SomeData8, SomeData9,
StringData>;
// Expect 20 different types, and put the type we care about first in the list
using Expect20Types_Leading =
ignition::physics::ExpectData<
StringData,
SomeData1, SomeData2, SomeData3, SomeData4, SomeData5,
SomeData6, SomeData7, SomeData8, SomeData9, SomeData10,
SomeData11, SomeData12, SomeData13, SomeData14, SomeData15,
SomeData16, SomeData17, SomeData18, SomeData19>;
// Expect 20 different types, and put the type we care about last in the list
using Expect20Types_Trailing =
ignition::physics::ExpectData<
SomeData1, SomeData2, SomeData3, SomeData4, SomeData5,
SomeData6, SomeData7, SomeData8, SomeData9, SomeData10,
SomeData11, SomeData12, SomeData13, SomeData14, SomeData15,
SomeData16, SomeData17, SomeData18, SomeData19,
StringData>;
ignition::physics::CompositeData CreatePerformanceTestData()
{
return CreateSomeData<StringData, DoubleData, IntData,
FloatData, VectorDoubleData, BoolData, CharData>();
}
template <typename CompositeType>
double RunPerformanceTest(CompositeType &data)
{
const auto start = std::chrono::high_resolution_clock::now();
for (std::size_t i=0; i < gNumTests; ++i)
{
data.template Get<StringData>();
}
const auto finish = std::chrono::high_resolution_clock::now();
const auto time = std::chrono::duration_cast<std::chrono::nanoseconds>(
finish - start).count();
const double avg = static_cast<double>(time)/static_cast<double>(gNumTests);
return avg;
}
// NaiveCompositionBase and NaiveComposition are used to produce a reference
// performance result that can help put the CompositeData performance in
// perspective.
class NaiveCompositionBase
{
};
template<typename T>
// cppcheck-suppress noConstructor
class NaiveComposition : public NaiveCompositionBase
{
public: const T &Get() const { return d; }
private: T d;
};
TEST(ExpectData, AccessTime)
{
ExpectString expect_1;
Expect3Types_Leading expect_3_leading;
Expect3Types_Trailing expect_3_trailing;
Expect10Types_Leading expect_10_leading;
Expect10Types_Trailing expect_10_trailing;
Expect20Types_Leading expect_20_leading;
Expect20Types_Trailing expect_20_trailing;
ignition::physics::CompositeData plain;
expect_1.Copy(CreatePerformanceTestData());
expect_3_leading.Copy(CreatePerformanceTestData());
expect_3_trailing.Copy(CreatePerformanceTestData());
expect_10_leading.Copy(CreatePerformanceTestData());
expect_10_trailing.Copy(CreatePerformanceTestData());
expect_20_leading.Copy(CreatePerformanceTestData());
expect_20_trailing.Copy(CreatePerformanceTestData());
plain.Copy(CreatePerformanceTestData());
double avg_expect_1 = 0.0;
double avg_expect_3_leading = 0.0;
double avg_expect_3_trailing = 0.0;
double avg_expect_10_leading = 0.0;
double avg_expect_10_trailing = 0.0;
double avg_expect_20_leading = 0.0;
double avg_expect_20_trailing = 0.0;
double avg_plain = 0.0;
double avg_naive = 0.0;
const std::size_t NumRuns = 100;
std::vector<NaiveCompositionBase*> basicComposition;
for (std::size_t j = 0; j < gNumTests; ++j)
{
if (j < gNumTests / 2)
basicComposition.push_back(new NaiveComposition<int>());
else
basicComposition.push_back(new NaiveComposition<std::string>());
}
for (std::size_t i = 0; i < NumRuns; ++i)
{
avg_expect_1 += RunPerformanceTest(expect_1);
avg_expect_3_leading += RunPerformanceTest(expect_3_leading);
avg_expect_3_trailing += RunPerformanceTest(expect_3_trailing);
avg_expect_10_leading += RunPerformanceTest(expect_10_leading);
avg_expect_10_trailing += RunPerformanceTest(expect_10_trailing);
avg_expect_20_leading += RunPerformanceTest(expect_20_leading);
avg_expect_20_trailing += RunPerformanceTest(expect_20_trailing);
avg_plain += RunPerformanceTest(plain);
const auto start = std::chrono::high_resolution_clock::now();
for (std::size_t j = 0; j < gNumTests; ++j)
{
if (j < gNumTests / 2)
static_cast<NaiveComposition<int>*>(basicComposition[j])->Get();
else
static_cast<NaiveComposition<std::string>*>(basicComposition[j])->Get();
}
const auto finish = std::chrono::high_resolution_clock::now();
const auto time = std::chrono::duration_cast<std::chrono::nanoseconds>(
finish - start).count();
avg_naive += static_cast<double>(time)/static_cast<double>(gNumTests);
}
EXPECT_LT(avg_expect_1, avg_plain);
EXPECT_LT(avg_expect_3_leading, avg_plain);
EXPECT_LT(avg_expect_3_trailing, avg_plain);
EXPECT_LT(avg_expect_10_leading, avg_plain);
EXPECT_LT(avg_expect_10_trailing, avg_plain);
EXPECT_LT(avg_expect_20_leading, avg_plain);
EXPECT_LT(avg_expect_20_trailing, avg_plain);
// These 6 results should be very close to each other. avg_expect_1 is an
// exception because it uses the plain ExpectData<T> instead of being wrapped
// in a SpecifyData<T> which adds just a tiny bit of overhead because it needs
// to make one additional function call.
const double baseline = avg_expect_3_leading;
EXPECT_LT(std::abs(avg_expect_3_trailing - baseline), baseline);
EXPECT_LT(std::abs(avg_expect_10_leading - baseline), baseline);
EXPECT_LT(std::abs(avg_expect_10_trailing - baseline), baseline);
EXPECT_LT(std::abs(avg_expect_20_leading - baseline), baseline);
EXPECT_LT(std::abs(avg_expect_20_trailing - baseline), baseline);
std::vector<std::string> labels = {
"1 expectation",
"3 expectations (leading)",
"3 expectations (ending)",
"10 expectations (leading)",
"10 expectations (trailing)",
"20 expectations (leading)",
"20 expectations (trailing)",
"No expectations",
"Naive composition: This is only a reference point" };
std::vector<double> avgs = {
avg_expect_1,
avg_expect_3_leading,
avg_expect_3_trailing,
avg_expect_10_leading,
avg_expect_10_trailing,
avg_expect_20_leading,
avg_expect_20_trailing,
avg_plain,
avg_naive };
for (std::size_t i = 0; i < labels.size(); ++i)
{
std::cout << std::fixed;
std::cout << std::setprecision(6);
std::cout << std::right;
std::cout << " --- " << labels[i] << " result ---\n"
<< "Avg time: " << std::setw(8) << std::right
<< avgs[i]/static_cast<double>(NumRuns)
<< " ns\n" << std::endl;
}
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 33.770428 | 80 | 0.724623 | [
"vector"
] |
8908d96897ab31c419f6bf77ea0c5d25f782cbbb | 3,251 | cpp | C++ | test/common_test.cpp | 4paradigm/prpc | 2d264b696dd08191346535b852bb2b5391506a20 | [
"Apache-2.0"
] | 2 | 2021-08-24T03:35:11.000Z | 2021-09-08T15:17:07.000Z | test/common_test.cpp | 4paradigm/prpc | 2d264b696dd08191346535b852bb2b5391506a20 | [
"Apache-2.0"
] | null | null | null | test/common_test.cpp | 4paradigm/prpc | 2d264b696dd08191346535b852bb2b5391506a20 | [
"Apache-2.0"
] | null | null | null | #include <cstdlib>
#include <cstdio>
#include <queue>
#include <string>
#include <glog/logging.h>
#include <gtest/gtest.h>
#include "common.h"
namespace paradigm4 {
namespace pico {
namespace core {
TEST(commonTest, pico_common_time_relevent_function_check) {
std::chrono::system_clock::time_point t0;
char fmt[] = "%c %Z";
std::string out_local = pico_format_time_point_local(t0, fmt);
std::string ans_local = "Thu Jan 1 08:00:00 1970 CST";
std::string out_gm = pico_format_time_point_gm(t0, fmt);
std::string ans_gm = "Thu Jan 1 00:00:00 1970 GMT";
EXPECT_EQ(out_local, ans_local);
EXPECT_EQ(out_gm, ans_gm);
auto init_time1 = pico_initialize_time();
sleep(1);
auto init_time2 = pico_initialize_time();
sleep(1);
auto cur_time1 = pico_current_time();
sleep(1);
auto cur_time2 = pico_current_time();
EXPECT_TRUE(init_time1 == init_time2);
EXPECT_FALSE(cur_time1 == cur_time2);
}
TEST(commonTest, pico_common_vectorappend_sgn_retry_check) {
EXPECT_TRUE(IsVector<std::vector<int>>::value);
EXPECT_FALSE(IsVector<int>::value);
EXPECT_FALSE(IsVector<std::string>::value);
EXPECT_FALSE(IsVector<std::deque<double>>::value);
std::vector<int> result = {1, 2};
std::vector<int> vect = {3, 4};
std::vector<int> ans = {1, 2, 3, 4};
vector_move_append(result, vect);
EXPECT_EQ(result.size(), ans.size());
for (size_t i = 0; i < ans.size(); ++i) {
EXPECT_EQ(result[i], ans[i]);
}
EXPECT_EQ(sgn( 7), 1);
EXPECT_EQ(sgn(-7), -1);
EXPECT_EQ(sgn( 0), 0);
EXPECT_EQ(sgn(7.77), 1);
EXPECT_EQ(sgn(-7.7), -1);
EXPECT_EQ(sgn(0.00), 0);
double small_rand = -1;
auto func = [](double& a) {
a = pico_real_random();
if (a < 0.2) {
return 0;
}
errno = EINTR;
return -1;
};
EXPECT_EQ(retry_eintr_call(func, small_rand), 0);
EXPECT_TRUE(small_rand < 0.2);
}
TEST(commonTest, pico_common_format_typename_hash_check) {
std::string format = "test %d %.2f %s";
std::string fmtret = format_string(format, 123, 7.77, "asdf1234");
std::string fmtans = "test 123 7.77 asdf1234";
EXPECT_TRUE(fmtret == fmtans);
EXPECT_TRUE(readable_typename<int>() == "int");
EXPECT_TRUE(readable_typename<bool>() == "bool");
EXPECT_TRUE(readable_typename<float>() == "float");
EXPECT_TRUE(readable_typename<std::string>() ==
"std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >");
int32_t hash32_1 = pico_murmurhash3_32("key1");
int32_t hash32_2 = pico_murmurhash3_32("key1");
int32_t hash32_3 = pico_murmurhash3_32("key2");
EXPECT_TRUE(hash32_1 == hash32_2);
EXPECT_TRUE(hash32_1 != hash32_3);
int64_t hash64_1 = pico_murmurhash3_64("long key 1");
int64_t hash64_2 = pico_murmurhash3_64("long key 1");
int64_t hash64_3 = pico_murmurhash3_64("long key 2");
EXPECT_TRUE(hash64_1 == hash64_2);
EXPECT_TRUE(hash64_1 != hash64_3);
}
} // namespace core
} // namespace pico
} // namespace paradigm4
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 30.961905 | 91 | 0.641341 | [
"vector"
] |
89094851bd304492fb3af8845e88bab8ec1f882f | 1,710 | hh | C++ | src/ArtificialViscosity/CheapVonNeumanViscosity.hh | jmikeowen/Spheral | 3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 22 | 2018-07-31T21:38:22.000Z | 2020-06-29T08:58:33.000Z | src/ArtificialViscosity/CheapVonNeumanViscosity.hh | markguozhiming/spheral | bbb982102e61edb8a1d00cf780bfa571835e1b61 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 41 | 2020-09-28T23:14:27.000Z | 2022-03-28T17:01:33.000Z | src/ArtificialViscosity/CheapVonNeumanViscosity.hh | markguozhiming/spheral | bbb982102e61edb8a1d00cf780bfa571835e1b61 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 7 | 2019-12-01T07:00:06.000Z | 2020-09-15T21:12:39.000Z | //---------------------------------Spheral++----------------------------------//
// A specialized version of the scalar VonNeuman viscosity, which uses the
// last stored version of DvDx to compute the velocity divergence.
//
// Created by JMO, Sun Jan 14 22:59:51 PST 2001
//----------------------------------------------------------------------------//
#ifndef CheapVonNeumanViscosity_HH
#define CheapVonNeumanViscosity_HH
#include "ArtificialViscosity.hh"
#include "VonNeumanViscosity.hh"
namespace Spheral {
template<typename Dimension>
class CheapVonNeumanViscosity: public VonNeumanViscosity<Dimension> {
public:
//--------------------------- Public Interface ---------------------------//
typedef typename Dimension::Scalar Scalar;
typedef typename Dimension::Vector Vector;
typedef typename Dimension::Tensor Tensor;
typedef typename Dimension::SymTensor SymTensor;
// Constructors.
CheapVonNeumanViscosity();
CheapVonNeumanViscosity(Scalar Clinear, Scalar Cquadratic);
// Destructor.
~CheapVonNeumanViscosity();
// Initialize the artificial viscosity for all FluidNodeLists in the given
// DataBase.
virtual
void initialize(const DataBase<Dimension>& dataBase,
typename ArtificialViscosity<Dimension>::ConstBoundaryIterator boundaryBegin,
typename ArtificialViscosity<Dimension>::ConstBoundaryIterator boundaryEnd,
const Scalar time,
const Scalar dt,
const TableKernel<Dimension>& W);
private:
//--------------------------- Private Interface ---------------------------//
};
}
#else
namespace Spheral {
// Forward declaration.
template<typename Dimension> class CheapVonNeumanViscosity;
}
#endif
| 31.090909 | 95 | 0.64152 | [
"vector"
] |
890aaa2c0a29a75951c8473689d041cc2a3cf1d1 | 362 | cpp | C++ | 12015/12015.cpp14.cpp | isac322/BOJ | 35959dd1a63d75ebca9ed606051f7a649d5c0c7b | [
"MIT"
] | 14 | 2017-05-02T02:00:42.000Z | 2021-11-16T07:25:29.000Z | 12015/12015.cpp14.cpp | isac322/BOJ | 35959dd1a63d75ebca9ed606051f7a649d5c0c7b | [
"MIT"
] | 1 | 2017-12-25T14:18:14.000Z | 2018-02-07T06:49:44.000Z | 12015/12015.cpp14.cpp | isac322/BOJ | 35959dd1a63d75ebca9ed606051f7a649d5c0c7b | [
"MIT"
] | 9 | 2016-03-03T22:06:52.000Z | 2020-04-30T22:06:24.000Z | #include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
unsigned long n, t;
vector<unsigned long> arr;
scanf("%lu", &n);
for (int i = 0; i < n; i++) {
scanf("%lu", &t);
auto iter = lower_bound(arr.begin(), arr.end(), t);
if (iter == arr.end()) arr.emplace_back(t);
else *iter = t;
}
printf("%lu", arr.size());
} | 20.111111 | 53 | 0.59116 | [
"vector"
] |
890ab0dd34d794fba0728e318f36215a40cd9ab6 | 1,117 | cpp | C++ | leetcode/permutations(46)/main.cpp | bryancalisto/competitive_prog | 776aefb73872acaf35f0dde08c6341c5cfb670a6 | [
"Unlicense"
] | null | null | null | leetcode/permutations(46)/main.cpp | bryancalisto/competitive_prog | 776aefb73872acaf35f0dde08c6341c5cfb670a6 | [
"Unlicense"
] | null | null | null | leetcode/permutations(46)/main.cpp | bryancalisto/competitive_prog | 776aefb73872acaf35f0dde08c6341c5cfb670a6 | [
"Unlicense"
] | null | null | null | //https://leetcode.com/problems/permutations/
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<vector<int>> permute(vector<int> &nums)
{
vector<vector<int>> result;
vector<int> currentSet;
return _permute(nums, currentSet, result);
}
vector<vector<int>> _permute(vector<int> &nums, vector<int> ¤tSet, vector<vector<int>> &answer)
{
if (nums.size() == 0)
{
answer.push_back(currentSet);
}
for (int i = 0; i < nums.size(); i++)
{
vector<int> newNums = nums;
newNums.erase(newNums.begin() + i);
currentSet.push_back(nums[i]);
_permute(newNums, currentSet, answer);
currentSet.pop_back();
}
return answer;
}
};
int main()
{
Solution sol;
// vector<int> nums = {1, 3, 4, 5, 6, 7, 9};
// vector<int> nums = {1, 3, 5, 6};
vector<int> nums = {1, 2, 3};
// vector<int> nums = {};
vector<vector<int>> res = sol.permute(nums);
for (int i = 0; i < res.size(); i++)
{
for (int j = 0; j < res[0].size(); j++)
{
cout << res[i][j] << endl;
}
cout << "===\n";
}
} | 20.685185 | 103 | 0.56043 | [
"vector"
] |
891021d5a2f29a8773141905cd765889fbb19c34 | 28,850 | cpp | C++ | src/chromalightnessdiagram.cpp | Qt-Widgets/perceptualcolor | 05006bf8707c3a22e1d13656117de89c2db05516 | [
"MIT"
] | 1 | 2021-01-10T06:31:27.000Z | 2021-01-10T06:31:27.000Z | src/chromalightnessdiagram.cpp | Qt-Widgets/perceptualcolor | 05006bf8707c3a22e1d13656117de89c2db05516 | [
"MIT"
] | null | null | null | src/chromalightnessdiagram.cpp | Qt-Widgets/perceptualcolor | 05006bf8707c3a22e1d13656117de89c2db05516 | [
"MIT"
] | null | null | null | // SPDX-License-Identifier: MIT
/*
* Copyright (c) 2020 Lukas Sommer somerluk@gmail.com
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
// Own header
#include "PerceptualColor/chromalightnessdiagram.h"
#include "PerceptualColor/helper.h"
#include "PerceptualColor/polarpointf.h"
#include <math.h>
#include <QDebug>
#include <QMouseEvent>
#include <QPainter>
#include <QtMath>
#include <lcms2.h>
namespace PerceptualColor {
/** @brief The constructor.
* @param parent Passed to the QWidget base class constructor
* @param f Passed to the QWidget base class constructor
*/
ChromaLightnessDiagram::ChromaLightnessDiagram(RgbColorSpace *colorSpace, QWidget *parent) : QWidget(parent)
{
// Setup LittleCMS (must be first thing because other operations rely on working LittleCMS)
m_rgbColorSpace = colorSpace;
// Simple initializations
// We don't use the reset methods as they rely on refreshDiagram
// (and refreshDiagram relies itself on m_hue, m_markerRadius and
// m_markerThickness)
cmsCIELCh temp;
temp.h = Helper::LchBoundaries::defaultHue;
temp.C = Helper::LchBoundaries::versatileSrgbChroma;
temp.L = Helper::LchBoundaries::defaultLightness;
m_color = FullColorDescription(
m_rgbColorSpace,
temp,
FullColorDescription::outOfGamutBehaviour::sacrifyChroma
);
m_markerRadius = default_markerRadius;
m_markerThickness = default_markerThickness;
updateBorder();
// Other initializations
// Accept focus only by keyboard tabbing and not by mouse click
// Focus by mouse click is handeled manually by mousePressEvent().
setFocusPolicy(Qt::FocusPolicy::TabFocus);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
}
/** @brief Updates the border() property.
*
* This function can be called after changes to markerRadius() or markerThickness() to
* update the border() property.
*/
void ChromaLightnessDiagram::updateBorder()
{
// Code
m_border = qRound(m_markerRadius + (m_markerThickness / static_cast<qreal>(2)));
}
// TODO high-dpi support
// TODO automatically scale marker radius and thickness with widget size
// TODO reasonable boundary for markerWidth and markerRadius and minimumSizeHint: How to make sure the diagram has at least a few pixels? And if it's very low: For precision wouldn't it be better to internally calculate with a higher-resolution pixmap for more precision? Alternative: for the border() property: better quint16? No, that's not a good idea...
/** Sets the color values corresponding to image coordinates.
*
* @param newImageCoordinates A coordinte pair within the image's coordinate
* system. This does not necessarily need to intersect with the actual
* displayed diagram or the gamut. It might even be negative or outside the
* image or even outside widget.
*
* \post If the coordinates are within the gamut diagram, then
* the corresponding values are set. If the coordinates
* are outside the gamut diagram, then a nearest-neigbbour-search is done,
* searching for the pixel that is less far from the cursor.
*/
void ChromaLightnessDiagram::setImageCoordinates(const QPoint newImageCoordinates)
{
updateDiagramCache();
QPoint correctedImageCoordinates = Helper::nearestNeighborSearch(newImageCoordinates, m_diagramImage);
QPointF chromaLightness;
cmsCIELCh lch;
if (correctedImageCoordinates != currentImageCoordinates()) {
chromaLightness = fromImageCoordinatesToChromaLightness(correctedImageCoordinates);
lch.C = chromaLightness.x();
lch.L = chromaLightness.y();
lch.h = m_color.toLch().h;
setColor(
FullColorDescription(
m_rgbColorSpace,
lch,
FullColorDescription::outOfGamutBehaviour::preserve
)
);
}
}
// TODO Do not use nearest neigbour or other pixel based search algorithms, but work directly with LittleCMS, maybe with a limited, but well-defined, precision.
/** @brief React on a mouse press event.
*
* Reimplemented from base class.
*
* Does not differenciate between left, middle and right mouse click.
* If the mouse is clicked within the \em displayed gamut, than the marker is placed here and further
* mouse movements are tracked.
*
* @param event The corresponding mouse event
*/
void ChromaLightnessDiagram::mousePressEvent(QMouseEvent *event)
{
QPoint imageCoordinates = fromWidgetCoordinatesToImageCoordinates(
event->pos()
);
if (imageCoordinatesInGamut(imageCoordinates)) { // TODO also accept out-of-gamut clicks when they are covered by the current marker.
// Mouse focus is handeled manually because so we can accept focus only
// on mouse clicks within the displayed gamut, while rejecting focus
// otherwise. In the constructor, therefore Qt::FocusPolicy::TabFocus
// is specified, so that manual handling of mouse focus is up to
// this code here.
// TODO Find another solution that guarantees that setFocusPolicy() API
// of this class behaves as expected, and not as a dirty hack that
// accepts mouse focus even when set to Qt::FocusPolicy::TabFocus.
setFocus(Qt::MouseFocusReason);
m_mouseEventActive = true;
setCursor(Qt::BlankCursor);
setImageCoordinates(imageCoordinates);
} else {
// Make sure default behaviour like drag-window in KDE's Breeze widget style works
QWidget::mousePressEvent(event);
}
}
/** @brief React on a mouse move event.
*
* Reimplemented from base class.
*
* Reacts only on mouse move events if previously there had been a mouse press
* event within the displayed gamut. If the mouse moves inside the \em displayed
* gamut, the marker is displaced there. If the mouse moves outside the
* \em display gamut, the marker is displaced to the nearest neigbbour pixel
* within gamut.
*
* If previously there had not been a mouse press event, the mouse move event is ignored.
*
* @param event The corresponding mouse event
*/
void ChromaLightnessDiagram::mouseMoveEvent(QMouseEvent *event)
{
QPoint imageCoordinates = fromWidgetCoordinatesToImageCoordinates(
event->pos()
);
if (m_mouseEventActive) {
if (imageCoordinatesInGamut(imageCoordinates)) {
setCursor(Qt::BlankCursor);
} else {
unsetCursor();
}
setImageCoordinates(imageCoordinates);
} else {
// Make sure default behaviour like drag-window in KDE's Breeze widget style works
QWidget::mousePressEvent(event);
}
}
/** @brief React on a mouse release event.
*
* Reimplemented from base class. Does not differenciate between left, middle and right mouse click.
*
* If the mouse is inside the \em displayed gamut, the marker is displaced there. If the mouse is
* outside the \em display gamut, the marker is displaced to the nearest neigbbour pixel within gamut.
*
* @param event The corresponding mouse event
*/
void ChromaLightnessDiagram::mouseReleaseEvent(QMouseEvent *event)
{
if (m_mouseEventActive) {
setImageCoordinates(
fromWidgetCoordinatesToImageCoordinates(event->pos())
);
unsetCursor();
m_mouseEventActive = false;
} else {
// Make sure default behaviour like drag-window in KDE's Breeze widget style works
QWidget::mousePressEvent(event);
}
}
// TODO What when m_color has a valid in-gamut color, but this color is out of the _displayed_ diagram? How to handle that?
/** @brief Paint the widget.
*
* Reimplemented from base class.
*
* Paints the widget. Takes the existing m_diagramImage and m_diagramPixmap and paints
* them on the widget. Paints, if approperiate, the focus indicator. Paints the marker.
* Relies on that m_diagramImage and m_diagramPixmap are up to date.
*
* @param event the paint event
*/
void ChromaLightnessDiagram::paintEvent(QPaintEvent* event)
{
// We do not paint directly on the widget, but on a QImage buffer first:
// Render anti-aliased looks better. But as Qt documentation says:
//
// “Renderhints are used to specify flags to QPainter that may or
// may not be respected by any given engine.”
//
// Painting here directly on the widget might lead to different
// anti-aliasing results depending on the underlying window system. This is
// especially problematic as anti-aliasing might shift or not a pixel to the
// left or to the right. So we paint on a QImage first. As QImage (at
// difference to QPixmap and a QWidget) is independant of native platform
// rendering, it guarantees identical anti-aliasing results on all
// platforms. Here the quote from QPainter class documentation:
//
// “To get the optimal rendering result using QPainter, you should use
// the platform independent QImage as paint device; i.e. using QImage
// will ensure that the result has an identical pixel representation
// on any platform.”
QImage paintBuffer(size(), QImage::Format_ARGB32);
paintBuffer.fill(Qt::transparent);
QPainter painter(&paintBuffer);
QPen pen;
// Paint the diagram itself as available in the cache.
updateDiagramCache();
painter.drawImage(m_border, m_border, m_diagramImage);
/* Paint a focus indicator.
*
* We could paint a focus indicator (round or rectangular) around the marker.
* Depending on the currently selected hue for the diagram, it looks ugly
* because the colors of focus indicator and diagram do not harmonize, or
* it is mostly invisible the the colors are similar. So this apporach does
* not work well.
*
* It seems better to paint a focus indicator for the whole widget.
* We could use the style primitives to paint a rectangular focus indicator
* around the whole widget:
* style()->drawPrimitive(QStyle::PE_FrameFocusRect, &option, &painter, this);
* However, this does not work well because the chroma-lightness diagram has
* usually a triangular shape. The style primitive, however, often paints
* just a line at the bottom of the widget. That does not look good. An
* alternative approach is that we paint ourself a focus indicator only
* on the left of the diagram (which is the place of black/grey/white,
* so the won't be any problems with non-harmonic colors). We can
* get the color from the current style:
* QColor hightlightColor = palette().color(QPalette::Highlight);
* QBrush highlightBrush = palette().highlight();
* Then we have to design the line that we want to display. It is better to
* do that ourself instead of relying on generic QStyle::PE_Frame or similar
* solutions as their result seems to be quite unpredictible accross various
* styles. So we use markerThickness as line width and paint it at the
* left-most possible position. As the border() property accomodates also to
* markerRadius, the distance of the focus line to the real diagram also
* does, which looks nice.
*/
if (hasFocus()) {
pen.setWidth(m_markerThickness);
pen.setColor(
palette().color(QPalette::Highlight)
);
painter.setPen(pen);
painter.drawLine(
m_markerThickness / 2, // 0.5 is rounded down to 0.0
0 + m_border,
m_markerThickness / 2, // 0.5 is rounded down to 0.0
size().height() - m_border
);
}
// Paint the marker on-the-fly.
// Render anti-aliased looks better. But as Qt documentation says: “Renderhints are used to
// specify flags to QPainter that may or may not be respected by any given engine.” Now, we
// are painting here directly on the widget, which might lead to different anti-aliasing
// results depending on the underlying window system. An alternative approach might be to
// do the rendering on a QImage first. As QImage (at difference to QPixmap and widgets) is
// independant of native platform rendering, it would garantee identical results on all
// platforms. But it seems a litte overkill, so we don't do that here. Anyway here the
// quote from QPainter class documentation:
//
// To get the optimal rendering result using QPainter, you should use the platform independent
// QImage as paint device; i.e. using QImage will ensure that the result has an identical pixel
// representation on any platform.
painter.setRenderHint(QPainter::Antialiasing);
QPoint imageCoordinates = currentImageCoordinates();
pen.setWidth(m_markerThickness);
int markerBackgroundLightness = m_color.toLch().L; // range: 0..100
if (markerBackgroundLightness >= 50) {
pen.setColor(Qt::black);
} else {
pen.setColor(Qt::white);
}
painter.setPen(pen);
painter.drawEllipse(
imageCoordinates.x() + m_border - m_markerRadius,
imageCoordinates.y() + m_border - m_markerRadius,
2 * m_markerRadius + 1,
2 * m_markerRadius + 1
);
// Paint the buffer to the actual widget
QPainter(this).drawImage(0, 0, paintBuffer);
}
/** @brief Transforms from widget to image coordinates
*
* @param widgetCoordinates a coordinate pair within the widget's coordinate system
* @returns the corresponding coordinate pair within m_diagramImage's coordinate system
*/
QPoint ChromaLightnessDiagram::fromWidgetCoordinatesToImageCoordinates(const QPoint widgetCoordinates) const
{
return widgetCoordinates - QPoint(m_border, m_border);
}
/** @brief React on key press events.
*
* Reimplemented from base class.
*
* Reacts on key press events. When the arrow keys are pressed, it moves the marker by one pixel
* into the desired direction if this is still within gamut. When @c Qt::Key_PageUp,
* @c Qt::Key_PageDown, @c Qt::Key_Home or @c Qt::Key_End are pressed, it moves the marker as much
* as possible into the desired direction as long as this is still in the gamut.
*
* @param event the paint event
*
* @warning This function might have an infinite loop if called when the currently selected
* color has no non-transparent pixel on its row or line. TODO This is a problem because it
* is well possibe this will arrive because of possible rounding errors!
*
* // TODO Still the darkest color is far from RGB zero on usual widget size. This has to get better to allow choosing RGB 0, 0, 0!!!
*/
void ChromaLightnessDiagram::keyPressEvent(QKeyEvent *event)
{
// TODO singleStep & pageStep for ALL graphical widgets expressed in LCh
// values, not in pixel. And the same values accross all widgets!
QPoint newImageCoordinates = currentImageCoordinates();
updateDiagramCache();
switch (event->key()) {
case Qt::Key_Up:
if (imageCoordinatesInGamut(newImageCoordinates + QPoint(0, -1))) {
newImageCoordinates += QPoint(0, -1);
}
break;
case Qt::Key_Down:
if (imageCoordinatesInGamut(newImageCoordinates + QPoint(0, 1))) {
newImageCoordinates += QPoint(0, 1);
}
break;
case Qt::Key_Left:
if (imageCoordinatesInGamut(newImageCoordinates + QPoint(-1, 0))) {
newImageCoordinates += QPoint(-1, 0);
}
break;
case Qt::Key_Right:
if (imageCoordinatesInGamut(newImageCoordinates + QPoint(1, 0))) {
newImageCoordinates += QPoint(1, 0);
}
break;
case Qt::Key_PageUp:
newImageCoordinates.setY(0);
while (!imageCoordinatesInGamut(newImageCoordinates + QPoint(0, 1))) {
newImageCoordinates += QPoint(0, 1);
}
break;
case Qt::Key_PageDown:
newImageCoordinates.setY(m_diagramImage.height() - 1);
while (!imageCoordinatesInGamut(newImageCoordinates + QPoint(0, -1))) {
newImageCoordinates += QPoint(0, -1);
}
break;
case Qt::Key_Home:
newImageCoordinates.setX(0);
while (!imageCoordinatesInGamut(newImageCoordinates + QPoint(1, 0))) {
newImageCoordinates += QPoint(1, 0);
}
break;
case Qt::Key_End:
newImageCoordinates.setX(m_diagramImage.width() - 1);
while (!imageCoordinatesInGamut(newImageCoordinates + QPoint(-1, 0))) {
newImageCoordinates += QPoint(-1, 0);
}
break;
default:
/* Quote from Qt documentation:
*
* If you reimplement this handler, it is very important that you call the base class
* implementation if you do not act upon the key.
*
* The default implementation closes popup widgets if the user presses the key sequence
* for QKeySequence::Cancel (typically the Escape key). Otherwise the event is ignored,
* so that the widget's parent can interpret it.
*/
QWidget::keyPressEvent(event);
return;
}
// Here we reach only if the key has been recognized. If not, in the default branch of the
// switch statement, we would have passed the keyPressEvent yet to the parent and returned.
// Set the new image coordinates (only takes effect when image coordinates are indeed different)
setImageCoordinates(newImageCoordinates);
}
/**
* @param imageCoordinates the image coordiantes
* @returns the chroma-lightness value for given image coordinates
*/
QPointF ChromaLightnessDiagram::fromImageCoordinatesToChromaLightness(const QPoint imageCoordinates)
{
updateDiagramCache();
return QPointF(
static_cast<qreal>(imageCoordinates.x()) * 100 / (m_diagramImage.height() - 1),
static_cast<qreal>(imageCoordinates.y()) * 100 / (m_diagramImage.height() - 1) * (-1) + 100
);
}
/**
* @returns the coordinates for m_color
*/
QPoint ChromaLightnessDiagram::currentImageCoordinates()
{
updateDiagramCache();
return QPoint(
qRound(m_color.toLch().C * (m_diagramImage.height() - 1) / 100),
qRound(m_color.toLch().L * (m_diagramImage.height() - 1) / 100 * (-1) + (m_diagramImage.height() - 1))
);
}
/** @brief Tests if image coordinates are in gamut.
* @returns @c true if the image coordinates are within the displayed gamut. Otherwise @c false.
*/
bool ChromaLightnessDiagram::imageCoordinatesInGamut(const QPoint imageCoordinates)
{
// variables
bool temp;
QColor diagramPixelColor;
// code
updateDiagramCache();
temp = false;
if (m_diagramImage.valid(imageCoordinates)) {
diagramPixelColor = m_diagramImage.pixelColor(imageCoordinates);
temp = ((diagramPixelColor.alpha() != 0));
}
return temp;
}
qreal ChromaLightnessDiagram::hue() const
{
return m_color.toLch().h;
}
/** @brief Set the hue
*
* convenience function
*
* @param newHue The new hue value to set.
*/
void ChromaLightnessDiagram::setHue(const qreal newHue)
{
if (newHue == m_color.toLch().h) {
return;
}
cmsCIELCh lch;
lch.h = newHue;
lch.C = m_color.toLch().C;
lch.L = m_color.toLch().L;
setColor(
FullColorDescription(
m_rgbColorSpace,
lch,
FullColorDescription::outOfGamutBehaviour::sacrifyChroma
)
);
}
/** @brief Setter for the color() property */
void ChromaLightnessDiagram::setColor(const FullColorDescription &newColor)
{
if (newColor == m_color) {
return;
}
FullColorDescription oldColor = m_color;
m_color = newColor;
// update if necessary, the diagram
if (m_color.toLch().h != oldColor.toLch().h) {
m_diagramCacheReady = false;;
}
// schedule a paint event
update();
Q_EMIT colorChanged(newColor);
}
/** @brief React on a resive event.
*
* Reimplemented from base class.
*
* @param event The corresponding resize event
*/
void ChromaLightnessDiagram::resizeEvent(QResizeEvent* event)
{
m_diagramCacheReady = false;
// As by Qt documentation: The widget will be erased and receive a paint event immediately after processing the resize event. No drawing need be (or should be) done inside this handler.
}
// TODO how to treat empty images because the color profile does not work or the resolution is too small?
/** @brief Provide the size hint.
*
* Reimplemented from base class.
*
* @returns the size hint
*
* @sa minimumSizeHint()
*/
QSize ChromaLightnessDiagram::sizeHint() const
{
return QSize(300, 300);
}
/** @brief Provide the minimum size hint.
*
* Reimplemented from base class.
*
* @returns the minimum size hint
*
* @sa sizeHint()
*/
QSize ChromaLightnessDiagram::minimumSizeHint() const
{
return QSize(100, 100);
}
// TODO rework all "throw" statements (also these in comments) and the qDebug() statements
// TODO what to do if a gamut allows lightness < 0 or lightness > 100 ???
// TODO what if a part of the gammut at the right is not displayed?
// TODO allow imaginary colors?
int ChromaLightnessDiagram::markerRadius() const
{
return m_markerRadius;
}
/** @brief Setter for the markerRadius() property.
*
* @param newMarkerRadius the new marker radius
*/
void ChromaLightnessDiagram::setMarkerRadius(const int newMarkerRadius)
{
// TODO bound markerRadius and markerThickness to maximum 10 px (or something like that) to make sure the minimal size hint of the widget still allows a diagram to be displayed. (And border property does not overflow.)
int temp = qMax(newMarkerRadius, 0);
if (m_markerRadius != temp) {
m_markerRadius = temp;
updateBorder();
m_diagramCacheReady = false; // because the border has changed, so the size of the pixmap will change.
update();
}
}
/** @brief Reset the markerRadius() property.
*/
void ChromaLightnessDiagram::resetMarkerRadius()
{
setMarkerRadius(default_markerRadius);
}
int ChromaLightnessDiagram::markerThickness() const
{
return m_markerThickness;
}
/** @brief Setter for the markerThickness() property.
*
* @param newMarkerThickness the new marker thickness
*/
void ChromaLightnessDiagram::setMarkerThickness(const int newMarkerThickness)
{
int temp = qMax(newMarkerThickness, 0);
if (m_markerThickness != temp) {
m_markerThickness = temp;
updateBorder();
m_diagramCacheReady = false; // because the border has changed, so the size of the pixmap will change.
update();
}
}
/** @brief Reset the markerThickness() property. */
void ChromaLightnessDiagram::resetMarkerThickness()
{
setMarkerThickness(default_markerThickness);
}
int ChromaLightnessDiagram::border() const
{
return m_border;
}
/** @brief Color of the current selection
*
* @returns color of the current selection
*/
FullColorDescription ChromaLightnessDiagram::color() const
{
return m_color;
}
/** @brief Generates an image of a chroma-lightness diagram.
*
* This function generates images of chroma-lightness diagrams in the Lch color space.
* This function should be thread-save as long as you do not use the same LittleCMS
* transform from different threads. (Also, out of the Qt library, it uses only QImage,
* and not QPixmap, to make sure the result can be passed around between threads.)
*
* @param imageHue the (Lch) hue of the image
* @param imageSize the size of the requested image
* @param colorTransform the LittleCMS color transform to use. The input profile must be based on
* cmsCreateLab4ProfileTHR() or cmsCreateLab4Profile(). The output profile must be an RGB
* profile.
* @returns A chroma-lightness diagram for the given hue. For the y axis, its heigth covers
* the lightness range 0..100. [Pixel (0) corresponds to value 100. Pixel (height-1) corresponds
* to value 0.] Its x axis uses always the same scale as the y axis. So if the size
* is a square, both @c x range and @c y range are from @c 0 to @c 100. If the
* width is larger than the height, the @c x range goes beyond @c 100. The image paints all
* the Lch values that are within the gamut of the RGB profile. All other values are
* Qt::transparent. Intentionally there is no anti-aliasing.
*/
QImage ChromaLightnessDiagram::diagramImage(
const qreal imageHue,
const QSize imageSize) const
{
cmsCIELCh LCh; // uses cmsFloat64Number internally
QColor rgbColor;
int x;
int y;
QImage temp_image = QImage(imageSize, QImage::Format_ARGB32);
const int maxHeight = imageSize.height() - 1;
const int maxWidth = imageSize.width() - 1;
// Test if image size is too small.
if ((maxHeight < 1) || (maxWidth < 1)) {
// TODO How to react correctly here? Exception?
// maxHeight and maxWidth must be at least >= 1 for our algorithm. If they are 0, this would crash (division by 0).
return temp_image;
}
// Initialize the image with transparency.
temp_image.fill(Qt::transparent);
// Paint the gamut.
LCh.h = PolarPointF::normalizedAngleDegree(imageHue);
for (y = 0; y <= maxHeight; ++y) {
LCh.L = y * static_cast<cmsFloat64Number>(100) / maxHeight; // floating point division thanks to 100 which is a "cmsFloat64Number"
for (x = 0; x <= maxWidth; ++x) {
// Using the same scale as on the y axis. floating point
// division thanks to 100 which is a "cmsFloat64Number"
LCh.C = x * static_cast<cmsFloat64Number>(100) / maxHeight;
rgbColor = m_rgbColorSpace->colorRgb(LCh);
if (rgbColor.isValid()) {
// The pixel is within the gamut
temp_image.setPixelColor(
x,
maxHeight - y,
rgbColor
);
/* If color is out-of-gamut: We have chroma on the x axis and
* lightness on the y axis. We are drawing the pixmap line per
* line, so we go for given lightness from low chroma to high
* chroma. Because of the nature of most gamuts, if once in a
* line we have an out-of-gamut value, all other pixels that
* are more at the right will be out-of-gamut also. So we
* could optimize our code and break here. But as we are not
* sure about this (we do not know the gamut at compile time)
* for the moment we do not optimize the code.
*/
}
}
}
return temp_image;
}
/** @brief Refresh the diagram and associated data
*
* This class has a cache of various data related to the diagram
* - @ref m_diagramImage
* - @ref m_diagramPixmap
* - @ref m_maxY
* - @ref m_minY
*
* This data is cached because it is often needed and it would be expensive to calculate it
* again and again on the fly.
*
* Calling this function updates this cached data. This is always necessary if the data
* the diagram relies on, has changed. For example, if the hue() property or the widget size
* have changed, this function has to be called.
*
* This function does not repaint the widget! After calling this function, you have to call
* manually @c update() to schedule a re-paint of the widget, if you wish so.
*/
void ChromaLightnessDiagram::updateDiagramCache()
{
if (m_diagramCacheReady) {
return;
}
// Update QImage
m_diagramImage = diagramImage(
m_color.toLch().h,
QSize(size().width() - 2 * m_border, size().height() - 2 * m_border)
);
// Mark cache as ready
m_diagramCacheReady = true;
}
}
| 38.262599 | 357 | 0.686031 | [
"render",
"shape",
"transform"
] |
8915a57365c3c4b614a8dd6875b53116b188298c | 2,285 | hpp | C++ | states/Playing.hpp | boavenn/SimpleSpaceShooter | e9cac301eae8a5c09b22ea51a7921eb81a26230b | [
"MIT"
] | null | null | null | states/Playing.hpp | boavenn/SimpleSpaceShooter | e9cac301eae8a5c09b22ea51a7921eb81a26230b | [
"MIT"
] | null | null | null | states/Playing.hpp | boavenn/SimpleSpaceShooter | e9cac301eae8a5c09b22ea51a7921eb81a26230b | [
"MIT"
] | null | null | null | #pragma once
#include "StateManager.hpp"
#include "../entities/Projectile.hpp"
#include "../util/Background.hpp"
#include "../util/Random.hpp"
#include "../weapons/OneShot.hpp"
#include "../entities/aliens/Alien01.hpp"
#include "../effects/ParticleExplosion.hpp"
#include "../effects/Explosion.hpp"
#include "../util/SoundMaking.hpp"
#include "../entities/pickups/Health.hpp"
#include "../entities/pickups/Speed.hpp"
#include "../entities/pickups/Money.hpp"
#include "../entities/pickups/ReloadTime.hpp"
#include "../entities/pickups/FireRate.hpp"
#include "../entities/pickups/BulletSpeed.hpp"
#include "../entities/pickups/BulletCapacity.hpp"
#include "../util/levels/Level.hpp"
#include "../util/HUD.hpp"
#include "../states/Shop.hpp"
#include "../util/FloatingText.hpp"
#include "GameOver.hpp"
typedef Random R;
class Playing : public State, public SoundMaking
{
public:
Playing(sf::RenderWindow& w, StateManager& sm);
~Playing();
void update(float dt, sf::Event e);
void draw();
void checkInput(float dt, sf::Event e);
static bool should_pause_sounds;
private:
Player* player = new Player();
std::vector<Projectile*> player_projectiles;
std::vector<Level*> levels;
std::vector<Alien*> aliens;
std::vector<Projectile*> alien_projectiles;
std::vector<Pickup*> pickups;
std::vector<FloatingText*> floating_texts;
Background* main_bg;
Background* layer1;
sf::Sprite sidebar_l;
sf::Sprite sidebar_r;
HUD* hud;
Box* level_teller;
Box* shop_teller;
std::vector<ParticleExplosion*> particle_explosions;
std::vector<Explosion*> sprite_explosions;
bool is_game_over = false;
bool gameover_loop = false;
bool should_tell_level = true;
bool should_tell_shop = false;
bool shop_active = false;
bool should_add_shop = false;
bool shop_added = false;
bool berserk_mode_activated = false;
size_t active_level = 1;
const size_t starting_level = 1;
const size_t max_levels = 10;
private:
void mapUpdates(float dt);
void playerUpdates(float dt);
void alienUpdates(float dt);
void effectUpdates(float dt);
void backgroundUpdates(float dt);
void pickupUpdates(float dt);
void floatingTextUpdates(float dt);
void levelTellerUpdate(float dt);
void shopTellerUpdate(float dt);
void tryAddingPickup(sf::Vector2f pos);
void tryStartingNewLevel();
};
| 26.569767 | 53 | 0.745733 | [
"vector"
] |
891aba78d8f5ad5b53ac5ca0b925815a1ea6654a | 2,731 | cpp | C++ | BattleTanks/Source/BattleTanks/Private/TankProjectile.cpp | Visherac/UnrealCourse_BattleTanks | 42b30469328495098162a9501437f26b2131e274 | [
"MIT"
] | null | null | null | BattleTanks/Source/BattleTanks/Private/TankProjectile.cpp | Visherac/UnrealCourse_BattleTanks | 42b30469328495098162a9501437f26b2131e274 | [
"MIT"
] | null | null | null | BattleTanks/Source/BattleTanks/Private/TankProjectile.cpp | Visherac/UnrealCourse_BattleTanks | 42b30469328495098162a9501437f26b2131e274 | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "TankProjectile.h"
#include "Engine/World.h"
#include "Kismet/GameplayStatics.h"
#include "TimerManager.h"
#include "Particles/ParticleSystemComponent.h"
#include "Components/StaticMeshComponent.h"
#include "PhysicsEngine/RadialForceComponent.h"
#include "GameFramework/ProjectileMovementComponent.h"
// Sets default values
ATankProjectile::ATankProjectile()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
CollisionMesh = CreateDefaultSubobject<UStaticMeshComponent>(FName("Collision Mesh"));
SetRootComponent(CollisionMesh);
CollisionMesh->SetNotifyRigidBodyCollision(true);
CollisionMesh->SetVisibility(false);
MovementComponent = CreateDefaultSubobject<UProjectileMovementComponent>(FName("Movement Component"));
MovementComponent->bAutoActivate = false;
LaunchParticle = CreateDefaultSubobject<UParticleSystemComponent>(FName("Launch Blast"));
LaunchParticle->AttachToComponent(CollisionMesh, FAttachmentTransformRules::KeepRelativeTransform);
ImpactParticle = CreateDefaultSubobject<UParticleSystemComponent>(FName("Impact Blast"));
ImpactParticle->AttachToComponent(CollisionMesh, FAttachmentTransformRules::KeepRelativeTransform);
ImpactParticle->bAutoActivate = false;
ImpactForce = CreateDefaultSubobject<URadialForceComponent>(FName("Impact Force"));
ImpactForce->AttachToComponent(CollisionMesh, FAttachmentTransformRules::KeepRelativeTransform);
}
// Called when the game starts or when spawned
void ATankProjectile::BeginPlay()
{
Super::BeginPlay();
CollisionMesh->OnComponentHit.AddDynamic(this, &ATankProjectile::OnHit);
}
void ATankProjectile::Launch(float Velocity)
{
MovementComponent->SetVelocityInLocalSpace(FVector::ForwardVector * Velocity);
MovementComponent->Activate();
}
void ATankProjectile::OnHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherHitComponent, FVector NormalImpulse, const FHitResult& HitResult)
{
LaunchParticle->Deactivate();
ImpactParticle->Activate();
ImpactForce->FireImpulse();
///remove collision mesh instantly to stop collision bugs
SetRootComponent(ImpactForce);
CollisionMesh->DestroyComponent();
///apply Damage
UGameplayStatics::ApplyRadialDamage(this, DamageAmount, GetActorLocation(), ImpactForce->Radius, UDamageType::StaticClass(), TArray<AActor*>());
///Remove the rest/particles after a destroy delay
FTimerHandle TimerHandle;
GetWorld()->GetTimerManager().SetTimer(TimerHandle, this, &ATankProjectile::OnHitTimerEnd, DestroyDelay);
}
void ATankProjectile::OnHitTimerEnd()
{
Destroy();
}
| 35.467532 | 174 | 0.809594 | [
"mesh"
] |
891f22f61d5c448782601dcee8b0026b4e5eb1aa | 302 | cpp | C++ | acwing/0891.cpp | zyzisyz/OJ | 55221a55515231182b6bd133edbdb55501a565fc | [
"Apache-2.0"
] | null | null | null | acwing/0891.cpp | zyzisyz/OJ | 55221a55515231182b6bd133edbdb55501a565fc | [
"Apache-2.0"
] | null | null | null | acwing/0891.cpp | zyzisyz/OJ | 55221a55515231182b6bd133edbdb55501a565fc | [
"Apache-2.0"
] | 2 | 2020-01-01T13:49:08.000Z | 2021-03-06T06:54:26.000Z | #include<iostream>
#include<vector>
using namespace std;
int n;
int main(void) {
cin>>n;
vector<int> table(n, 0);
for(int i=0; i<n; i++) {
cin>>table[i];
}
int res = table[0];
for(int i=1; i<n; i++){
res = res^table[i];
}
if(res){
cout<<"Yes"<<endl;
}
else{
cout<<"No"<<endl;
}
}
| 12.08 | 25 | 0.546358 | [
"vector"
] |
891fd0bd077c271b1547ff73aa1f3985817b305e | 8,221 | cpp | C++ | IfcPlusPlus/src/ifcpp/IFC4/IfcGeometricRepresentationSubContext.cpp | linsipese/ifcppstudy | e09f05d276b5e129fcb6be65800472979cd4c800 | [
"MIT"
] | 1 | 2018-10-23T09:43:07.000Z | 2018-10-23T09:43:07.000Z | IfcPlusPlus/src/ifcpp/IFC4/IfcGeometricRepresentationSubContext.cpp | linsipese/ifcppstudy | e09f05d276b5e129fcb6be65800472979cd4c800 | [
"MIT"
] | null | null | null | IfcPlusPlus/src/ifcpp/IFC4/IfcGeometricRepresentationSubContext.cpp | linsipese/ifcppstudy | e09f05d276b5e129fcb6be65800472979cd4c800 | [
"MIT"
] | null | null | null | /* -*-c++-*- IfcPlusPlus - www.ifcplusplus.com - Copyright (C) 2011 Fabian Gerold
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#include <sstream>
#include <limits>
#include "ifcpp/model/IfcPPException.h"
#include "ifcpp/model/IfcPPAttributeObject.h"
#include "ifcpp/model/IfcPPGuid.h"
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/IfcPPEntityEnums.h"
#include "include/IfcAxis2Placement.h"
#include "include/IfcCoordinateOperation.h"
#include "include/IfcDimensionCount.h"
#include "include/IfcDirection.h"
#include "include/IfcGeometricProjectionEnum.h"
#include "include/IfcGeometricRepresentationContext.h"
#include "include/IfcGeometricRepresentationSubContext.h"
#include "include/IfcLabel.h"
#include "include/IfcPositiveRatioMeasure.h"
#include "include/IfcReal.h"
#include "include/IfcRepresentation.h"
// ENTITY IfcGeometricRepresentationSubContext
IfcGeometricRepresentationSubContext::IfcGeometricRepresentationSubContext() { m_entity_enum = IFCGEOMETRICREPRESENTATIONSUBCONTEXT; }
IfcGeometricRepresentationSubContext::IfcGeometricRepresentationSubContext( int id ) { m_id = id; m_entity_enum = IFCGEOMETRICREPRESENTATIONSUBCONTEXT; }
IfcGeometricRepresentationSubContext::~IfcGeometricRepresentationSubContext() {}
shared_ptr<IfcPPObject> IfcGeometricRepresentationSubContext::getDeepCopy( IfcPPCopyOptions& options )
{
shared_ptr<IfcGeometricRepresentationSubContext> copy_self( new IfcGeometricRepresentationSubContext() );
if( m_ContextIdentifier ) { copy_self->m_ContextIdentifier = dynamic_pointer_cast<IfcLabel>( m_ContextIdentifier->getDeepCopy(options) ); }
if( m_ContextType ) { copy_self->m_ContextType = dynamic_pointer_cast<IfcLabel>( m_ContextType->getDeepCopy(options) ); }
if( m_CoordinateSpaceDimension ) { copy_self->m_CoordinateSpaceDimension = dynamic_pointer_cast<IfcDimensionCount>( m_CoordinateSpaceDimension->getDeepCopy(options) ); }
if( m_Precision ) { copy_self->m_Precision = dynamic_pointer_cast<IfcReal>( m_Precision->getDeepCopy(options) ); }
if( m_WorldCoordinateSystem ) { copy_self->m_WorldCoordinateSystem = dynamic_pointer_cast<IfcAxis2Placement>( m_WorldCoordinateSystem->getDeepCopy(options) ); }
if( m_TrueNorth ) { copy_self->m_TrueNorth = dynamic_pointer_cast<IfcDirection>( m_TrueNorth->getDeepCopy(options) ); }
if( m_ParentContext ) { copy_self->m_ParentContext = dynamic_pointer_cast<IfcGeometricRepresentationContext>( m_ParentContext->getDeepCopy(options) ); }
if( m_TargetScale ) { copy_self->m_TargetScale = dynamic_pointer_cast<IfcPositiveRatioMeasure>( m_TargetScale->getDeepCopy(options) ); }
if( m_TargetView ) { copy_self->m_TargetView = dynamic_pointer_cast<IfcGeometricProjectionEnum>( m_TargetView->getDeepCopy(options) ); }
if( m_UserDefinedTargetView ) { copy_self->m_UserDefinedTargetView = dynamic_pointer_cast<IfcLabel>( m_UserDefinedTargetView->getDeepCopy(options) ); }
return copy_self;
}
void IfcGeometricRepresentationSubContext::getStepLine( std::stringstream& stream ) const
{
stream << "#" << m_id << "= IFCGEOMETRICREPRESENTATIONSUBCONTEXT" << "(";
if( m_ContextIdentifier ) { m_ContextIdentifier->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_ContextType ) { m_ContextType->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_CoordinateSpaceDimension ) { m_CoordinateSpaceDimension->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_Precision ) { m_Precision->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_WorldCoordinateSystem ) { m_WorldCoordinateSystem->getStepParameter( stream, true ); } else { stream << "*" ; }
stream << ",";
if( m_TrueNorth ) { stream << "#" << m_TrueNorth->m_id; } else { stream << "*"; }
stream << ",";
if( m_ParentContext ) { stream << "#" << m_ParentContext->m_id; } else { stream << "$"; }
stream << ",";
if( m_TargetScale ) { m_TargetScale->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_TargetView ) { m_TargetView->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_UserDefinedTargetView ) { m_UserDefinedTargetView->getStepParameter( stream ); } else { stream << "$"; }
stream << ");";
}
void IfcGeometricRepresentationSubContext::getStepParameter( std::stringstream& stream, bool ) const { stream << "#" << m_id; }
void IfcGeometricRepresentationSubContext::readStepArguments( const std::vector<std::wstring>& args, const boost::unordered_map<int,shared_ptr<IfcPPEntity> >& map )
{
const int num_args = (int)args.size();
if( num_args != 10 ){ std::stringstream err; err << "Wrong parameter count for entity IfcGeometricRepresentationSubContext, expecting 10, having " << num_args << ". Entity ID: " << m_id << std::endl; throw IfcPPException( err.str().c_str() ); }
m_ContextIdentifier = IfcLabel::createObjectFromSTEP( args[0] );
m_ContextType = IfcLabel::createObjectFromSTEP( args[1] );
m_CoordinateSpaceDimension = IfcDimensionCount::createObjectFromSTEP( args[2] );
m_Precision = IfcReal::createObjectFromSTEP( args[3] );
m_WorldCoordinateSystem = IfcAxis2Placement::createObjectFromSTEP( args[4], map );
readEntityReference( args[5], m_TrueNorth, map );
readEntityReference( args[6], m_ParentContext, map );
m_TargetScale = IfcPositiveRatioMeasure::createObjectFromSTEP( args[7] );
m_TargetView = IfcGeometricProjectionEnum::createObjectFromSTEP( args[8] );
m_UserDefinedTargetView = IfcLabel::createObjectFromSTEP( args[9] );
}
void IfcGeometricRepresentationSubContext::getAttributes( std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > >& vec_attributes )
{
IfcGeometricRepresentationContext::getAttributes( vec_attributes );
vec_attributes.push_back( std::make_pair( "ParentContext", m_ParentContext ) );
vec_attributes.push_back( std::make_pair( "TargetScale", m_TargetScale ) );
vec_attributes.push_back( std::make_pair( "TargetView", m_TargetView ) );
vec_attributes.push_back( std::make_pair( "UserDefinedTargetView", m_UserDefinedTargetView ) );
}
void IfcGeometricRepresentationSubContext::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > >& vec_attributes_inverse )
{
IfcGeometricRepresentationContext::getAttributesInverse( vec_attributes_inverse );
}
void IfcGeometricRepresentationSubContext::setInverseCounterparts( shared_ptr<IfcPPEntity> ptr_self_entity )
{
IfcGeometricRepresentationContext::setInverseCounterparts( ptr_self_entity );
shared_ptr<IfcGeometricRepresentationSubContext> ptr_self = dynamic_pointer_cast<IfcGeometricRepresentationSubContext>( ptr_self_entity );
if( !ptr_self ) { throw IfcPPException( "IfcGeometricRepresentationSubContext::setInverseCounterparts: type mismatch" ); }
if( m_ParentContext )
{
m_ParentContext->m_HasSubContexts_inverse.push_back( ptr_self );
}
}
void IfcGeometricRepresentationSubContext::unlinkFromInverseCounterparts()
{
IfcGeometricRepresentationContext::unlinkFromInverseCounterparts();
if( m_ParentContext )
{
std::vector<weak_ptr<IfcGeometricRepresentationSubContext> >& HasSubContexts_inverse = m_ParentContext->m_HasSubContexts_inverse;
for( auto it_HasSubContexts_inverse = HasSubContexts_inverse.begin(); it_HasSubContexts_inverse != HasSubContexts_inverse.end(); )
{
shared_ptr<IfcGeometricRepresentationSubContext> self_candidate( *it_HasSubContexts_inverse );
if( self_candidate.get() == this )
{
it_HasSubContexts_inverse= HasSubContexts_inverse.erase( it_HasSubContexts_inverse );
}
else
{
++it_HasSubContexts_inverse;
}
}
}
}
| 60.896296 | 246 | 0.763532 | [
"vector",
"model"
] |
892409a60db5d45a6b3aa07e6191528c97aed52c | 1,959 | cpp | C++ | test/bstream/test4.cpp | Collobos/nodeoze | 40d98bb085d27f6c283aac61d2b373bf761188d6 | [
"MIT"
] | null | null | null | test/bstream/test4.cpp | Collobos/nodeoze | 40d98bb085d27f6c283aac61d2b373bf761188d6 | [
"MIT"
] | null | null | null | test/bstream/test4.cpp | Collobos/nodeoze | 40d98bb085d27f6c283aac61d2b373bf761188d6 | [
"MIT"
] | null | null | null | #include <nodeoze/test.h>
#include <nodeoze/bstream.h>
#include <nodeoze/bstream/ombstream.h>
#include <nodeoze/bstream/imbstream.h>
#include <nodeoze/bstream/stdlib.h>
#include <utility>
#include <thread>
#include <chrono>
using namespace nodeoze;
namespace test_4
{
struct struct_A
{
struct_A() {}
struct_A( int v_0, float v_1, std::string const& v_2, std::vector< unsigned int > const v_3 )
: m_0{ v_0 }, m_1{ v_1 }, m_2{ v_2 }, m_3{ v_3 } {}
int m_0;
float m_1;
std::string m_2;
std::vector< unsigned int > m_3;
friend bool operator==( struct_A const& a, struct_A const& b )
{
return
a.m_0 == b.m_0 &&
a.m_1 == b.m_1 &&
a.m_2 == b.m_2 &&
a.m_3 == b.m_3;
}
};
} // namespace test_4
template<>
struct bstream::serializer< test_4::struct_A >
{
static inline bstream::obstream& put( bstream::obstream& os, test_4::struct_A const& obj )
{
os.write_array_header( 4 );
os << obj.m_0 << obj.m_1 << obj.m_2 << obj.m_3;
return os;
}
};
template<>
struct bstream::ref_deserializer< test_4::struct_A >
{
static inline bstream::ibstream& get( bstream::ibstream& is, test_4::struct_A& obj )
{
is.check_array_header( 4 );
is >> obj.m_0 >> obj.m_1 >> obj.m_2 >> obj.m_3;
return is;
}
};
using namespace test_4;
TEST_CASE( "nodeoze/smoke/bstream/composite_types/0" )
{
// std::this_thread::sleep_for ( std::chrono::seconds( 10 ) );
bstream::context<> cntxt;
bstream::ombstream os{ 1024, cntxt };
struct_A a0{ -7, 3.5, "zoot", { 1, 1, 2, 3, 5, 8, 13 } };
os << a0;
bstream::imbstream is{ os.get_buffer(), cntxt };
struct_A a1;
is >> a1;
CHECK( a0 == a1 );
using p = std::pair< std::string, test_4::struct_A >;
p p0 = std::make_pair< std::string, test_4::struct_A >( "allures", struct_A{ a0 } );
os.clear();
os << p0;
is.use( os.get_buffer() );
p p1;
is >> p1;
CHECK( p0 == p1 );
}
| 19.59 | 97 | 0.602348 | [
"vector"
] |
892946e492fcd8a0ab302435ab0b13928bdfafc3 | 12,672 | cpp | C++ | moveit_calibration_plugins/handeye_calibration_target/src/handeye_target_aruco.cpp | RoboticsYY/moveit_calibration | e37d4f707a5e966fb19620f3eaa2235692cd09d4 | [
"BSD-3-Clause"
] | 1 | 2021-04-25T12:32:22.000Z | 2021-04-25T12:32:22.000Z | moveit_calibration_plugins/handeye_calibration_target/src/handeye_target_aruco.cpp | RoboticsYY/moveit_calibration | e37d4f707a5e966fb19620f3eaa2235692cd09d4 | [
"BSD-3-Clause"
] | 2 | 2020-07-02T17:43:10.000Z | 2020-08-10T06:51:42.000Z | moveit_calibration_plugins/handeye_calibration_target/src/handeye_target_aruco.cpp | RoboticsYY/moveit_calibration | e37d4f707a5e966fb19620f3eaa2235692cd09d4 | [
"BSD-3-Clause"
] | null | null | null | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2019, Intel Corporation.
* 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 Intel nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Yu Yan */
#include <moveit/handeye_calibration_target/handeye_target_aruco.h>
namespace moveit_handeye_calibration
{
const std::string LOGNAME = "handeye_aruco_target";
// Predefined ARUCO dictionaries in OpenCV for creating ARUCO marker board
const std::map<std::string, cv::aruco::PREDEFINED_DICTIONARY_NAME> ARUCO_DICTIONARY = {
{ "DICT_4X4_250", cv::aruco::DICT_4X4_250 },
{ "DICT_5X5_250", cv::aruco::DICT_5X5_250 },
{ "DICT_6X6_250", cv::aruco::DICT_6X6_250 },
{ "DICT_7X7_250", cv::aruco::DICT_7X7_250 },
{ "DICT_ARUCO_ORIGINAL", cv::aruco::DICT_ARUCO_ORIGINAL }
};
bool HandEyeArucoTarget::initialize(int markers_x, int markers_y, int marker_size, int separation, int border_bits,
const std::string& dictionary_id, double marker_measured_size,
double marker_measured_separation)
{
marker_dictionaries_ = ARUCO_DICTIONARY;
target_params_ready_ =
setTargetIntrinsicParams(markers_x, markers_y, marker_size, separation, border_bits, dictionary_id) &&
setTargetDimension(marker_measured_size, marker_measured_separation);
return target_params_ready_;
}
std::vector<std::string> HandEyeArucoTarget::getDictionaryIds() const
{
std::vector<std::string> dictionary_ids;
for (const std::pair<const std::string, cv::aruco::PREDEFINED_DICTIONARY_NAME>& name : marker_dictionaries_)
dictionary_ids.push_back(name.first);
return dictionary_ids;
}
bool HandEyeArucoTarget::setTargetIntrinsicParams(int markers_x, int markers_y, int marker_size, int separation,
int border_bits, const std::string& dictionary_id)
{
if (markers_x <= 0 || markers_y <= 0 || marker_size <= 0 || separation <= 0 || border_bits <= 0 ||
marker_dictionaries_.find(dictionary_id) == marker_dictionaries_.end())
{
ROS_ERROR_STREAM_NAMED(LOGNAME, "Invalid target intrinsic params.\n"
<< "markers_x_ " << std::to_string(markers_x) << "\n"
<< "markers_y_ " << std::to_string(markers_y) << "\n"
<< "marker_size " << std::to_string(marker_size) << "\n"
<< "separation " << std::to_string(separation) << "\n"
<< "border_bits " << std::to_string(border_bits) << "\n"
<< "dictionary_id " << dictionary_id << "\n");
return false;
}
std::lock_guard<std::mutex> aruco_lock(aruco_mutex_);
markers_x_ = markers_x;
markers_y_ = markers_y;
marker_size_ = marker_size;
separation_ = separation;
border_bits_ = border_bits;
const auto& it = marker_dictionaries_.find(dictionary_id);
dictionary_id_ = it->second;
return true;
}
bool HandEyeArucoTarget::setTargetDimension(double marker_measured_size, double marker_measured_separation)
{
if (marker_measured_size <= 0 || marker_measured_separation <= 0)
{
ROS_ERROR_NAMED(LOGNAME, "Invalid target measured dimensions: marker_size %f, marker_seperation %f",
marker_measured_size, marker_measured_separation);
return false;
}
std::lock_guard<std::mutex> aruco_lock(aruco_mutex_);
marker_size_real_ = marker_measured_size;
marker_separation_real_ = marker_measured_separation;
ROS_INFO_STREAM_NAMED(LOGNAME, "Set target real dimensions: \n"
<< "marker_measured_size " << std::to_string(marker_measured_size) << "\n"
<< "marker_measured_separation " << std::to_string(marker_measured_separation)
<< "\n");
return true;
}
bool HandEyeArucoTarget::createTargetImage(cv::Mat& image) const
{
cv::Size image_size;
image_size.width = markers_x_ * (marker_size_ + separation_) - separation_ + 2 * separation_;
image_size.height = markers_y_ * (marker_size_ + separation_) - separation_ + 2 * separation_;
try
{
// Create target
cv::Ptr<cv::aruco::Dictionary> dictionary = cv::aruco::getPredefinedDictionary(dictionary_id_);
cv::Ptr<cv::aruco::GridBoard> board =
cv::aruco::GridBoard::create(markers_x_, markers_y_, float(marker_size_), float(separation_), dictionary);
// Create target image
board->draw(image_size, image, separation_, border_bits_);
}
catch (const cv::Exception& e)
{
ROS_ERROR_STREAM_NAMED(LOGNAME, "Aruco target image creation exception: " << e.what());
return false;
}
return true;
}
bool HandEyeArucoTarget::detectTargetPose(cv::Mat& image)
{
std::lock_guard<std::mutex> base_lock(base_mutex_);
try
{
// Detect aruco board
aruco_mutex_.lock();
cv::Ptr<cv::aruco::Dictionary> dictionary = cv::aruco::getPredefinedDictionary(dictionary_id_);
cv::Ptr<cv::aruco::GridBoard> board =
cv::aruco::GridBoard::create(markers_x_, markers_y_, marker_size_real_, marker_separation_real_, dictionary);
aruco_mutex_.unlock();
cv::Ptr<cv::aruco::DetectorParameters> params_ptr(new cv::aruco::DetectorParameters());
#if CV_MAJOR_VERSION == 3 && CV_MINOR_VERSION == 2
params_ptr->doCornerRefinement = true;
#else
params_ptr->cornerRefinementMethod = cv::aruco::CORNER_REFINE_NONE;
#endif
std::vector<int> marker_ids;
std::vector<std::vector<cv::Point2f>> marker_corners;
cv::aruco::detectMarkers(image, dictionary, marker_corners, marker_ids, params_ptr);
if (marker_ids.empty())
{
ROS_DEBUG_STREAM_NAMED(LOGNAME, "No aruco marker detected.");
return false;
}
// Refine markers borders
std::vector<std::vector<cv::Point2f>> rejected_corners;
cv::aruco::refineDetectedMarkers(image, board, marker_corners, marker_ids, rejected_corners, camera_matrix_,
distortion_coeffs_);
// Estimate aruco board pose
int valid = cv::aruco::estimatePoseBoard(marker_corners, marker_ids, board, camera_matrix_, distortion_coeffs_,
rotation_vect_, translation_vect_);
// Draw the markers and frame axis if at least one marker is detected
if (valid == 0)
{
ROS_WARN_STREAM_NAMED(LOGNAME, "Cannot estimate aruco board pose.");
return false;
}
if (std::log10(std::fabs(rotation_vect_[0])) > 10 || std::log10(std::fabs(rotation_vect_[1])) > 10 ||
std::log10(std::fabs(rotation_vect_[2])) > 10 || std::log10(std::fabs(translation_vect_[0])) > 10 ||
std::log10(std::fabs(translation_vect_[1])) > 10 || std::log10(std::fabs(translation_vect_[2])) > 10)
{
ROS_WARN_STREAM_NAMED(LOGNAME, "Invalid target pose, please check CameraInfo msg.");
return false;
}
cv::Mat image_rgb;
cv::cvtColor(image, image_rgb, cv::COLOR_GRAY2RGB);
cv::aruco::drawDetectedMarkers(image_rgb, marker_corners);
drawAxis(image_rgb, camera_matrix_, distortion_coeffs_, rotation_vect_, translation_vect_, 0.1);
image = image_rgb;
}
catch (const cv::Exception& e)
{
ROS_ERROR_STREAM_NAMED(LOGNAME, "Aruco target detection exception: " << e.what());
return false;
}
return true;
}
geometry_msgs::TransformStamped HandEyeArucoTarget::getTransformStamped(const std::string& frame_id) const
{
geometry_msgs::TransformStamped transform_stamped;
transform_stamped.header.stamp = ros::Time::now();
transform_stamped.header.frame_id = frame_id;
transform_stamped.child_frame_id = "handeye_target";
tf2::Quaternion quaternion(0, 0, 0, 1);
convertToTFQuaternion(rotation_vect_, quaternion);
transform_stamped.transform.rotation.x = quaternion.getX();
transform_stamped.transform.rotation.y = quaternion.getY();
transform_stamped.transform.rotation.z = quaternion.getZ();
transform_stamped.transform.rotation.w = quaternion.getW();
std::vector<double> translation(3, 0);
convertToStdVector(translation_vect_, translation);
transform_stamped.transform.translation.x = translation[0];
transform_stamped.transform.translation.y = translation[1];
transform_stamped.transform.translation.z = translation[2];
return transform_stamped;
}
bool HandEyeArucoTarget::convertToTFQuaternion(const cv::Vec3d& input_rvect, tf2::Quaternion& quaternion) const
{
if (input_rvect.rows != 3 || input_rvect.cols != 1) // 3x1 rotation vector
{
ROS_ERROR_NAMED(LOGNAME, "Wrong rotation vector dimensions: %dx%d, required to be 3x1", input_rvect.rows,
input_rvect.cols);
return false;
}
cv::Mat rotation_matrix;
cv::Rodrigues(input_rvect, rotation_matrix);
if (rotation_matrix.rows != 3 || rotation_matrix.cols != 3) // 3x3 rotation matrix
{
ROS_ERROR_NAMED(LOGNAME, "Wrong rotation matrix dimensions: %dx%d, required to be 3x3", rotation_matrix.rows,
rotation_matrix.cols);
return false;
}
tf2::Matrix3x3 m;
m.setValue(rotation_matrix.ptr<double>(0)[0], rotation_matrix.ptr<double>(0)[1], rotation_matrix.ptr<double>(0)[2],
rotation_matrix.ptr<double>(1)[0], rotation_matrix.ptr<double>(1)[1], rotation_matrix.ptr<double>(1)[2],
rotation_matrix.ptr<double>(2)[0], rotation_matrix.ptr<double>(2)[1], rotation_matrix.ptr<double>(2)[2]);
m.getRotation(quaternion);
return true;
}
bool HandEyeArucoTarget::convertToStdVector(const cv::Vec3d& input_tvect, std::vector<double>& translation) const
{
if (input_tvect.rows != 3 || input_tvect.cols != 1) // 3x1 translation vector
{
ROS_ERROR_NAMED(LOGNAME, "Wrong rotation matrix dimensions: %dx%d, required to be 3x1", input_tvect.rows,
input_tvect.cols);
return false;
}
translation.clear();
translation.resize(3);
for (size_t i = 0; i < 3; ++i)
translation[i] = input_tvect[i];
return true;
}
void HandEyeArucoTarget::drawAxis(cv::InputOutputArray _image, cv::InputArray _cameraMatrix, cv::InputArray _distCoeffs,
cv::InputArray _rvec, cv::InputArray _tvec, float length) const
{
CV_Assert(_image.getMat().total() != 0 && (_image.getMat().channels() == 1 || _image.getMat().channels() == 3));
CV_Assert(length > 0);
// project axis points
std::vector<cv::Point3f> axis_points;
axis_points.push_back(cv::Point3f(0, 0, 0));
axis_points.push_back(cv::Point3f(length, 0, 0));
axis_points.push_back(cv::Point3f(0, length, 0));
axis_points.push_back(cv::Point3f(0, 0, length));
std::vector<cv::Point2f> image_points;
cv::projectPoints(axis_points, _rvec, _tvec, _cameraMatrix, _distCoeffs, image_points);
// draw axis lines
cv::line(_image, image_points[0], image_points[1], cv::Scalar(255, 0, 0), 3);
cv::line(_image, image_points[0], image_points[2], cv::Scalar(0, 255, 0), 3);
cv::line(_image, image_points[0], image_points[3], cv::Scalar(0, 0, 255), 3);
}
} // namespace moveit_handeye_calibration
| 42.381271 | 120 | 0.683712 | [
"vector",
"transform"
] |
892a8d18ee6f676698f73bccf6221bb524e4ac0f | 928 | cpp | C++ | CodeForces/1152B_Neko_Performs_Cat_Furrier_Transform.cpp | ASM-ATIKUR/Competitive_Programming_Atikur_Rahman | 9552e4dca7daad5c07542514d4b8c8baabea1989 | [
"MIT"
] | null | null | null | CodeForces/1152B_Neko_Performs_Cat_Furrier_Transform.cpp | ASM-ATIKUR/Competitive_Programming_Atikur_Rahman | 9552e4dca7daad5c07542514d4b8c8baabea1989 | [
"MIT"
] | null | null | null | CodeForces/1152B_Neko_Performs_Cat_Furrier_Transform.cpp | ASM-ATIKUR/Competitive_Programming_Atikur_Rahman | 9552e4dca7daad5c07542514d4b8c8baabea1989 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main()
{
int x, a, cnt, pt, i, ans=0;
vector <int> v;
cin>>x;
while(1)
{
a=x;
cnt=1;
i=1;
pt=0;
int pb=0;
while(a>0)
{
//cout<<(a&1)<<endl;
if(!(a&1))
{pt=i;pb=cnt;}
i*=2;
cnt++;
a=a>>1;
}
if(pt==0)
break;
//cout<<"...";
ans++;
v.push_back(pb);
x=x^(pt*2-1);
a=x;
cnt=0;
while(a>0)
{
if(!(a&1))
{cnt++;}
a=a>>1;
}
if(cnt==0)
break;
ans++;
x++;
}
//cout<<x<<endl;
cout<<ans<<endl;
a=v.size();
for(i=0; i<a; i++)
{
if(i==a-1)
printf("%d\n", v[i]);
else printf("%d ", v[i]);
}
return 0;
}
| 16 | 33 | 0.292026 | [
"vector"
] |
9f1c63e4f1aa998797f6430d6f83470ffe80078d | 3,899 | cpp | C++ | cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/err/check_matching_dims_test.cpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | null | null | null | cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/err/check_matching_dims_test.cpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | null | null | null | cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/err/check_matching_dims_test.cpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | null | null | null | #include <stan/math/prim/mat.hpp>
#include <gtest/gtest.h>
#include <test/unit/util.hpp>
TEST(ErrorHandlingMatrix, checkMatchingDimsMatrix) {
Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> y;
Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> x;
y.resize(3,3);
x.resize(3,3);
EXPECT_NO_THROW(stan::math::check_matching_dims("checkMatchingDims", "x", x,
"y", y));
x.resize(0,0);
y.resize(0,0);
EXPECT_NO_THROW(stan::math::check_matching_dims("checkMatchingDims", "x", x,
"y", y));
y.resize(1,2);
EXPECT_THROW(stan::math::check_matching_dims("checkMatchingDims", "x", x,
"y", y),
std::invalid_argument);
x.resize(2,1);
EXPECT_THROW(stan::math::check_matching_dims("checkMatchingDims", "x", x,
"y", y),
std::invalid_argument);
}
TEST(ErrorHandlingMatrix, checkMatchingDimsMatrix_nan) {
Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> y;
Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> x;
double nan = std::numeric_limits<double>::quiet_NaN();
y.resize(3,3);
x.resize(3,3);
y << nan, nan, nan,nan, nan, nan,nan, nan, nan;
x << nan, nan, nan,nan, nan, nan,nan, nan, nan;
EXPECT_NO_THROW(stan::math::check_matching_dims("checkMatchingDims", "x", x,
"y", y));
x.resize(0,0);
y.resize(0,0);
EXPECT_NO_THROW(stan::math::check_matching_dims("checkMatchingDims", "x", x,
"y", y));
y.resize(1,2);
y << nan, nan;
EXPECT_THROW(stan::math::check_matching_dims("checkMatchingDims", "x", x,
"y", y),
std::invalid_argument);
x.resize(2,1);
x << nan, nan;
EXPECT_THROW(stan::math::check_matching_dims("checkMatchingDims", "x", x,
"y", y),
std::invalid_argument);
}
TEST(ErrorHandlingMatrix, checkMatchingDims_compile_time_sizes) {
using stan::math::check_matching_dims;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> m_dynamic;
Eigen::Matrix<double, 2, 2> m_2x2;
Eigen::Matrix<double, Eigen::Dynamic, 1> vector(4);
Eigen::Matrix<double, 1, Eigen::Dynamic> rowvector(4);
m_dynamic.resize(2,2);
EXPECT_NO_THROW(check_matching_dims("check_matching_dims", "dynamic", m_dynamic,
"2x2", m_2x2));
m_dynamic.resize(3,3);
EXPECT_THROW_MSG(check_matching_dims("check_matching_dims", "dynamic", m_dynamic,
"2x2", m_2x2),
std::invalid_argument,
"check_matching_dims: Rows of dynamic (3) and rows of 2x2 (2) must match in size");
m_dynamic.resize(4,1);
EXPECT_NO_THROW(check_matching_dims("check_matching_dims", "dynamic", m_dynamic,
"vector", vector));
m_dynamic.resize(3,1);
EXPECT_THROW_MSG(check_matching_dims("check_matching_dims", "dynamic", m_dynamic,
"vector", vector),
std::invalid_argument,
"check_matching_dims: Rows of dynamic (3) and rows of vector (4) must match in size");
m_dynamic.resize(1,4);
EXPECT_NO_THROW(check_matching_dims("check_matching_dims", "dynamic", m_dynamic,
"rowvector", rowvector));
m_dynamic.resize(1,3);
EXPECT_THROW_MSG(check_matching_dims("check_matching_dims", "dynamic", m_dynamic,
"rowvector", rowvector),
std::invalid_argument,
"check_matching_dims: Columns of dynamic (3) and columns of rowvector (4) must match in size");
}
| 38.60396 | 114 | 0.566299 | [
"vector"
] |
9f2d75c7f626777333a0ed457ba1ce95d86e6707 | 12,133 | cpp | C++ | main.cpp | rfordyce/sudoku_solver | 39a65dea0010088d473b5505196660bad7a55091 | [
"MIT"
] | null | null | null | main.cpp | rfordyce/sudoku_solver | 39a65dea0010088d473b5505196660bad7a55091 | [
"MIT"
] | null | null | null | main.cpp | rfordyce/sudoku_solver | 39a65dea0010088d473b5505196660bad7a55091 | [
"MIT"
] | null | null | null | #include <iostream>
#include <iomanip>
#include <vector>
#include <getopt.h> //for getopt()
#include <cstdlib> //for exit()
#include <string>
#include "entry.hpp"
#include "setup.cpp"
#include "brute.cpp"
void printBoard(char type='x')
{
std::cout << "i" << iterations << " ";
switch(type) {
case 'r':
std::cout << "rows:";
break;
case 'c':
std::cout << "columns:";
break;
case 's':
std::cout << "subsquares:";
break;
default:
std::cout << "values:";
break;
}
for (int i = 0; i < 81; i++) {
if (i % 9 == 0) std::cout << std::endl;
switch(type) {
case 'r':
std::cout << board.at(i).row;
break;
case 'c':
std::cout << board.at(i).column;
break;
case 's':
std::cout << board.at(i).subsquare;
break;
default:
if (board.at(i).value > 0) {
std::cout << board.at(i).value;
} else {
std::cout << "_";
}
break;
}
std::cout << " ";
}
std::cout << std::endl << std::endl;;
}/**/
void printBoardEverything()
{
for (int r = 0; r < 9; r++) {//rows
for (int c = 0; c < 9; c++) {
if ((*rows[r][c]).value > 0) {
std::cout << "\u250C\u2500\u2510";
} else {
for (int v = 1; v <= 3; v++) {
if ((*rows[r][c]).numbers[v] > 0) {
std::cout << (*rows[r][c]).numbers[v];
} else { std::cout << "_";}
}
}
if ((c + 1) % 3 == 0 and c < 8) std::cout << " ";
}
std::cout << std::endl;
for (int c = 0; c < 9; c++) {
if ((*rows[r][c]).value > 0) {
std::cout << "\u2502" << (*rows[r][c]).value << "\u2502";
} else {
for (int v = 4; v <= 6; v++) {
if ((*rows[r][c]).numbers[v] > 0) {
std::cout << (*rows[r][c]).numbers[v];
} else { std::cout << "_";}
}
}
if ((c + 1) % 3 == 0 and c < 8) std::cout << " ";
}
std::cout << std::endl;
for (int c = 0; c < 9; c++) {
if ((*rows[r][c]).value > 0) {
std::cout << "\u2514\u2500\u2518";
} else {
for (int v = 7; v <= 9; v++) {
if ((*rows[r][c]).numbers[v] > 0) {
std::cout << (*rows[r][c]).numbers[v];
} else { std::cout << "_";}
}
}
if ((c + 1) % 3 == 0 and c < 8) std::cout << " ";
}
std::cout << std::endl;
if ((r + 1) % 3 == 0 and r < 8) std::cout << " \n " << std::endl;
}
}
void setValue(entry* e, int v)
{
(*e).value = v;
for (int i = 0; i < 9; i++) { //clean value from surrounding
(*rows[(*e).row][i]).numbers[v] = 0;
(*columns[(*e).column][i]).numbers[v] = 0;
(*subsquares[(*e).subsquare][i]).numbers[v] = 0;
}
for (int x = 1; x <= 9; x++)
(*e).numbers[x] = 0;
std::cout << "set " << (*e).index << " to " << v << std::endl;
}
void inputText()
{
char cont = 'x';
std::string lines[9];
//get input
//test length of first line, and assign length based upon that
//put into board
//check board
while (true) {
std::cout << "input: (q or ctrl+c to quit)" << std::endl;
getline(std::cin,lines[0]);
if (lines[0][0] == 'q') exit(0); //user input is trash
getline(std::cin,lines[1]);
getline(std::cin,lines[2]);
getline(std::cin,lines[3]);
getline(std::cin,lines[4]);
getline(std::cin,lines[5]);
getline(std::cin,lines[6]);
getline(std::cin,lines[7]);
getline(std::cin,lines[8]);
std::cout << "lines[0].size() : " << lines[0].size() << std::endl;
switch(lines[0].size()) {
case 9: //fixme
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
board.at(i * 9 + j).value = lines[i][j];
break;
case 17: // intentional fallover
case 18:
for (int i = 0; i < 9; i++)
for (int j = 0; j < 18; j++)
if (j % 2 == 0)
if (lines[i][j] - '0' >= 1 and lines[i][j] - '0' <= 9)
//board.at(i * 9 + j / 2).value = lines[i][j] - '0';
setValue(&board.at(i * 9 + j / 2), lines[i][j] - '0');
/* for (int i = 0; i < 81; i++) // clean the numbers from input!
if (board.at(i).value > 0) {
for (int r = 0; r < 9; r++)
(*rows[board.at(i).row][r]).numbers[board.at(i).value + 1] = 0;
for (int c = 0; c < 9; c++)
(*columns[board.at(i).column][c]).numbers[board.at(i).value + 1] = 0;
for (int s = 0; s < 9; s++)
(*subsquares[board.at(i).subsquare][s]).numbers[board.at(i).value + 1] = 0;
for (int v = 1; v <= 9; v++)
board.at(i).numbers[v] = 0;
}*/
break;
default:
std::cout << "make the rows divisible by 9 or 18!" << std::endl;
exit(0);
}
printBoard();
std::cout << "is this ok? (y/n/q): ";
std::cin >> cont;
if (cont == 'y') return;
if (cont == 'q') exit(0);
// reset stuff
for (int i = 0; i < 9 ; i++)
lines[i] = "";
for (int i = 0; i < 81; i++)
board.at(i).value = 0;
}
}
void inputFile()
{
return;
}
//sweep rows for invalid numbers
//sweep columns for invalid numbers
//sweep subsquares for invalid numbers
//check if no other in row have value n
//check if no other in column have value n
//check if no other in subsquare have value n
//test if board complete
void testOnlyValidPositionRows(entry* e, int v)
{
for (int i = 0; i < 9; i++)
if (i != (*e).row) {// not itself
if ((*rows[(*e).row][i]).value == v) return; //value is in another box already! (shouldn't happen)
if ((*columns[(*e).column][i]).value == v) return;
if ((*subsquares[(*e).subsquare][i]).value == v) return;
if ((*rows[(*e).row][i]).numbers[v] > 0) return; //this is not the only valid spot!
}
setValue(e,v);
}
void testOnlyValidPositionColumns(entry* e, int v)
{
for (int i = 0; i < 9; i++)
if (i != (*e).column) {// not itself
if ((*rows[(*e).row][i]).value == v) return; //value is in another box already! (shouldn't happen)
if ((*columns[(*e).column][i]).value == v) return;
if ((*subsquares[(*e).subsquare][i]).value == v) return;
if ((*columns[(*e).column][i]).numbers[v] > 0) return; //this is not the only valid spot!
}
setValue(e,v);
}
void testOnlyValidPositionSubsquares(entry* e, int v)
{
for (int i = 0; i < 9; i++)
if (i != (*e).subsquare) {// not itself
if ((*rows[(*e).row][i]).value == v) return; //value is in another box already! (shouldn't happen)
if ((*columns[(*e).column][i]).value == v) return;
if ((*subsquares[(*e).subsquare][i]).value == v) return;
if ((*subsquares[(*e).subsquare][i]).numbers[v] > 0) return; //this is not the only valid spot!
}
//setValue(e,v);
}
bool testUniqueCandidateRows(entry* e, int v)
{
for (int i = 0; i < 9; i++)
if (not (i == (*e).row)) {// not itself
switch((*e).row % 3) {
case 0: //+1+2
if ((*rows[(*e).row + 1][i]).value == v) return false;
if ((*rows[(*e).row + 2][i]).value == v) return false;
if ((*rows[(*e).row + 1][i]).numbers[v] == v) return false;
if ((*rows[(*e).row + 2][i]).numbers[v] == v) return false;
break;
case 1: //-1+1
if ((*rows[(*e).row - 1][i]).value == v) return false;
if ((*rows[(*e).row + 1][i]).value == v) return false;
if ((*rows[(*e).row - 1][i]).numbers[v] == v) return false;
if ((*rows[(*e).row + 1][i]).numbers[v] == v) return false;
break;
case 2: //-1-2
if ((*rows[(*e).row - 1][i]).value == v) return false;
if ((*rows[(*e).row - 2][i]).value == v) return false;
if ((*rows[(*e).row - 1][i]).numbers[v] == v) return false;
if ((*rows[(*e).row - 2][i]).numbers[v] == v) return false;
break;
default:; //exit(-1); //invalid entry
std::cout << "invalid entry row " << (*e).row << " in testUniqueCandidateRows. v = " << v << std::endl;
exit(-1);
}
}
return true;
}/**/
bool testUniqueCandidateColumns(entry* e, int v)
{
for (int i = 0; i < 9; i++)
if (not (i == (*e).column)) {// not itself
switch((*e).column % 3) {
case 0: //+1+2
if ((*columns[(*e).column + 1][i]).value == v) return false;
if ((*columns[(*e).column + 2][i]).value == v) return false;
if ((*columns[(*e).column + 1][i]).numbers[v] == v) return false;
if ((*columns[(*e).column + 2][i]).numbers[v] == v) return false;
break;
case 1: //-1+1
if ((*columns[(*e).column - 1][i]).value == v) return false;
if ((*columns[(*e).column + 1][i]).value == v) return false;
if ((*columns[(*e).column - 1][i]).numbers[v] == v) return false;
if ((*columns[(*e).column + 1][i]).numbers[v] == v) return false;
break;
case 2: //-1-2
if ((*columns[(*e).column - 1][i]).value == v) return false;
if ((*columns[(*e).column - 2][i]).value == v) return false;
if ((*columns[(*e).column - 1][i]).numbers[v] == v) return false;
if ((*columns[(*e).column - 2][i]).numbers[v] == v) return false;
break;
default:; //exit(-1); //invalid entry
std::cout << "invalid entry column " << (*e).column << " in testUniqueCandidateColumns. v = " << v << std::endl;
exit(-1);
}
}
return true;
}/**/
void testEntry(entry* e)
{
// update numbers to exclude duplicates of known values
for (int v = 1; v <= 9; v++) { //for each value in numbers[]
for (int i = 0; i < 9; i++) { // this does check itself, but is probably faster than testing if it is itself
if ((*e).numbers[v] > 0)
if ((*rows[(*e).row][i]).value == (*e).numbers[v]) (*e).numbers[v] = 0;
if ((*e).numbers[v] > 0)
if ((*columns[(*e).column][i]).value == (*e).numbers[v]) (*e).numbers[v] = 0;
if ((*e).numbers[v] > 0)
if ((*subsquares[(*e).subsquare][i]).value == (*e).numbers[v]) (*e).numbers[v] = 0;
}
}
// test if only valid position for numbers (no other numbers[] include it!)
for (int v = 1; v <= 9; v++) { //for each value in numbers[]
if ((*e).numbers[v] > 0)
testOnlyValidPositionRows(e,v);
if ((*e).numbers[v] > 0)
testOnlyValidPositionColumns(e,v);
if ((*e).numbers[v] > 0)
testOnlyValidPositionSubsquares(e,v);
}
//test for unique candidate https://www.kristanix.com/sudokuepic/sudoku-solving-techniques.php
for (int v = 1; v <= 9; v++) // possibly redundant in this program
if ((*e).numbers[v] > 0)
if (testUniqueCandidateRows(e,v))
if(testUniqueCandidateColumns(e,v)) {
std::cout << "found a unique candidate!\n";
setValue(e,v);
}
}/**/
void validateEntry(entry* e)
{
int value = 0;
for (int v = 1; v <= 9; v++) { //numbers index
if ((*e).numbers[v] > 0 ) { // potential value
if (value > 0) return; //other entries have values!
value = (*e).numbers[v];
}
}
if (value == 0) { //safeguard; can be removed later
std::cout << (*e).index << ": value == 0\n";
printBoardEverything();
exit(-1);
}
setValue(e,value);
}/**/
void sweepEntries()
{
for (int i = 0; i < 81 ; i++) {
if (board.at(i).value < 1) testEntry(&board.at(i)); //no value yet!
}
for (int i = 0; i < 81 ; i++) {
if (board.at(i).value < 1) validateEntry(&board.at(i)); //no value yet!
}
}/**/
bool testBoardComplete()
{
for (int i = 0; i < 81; i++)
if (board.at(i).value < 1) return false; //there is an unset value!
return true;
}/**/
int main(int argc, char* argv[])
{
setupArrays();
int c;
while ((c = getopt(argc, argv, "idh")) != -1) {
switch (c) {
case 'i':
inputText();
break;
case 'd':
DISPLAY_PROGRESS = true;
break;
case 'f':
inputFile();
break;
case 'm':
MAX_ITERATIONS = atoi(optarg);
break;
case 'h':
default: // fallover as bad flag displays help too!
std::cout << "sudoku help" << std::endl
<< "h\ttThis help menu" << std::endl
<< "i\tRegular Input" << std::endl
<< "d\tOutput the full layout whenever a new value is found" << std::endl
<< "f\tSpecify a file to read from" << std::endl
;
exit(0); break;
}
}
//get layout
std::cout << "Program beginning.." << std::endl;
//filltestvalues(); //temporary test
//test layout is valid
printBoard();
do {
///printBoardEverything();
sweepEntries();
iterations++;
//if (iterations % 5000 == 0) std::cout << "iterations: " << iterations << std::endl;
if (iterations > 900) {
std::cout << "layouts: " << layoutsRemaining() << std::endl;
printBoardEverything();
exit(0);
}
} while (not testBoardComplete());
printBoard(); // final output!
printBoardEverything();
return 0;
}/**/
| 29.884236 | 135 | 0.528476 | [
"vector"
] |
9f331071844c39b2e02f67eae3967f55e0725b02 | 2,302 | cc | C++ | components/password_manager/core/browser/http_password_migrator.cc | google-ar/chromium | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 777 | 2017-08-29T15:15:32.000Z | 2022-03-21T05:29:41.000Z | components/password_manager/core/browser/http_password_migrator.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 66 | 2017-08-30T18:31:18.000Z | 2021-08-02T10:59:35.000Z | components/password_manager/core/browser/http_password_migrator.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 123 | 2017-08-30T01:19:34.000Z | 2022-03-17T22:55:31.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/password_manager/core/browser/http_password_migrator.h"
#include "components/password_manager/core/browser/password_store.h"
#include "url/gurl.h"
#include "url/url_constants.h"
namespace password_manager {
HttpPasswordMigrator::HttpPasswordMigrator(const GURL& https_origin,
PasswordStore* password_store,
Consumer* consumer)
: consumer_(consumer), password_store_(password_store) {
DCHECK(password_store_);
DCHECK(https_origin.is_valid());
DCHECK(https_origin.SchemeIs(url::kHttpsScheme)) << https_origin;
GURL::Replacements rep;
rep.SetSchemeStr(url::kHttpScheme);
GURL http_origin = https_origin.ReplaceComponents(rep);
PasswordStore::FormDigest form(autofill::PasswordForm::SCHEME_HTML,
http_origin.GetOrigin().spec(), http_origin);
password_store_->GetLogins(form, this);
}
HttpPasswordMigrator::~HttpPasswordMigrator() = default;
void HttpPasswordMigrator::OnGetPasswordStoreResults(
std::vector<std::unique_ptr<autofill::PasswordForm>> results) {
// Android and PSL matches are ignored.
results.erase(
std::remove_if(results.begin(), results.end(),
[](const std::unique_ptr<autofill::PasswordForm>& form) {
return form->is_affiliation_based_match ||
form->is_public_suffix_match;
}),
results.end());
// Add the new credentials to the password store. The HTTP forms aren't
// removed for now.
for (const auto& form : results) {
GURL::Replacements rep;
rep.SetSchemeStr(url::kHttpsScheme);
form->origin = form->origin.ReplaceComponents(rep);
form->signon_realm = form->origin.spec();
form->action = form->origin;
form->form_data = autofill::FormData();
form->generation_upload_status = autofill::PasswordForm::NO_SIGNAL_SENT;
form->skip_zero_click = false;
password_store_->AddLogin(*form);
}
if (consumer_)
consumer_->ProcessMigratedForms(std::move(results));
}
} // namespace password_manager
| 37.737705 | 78 | 0.68245 | [
"vector"
] |
9f3b55bf696725d9a09ef17bcc6ec41cdb9ac05b | 10,844 | hpp | C++ | src/core/math/matrix.hpp | qkmaxware/Qlib | 60e346aa978ab78f40e496d35b637863f140ef20 | [
"MIT"
] | 1 | 2019-03-29T22:39:00.000Z | 2019-03-29T22:39:00.000Z | src/core/math/matrix.hpp | qkmaxware/Qlib | 60e346aa978ab78f40e496d35b637863f140ef20 | [
"MIT"
] | null | null | null | src/core/math/matrix.hpp | qkmaxware/Qlib | 60e346aa978ab78f40e496d35b637863f140ef20 | [
"MIT"
] | null | null | null | #ifndef _QLIB_MATH_MATRIX_H
#define _QLIB_MATH_MATRIX_H
#include "complex.hpp"
#include "./../general/object.hpp"
#include <stdexcept>
#include <vector>
#include <math.h>
#include <sstream>
namespace qlib {
namespace math {
//----------------------------------------------------------
//Early declarations (before defined)
//----------------------------------------------------------
class matrix;
matrix operator * (matrix a, matrix b);
//----------------------------------------------------------
// Class definition
//----------------------------------------------------------
/// </Summary>
/// Complex matrix class
/// </Summary>
class matrix : public xobject {
private:
/// </Summary>
/// Flattened 1d array of matrix values
/// </Summary>
std::vector<complex> values;
/// </Summary>
/// Number of rows
/// </Summary>
size_t rows;
/// </Summary>
/// Number of columns
/// </Summary>
size_t columns;
/// </Summary>
/// Number of elements
/// </Summary>
size_t length;
public:
/// </Summary>
/// Create an empty matrix of this size
/// </Summary>
matrix(size_t rows, size_t columns){
this->rows = rows > 0 ? rows : 1;
this->columns = columns > 0 ? columns : 1;
this->length = (this->rows) * (this->columns);
this->values = std::vector<complex>(this->length);
for(size_t i = 0; i < this->length; i++)
this->values[i] = complex();
}
/// </Summary>
/// Create a matrix of this size with the given values in compressed row->column form
/// </Summary>
matrix(size_t rows, size_t columns, std::vector<complex> values) : matrix(rows, columns){
size_t smallest = this->length < values.size() ? this->length : values.size();
for(size_t i = 0; i < smallest; i++){
this->values[i] = values[i];
}
}
/// </Summary>
/// Matrix destructor
/// </Summary>
~matrix(){
//delete this->values;
}
/// </Summary>
/// Get the matrix representing the transposition of this matrix
/// </Summary>
matrix transpose(){
matrix m(this->columns, this->rows);
for(size_t r = 0; r < this->rows; r++){
for(size_t c = 0; c < this->columns; c++){
m(c,r) = (*this)(r,c);
}
}
return m;
}
/// </Summary>
/// Get the matrix representing the adjoint (complex conjugate transpose) of this matrix
/// </Summary>
matrix adjoint(){
matrix m(this->columns, this->rows);
for(size_t r = 0; r < this->rows; r++){
for(size_t c = 0; c < this->columns; c++){
m(c,r) = (*this)(r,c).conjugate();
}
}
return m;
}
/// </Summary>
/// Test if this matrix represents a square matrix
/// </Summary>
bool isSquare(){
return (this->countRows() != this->countColumns());
}
/// </Summary>
/// Test if this matrix represents a unitary matrix
/// </Summary>
bool isUnitary(){
matrix a = *this;
matrix a_dagger = this->adjoint();
matrix q = a * a_dagger;
//Is 'q' approximately I
for(size_t r = 0; r < q.countRows(); r++){
for(size_t c = 0; c < q.countColumns(); c++){
if(r == c){
//Approx 1
if(!q(r,c).isApproximatelyOne())
return false;
}else {
//Approx 0
if(!q(r,c).isApproximatelyZero())
return false;
}
}
}
return true;
}
/// </Summary>
/// Test if this matrix represents a column matrix
/// </Summary>
bool isColumn(){
return (this->countColumns() == 1);
}
/// </Summary>
/// Test if this matrix represents a row matrix
/// </Summary>
bool isRow(){
return (this->countRows() == 1);
}
/// </Summary>
/// Get element from matrix
/// </Summary>
complex& operator() (size_t r, size_t c) {
size_t idx = r * columns + c;
if(idx < 0 || idx >= length){
throw std::out_of_range("Row or column is out of range");
}
return values[idx];
}
/// </Summary>
/// Get element from matrix
/// </Summary>
complex& operator() (size_t idx) {
if(idx < 0 || idx >= length){
throw std::out_of_range("Row or column is out of range");
}
return values[idx];
}
/// </Summary>
/// Number of rows
/// </Summary>
size_t countRows(){
return this->rows;
}
/// </Summary>
/// Number of columns
/// </Summary>
size_t countColumns(){
return this->columns;
}
/// </Summary>
/// Total number of elements
/// </Summary>
size_t size(){
return this->length;
}
/// </Summary>
/// Set element in matrix
/// </Summary>
void set(size_t r, size_t c, complex value){
size_t idx = r * columns + c;
if(idx < 0 || idx >= length){
throw std::out_of_range("Row or column is out of range");
}
this->values[idx] = value;
}
/// </Summary>
/// Set element in matrix
/// </Summary>
void set(size_t idx, complex value){
if(idx < 0 || idx >= length){
throw std::out_of_range("Row or column is out of range");
}
this->values[idx] = value;
}
/// </Summary>
/// Get element from matrix
/// </Summary>
complex get(size_t r, size_t c){
size_t idx = r * columns + c;
if(idx < 0 || idx >= length){
throw std::out_of_range("Row or column is out of range");
}
return this->values[idx];
}
/// </Summary>
/// Get element from matrix
/// </Summary>
complex get(size_t idx){
if(idx < 0 || idx >= length){
throw std::out_of_range("Row or column is out of range");
}
return this->values[idx];
}
/// </Summary>
/// String representation
/// </Summary>
std::string toString(){
std::stringstream sb;
sb << "{";
for(size_t r = 0; r < this->rows; r++){
if(r != 0)
sb << ";";
sb << "{";
for(size_t c = 0; c < this->columns; c++){
if(c != 0)
sb << ",";
sb << get(r, c).toString();
}
sb << "}";
}
sb << "}";
return sb.str();
};
/// <Summary>
/// Iterator starting at element 0,0
/// </Summary>
std::vector<complex>::iterator begin(){
return (this->values).begin();
}
/// <Summary>
/// Iterator starting after element rows-1,columns-1
/// </Summary>
std::vector<complex>::iterator end(){
return (this->values).end();
}
};
//----------------------------------------------------------
// Operators
//----------------------------------------------------------
/// </Summary>
/// Add two matrices
/// </Summary>
matrix operator + (matrix a, matrix b){
if(a.countRows() != b.countRows() || a.countColumns() != b.countColumns()){
throw std::length_error("Matrix dims do not match");
}
matrix m(a.countRows(), a.countColumns());
for(size_t i = 0; i < a.size(); i++){
m.set(i, a.get(i) + b.get(i));
}
return m;
}
/// </Summary>
/// Subtract two matrices
/// </Summary>
matrix operator - (matrix a, matrix b){
if(a.countRows() != b.countRows() || a.countColumns() != b.countColumns()){
throw std::length_error("Matrix dims do not match");
}
matrix m(a.countRows(), a.countColumns());
for(size_t i = 0; i < a.size(); i++){
m.set(i, a.get(i) - b.get(i));
}
return m;
}
/// </Summary>
/// Scale up a matrix by a scalar quantity
/// </Summary>
matrix operator * (complex s, matrix a){
matrix m(a.countRows(), a.countColumns());
for(size_t i = 0; i < a.size(); i++){
m.set(i, a.get(i) * s);
}
return m;
}
/// </Summary>
/// Scale up a matrix by a scalar quantity
/// </Summary>
matrix operator * (matrix a, complex s){
matrix m(a.countRows(), a.countColumns());
for(size_t i = 0; i < a.size(); i++){
m.set(i, a.get(i) * s);
}
return m;
}
/// </Summary>
/// Scale down a matrix by a scalar quantity
/// </Summary>
matrix operator / (matrix a, complex s){
matrix m(a.countRows(), a.countColumns());
for(size_t i = 0; i < a.size(); i++){
m.set(i, a.get(i) / s);
}
return m;
}
/// </Summary>
/// Multiply two matrices
/// </Summary>
matrix operator * (matrix a, matrix b){
if(a.countColumns() != b.countRows()){
throw std::length_error("Matrix dims do not match");
}
matrix m(a.countRows(), b.countColumns());
for(size_t i = 0; i < a.countRows(); i++){
for(size_t j = 0; j < b.countColumns(); j++){
complex sum = 0;
for(size_t k = 0; k < a.countColumns(); k++){
sum = sum + a(i,k) * b(k,j);
}
m.set(i,j, sum);
}
}
return m;
}
/// </Summary>
/// Compute the Kronicker tensor product of two matrices
/// </Summary>
matrix operator << (matrix a, matrix b){
//Compute width
size_t nw = a.countColumns() * b.countColumns();
size_t nh = a.countRows() * b.countRows();
//Create matrix;
matrix m(nh, nw);
//Loop over all elements setting as necessary
for(size_t ar = 0; ar < a.countRows(); ar++){
for(size_t ac = 0; ac < a.countColumns(); ac++){
for(size_t br = 0; br < b.countRows(); br++){
for(size_t bc = 0; bc < b.countColumns(); bc++){
m(br + ar * b.countRows(), bc + ac * b.countColumns()) = a(ar, ac) * b(br, bc);
}
}
}
}
return m;
}
}
}
#endif | 28.020672 | 100 | 0.447621 | [
"object",
"vector"
] |
9f45de9f143b73aaa27508449200cdfa30321fb3 | 7,429 | cxx | C++ | Code/Numerics/itkSingleValuedVnlCostFunctionAdaptor.cxx | kiranhs/ITKv4FEM-Kiran | 0e4ab3b61b5fc4c736f04a73dd19e41390f20152 | [
"BSD-3-Clause"
] | 1 | 2018-04-15T13:32:43.000Z | 2018-04-15T13:32:43.000Z | Code/Numerics/itkSingleValuedVnlCostFunctionAdaptor.cxx | kiranhs/ITKv4FEM-Kiran | 0e4ab3b61b5fc4c736f04a73dd19e41390f20152 | [
"BSD-3-Clause"
] | null | null | null | Code/Numerics/itkSingleValuedVnlCostFunctionAdaptor.cxx | kiranhs/ITKv4FEM-Kiran | 0e4ab3b61b5fc4c736f04a73dd19e41390f20152 | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkSingleValuedVnlCostFunctionAdaptor.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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 notices for more information.
=========================================================================*/
#include "itkSingleValuedVnlCostFunctionAdaptor.h"
#include "itkExceptionObject.h"
namespace itk
{
/** Constructor. */
SingleValuedVnlCostFunctionAdaptor
::SingleValuedVnlCostFunctionAdaptor(unsigned int spaceDimension):
vnl_cost_function(spaceDimension)
{
m_ScalesInitialized = false;
m_NegateCostFunction = false;
m_Reporter = Object::New();
}
/** Set current parameters scaling. */
void
SingleValuedVnlCostFunctionAdaptor
::SetScales(const ScalesType & scales)
{
m_Scales = scales;
m_ScalesInitialized = true;
}
/** Delegate computation of the value to the CostFunction. */
SingleValuedVnlCostFunctionAdaptor::InternalMeasureType
SingleValuedVnlCostFunctionAdaptor
::f( const InternalParametersType & inparameters )
{
if( !m_CostFunction )
{
itkGenericExceptionMacro(<<"Attempt to use a SingleValuedVnlCostFunctionAdaptor without any CostFunction plugged in");
}
// Use scales if they are provided
ParametersType parameters(inparameters.size());
if(m_ScalesInitialized)
{
for(unsigned int i=0;i<parameters.size();i++)
{
parameters[i] = inparameters[i]/m_Scales[i];
}
}
else
{
parameters.SetData(const_cast<double*>(inparameters.data_block()));
}
InternalMeasureType value = static_cast<InternalMeasureType>( m_CostFunction->GetValue( parameters ));
if( m_NegateCostFunction )
{
value *= -1.0;
}
// Notify observers. This is used for overcoming the limitaion of VNL
// optimizers of not providing callbacks per iteration.
m_CachedValue = value;
m_CachedCurrentParameters = parameters;
this->ReportIteration( FunctionEvaluationIterationEvent() );
return value;
}
/** Delegate computation of the gradient to the costfunction. */
void
SingleValuedVnlCostFunctionAdaptor
::gradf( const InternalParametersType & inparameters,
InternalDerivativeType & gradient )
{
if( !m_CostFunction )
{
itkGenericExceptionMacro("Attempt to use a SingleValuedVnlCostFunctionAdaptor without any CostFunction plugged in");
}
// Use scales if they are provided
ParametersType parameters(inparameters.size());
if(m_ScalesInitialized)
{
for(unsigned int i=0;i<parameters.size();i++)
{
parameters[i] = inparameters[i]/m_Scales[i];
}
}
else
{
parameters.SetData(const_cast<double*>(inparameters.data_block()));
}
m_CostFunction->GetDerivative( parameters, m_CachedDerivative );
this->ConvertExternalToInternalGradient( m_CachedDerivative, gradient);
// Notify observers. This is used for overcoming the limitaion of VNL
// optimizers of not providing callbacks per iteration.
// Note that m_CachedDerivative is already loaded in the GetDerivative() above.
m_CachedCurrentParameters = parameters;
this->ReportIteration( GradientEvaluationIterationEvent() );
}
/** Delegate computation of value and gradient to the costfunction. */
void
SingleValuedVnlCostFunctionAdaptor
::compute( const InternalParametersType & x,
InternalMeasureType * fun,
InternalDerivativeType * g )
{
// delegate the computation to the CostFunction
ParametersType parameters( x.size());
double measure;
if(m_ScalesInitialized)
{
for(unsigned int i=0;i<parameters.size();i++)
{
parameters[i] = x[i]/m_Scales[i];
}
}
else
{
parameters.SetData(const_cast<double*>(x.data_block()));
}
m_CostFunction->GetValueAndDerivative( parameters, measure, m_CachedDerivative );
if( g ) // sometimes Vnl doesn't pass a valid pointer
{
this->ConvertExternalToInternalGradient( m_CachedDerivative, *g );
}
if( fun ) // paranoids have longer lives...
{
if( !m_NegateCostFunction )
{
*fun = static_cast<InternalMeasureType>( measure );
}
else
{
*fun = static_cast<InternalMeasureType>( - measure );
}
}
// Notify observers. This is used for overcoming the limitaion of VNL
// optimizers of not providing callbacks per iteration.
// Note that m_CachedDerivative is already loaded in the GetDerivative() above.
m_CachedValue = *fun;
m_CachedCurrentParameters = parameters;
this->ReportIteration( FunctionAndGradientEvaluationIterationEvent() );
}
/** Convert external derviative measures into internal type */
void
SingleValuedVnlCostFunctionAdaptor
::ConvertExternalToInternalGradient( const DerivativeType & input,
InternalDerivativeType & output ) const
{
const unsigned int size = input.size();
output = InternalDerivativeType(size);
for( unsigned int i=0; i<size; i++ )
{
if( !m_NegateCostFunction )
{
output[i] = input[i];
}
else
{
output[i] = -input[i];
}
if(m_ScalesInitialized)
{
output[i] /= m_Scales[i];
}
}
}
/** Set whether the cost function should be negated or not. This is useful for
* adapting optimizers that are only minimizers. */
void
SingleValuedVnlCostFunctionAdaptor
::SetNegateCostFunction( bool flag )
{
m_NegateCostFunction = flag;
}
/** Returns whether the cost function is going to be negated or not.
* This is useful for adapting optimizers that are only minimizers. */
bool
SingleValuedVnlCostFunctionAdaptor
::GetNegateCostFunction() const
{
return m_NegateCostFunction;
}
/** This method reports iterations events. It is intended to
* help monitoring the progress of the optimization process. */
void
SingleValuedVnlCostFunctionAdaptor
::ReportIteration( const EventObject & event ) const
{
this->m_Reporter->InvokeEvent( event );
}
/** Connects a Command/Observer to the internal reporter class.
* This is useful for reporting iteration event to potential observers. */
unsigned long
SingleValuedVnlCostFunctionAdaptor
::AddObserver(const EventObject & event, Command * command) const
{
return m_Reporter->AddObserver( event, command );
}
/** Return the cached value of the cost function */
const SingleValuedVnlCostFunctionAdaptor::MeasureType &
SingleValuedVnlCostFunctionAdaptor
::GetCachedValue() const
{
return m_CachedValue;
}
/** Return the cached value of the cost function derivative */
const SingleValuedVnlCostFunctionAdaptor::DerivativeType &
SingleValuedVnlCostFunctionAdaptor
::GetCachedDerivative() const
{
return m_CachedDerivative;
}
/** Return the cached value of the parameters used for computing the function */
const SingleValuedVnlCostFunctionAdaptor::ParametersType &
SingleValuedVnlCostFunctionAdaptor
::GetCachedCurrentParameters() const
{
return m_CachedCurrentParameters;
}
} // end namespace itk
| 28.033962 | 122 | 0.701171 | [
"object"
] |
9f4ce39fb7e75e02b14cec63c63ca265a9e30a65 | 1,205 | hpp | C++ | Engine/Code/Engine/Math/Random.hpp | tonyatpeking/SmuSpecialTopic | b61d44e4efacb3c504847deb4d00234601bca49c | [
"MIT"
] | null | null | null | Engine/Code/Engine/Math/Random.hpp | tonyatpeking/SmuSpecialTopic | b61d44e4efacb3c504847deb4d00234601bca49c | [
"MIT"
] | null | null | null | Engine/Code/Engine/Math/Random.hpp | tonyatpeking/SmuSpecialTopic | b61d44e4efacb3c504847deb4d00234601bca49c | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
class Rgba;
class Vec2;
class Vec3;
namespace Random
{
extern int g_seed;
void InitSeed();
void SetSeed( unsigned int seed );
bool CheckChance( float chanceForSuccess ); // If 0.27f passed, returns true 27% of the time
float FloatZeroToOne(); // Gives floats in [0.0f,1.0f]
float FloatMinusOneToOne(); // Gives floats in [-1.f,1.f]
float FloatInRange( float minInclusive, float maxInclusive ); // Gives floats in [min,max]
int IntInRange( int minInclusive, int maxInclusive ); // Gives integers in [min,max]
int IntLessThan( int maxNotInclusive ); // Gives integers in [0,max-1]
unsigned char Char();
unsigned char CharInRange( unsigned char minInclusive, unsigned char maxInclusive);
float RotationDegrees(); // Gives floats in [0.0f,360.0f]
Vec2 Direction();
Vec2 PointInCircle( float radius );
Vec2 PointInCircle01();
Vec2 Vec2InRange( const Vec2& min, const Vec2& max );
Vec3 Vec3InRange( const Vec3& min, const Vec3& max );
Rgba Color();
Rgba ColorInRange( const Rgba& colorA, const Rgba& colorB );
// collections
void UniqueValuesInRange( int numOfValues, int minInclusive, int maxInclusive,
std::vector<int>& out_uniqueValues);
}
| 25.638298 | 92 | 0.729461 | [
"vector"
] |
9f58718ed30b5f559a389dae99742540741d76d4 | 4,825 | hpp | C++ | Patcher/Source/DirTree/TreeModel.hpp | sylwow/SharpsenBox | 856c8751a6c236598d5f615b87b216365f85064b | [
"MIT"
] | 6 | 2020-10-04T11:26:25.000Z | 2022-01-10T13:52:57.000Z | Patcher/Source/DirTree/TreeModel.hpp | sylwow/LaunchBox | 856c8751a6c236598d5f615b87b216365f85064b | [
"MIT"
] | null | null | null | Patcher/Source/DirTree/TreeModel.hpp | sylwow/LaunchBox | 856c8751a6c236598d5f615b87b216365f85064b | [
"MIT"
] | 1 | 2021-03-28T15:10:50.000Z | 2021-03-28T15:10:50.000Z | #pragma once
#include <QObject>
#include <QQmlApplicationEngine>
#include <QDebug>
#include <QThread>
#include <QAbstractItemModel>
#include <QObject>
#include <QDir>
#include <QStandardItemModel>
#include <QStandardItem>
#include "IQmlObject.hpp"
#include "TreeItem.hpp"
#include <iostream>
#include <filesystem>
#include <QHash>
#include "setUpTreeModel.hpp"
namespace dt {
class TreeModel : public QAbstractItemModel {
Q_OBJECT
public:
static TreeModel& getObject() {
static TreeModel uc(false);
return uc;
}
static int index_;
// implementation IQmlObject
void update() {};
std::string getName() {
return TYPENAME(TreeModel);
}
void init(bool packet);
// Qml properties
Q_PROPERTY(QString packetName WRITE setPacketName READ getPacketName);
Q_INVOKABLE void setPacketName(QString str) {
packetName_ = str.toStdString();
}
Q_INVOKABLE QString getPacketName() {
return packetName_.c_str();
}
Q_PROPERTY(double percentage READ getPercent NOTIFY percentChanged);
Q_PROPERTY(bool available READ getAval NOTIFY avalChanged);
Q_INVOKABLE double getPercent() {
return percentage_;
}
Q_INVOKABLE double getAval() {
return available_;
}
TreeModel(bool packet = true, QObject* parent = nullptr);
~TreeModel();
QVariant data(const QModelIndex& index, int role) const override;
QVariant headerData(int section, Qt::Orientation orientation,
int role = Qt::DisplayRole) const override;
QModelIndex index(int row, int column,
const QModelIndex& parent = QModelIndex()) const override;
QModelIndex parent(const QModelIndex& index) const override;
int rowCount(const QModelIndex& parent = QModelIndex()) const override;
int columnCount(const QModelIndex& parent = QModelIndex()) const override;
TreeItem* item(const QModelIndex& index) { return static_cast<TreeItem*>(index.internalPointer()); }
Qt::ItemFlags flags(const QModelIndex& index) const override;
// bool setData(const QModelIndex& index, const QVariant& value,
// int role = Qt::EditRole) override;
bool setHeaderData(int section, Qt::Orientation orientation,
const QVariant& value, int role = Qt::EditRole) override;
// bool insertColumns(int position, int columns,
// const QModelIndex& parent = QModelIndex()) override;
// bool removeColumns(int position, int columns,
// const QModelIndex& parent = QModelIndex()) override;
// bool insertRows(int position, int rows,
// const QModelIndex& parent = QModelIndex()) override;
Q_INVOKABLE QModelIndex unbindRows(const QModelIndexList& list);
Q_INVOKABLE void setSelected(const QModelIndex& index);
Q_INVOKABLE void unsetSelected(const QModelIndex& index);
Q_INVOKABLE void print(const QModelIndexList list) {
for (int i = 0; i < list.size(); i++) {
std::cout << list[i].data().toString().toStdString() << std::endl;
}
}
void bind(const QModelIndex& list);
Q_INVOKABLE void remove(const QModelIndexList& list);
Q_INVOKABLE QAbstractItemModel* getNewPacket() { auto* ptr = new TreeModel(); packets.push_back(ptr); return packets.back(); }
Q_INVOKABLE QAbstractItemModel* getPacket(int index) { return packets[index]; }
Q_INVOKABLE int getFileState(const QModelIndex& index) {
if (index.isValid())
return item(index)->getState();
return 1;
}
static void setRoot(std::filesystem::path path) { rootDir_ = path; }
static std::filesystem::path& getRoot() { return rootDir_; }
QMimeData* mimeData(const QModelIndexList& indexes) const override;
QVector<TreeModel*>& getPackets() { return packets; }
TreeItem* rootItemPtr() { return rootItem->child(0); }
st::setUpModel& getSetUpModel() { return setUp_; }
void setPackName(std::string& str) { packetName_ = str; }
signals:
void percentChanged();
void avalChanged();
public slots:
void bind(const QModelIndexList& list);
void errorChatched(QString err) {};
void readEnded() { endResetModel(); available_ = true; avalChanged(); }
void readState(double percentage) { percentage_ = percentage; percentChanged(); }
private:
struct data {
TreeItem* item;
std::string path;
bool dir;
std::vector<std::string> folders;
int depth;
} dataToInsert_;
double percentage_;
void merge(TreeItem* parent, TreeItem* toInsert);
QModelIndex* rootIndex_;
void addData(TreeItem* parent);
QSet<QModelIndex> selectedToMove_;
void setupModelData(const std::filesystem::path, TreeItem* parent);
TreeItem* getItem(const QModelIndex& index) const;
static std::filesystem::path rootDir_;
TreeItem* rootItem;
QVector<TreeModel*> packets;
size_t total_;
size_t actual_ = 0;
st::setUpModel setUp_;
bool available_ = false;
std::string packetName_ = std::string("packet") + std::to_string(index_++) + ".zip";
bool load_ = false;
};
}
| 31.535948 | 128 | 0.723109 | [
"vector"
] |
9f750cddc807f8e16ee426255dab02af3d2bed4d | 1,198 | cpp | C++ | ural/1207.cpp | jffifa/algo-solution | af2400d6071ee8f777f9473d6a34698ceef08355 | [
"MIT"
] | 5 | 2015-07-14T10:29:25.000Z | 2016-10-11T12:45:18.000Z | ural/1207.cpp | jffifa/algo-solution | af2400d6071ee8f777f9473d6a34698ceef08355 | [
"MIT"
] | null | null | null | ural/1207.cpp | jffifa/algo-solution | af2400d6071ee8f777f9473d6a34698ceef08355 | [
"MIT"
] | 3 | 2016-08-23T01:05:26.000Z | 2017-05-28T02:04:20.000Z | /*
Problem: Ural1207
Algorithm: Geometry
Time: O()
Memory: O()
Detail: Simple
Coded by Biribiri
*/
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int MaxN = 10000;
const double INF = 1e9;
const double EPS = 1e-6;
const double PI = acos((double)-1);
struct SPoint
{
double x, y, angle;
int id;
SPoint() {}
SPoint(double X, double Y): x(X), y(Y) {}
friend SPoint operator - (const SPoint &P1, const SPoint &P2)
{return SPoint(P1.x-P2.x, P1.y-P2.y);}
friend bool operator < (const SPoint &P1, const SPoint &P2)
{return P1.angle < P2.angle;}
};
double Angle(const SPoint &P, const SPoint &P0)
{return atan2(P.x-P0.x, P.y-P0.y);}
int N, MinID;
SPoint P[MaxN+1];
int main()
{
scanf("%d", &N);
MinID = 0;
for (int i = 0; i < N; ++i)
{
scanf("%lf%lf", &P[i].x, &P[i].y);
P[i].id = i;
if (P[i].y == P[MinID].y)
{if (P[i].x < P[MinID].x) MinID = i;}
else
{if (P[i].y < P[MinID].y) MinID = i;}
}
swap(P[0], P[MinID]);
for (int i = 1; i < N; ++i)
P[i].angle = Angle(P[i], P[0]);
sort(P+1, P+N);
printf("%d %d\n", P[0].id+1, P[N>>1].id+1);
return 0;
}
| 20.305085 | 63 | 0.556761 | [
"geometry"
] |
9f7b10137d48516a23bfc6e89428c3a809d23009 | 5,694 | cpp | C++ | Plain/src/Common/MeshProcessing.cpp | Gaukler/PlainRenderer | cf0f41a2300bee9f29a886230c061776cb29ba5e | [
"MIT"
] | 9 | 2021-04-09T14:07:45.000Z | 2022-03-06T07:51:14.000Z | Plain/src/Common/MeshProcessing.cpp | Gaukler/PlainRenderer | cf0f41a2300bee9f29a886230c061776cb29ba5e | [
"MIT"
] | 14 | 2021-04-10T11:06:06.000Z | 2021-05-07T14:20:34.000Z | Plain/src/Common/MeshProcessing.cpp | Gaukler/PlainRenderer | cf0f41a2300bee9f29a886230c061776cb29ba5e | [
"MIT"
] | null | null | null | #include "pch.h"
#include "MeshProcessing.h"
#include "Common/CompressedTypes.h"
std::vector<AxisAlignedBoundingBox> AABBListFromMeshes(const std::vector<MeshData>& meshes) {
std::vector<AxisAlignedBoundingBox> AABBList;
AABBList.reserve(meshes.size());
for (const MeshData& meshData : meshes) {
AABBList.push_back(axisAlignedBoundingBoxFromPositions(meshData.positions));
}
return AABBList;
}
std::vector<MeshBinary> meshesToBinary(const std::vector<MeshData>& meshes, const std::vector<AxisAlignedBoundingBox>& AABBList) {
assert(meshes.size() == AABBList.size());
std::vector<MeshBinary> meshesBinary;
meshesBinary.reserve(meshes.size());
for (size_t meshIndex = 0; meshIndex < meshes.size(); meshIndex++) {
const MeshData& meshData = meshes[meshIndex];
MeshBinary meshBinary;
meshBinary.texturePaths = meshData.texturePaths;
meshBinary.boundingBox = AABBList[meshIndex];
meshBinary.meanAlbedo = meshData.meanAlbedo;
//index buffer
meshBinary.indexCount = (uint32_t)meshData.indices.size();
if (meshBinary.indexCount < std::numeric_limits<uint16_t>::max()) {
//half precision indices are enough
//calculate lower precision indices
meshBinary.indexBuffer.reserve(meshBinary.indexCount);
for (const auto index : meshData.indices) {
meshBinary.indexBuffer.push_back((uint16_t)index);
}
}
else {
//copy full precision indices
const uint32_t entryPerIndex = 2; //two 16 bit entries needed for one 32 bit index
meshBinary.indexBuffer.resize((size_t)meshBinary.indexCount * (size_t)entryPerIndex);
const size_t copySize = sizeof(uint32_t) * meshBinary.indexCount;
memcpy(meshBinary.indexBuffer.data(), meshData.indices.data(), copySize);
}
//vertex buffer
assert(meshData.positions.size() == meshData.uvs.size());
assert(meshData.positions.size() == meshData.normals.size());
assert(meshData.positions.size() == meshData.tangents.size());
assert(meshData.positions.size() == meshData.bitangents.size());
meshBinary.vertexCount = (uint32_t)meshData.positions.size();
//precision and type must correspond to types in VertexInput.h
for (size_t i = 0; i < meshBinary.vertexCount; i++) {
//position
meshBinary.vertexBuffer.push_back(((uint8_t*)&meshData.positions[i].x)[0]);
meshBinary.vertexBuffer.push_back(((uint8_t*)&meshData.positions[i].x)[1]);
meshBinary.vertexBuffer.push_back(((uint8_t*)&meshData.positions[i].x)[2]);
meshBinary.vertexBuffer.push_back(((uint8_t*)&meshData.positions[i].x)[3]);
meshBinary.vertexBuffer.push_back(((uint8_t*)&meshData.positions[i].y)[0]);
meshBinary.vertexBuffer.push_back(((uint8_t*)&meshData.positions[i].y)[1]);
meshBinary.vertexBuffer.push_back(((uint8_t*)&meshData.positions[i].y)[2]);
meshBinary.vertexBuffer.push_back(((uint8_t*)&meshData.positions[i].y)[3]);
meshBinary.vertexBuffer.push_back(((uint8_t*)&meshData.positions[i].z)[0]);
meshBinary.vertexBuffer.push_back(((uint8_t*)&meshData.positions[i].z)[1]);
meshBinary.vertexBuffer.push_back(((uint8_t*)&meshData.positions[i].z)[2]);
meshBinary.vertexBuffer.push_back(((uint8_t*)&meshData.positions[i].z)[3]);
//uv stored as 16 bit signed float
const auto uHalf = glm::packHalf(glm::vec1(meshData.uvs[i].x));
meshBinary.vertexBuffer.push_back(((uint8_t*)&uHalf)[0]);
meshBinary.vertexBuffer.push_back(((uint8_t*)&uHalf)[1]);
const auto vHalf = glm::packHalf(glm::vec1(meshData.uvs[i].y));
meshBinary.vertexBuffer.push_back(((uint8_t*)&vHalf)[0]);
meshBinary.vertexBuffer.push_back(((uint8_t*)&vHalf)[1]);
//normal stored as 32 bit R10G10B10A2
{
const NormalizedR10G10B10A2 normalCompressed = vec3ToNormalizedR10B10G10A2(meshData.normals[i]);
meshBinary.vertexBuffer.push_back(((uint8_t*)&normalCompressed)[0]);
meshBinary.vertexBuffer.push_back(((uint8_t*)&normalCompressed)[1]);
meshBinary.vertexBuffer.push_back(((uint8_t*)&normalCompressed)[2]);
meshBinary.vertexBuffer.push_back(((uint8_t*)&normalCompressed)[3]);
}
//tangent stored as 32 bit R10G10B10A2
{
const NormalizedR10G10B10A2 tangentCompressed = vec3ToNormalizedR10B10G10A2(meshData.tangents[i]);
meshBinary.vertexBuffer.push_back(((uint8_t*)&tangentCompressed)[0]);
meshBinary.vertexBuffer.push_back(((uint8_t*)&tangentCompressed)[1]);
meshBinary.vertexBuffer.push_back(((uint8_t*)&tangentCompressed)[2]);
meshBinary.vertexBuffer.push_back(((uint8_t*)&tangentCompressed)[3]);
}
//bitangent stored as 32 bit R10G10B10A2
{
const NormalizedR10G10B10A2 bitangentCompressed = vec3ToNormalizedR10B10G10A2(meshData.bitangents[i]);
meshBinary.vertexBuffer.push_back(((uint8_t*)&bitangentCompressed)[0]);
meshBinary.vertexBuffer.push_back(((uint8_t*)&bitangentCompressed)[1]);
meshBinary.vertexBuffer.push_back(((uint8_t*)&bitangentCompressed)[2]);
meshBinary.vertexBuffer.push_back(((uint8_t*)&bitangentCompressed)[3]);
}
}
meshesBinary.push_back(meshBinary);
}
return meshesBinary;
} | 50.389381 | 130 | 0.650509 | [
"vector"
] |
9f7ff7898245f0cc4e7c50b5ae0e740c488fe2bd | 605 | cpp | C++ | Assignments/hw10/solution/solution_bonus/testActivity.cpp | henrisota/Algorithms-and-Data-Structures | 88de93a920b57290c0a63b967073da2e09c5a34d | [
"MIT"
] | null | null | null | Assignments/hw10/solution/solution_bonus/testActivity.cpp | henrisota/Algorithms-and-Data-Structures | 88de93a920b57290c0a63b967073da2e09c5a34d | [
"MIT"
] | null | null | null | Assignments/hw10/solution/solution_bonus/testActivity.cpp | henrisota/Algorithms-and-Data-Structures | 88de93a920b57290c0a63b967073da2e09c5a34d | [
"MIT"
] | null | null | null | /*
CH-231-A
hw10_p2.cpp
Henri Sota
h.sota@jacobs-university.de
*/
#include <iostream>
#include <vector>
#include "Activity.h"
int main() {
std::vector<Activity> list = {
Activity(1, 4),
Activity(3, 5),
Activity(0, 6),
Activity(5, 7),
Activity(3, 9),
Activity(5, 9),
Activity(6, 10),
Activity(8, 11),
Activity(8, 12),
Activity(2, 14),
Activity(12, 16)
};
std::vector<Activity> solution = greedyActivitySelector(list);
std::cout << "Optimal solution set of activities:" << std::endl;
for (Activity activity: solution)
std::cout << activity << std::endl;
return 0;
} | 18.333333 | 65 | 0.639669 | [
"vector"
] |
9f8f17101745dd4d0e1375847c874155c93d757b | 1,213 | hpp | C++ | scenes/3D_graphics/01_modeling/HumanConstructions.hpp | victor-radermecker/Island-Project | 3284cea0ec5b143bfe410b0999caa06e79498df5 | [
"MIT"
] | null | null | null | scenes/3D_graphics/01_modeling/HumanConstructions.hpp | victor-radermecker/Island-Project | 3284cea0ec5b143bfe410b0999caa06e79498df5 | [
"MIT"
] | null | null | null | scenes/3D_graphics/01_modeling/HumanConstructions.hpp | victor-radermecker/Island-Project | 3284cea0ec5b143bfe410b0999caa06e79498df5 | [
"MIT"
] | null | null | null | #pragma once
#include "main/scene_base/base.hpp"
using namespace vcl;
struct treasure_model
{
// init and draw
void init_all();
void draw_all(std::map<std::string, GLuint>& shaders, scene_structure& scene);
vcl::hierarchy_mesh_drawable hierarchy_treasure;
//Functions
void create_treasure_box();
void open_chest();
void draw_treasure(std::map<std::string, GLuint>& shaders, scene_structure& scene);
mesh mesh_primitive_parallelepiped_chest(const vcl::vec3& p0, const vcl::vec3& u1, const vcl::vec3& u2, const vcl::vec3& u3, std::string part);
void mouse_click(scene_structure& scene, GLFWwindow* window, int, int, int);
bool open_chest_bool = false;
vec3 chest_position;
//Gluint wooden texture
GLuint wood_texture_id;
GLuint treasure_texture_id;
//Bridge
vcl::mesh_drawable bridge;
vcl::vec3 bridge_position;
GLuint bridge_texture_id;
void set_bridge();
mesh create_bridge();
void draw_bridge(std::map<std::string, GLuint>& shaders, scene_structure& scene);
//Canoe
vcl::mesh_drawable canoe;
vcl::vec3 canoe_position;
GLuint canoe_texture_id;
void set_canoe();
mesh create_canoe();
void draw_canoe(std::map<std::string, GLuint>& shaders, scene_structure& scene);
};
| 23.784314 | 144 | 0.754328 | [
"mesh"
] |
9f936f5bea1c75d40996ecdfacd14083199dfaf8 | 36,918 | cc | C++ | extensions/cuda/stats.cc | lijun99/pyre | 004dfd4c06489b4ba5b32877338ca6440f2d523b | [
"BSD-3-Clause"
] | 3 | 2019-08-02T21:02:47.000Z | 2021-09-08T13:59:43.000Z | extensions/cuda/stats.cc | lijun99/pyre | 004dfd4c06489b4ba5b32877338ca6440f2d523b | [
"BSD-3-Clause"
] | null | null | null | extensions/cuda/stats.cc | lijun99/pyre | 004dfd4c06489b4ba5b32877338ca6440f2d523b | [
"BSD-3-Clause"
] | null | null | null | // -*- C++ -*-
// -*- coding: utf-8 -*-
//
// Lijun Zhu
// california institute of technology
// (c) 2016-2019 all rights reserved
//
#include <portinfo>
#include <Python.h>
#include <pyre/journal.h>
#include <iostream>
#include <sstream>
// my declarations
#include "stats.h"
// local support
#include "capsules.h"
#include "exceptions.h"
#include "dtypes.h"
// access to cudalib definitions
#include <pyre/cuda.h>
// types
namespace pyre { namespace extensions { namespace cuda { namespace stats {
const char * const matrix_capsule_t = pyre::extensions::cuda::matrix::capsule_t;
const char * const vector_capsule_t = pyre::extensions::cuda::vector::capsule_t;
using matrix_t = ::cuda_matrix;
using vector_t = ::cuda_vector;
}}}}
// vector minimum
const char * const pyre::extensions::cuda::stats::vector_amin__name__ = "vector_amin";
const char * const pyre::extensions::cuda::stats::vector_amin__doc__ =
"minimum value of a vector";
PyObject *
pyre::extensions::cuda::stats::
vector_amin(PyObject *, PyObject * args) {
// the arguments
PyObject * vCapsule;
size_t n, stride;
double result;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!kk:vector_amin",
&PyCapsule_Type, &vCapsule,
&n, &stride);
// if something went wrong
if (!status) return 0;
// bail out if the two capsules are not valid
if (!PyCapsule_IsValid(vCapsule, vector_capsule_t) )
{
PyErr_SetString(PyExc_TypeError, "invalid vector capsule");
return 0;
}
// get the vector
const vector_t * v = static_cast<const vector_t *>(PyCapsule_GetPointer(vCapsule, vector_capsule_t));
// for different data type
switch(v->dtype) {
case PYCUDA_DOUBLE: //double
result = cudalib::statistics::min<double>((const double *)v->data, n, stride);
break;
case PYCUDA_FLOAT: // float
result = (double) cudalib::statistics::min<float>((const float *)v->data, n, stride);
break;
default:
PyErr_SetString(PyExc_TypeError, "unsupported vector data type");
return 0;
}
// all done, return
return PyFloat_FromDouble(result);
}
// vector maximum
const char * const pyre::extensions::cuda::stats::vector_amax__name__ = "vector_amax";
const char * const pyre::extensions::cuda::stats::vector_amax__doc__ =
"maximum value of a vector";
PyObject *
pyre::extensions::cuda::stats::
vector_amax(PyObject *, PyObject * args) {
// the arguments
PyObject * vCapsule;
size_t n, stride;
double result;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!kk:vector_amax",
&PyCapsule_Type, &vCapsule,
&n, &stride);
// if something went wrong
if (!status) return 0;
// bail out if the two capsules are not valid
if (!PyCapsule_IsValid(vCapsule, vector_capsule_t) )
{
PyErr_SetString(PyExc_TypeError, "invalid vector capsule");
return 0;
}
// get the vector
const vector_t * v = static_cast<const vector_t *>(PyCapsule_GetPointer(vCapsule, vector_capsule_t));
// for different data type
switch(v->dtype) {
case PYCUDA_DOUBLE: //double
result = cudalib::statistics::max<double>((const double *)v->data, n, stride);
break;
case PYCUDA_FLOAT: // float
result = (double) cudalib::statistics::max<float>((const float *)v->data, n, stride);
break;
default:
PyErr_SetString(PyExc_TypeError, "unsupported vector data type");
return 0;
}
// all done, return
return PyFloat_FromDouble(result);
}
// vector sum
const char * const pyre::extensions::cuda::stats::vector_sum__name__ = "vector_sum";
const char * const pyre::extensions::cuda::stats::vector_sum__doc__ =
"maximum value of a vector";
PyObject *
pyre::extensions::cuda::stats::
vector_sum(PyObject *, PyObject * args) {
// the arguments
PyObject * vCapsule;
size_t n, stride;
double result;
long long iresult;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!kk:vector_sum",
&PyCapsule_Type, &vCapsule,
&n, &stride);
// if something went wrong
if (!status) return 0;
// bail out if the two capsules are not valid
if (!PyCapsule_IsValid(vCapsule, vector_capsule_t) )
{
PyErr_SetString(PyExc_TypeError, "invalid vector capsule");
return 0;
}
// get the vector
const vector_t * v = static_cast<const vector_t *>(PyCapsule_GetPointer(vCapsule, vector_capsule_t));
// for different data type
switch(v->dtype) {
case PYCUDA_DOUBLE: //double
result = cudalib::statistics::sum<double>((const double *)v->data, n, stride);
return PyFloat_FromDouble(result);
break;
case PYCUDA_FLOAT: // float
result = (double) cudalib::statistics::sum<float>((const float *)v->data, n, stride);
return PyFloat_FromDouble(result);
break;
case PYCUDA_INT:
iresult = (long long) cudalib::statistics::sum<int>((const int *)v->data, n, stride);
return PyLong_FromLongLong(iresult);
break;
case PYCUDA_ULONGLONG:
iresult = (long long) cudalib::statistics::sum<unsigned long long>
((const unsigned long long *)v->data, n, stride);
return PyLong_FromLongLong(iresult);
default:
PyErr_SetString(PyExc_TypeError, "unsupported vector data type");
return 0;
}
// all done,
}
// vector mean
const char * const pyre::extensions::cuda::stats::vector_mean__name__ = "vector_mean";
const char * const pyre::extensions::cuda::stats::vector_mean__doc__ =
"mean value of a vector";
PyObject *
pyre::extensions::cuda::stats::
vector_mean(PyObject *, PyObject * args) {
// the arguments
PyObject * vCapsule;
size_t n, stride;
double result;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!kk:vector_mean",
&PyCapsule_Type, &vCapsule,
&n, &stride);
// if something went wrong
if (!status) return 0;
// bail out if the two capsules are not valid
if (!PyCapsule_IsValid(vCapsule, vector_capsule_t) )
{
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule");
return 0;
}
// get the vector
const vector_t * v = static_cast<const vector_t *>(PyCapsule_GetPointer(vCapsule, vector_capsule_t));
// for different data type
switch(v->dtype) {
case PYCUDA_DOUBLE: //double
result = cudalib::statistics::mean<double>((const double *)v->data, n, stride);
break;
case PYCUDA_FLOAT: // float
result = (double) cudalib::statistics::mean<float>((const float *)v->data, n, stride);
break;
default:
PyErr_SetString(PyExc_TypeError, "unsupported vector data type");
return 0;
}
// all done, return
return PyFloat_FromDouble(result);
}
// vector std
const char * const pyre::extensions::cuda::stats::vector_std__name__ = "vector_std";
const char * const pyre::extensions::cuda::stats::vector_std__doc__ =
"std value of a vector";
PyObject *
pyre::extensions::cuda::stats::
vector_std(PyObject *, PyObject * args) {
// the arguments
PyObject * vCapsule;
double mean;
size_t n, stride;
int ddof;
double result;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!dkki:vector_std",
&PyCapsule_Type, &vCapsule,
&mean,
&n, &stride, &ddof);
// if something went wrong
if (!status) return 0;
// bail out if the two capsules are not valid
if (!PyCapsule_IsValid(vCapsule, vector_capsule_t) )
{
PyErr_SetString(PyExc_TypeError, "invalid vector capsule");
return 0;
}
// get the vector
const vector_t * v = static_cast<const vector_t *>(PyCapsule_GetPointer(vCapsule, vector_capsule_t));
// for different data type
switch(v->dtype) {
case PYCUDA_DOUBLE: //double
result = cudalib::statistics::std<double>((const double *)v->data, mean, n, stride, ddof);
break;
case PYCUDA_FLOAT: // float
{
float fmean = (float)mean;
result = (double) cudalib::statistics::std<float>((const float *)v->data, fmean, n, stride, ddof);
break;
}
default:
PyErr_SetString(PyExc_TypeError, "unsupported vector data type");
return 0;
}
// all done, return
return PyFloat_FromDouble(result);
}
// matrix minimum
const char * const pyre::extensions::cuda::stats::matrix_amin__name__ = "matrix_amin";
const char * const pyre::extensions::cuda::stats::matrix_amin__doc__ =
"minimum value of a matrix";
PyObject *
pyre::extensions::cuda::stats::
matrix_amin(PyObject *, PyObject * args) {
// the arguments
PyObject * mCapsule;
size_t n, stride;
double result;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!kk:matrix_amin",
&PyCapsule_Type, &mCapsule,
&n, &stride);
// if something went wrong
if (!status) return 0;
// bail out if the two capsules are not valid
if (!PyCapsule_IsValid(mCapsule, matrix_capsule_t) )
{
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule");
return 0;
}
// get the matrix
const matrix_t * m = static_cast<const matrix_t *>(PyCapsule_GetPointer(mCapsule, matrix_capsule_t));
// for different data type
switch(m->dtype) {
case PYCUDA_DOUBLE: //double
result = cudalib::statistics::min<double>((const double *)m->data, n, stride);
break;
case PYCUDA_FLOAT: // float
result = (double) cudalib::statistics::min<float>((const float *)m->data, n, stride);
break;
default:
PyErr_SetString(PyExc_TypeError, "unsupported matrix/vector data type");
return 0;
}
// all done, return
return PyFloat_FromDouble(result);
}
// matrix maximum
const char * const pyre::extensions::cuda::stats::matrix_amax__name__ = "matrix_amax";
const char * const pyre::extensions::cuda::stats::matrix_amax__doc__ =
"maximum value of a matrix";
PyObject *
pyre::extensions::cuda::stats::
matrix_amax(PyObject *, PyObject * args) {
// the arguments
PyObject * mCapsule;
size_t n, stride;
double result;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!kk:matrix_amax",
&PyCapsule_Type, &mCapsule,
&n, &stride);
// if something went wrong
if (!status) return 0;
// bail out if the two capsules are not valid
if (!PyCapsule_IsValid(mCapsule, matrix_capsule_t) )
{
PyErr_SetString(PyExc_TypeError, "invalid matrix/vector capsule");
return 0;
}
// get the matrix
const matrix_t * m = static_cast<const matrix_t *>(PyCapsule_GetPointer(mCapsule, matrix_capsule_t));
// for different data type
switch(m->dtype) {
case PYCUDA_DOUBLE: //double
result = cudalib::statistics::max<double>((const double *)m->data, n, stride);
break;
case PYCUDA_FLOAT: // float
result = (double) cudalib::statistics::max<float>((const float *)m->data, n, stride);
break;
default:
PyErr_SetString(PyExc_TypeError, "unsupported matrix data type");
return 0;
}
// all done, return
return PyFloat_FromDouble(result);
}
// matrix sum (all elements)
const char * const pyre::extensions::cuda::stats::matrix_sum__name__ = "matrix_sum";
const char * const pyre::extensions::cuda::stats::matrix_sum__doc__ =
"sum of a matrix (all elements)";
PyObject *
pyre::extensions::cuda::stats::
matrix_sum(PyObject *, PyObject * args) {
// the arguments
PyObject * mCapsule;
size_t n, stride;
double result;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!kk:matrix_sum",
&PyCapsule_Type, &mCapsule, &n, &stride);
// if something went wrong
if (!status) return 0;
// bail out if the two capsules are not valid
if (!PyCapsule_IsValid(mCapsule, matrix_capsule_t) )
{
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule");
return 0;
}
// get the matrix
const matrix_t * m = static_cast<const matrix_t *>(PyCapsule_GetPointer(mCapsule, matrix_capsule_t));
// for different data type
switch(m->dtype) {
case PYCUDA_DOUBLE: //double
result = cudalib::statistics::sum<double>((const double *)m->data, n, stride);
break;
case PYCUDA_FLOAT: // float
result = (double) cudalib::statistics::sum<float>((const float *)m->data, n, stride);
break;
default:
PyErr_SetString(PyExc_TypeError, "unsupported matrix data type");
return 0;
}
// all done, return
return PyFloat_FromDouble(result);
}
// mean values of all elements matrix
const char * const pyre::extensions::cuda::stats::matrix_mean_flattened__name__ = "matrix_mean_flattened";
const char * const pyre::extensions::cuda::stats::matrix_mean_flattened__doc__ =
"mean values a (flattened) matrix ";
PyObject *
pyre::extensions::cuda::stats::
matrix_mean_flattened(PyObject *, PyObject * args) {
// the arguments
PyObject * matrixCapsule;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!:matrix_mean_flattened",
&PyCapsule_Type, &matrixCapsule);
// if something went wrong
if (!status) return 0;
// bail out if the two capsules are not valid
if (!PyCapsule_IsValid(matrixCapsule, matrix_capsule_t))
{
PyErr_SetString(PyExc_TypeError, "invalid matrix capsule");
return 0;
}
// get the matrix
const matrix_t * m = static_cast<const matrix_t *>(PyCapsule_GetPointer(matrixCapsule, matrix_capsule_t));
// result
double mean;
// for different data type
switch(m->dtype) {
case PYCUDA_DOUBLE: //double
mean = cudalib::statistics::mean<double>((const double *)m->data, m->size, 1);
break;
case PYCUDA_FLOAT: // float
mean = (double) cudalib::statistics::mean<double>((const double *)m->data, m->size, 1);
break;
default:
PyErr_SetString(PyExc_TypeError, "unsupported matrix data type");
return 0;
}
// return mean
return PyFloat_FromDouble(mean);
}
// mean of a batch of vectors stored in matrix
const char * const pyre::extensions::cuda::stats::matrix_mean__name__ = "matrix_mean";
const char * const pyre::extensions::cuda::stats::matrix_mean__doc__ =
"mean values along row or column of a matrix ";
PyObject *
pyre::extensions::cuda::stats::
matrix_mean(PyObject *, PyObject * args) {
// the arguments
PyObject * matrixCapsule, * meanCapsule;
int axis;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!O!i:matrix_mean",
&PyCapsule_Type, &matrixCapsule,
&PyCapsule_Type, &meanCapsule,
&axis);
// if something went wrong
if (!status) return 0;
// bail out if the two capsules are not valid
if (!PyCapsule_IsValid(matrixCapsule, matrix_capsule_t)
|| !PyCapsule_IsValid(meanCapsule, vector_capsule_t) )
{
PyErr_SetString(PyExc_TypeError, "invalid matrix/vector capsule");
return 0;
}
// get the matrix
const matrix_t * m = static_cast<const matrix_t *>(PyCapsule_GetPointer(matrixCapsule, matrix_capsule_t));
vector_t * mean = static_cast<vector_t *>(PyCapsule_GetPointer(meanCapsule, vector_capsule_t));
// for different axis
switch(axis) {
case 0: // along row
// for different data type
switch(m->dtype) {
case PYCUDA_DOUBLE: //double
cudalib::statistics::matrix_mean_over_rows<double>(*m, *mean);
break;
case PYCUDA_FLOAT: // float
cudalib::statistics::matrix_mean_over_rows<float>(*m, *mean);
break;
default:
PyErr_SetString(PyExc_TypeError, "unsupported matrix data type");
return 0;
}
break;
case 1: // along col
// for different data type
switch(m->dtype) {
case PYCUDA_DOUBLE: //double
cudalib::statistics::matrix_mean_over_cols<double>(*m, *mean);
break;
case PYCUDA_FLOAT: // float
cudalib::statistics::matrix_mean_over_cols<float>(*m, *mean);
break;
default:
PyErr_SetString(PyExc_TypeError, "unsupported matrix data type");
return 0;
}
break;
default:
return 0;
}
// return none
Py_RETURN_NONE;
}
// mean, sd of a batch of vectors stored in matrix
const char * const pyre::extensions::cuda::stats::matrix_mean_std__name__ = "matrix_mean_std";
const char * const pyre::extensions::cuda::stats::matrix_mean_std__doc__ =
"mean values and standard deviations along row or column of a matrix ";
PyObject *
pyre::extensions::cuda::stats::
matrix_mean_std(PyObject *, PyObject * args) {
// the arguments
PyObject * matrixCapsule, * meanCapsule, * sdCapsule;
int axis;
int ddof;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!O!O!ii:matrix_mean_std",
&PyCapsule_Type, &matrixCapsule,
&PyCapsule_Type, &meanCapsule,
&PyCapsule_Type, &sdCapsule,
&axis, &ddof);
// if something went wrong
if (!status) return 0;
// bail out if the two capsules are not valid
if (!PyCapsule_IsValid(matrixCapsule, matrix_capsule_t)
|| !PyCapsule_IsValid(meanCapsule, vector_capsule_t)
|| !PyCapsule_IsValid(sdCapsule, vector_capsule_t) )
{
PyErr_SetString(PyExc_TypeError, "invalid matrix/vector capsule");
return 0;
}
// get the matrix
const matrix_t * m = static_cast<const matrix_t *>(PyCapsule_GetPointer(matrixCapsule, matrix_capsule_t));
vector_t * mean = static_cast<vector_t *>(PyCapsule_GetPointer(meanCapsule, vector_capsule_t));
vector_t * sd = static_cast<vector_t *>(PyCapsule_GetPointer(sdCapsule, vector_capsule_t));
// for different axis
switch(axis) {
case 0: // along row
// for different data type
switch(m->dtype) {
case PYCUDA_DOUBLE: //double
cudalib::statistics::matrix_mean_std_over_rows<double>(*m, *mean, *sd, ddof);
break;
case PYCUDA_FLOAT: // float
cudalib::statistics::matrix_mean_std_over_rows<float>(*m, *mean, *sd, ddof);
break;
default:
PyErr_SetString(PyExc_TypeError, "unsupported matrix data type");
return 0;
}
break;
case 1: // along col
// for different data type
switch(m->dtype) {
case PYCUDA_DOUBLE: //double
cudalib::statistics::matrix_mean_std_over_cols<double>(*m, *mean, *sd, ddof);
break;
case PYCUDA_FLOAT: // float
cudalib::statistics::matrix_mean_std_over_cols<float>(*m, *mean, *sd, ddof);
break;
default:
PyErr_SetString(PyExc_TypeError, "unsupported matrix data type");
return 0;
}
break;
default: // sum over all elements
// to be done
return 0;
}
// return none
Py_RETURN_NONE;
}
// vector L1norm
const char * const pyre::extensions::cuda::stats::L1norm__name__ = "L1norm";
const char * const pyre::extensions::cuda::stats::L1norm__doc__ =
"maximum value of a vector";
PyObject *
pyre::extensions::cuda::stats::
L1norm(PyObject *, PyObject * args) {
// the arguments
PyObject * vCapsule;
size_t n, stride;
double result;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!kk:L1norm",
&PyCapsule_Type, &vCapsule, &n, &stride);
// if something went wrong
if (!status) return 0;
// bail out if the two capsules are not valid
if (!PyCapsule_IsValid(vCapsule, vector_capsule_t) )
{
PyErr_SetString(PyExc_TypeError, "invalid vector capsule");
return 0;
}
// get the vector
const vector_t * v = static_cast<const vector_t *>(PyCapsule_GetPointer(vCapsule, vector_capsule_t));
// for different data type
switch(v->dtype) {
case PYCUDA_DOUBLE: //double
result = cudalib::statistics::L1norm<double>((const double *)v->data, n, stride);
break;
case PYCUDA_FLOAT: // float
result = (double) cudalib::statistics::L1norm<float>((const float *)v->data, n, stride);
break;
default:
PyErr_SetString(PyExc_TypeError, "unsupported vector data type");
return 0;
}
// all done, return
return PyFloat_FromDouble(result);
}
// vector L2norm
const char * const pyre::extensions::cuda::stats::L2norm__name__ = "L2norm";
const char * const pyre::extensions::cuda::stats::L2norm__doc__ =
"maximum value of a vector";
PyObject *
pyre::extensions::cuda::stats::
L2norm(PyObject *, PyObject * args) {
// the arguments
PyObject * vCapsule;
size_t n, stride;
double result;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!kk:L2norm",
&PyCapsule_Type, &vCapsule, &n, &stride);
// if something went wrong
if (!status) return 0;
// bail out if the two capsules are not valid
if (!PyCapsule_IsValid(vCapsule, vector_capsule_t) )
{
PyErr_SetString(PyExc_TypeError, "invalid vector capsule");
return 0;
}
// get the vector
const vector_t * v = static_cast<const vector_t *>(PyCapsule_GetPointer(vCapsule, vector_capsule_t));
// for different data type
switch(v->dtype) {
case PYCUDA_DOUBLE: //double
result = cudalib::statistics::L2norm<double>((const double *)v->data, n, stride);
break;
case PYCUDA_FLOAT: // float
result = (double) cudalib::statistics::L2norm<float>((const float *)v->data, n, stride);
break;
default:
PyErr_SetString(PyExc_TypeError, "unsupported vector data type");
return 0;
}
// all done, return
return PyFloat_FromDouble(result);
}
// vector Linfnorm
const char * const pyre::extensions::cuda::stats::Linfnorm__name__ = "Linfnorm";
const char * const pyre::extensions::cuda::stats::Linfnorm__doc__ =
"maximum value of a vector";
PyObject *
pyre::extensions::cuda::stats::
Linfnorm(PyObject *, PyObject * args) {
// the arguments
PyObject * vCapsule;
size_t n, stride;
double result;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!kk:Linfnorm",
&PyCapsule_Type, &vCapsule, &n, &stride);
// if something went wrong
if (!status) return 0;
// bail out if the two capsules are not valid
if (!PyCapsule_IsValid(vCapsule, vector_capsule_t) )
{
PyErr_SetString(PyExc_TypeError, "invalid vector capsule");
return 0;
}
// get the vector
const vector_t * v = static_cast<const vector_t *>(PyCapsule_GetPointer(vCapsule, vector_capsule_t));
// for different data type
switch(v->dtype) {
case PYCUDA_DOUBLE: //double
result = cudalib::statistics::Linfnorm<double>((const double *)v->data, n, stride);
break;
case PYCUDA_FLOAT: // float
result = (double) cudalib::statistics::Linfnorm<float>((const float *)v->data, n, stride);
break;
default:
PyErr_SetString(PyExc_TypeError, "unsupported vector data type");
return 0;
}
// all done, return
return PyFloat_FromDouble(result);
}
// vector vector_covariance
const char * const pyre::extensions::cuda::stats::vector_covariance__name__ = "vector_covariance";
const char * const pyre::extensions::cuda::stats::vector_covariance__doc__ =
"covariance between two vectors";
PyObject *
pyre::extensions::cuda::stats::
vector_covariance(PyObject *, PyObject * args) {
// the arguments
PyObject * v1Capsule, * v2Capsule;
size_t n, stride;
int ddof;
double result;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!O!kki:vector_covariance",
&PyCapsule_Type, &v1Capsule,
&PyCapsule_Type, &v2Capsule,
&n, &stride, &ddof);
// if something went wrong
if (!status) return 0;
// bail out if the two capsules are not valid
if ( !PyCapsule_IsValid(v1Capsule, vector_capsule_t)
|| !PyCapsule_IsValid(v2Capsule, vector_capsule_t) )
{
PyErr_SetString(PyExc_TypeError, "invalid vector capsule");
return 0;
}
// get the vector
const vector_t * v1 = static_cast<const vector_t *>(PyCapsule_GetPointer(v1Capsule, vector_capsule_t));
const vector_t * v2 = static_cast<const vector_t *>(PyCapsule_GetPointer(v2Capsule, vector_capsule_t));
// for different data type
switch(v1->dtype) {
case PYCUDA_DOUBLE: //double
result = cudalib::statistics::covariance<double>((const double *)v1->data, (const double *)v2->data, n, stride, ddof);
break;
case PYCUDA_FLOAT: // float
result = (double) cudalib::statistics::covariance<float>((const float *)v1->data, (const float *)v2->data, n, stride, ddof);
break;
default:
PyErr_SetString(PyExc_TypeError, "unsupported vector data type");
return 0;
}
// all done, return
return PyFloat_FromDouble(result);
}
// vector vector_correlation
const char * const pyre::extensions::cuda::stats::vector_correlation__name__ = "vector_correlation";
const char * const pyre::extensions::cuda::stats::vector_correlation__doc__ =
"correlation between two vectors";
PyObject *
pyre::extensions::cuda::stats::
vector_correlation(PyObject *, PyObject * args) {
// the arguments
PyObject * v1Capsule, * v2Capsule;
size_t n, stride;
double result;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!O!kk:vector_correlation",
&PyCapsule_Type, &v1Capsule,
&PyCapsule_Type, &v2Capsule,
&n, &stride);
// if something went wrong
if (!status) return 0;
// bail out if the two capsules are not valid
if ( !PyCapsule_IsValid(v1Capsule, vector_capsule_t)
|| !PyCapsule_IsValid(v2Capsule, vector_capsule_t) )
{
PyErr_SetString(PyExc_TypeError, "invalid vector capsule");
return 0;
}
// get the vector
const vector_t * v1 = static_cast<const vector_t *>(PyCapsule_GetPointer(v1Capsule, vector_capsule_t));
const vector_t * v2 = static_cast<const vector_t *>(PyCapsule_GetPointer(v2Capsule, vector_capsule_t));
// for different data type
switch(v1->dtype) {
case PYCUDA_DOUBLE: //double
result = cudalib::statistics::correlation<double>((const double *)v1->data, (const double *)v2->data, n, stride);
break;
case PYCUDA_FLOAT: // float
result = (double) cudalib::statistics::correlation<float>((const float *)v1->data, (const float *)v2->data, n, stride);
break;
default:
PyErr_SetString(PyExc_TypeError, "unsupported vector data type");
return 0;
}
// all done, return
return PyFloat_FromDouble(result);
}
// covariance between rows or cols of two matrices
const char * const pyre::extensions::cuda::stats::matrix_covariance__name__ = "matrix_covariance";
const char * const pyre::extensions::cuda::stats::matrix_covariance__doc__ =
"covariance between rows or cols of two matrices";
PyObject *
pyre::extensions::cuda::stats::
matrix_covariance(PyObject *, PyObject * args) {
// the arguments
PyObject * m1Capsule, * m2Capsule, * resultCapsule;
int axis;
int ddof;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!O!O!ii:matrix_covariance",
&PyCapsule_Type, &m1Capsule,
&PyCapsule_Type, &m2Capsule,
&PyCapsule_Type, &resultCapsule,
&axis, &ddof);
// if something went wrong
if (!status) return 0;
// bail out if the two capsules are not valid
if (!PyCapsule_IsValid(m1Capsule, matrix_capsule_t)
|| !PyCapsule_IsValid(m2Capsule, matrix_capsule_t)
|| !PyCapsule_IsValid(resultCapsule, vector_capsule_t) )
{
PyErr_SetString(PyExc_TypeError, "invalid matrix/vector capsule");
return 0;
}
// get the matrix
const matrix_t * m1 = static_cast<const matrix_t *>(PyCapsule_GetPointer(m1Capsule, matrix_capsule_t));
const matrix_t * m2 = static_cast<const matrix_t *>(PyCapsule_GetPointer(m2Capsule, matrix_capsule_t));
vector_t * result = static_cast<vector_t *>(PyCapsule_GetPointer(resultCapsule, vector_capsule_t));
// for different axis
switch(axis) {
case 0: // along row
// for different data type
switch(m1->dtype) {
case PYCUDA_DOUBLE: //double
cudalib::statistics::covariance_batched<double>(
(double *)result->data, // cov
(const double *)m1->data, // m1
(const double *)m2->data, // m2
m1->size1, // n (number of rows)
m1->size2, // batch
1, // stride between batches
m1->size2, // stride between elements
ddof // delta degrees of freedom
);
break;
case PYCUDA_FLOAT: // float
cudalib::statistics::covariance_batched<float>(
(float *)result->data, // cov
(const float *)m1->data, // m1
(const float *)m2->data, // m2
m1->size1, // n (number of rows)
m1->size2, // batch
1, // stride between batches
m1->size2, // stride between elements
ddof // delta degrees of freedom
);
break;
default:
PyErr_SetString(PyExc_TypeError, "unsupported matrix data type");
return 0;
}
break;
case 1: // along col
// for different data type
switch(m1->dtype) {
case PYCUDA_DOUBLE: //double
cudalib::statistics::covariance_batched<double>(
(double *)result->data, // cov
(const double *)m1->data, // m1
(const double *)m2->data, // m2
m1->size2, // n (number of cols)
m1->size1, // batch
m1->size2, // stride between batches
1, // stride between elements
ddof // delta degrees of freedom
);
break;
case PYCUDA_FLOAT: // float
cudalib::statistics::covariance_batched<float>(
(float *)result->data, // cov
(const float *)m1->data, // m1
(const float *)m2->data, // m2
m1->size2, // n (number of cols)
m1->size1, // batch
m1->size2, // stride between batches
1, // stride between elements
ddof // delta degrees of freedom
);
break;
default:
PyErr_SetString(PyExc_TypeError, "unsupported matrix data type");
return 0;
}
break;
default: // sum over all elements
// to be done
return 0;
}
// return none
Py_RETURN_NONE;
}
// correlation between rows or cols of two matrices
const char * const pyre::extensions::cuda::stats::matrix_correlation__name__ = "matrix_correlation";
const char * const pyre::extensions::cuda::stats::matrix_correlation__doc__ =
"correlation between rows or cols of two matrices";
PyObject *
pyre::extensions::cuda::stats::
matrix_correlation(PyObject *, PyObject * args) {
// the arguments
PyObject * m1Capsule, * m2Capsule, * resultCapsule;
int axis;
// unpack the argument tuple
int status = PyArg_ParseTuple(
args, "O!O!O!i:stats_matrix_correlation",
&PyCapsule_Type, &m1Capsule,
&PyCapsule_Type, &m2Capsule,
&PyCapsule_Type, &resultCapsule,
&axis);
// if something went wrong
if (!status) return 0;
// bail out if the two capsules are not valid
if (!PyCapsule_IsValid(m1Capsule, matrix_capsule_t)
|| !PyCapsule_IsValid(m2Capsule, matrix_capsule_t)
|| !PyCapsule_IsValid(resultCapsule, vector_capsule_t) )
{
PyErr_SetString(PyExc_TypeError, "invalid matrix/vector capsule");
return 0;
}
// get the matrix
const matrix_t * m1 = static_cast<const matrix_t *>(PyCapsule_GetPointer(m1Capsule, matrix_capsule_t));
const matrix_t * m2 = static_cast<const matrix_t *>(PyCapsule_GetPointer(m2Capsule, matrix_capsule_t));
vector_t * result = static_cast<vector_t *>(PyCapsule_GetPointer(resultCapsule, vector_capsule_t));
// for different axis
switch(axis) {
case 0: // along row
// for different data type
switch(m1->dtype) {
case PYCUDA_DOUBLE: //double
cudalib::statistics::correlation_batched<double>(
(double *)result->data, // cov
(const double *)m1->data, // m1
(const double *)m2->data, // m2
m1->size1, // n (number of rows)
m1->size2, // batch
1, // stride between batches
m1->size2 // stride between elements
);
break;
case PYCUDA_FLOAT: // float
cudalib::statistics::correlation_batched<float>(
(float *)result->data, // cov
(const float *)m1->data, // m1
(const float *)m2->data, // m2
m1->size1, // n (number of rows)
m1->size2, // batch
1, // stride between batches
m1->size2 // stride between elements
);
break;
default:
PyErr_SetString(PyExc_TypeError, "unsupported matrix data type");
return 0;
}
break;
case 1: // along col
// for different data type
switch(m1->dtype) {
case PYCUDA_DOUBLE: //double
cudalib::statistics::correlation_batched<double>(
(double *)result->data, // cov
(const double *)m1->data, // m1
(const double *)m2->data, // m2
m1->size2, // n (number of cols)
m1->size1, // batch
m1->size2, // stride between batches
1 // stride between elements
);
break;
case PYCUDA_FLOAT: // float
cudalib::statistics::correlation_batched<float>(
(float *)result->data, // cov
(const float *)m1->data, // m1
(const float *)m2->data, // m2
m1->size2, // n (number of cols)
m1->size1, // batch
m1->size2, // stride between batches
1 // stride between elements
);
break;
default:
PyErr_SetString(PyExc_TypeError, "unsupported matrix data type");
return 0;
}
break;
default: // sum over all elements
// to be done
return 0;
}
// return none
Py_RETURN_NONE;
}
// end of file
| 34.567416 | 132 | 0.601116 | [
"vector"
] |
9f950e3f1f291c6a416b011efdb0b057cfc78a36 | 614 | cpp | C++ | Greedy/Greedy.cpp | jordantonni/HackerRank_Algorithms | 48c6df9688d4d45e7249c29fd70aba67234c74cd | [
"MIT"
] | null | null | null | Greedy/Greedy.cpp | jordantonni/HackerRank_Algorithms | 48c6df9688d4d45e7249c29fd70aba67234c74cd | [
"MIT"
] | null | null | null | Greedy/Greedy.cpp | jordantonni/HackerRank_Algorithms | 48c6df9688d4d45e7249c29fd70aba67234c74cd | [
"MIT"
] | null | null | null | // https://www.hackerrank.com/challenges/greedy-florist/problem
// Jordan Tonni
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
int main()
{
int n, k;
cin >> n >> k;
vector<int> prices(n);
for(int i=0; i<n; ++i)
cin >> prices[i];
sort(begin(prices), end(prices), std::greater<int>());
size_t total {0};
for(int i=0; i<prices.size(); ++i){
int numFlo = std::floor(i / k) + 1;
total += numFlo * prices[i];
}
cout << total;
return 0;
}
| 18.606061 | 63 | 0.557003 | [
"vector"
] |
9f953d37f91ffa17e3c0fa6bed9de6dc86ded3ec | 6,728 | hpp | C++ | common/glf/glf.hpp | Groovounet/ogl-samples | 7f8be365d1823b8609caf539d790c90712cd4c46 | [
"Unlicense"
] | null | null | null | common/glf/glf.hpp | Groovounet/ogl-samples | 7f8be365d1823b8609caf539d790c90712cd4c46 | [
"Unlicense"
] | null | null | null | common/glf/glf.hpp | Groovounet/ogl-samples | 7f8be365d1823b8609caf539d790c90712cd4c46 | [
"Unlicense"
] | 2 | 2020-12-30T04:44:14.000Z | 2021-03-17T00:43:45.000Z | #ifndef GLF_WINDOW_INCLUDED
#define GLF_WINDOW_INCLUDED
//#pragma warning(disable : once)
// OpenGL
#ifdef WIN32
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
# include <GL/glew.h>
# include <GL/wglew.h>
# include <cl/cl.h>
# include <cl/cl_ext.h>
# include <cl/cl_gl.h>
# include <cl/cl_gl_ext.h>
//# include <GL/glext.h>
#elif defined(linux) || defined(__linux)
# include <GL/glew.h>
# define GL_GLEXT_PROTOTYPES 1
# include <GL/gl.h>
# include <GL/glext.h>
#elif defined(__APPLE__)
# include <OpenGL/gl.h>
#else
# error "Unsupported platform"
#endif
// GLF libraries
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/half_float.hpp>
#include <glm/gtc/type_precision.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/random.hpp>
#include <glm/gtc/noise.hpp>
#include <glm/gtx/euler_angles.hpp>
#include <gli/gli.hpp>
#include <gli/gtx/loader.hpp>
// STL
#include <vector>
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
namespace glf
{
#ifdef WIN32
static std::string const DATA_DIRECTORY("../data/");
#else
static std::string const DATA_DIRECTORY("../../data/");
#endif
enum mouse_button
{
MOUSE_BUTTON_NONE = 0,
MOUSE_BUTTON_LEFT = (1 << 0),
MOUSE_BUTTON_RIGHT = (1 << 1),
MOUSE_BUTTON_MIDDLE = (1 << 2)
};
struct window
{
window(glm::ivec2 const & Size) :
Size(Size),
MouseOrigin(Size >> 1),
MouseCurrent(Size >> 1),
TranlationOrigin(0, 4),
TranlationCurrent(0, 4),
RotationOrigin(0),
RotationCurrent(0),
MouseButtonFlags(0)
{
memset(KeyPressed, 0, sizeof(KeyPressed));
}
glm::ivec2 Size;
glm::vec2 MouseOrigin;
glm::vec2 MouseCurrent;
glm::vec2 TranlationOrigin;
glm::vec2 TranlationCurrent;
glm::vec2 RotationOrigin;
glm::vec2 RotationCurrent;
int MouseButtonFlags;
std::size_t KeyPressed[256];
};
std::string loadFile(std::string const & Filename);
bool checkError(const char* Title);
bool checkProgram(GLuint ProgramName);
bool checkShader(GLuint ShaderName, char const* Source);
bool validateProgram(GLuint ProgramName);
int version(int Major, int Minor);
int run();
namespace semantic
{
namespace uniform
{
enum type
{
MATERIAL = 0,
TRANSFORM0 = 1,
TRANSFORM1 = 2
};
};
namespace image
{
enum type
{
DIFFUSE = 0,
PICKING = 1
};
}//namesapce image
namespace attr
{
enum type
{
POSITION = 0,
COLOR = 3,
TEXCOORD = 4
};
}//namespace attr
namespace vert
{
enum type
{
POSITION = 0,
COLOR = 3,
TEXCOORD = 4,
INSTANCE = 7
};
}//namespace vert
namespace frag
{
enum type
{
COLOR = 0,
RED = 0,
GREEN = 1,
BLUE = 2,
ALPHA = 0
};
}//namespace frag
namespace renderbuffer
{
enum type
{
DEPTH,
COLOR0
};
}//namespace renderbuffer
}//namespace semantic
struct vertex_v2fv2f
{
vertex_v2fv2f
(
glm::vec2 const & Position,
glm::vec2 const & Texcoord
) :
Position(Position),
Texcoord(Texcoord)
{}
glm::vec2 Position;
glm::vec2 Texcoord;
};
struct vertex_v3fv2f
{
vertex_v3fv2f
(
glm::vec3 const & Position,
glm::vec2 const & Texcoord
) :
Position(Position),
Texcoord(Texcoord)
{}
glm::vec3 Position;
glm::vec2 Texcoord;
};
struct vertex_v3fv3f
{
vertex_v3fv3f
(
glm::vec3 const & Position,
glm::vec3 const & Texcoord
) :
Position(Position),
Texcoord(Texcoord)
{}
glm::vec3 Position;
glm::vec3 Texcoord;
};
struct vertex_v4fv2f
{
vertex_v4fv2f
(
glm::vec4 const & Position,
glm::vec2 const & Texcoord
) :
Position(Position),
Texcoord(Texcoord)
{}
glm::vec4 Position;
glm::vec2 Texcoord;
};
struct vertex_v2fc4f
{
vertex_v2fc4f
(
glm::vec2 const & Position,
glm::vec4 const & Color
) :
Position(Position),
Color(Color)
{}
glm::vec2 Position;
glm::vec4 Color;
};
struct vertex_v4fc4f
{
vertex_v4fc4f
(
glm::vec4 const & Position,
glm::vec4 const & Color
) :
Position(Position),
Color(Color)
{}
glm::vec4 Position;
glm::vec4 Color;
};
struct vertex_v2fc4ub
{
vertex_v2fc4ub
(
glm::vec2 const & Position,
glm::u8vec4 const & Color
) :
Position(Position),
Color(Color)
{}
glm::vec2 Position;
glm::u8vec4 Color;
};
struct vertex_v2fv2fv4ub
{
vertex_v2fv2fv4ub
(
glm::vec2 const & Position,
glm::vec2 const & Texcoord,
glm::u8vec4 const & Color
) :
Position(Position),
Texcoord(Texcoord),
Color(Color)
{}
glm::vec2 Position;
glm::vec2 Texcoord;
glm::u8vec4 Color;
};
struct vertexattrib
{
vertexattrib() :
Enabled(GL_FALSE),
//Binding(0),
Size(4),
Stride(0),
Type(GL_FLOAT),
Normalized(GL_FALSE),
Integer(GL_FALSE),
Long(GL_FALSE),
Divisor(0),
Pointer(NULL)
{}
vertexattrib
(
GLint Enabled,
//GLint Binding,
GLint Size,
GLint Stride,
GLint Type,
GLint Normalized,
GLint Integer,
GLint Long,
GLint Divisor,
GLvoid* Pointer
) :
Enabled(Enabled),
//Binding(Binding),
Size(Size),
Stride(Stride),
Type(Type),
Normalized(Normalized),
Integer(Integer),
Long(Long),
Divisor(Divisor),
Pointer(Pointer)
{}
GLint Enabled;
//GLint Binding;
GLint Size;
GLint Stride;
GLint Type;
GLint Normalized;
GLint Integer;
GLint Long;
GLint Divisor;
GLvoid* Pointer;
};
bool operator== (vertexattrib const & A, vertexattrib const & B)
{
return A.Enabled == B.Enabled &&
A.Size == B.Size &&
A.Stride == B.Stride &&
A.Type == B.Type &&
A.Normalized == B.Normalized &&
A.Integer == B.Integer &&
A.Long == B.Long;
}
bool operator!= (vertexattrib const & A, vertexattrib const & B)
{
return !(A == B);
}
}//namespace glf
namespace
{
extern glf::window Window;
}//namespace
#define GLF_BUFFER_OFFSET(i) ((char *)NULL + (i))
#ifndef GL_EXTERNAL_VIRTUAL_MEMORY_BUFFER_AMD
#define GL_EXTERNAL_VIRTUAL_MEMORY_BUFFER_AMD 0x9160
#endif
#ifndef WGL_CONTEXT_CORE_PROFILE_BIT_ARB
#define WGL_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
#endif
#ifndef WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB
#define WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
#endif
#ifndef WGL_CONTEXT_ES2_PROFILE_BIT_EXT
#define WGL_CONTEXT_ES2_PROFILE_BIT_EXT 0x00000004
#endif
#ifndef GLX_CONTEXT_CORE_PROFILE_BIT_ARB
#define GLX_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
#endif
#ifndef GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB
#define GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
#endif
#ifndef WGLX_CONTEXT_ES2_PROFILE_BIT_EXT
#define WGLX_CONTEXT_ES2_PROFILE_BIT_EXT 0x00000004
#endif
#include "glf.inl"
#endif//GLF_WINDOW_INCLUDED
| 17.076142 | 65 | 0.669738 | [
"vector"
] |
7a0476a76a6302c57f14b0116d8cef1aa4cd677e | 557 | cc | C++ | primer/examples/iterators.cc | CaffeineViking/concepts-primer | 041cec40fa4a25cd954ce91da6d9d10ee31499a3 | [
"MIT"
] | 17 | 2019-05-01T21:49:43.000Z | 2022-02-25T06:50:47.000Z | primer/examples/iterators.cc | CaffeineViking/concepts-primer | 041cec40fa4a25cd954ce91da6d9d10ee31499a3 | [
"MIT"
] | null | null | null | primer/examples/iterators.cc | CaffeineViking/concepts-primer | 041cec40fa4a25cd954ce91da6d9d10ee31499a3 | [
"MIT"
] | null | null | null | #include "concepts.h"
#include <list>
#include <vector>
#include <forward_list>
int main(int, char**) {
std::forward_list fl { 1, 2, 3, 4, 5 };
ForwardIterator fi { fl.begin() };
std::list bl { 1, 2, 3, 4, 5 };
BidirectionalIterator bi { bl.begin() };
std::vector ra { 1, 2, 3, 4, 5 };
RandomAccessIterator ri { ra.begin() };
ForwardIterator af { bl.begin() };
#if false // neither of these will compile!!
BidirectionalIterator nb { fl.begin() };
RandomAccessIterator nr { bl.begin() };
#endif
return 0;
}
| 19.206897 | 44 | 0.601436 | [
"vector"
] |
7a1438c919534d427c4d87154effe9fabcda7148 | 652 | cpp | C++ | iMvc/iMvc.cpp | mkinsz/iProject | b3cd3b41549131c36866a94575b3ae0ce24f66b6 | [
"Apache-2.0"
] | null | null | null | iMvc/iMvc.cpp | mkinsz/iProject | b3cd3b41549131c36866a94575b3ae0ce24f66b6 | [
"Apache-2.0"
] | null | null | null | iMvc/iMvc.cpp | mkinsz/iProject | b3cd3b41549131c36866a94575b3ae0ce24f66b6 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <memory>
#include "PegRow.h"
#include "Peg.h"
#include "GameModel.h"
#include "GameView.h"
#include "GameController.h"
int main()
{
// Create Game Model
std::shared_ptr<GameModel> gameModelPtr = std::make_shared<GameModel>(12, 4);
// Create Game Controller
std::shared_ptr<GameController> gameControllerPtr = std::make_shared<GameController>(gameModelPtr);
gameControllerPtr->init();
// Create Game View
std::shared_ptr<GameView> gameViewObj = std::make_shared<GameView>(gameModelPtr, gameControllerPtr);
gameModelPtr->attach(gameViewObj);
// Start the Game
gameViewObj->render();
return EXIT_SUCCESS;
}
| 22.482759 | 101 | 0.748466 | [
"render",
"model"
] |
7a1beb709202a7b52a58eba160b34bd9de4ec7d6 | 14,814 | cpp | C++ | gdal-drivers/solid.cpp | melowntech/gdal-drivers | 50b931502fe1ad8fbee1f534ecd26b6fab46e7a0 | [
"BSD-2-Clause"
] | 1 | 2018-08-26T07:36:21.000Z | 2018-08-26T07:36:21.000Z | gdal-drivers/solid.cpp | melowntech/gdal-drivers | 50b931502fe1ad8fbee1f534ecd26b6fab46e7a0 | [
"BSD-2-Clause"
] | 1 | 2017-06-26T18:55:26.000Z | 2017-09-08T18:47:01.000Z | gdal-drivers/solid.cpp | Melown/gdal-drivers | 1457d5ea9587d4063e7a199aa467cbfb65a9e8da | [
"BSD-2-Clause"
] | 1 | 2019-09-25T05:09:58.000Z | 2019-09-25T05:09:58.000Z | /**
* Copyright (c) 2017 Melown Technologies SE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* @file solid.cpp
*/
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <iterator>
#include <fstream>
#include <iomanip>
#include "dbglog/dbglog.hpp"
#include "utility/raise.hpp"
#include "utility/multivalue.hpp"
#include "utility/streams.hpp"
#include "geo/gdal.hpp"
#include "geo/po.hpp"
#include "detail/geotransform.hpp"
#include "solid.hpp"
namespace po = boost::program_options;
namespace gdal_drivers {
void writeConfig(const boost::filesystem::path &file
, const SolidDataset::Config &config)
{
std::ofstream f;
f.exceptions(std::ios::badbit | std::ios::failbit);
f.open(file.string(), std::ios_base::out | std::ios_base::trunc);
f << std::scientific << std::setprecision(16);
f << "[solid]"
<< "\nsrs = " << config.srs
<< "\nsize = " << config.size
<< "\ntileSize = " << config.tileSize
;
if (const auto *extents = config.extents()) {
f << "\nextents = " << *extents;
} if (const auto *geoTransform = config.geoTransform()) {
f << "\ngeoTransform = " << detail::GeoTransformWrapper{*geoTransform};
} else {
LOGTHROW(err1, std::runtime_error)
<< "Neither extents nor geoTransform are set.";
}
f << "\n\n";
f.unsetf(std::ios_base::floatfield);
for (const auto &band : config.bands) {
f << "\n[band]"
<< "\nvalue = " << band.value
<< "\ndataType = " << band.dataType
<< "\ncolorInterpretation = " << band.colorInterpretation
<< "\n";
}
f.close();
}
/**
* @brief BorderedAreaRasterBand
*/
class SolidDataset::RasterBand : public ::GDALRasterBand {
public:
RasterBand(SolidDataset *dset, const Config::Band &band
, const std::vector<math::Size2> &overviews);
virtual ~RasterBand() {
for (auto &ovr : ovrBands_) { delete ovr; }
}
virtual CPLErr IReadBlock(int blockCol, int blockRow, void *image);
virtual GDALColorInterp GetColorInterpretation() {
return colorInterpretation_;
}
virtual int GetOverviewCount() { return overviews_.size(); }
virtual GDALRasterBand* GetOverview(int index) {
if (index >= int(ovrBands_.size())) { return nullptr; }
auto &ovr(ovrBands_[index]);
if (!ovr) {
ovr = new OvrBand(this, overviews_[index]);
}
return ovr;
}
private:
class OvrBand : public ::GDALRasterBand {
public:
OvrBand(RasterBand *owner, const math::Size2 &size)
: owner_(owner)
{
poDS = owner->poDS;
nBand = owner->nBand;
nBlockXSize = owner->nBlockXSize;
nBlockYSize = owner->nBlockYSize;
eDataType = owner->eDataType;
nRasterXSize = size.width;
nRasterYSize = size.height;
}
virtual CPLErr IReadBlock(int blockCol, int blockRow, void *image) {
return owner_->IReadBlock(blockCol, blockRow, image);
}
virtual GDALColorInterp GetColorInterpretation() {
return owner_->GetColorInterpretation();
}
private:
RasterBand *owner_;
};
friend class OvrBand;
template <typename T>
void createBlock(const T &value, std::size_t count)
{
auto *block(new T[count]);
std::fill_n(block, count, value);
block_ = std::shared_ptr<T>(block, [](T *block) { delete [] block; });
blockSize_ = count * sizeof(T);
}
/** Block of pregenerated data.
*/
std::shared_ptr<void> block_;
/** Size of block of pregenerated data in bytes.
*/
std::size_t blockSize_;
::GDALColorInterp colorInterpretation_;
std::vector<math::Size2> overviews_;
std::vector< ::GDALRasterBand*> ovrBands_;
};
GDALDataset* SolidDataset::Open(GDALOpenInfo *openInfo)
{
::CPLErrorReset();
po::options_description config("solid color GDAL driver");
po::variables_map vm;
Config cfg;
config.add_options()
("solid.srs", po::value(&cfg.srs)->required()
, "SRS definition. Use [WKT], +proj or EPSG:num.")
("solid.size", po::value(&cfg.size)->required()
, "Size of dataset (WxH).")
("solid.extents", po::value<math::Extents2>()
, "Geo extents of dataset (ulx,uly:urx,ury).")
("solid.geoTransform", po::value<detail::GeoTransformWrapper>()
, "Geo transform matrix (m00, m01, m02, m10, m11, m12).")
("solid.tileSize", po::value(&cfg.tileSize)
->default_value(math::Size2(256, 256))->required()
, "Tile size.")
;
using utility::multi_value;
config.add_options()
("band.value", multi_value<decltype(Config::Band::value)>()
, "Value to return.")
("band.dataType", multi_value<decltype(Config::Band::dataType)>()
, "Data type.")
("band.colorInterpretation"
, multi_value<decltype(Config::Band::colorInterpretation)>()
, "Color interpretation.")
;
po::basic_parsed_options<char> parsed(&config);
// try to parse file -> cannot parse -> probably not a solid file format
try {
std::ifstream f;
f.exceptions(std::ifstream::failbit | std::ifstream::badbit);
f.open(openInfo->pszFilename);
f.exceptions(std::ifstream::badbit);
parsed = (po::parse_config_file(f, config));
if (parsed.options.empty()) {
// structure valid but nothing read -> not a solid file
return nullptr;
}
} catch (...) { return nullptr; }
// no updates
if (openInfo->eAccess == GA_Update) {
CPLError(CE_Failure, CPLE_NotSupported,
"The Quadtree Solid driver does not support update "
"access to existing datasets.\n");
return nullptr;
}
// initialize dataset
try {
po::store(parsed, vm);
po::notify(vm);
bool hasExtents(vm.count("solid.extents"));
bool hasGeoTransform(vm.count("solid.geoTransform"));
if (hasExtents && hasGeoTransform) {
CPLError(CE_Failure, CPLE_IllegalArg
, "SolidDataset initialization failure:"
" both extents and geoTransform are set.\n");
return nullptr;
}
if (!hasExtents && !hasGeoTransform) {
CPLError(CE_Failure, CPLE_IllegalArg
, "SolidDataset initialization failure:"
" both extents and geoTransform are unset.\n");
return nullptr;
}
if (hasExtents) {
cfg.extents(vm["solid.extents"].as<math::Extents2>());
} else {
cfg.geoTransform
(vm["solid.geoTransform"].as<detail::GeoTransformWrapper>()
.value);
}
// process bands
auto &bands(cfg.bands);
bands.resize(vm["band.value"].as<std::vector<double> >().size());
using utility::process_multi_value;
process_multi_value(vm, "band.value"
, bands, &Config::Band::value);
process_multi_value(vm, "band.dataType"
, bands, &Config::Band::dataType);
process_multi_value(vm, "band.colorInterpretation"
, bands, &Config::Band::colorInterpretation);
return new SolidDataset(cfg);
} catch (const std::runtime_error & e) {
CPLError(CE_Failure, CPLE_IllegalArg
, "SolidDataset initialization failure (%s).\n", e.what());
return nullptr;
}
}
GDALDataset* SolidDataset::CreateCopy(const char *path
, GDALDataset *src
, int strict
, char **options
, GDALProgressFunc, void *)
{
auto bands(src->GetRasterCount());
std::vector<double> colors(bands, 0);
{
auto **rawColors(CSLFetchNameValueMultiple(options, "COLOR"));
for (auto &color : colors) {
if (!rawColors) { break; }
try {
color = boost::lexical_cast<double>(*rawColors);
} catch (...) {
CPLError(CE_Failure, CPLE_IllegalArg
, "SolidDataset create failure:"
" invalid color value %s.\n", *rawColors);
return nullptr;
}
++rawColors;
}
}
Config config;
// copy SRS
config.srs = geo::SrsDefinition
(src->GetProjectionRef(), geo::SrsDefinition::Type::wkt);
// copy raster size
config.size.width = src->GetRasterXSize();
config.size.height = src->GetRasterYSize();
// copy geo transformation
geo::GeoTransform gt;
src->GetGeoTransform(gt.data());
config.geoTransform(gt);
// copy bands
for (int i(1); i <= bands; ++i) {
auto *b(src->GetRasterBand(i));
config.bands.emplace_back(colors[i - 1], b->GetRasterDataType()
, b->GetColorInterpretation());
}
writeConfig(path, config);
return new SolidDataset(config);
(void) strict;
}
SolidDataset::SolidDataset(const Config &config)
: SrsHoldingDataset(config.srs)
, config_(config)
{
if (const auto *extents = config_.extents()) {
const auto &e(*extents);
auto es(math::size(e));
geoTransform_[0] = e.ll(0);
geoTransform_[1] = es.width / nRasterXSize;
geoTransform_[2] = 0.0;
geoTransform_[3] = e.ur(1);
geoTransform_[4] = 0.0;
geoTransform_[5] = -es.height / nRasterYSize;;
} else if (const auto *geoTransform = config_.geoTransform()) {
geoTransform_ = *geoTransform;
}
nRasterXSize = config_.size.width;
nRasterYSize = config_.size.height;
// prepare overviews
std::vector<math::Size2> overviews;
{
auto size(config_.size);
auto halve([&]()
{
size.width = int(std::round(size.width / 2.0));
size.height = int(std::round(size.height / 2.0));
});
halve();
while ((size.width >= config_.tileSize.width)
|| (size.height >= config_.tileSize.height))
{
overviews.push_back(size);
halve();
}
}
// NB: bands are 1-based, start with zero, pre-increment before setting band
int i(0);
for (const auto &band : config_.bands) {
SetBand(++i, new RasterBand(this, band, overviews));
}
}
CPLErr SolidDataset::GetGeoTransform(double *padfTransform)
{
std::copy(geoTransform_.begin(), geoTransform_.end()
, padfTransform);
return CE_None;
return CE_None;
}
SolidDataset::RasterBand
::RasterBand(SolidDataset *dset , const Config::Band &band
, const std::vector<math::Size2> &overviews)
: block_(), blockSize_()
, colorInterpretation_(band.colorInterpretation)
, overviews_(overviews)
, ovrBands_(overviews.size(), nullptr)
{
const auto &cfg(dset->config_);
poDS = dset;
nBand = 1;
nBlockXSize = cfg.tileSize.width;
nBlockYSize = cfg.tileSize.height;
eDataType = band.dataType;
nRasterXSize = cfg.size.width;
nRasterYSize = cfg.size.height;
auto count(math::area(cfg.tileSize));
switch (eDataType) {
case ::GDT_Byte:
createBlock<std::uint8_t>(band.value, count);
break;
case ::GDT_UInt16:
createBlock<std::uint16_t>(band.value, count);
break;
case ::GDT_Int16:
createBlock<std::int16_t>(band.value, count);
break;
case ::GDT_UInt32:
createBlock<std::uint32_t>(band.value, count);
break;
case ::GDT_Int32:
createBlock<std::int32_t>(band.value, count);
break;
case ::GDT_Float32:
createBlock<float>(band.value, count);
break;
case ::GDT_Float64:
createBlock<double>(band.value, count);
break;
default:
utility::raise<std::runtime_error>
("Unsupported data type <%s>.", eDataType);
};
}
CPLErr SolidDataset::RasterBand::IReadBlock(int, int, void *rawImage)
{
// copy pregenerated data into output image
std::memcpy(rawImage, block_.get(), blockSize_);
return CE_None;
}
const math::Extents2* SolidDataset::Config::extents() const
{
return detail::extents(extentsOrGeoTransform_);
}
const geo::GeoTransform* SolidDataset::Config::geoTransform() const
{
return detail::geoTransform(extentsOrGeoTransform_);
}
std::unique_ptr<SolidDataset>
SolidDataset::create(const boost::filesystem::path &path, const Config &config)
{
std::unique_ptr<SolidDataset> solid(new SolidDataset(config));
writeConfig(path, config);
return solid;
}
} // namespace gdal_drivers
/* GDALRegister_SolidDataset */
void GDALRegister_SolidDataset()
{
if (!GDALGetDriverByName("Solid")) {
std::unique_ptr<GDALDriver> driver(new GDALDriver());
driver->SetDescription("Solid");
driver->SetMetadataItem
(GDAL_DMD_LONGNAME
, "Driver that returns solid valid in all pixels.");
driver->SetMetadataItem(GDAL_DMD_EXTENSION, "");
driver->pfnOpen = gdal_drivers::SolidDataset::Open;
driver->pfnCreateCopy = gdal_drivers::SolidDataset::CreateCopy;
GetGDALDriverManager()->RegisterDriver(driver.release());
}
}
| 30.294479 | 80 | 0.603011 | [
"vector",
"transform",
"solid"
] |
7a1ea8c7e5c4615bf39d64ad3095376b32eae960 | 10,946 | cpp | C++ | src/hdf5_imputation.cpp | isglobal-brge/BigDataStatMeth | e19ab43b052dab1a066d5adff3c6778868f247b0 | [
"MIT"
] | 2 | 2020-07-02T00:34:59.000Z | 2021-02-03T11:30:31.000Z | src/hdf5_imputation.cpp | isglobal-brge/BigDataStatMeth | e19ab43b052dab1a066d5adff3c6778868f247b0 | [
"MIT"
] | null | null | null | src/hdf5_imputation.cpp | isglobal-brge/BigDataStatMeth | e19ab43b052dab1a066d5adff3c6778868f247b0 | [
"MIT"
] | 1 | 2021-01-22T16:34:39.000Z | 2021-01-22T16:34:39.000Z | #include "include/hdf5_imputation.h"
// Get value for imputation
int get_value_to_impute_discrete(std::map<double, double> probMap)
{
std::vector <double> probs;
// Get values and counts for each map element
for( auto it = probMap.begin(); it != probMap.end(); ++it )
probs.push_back( it->second );
// remove last element (corresponds to 3=<NA>)
probs.erase(probs.end() - 1);
// Get total count
double totalSNPS = std::accumulate(probs.begin(), probs.end(), decltype(probs)::value_type(0));
// Get probabilities without <NA>
for (std::vector<double>::iterator it = probs.begin() ; it != probs.end(); ++it)
*it = *it/totalSNPS;
// Generate value with given probabilities
std::random_device rd;
std::mt19937 gen(rd());
std::discrete_distribution<> d(probs.begin(), probs.end());
return (d(gen));
}
// Convert NumericVector to map (key:vlues - value: frequency value in vector)
std::map<double, double> VectortoOrderedMap_SNP_counts( Eigen::VectorXd vdata)
{
std::map<double, double> mapv;
try
{
int position = 0;
//.commented 20201120 - warning check().// int vlength = vdata.size();
std::vector<double> v(vdata.data(), vdata.data()+vdata.size());
std::sort(v.begin(), v.end() ); // Sort vector to optimize search and count
for (size_t i = 0; i <= *std::max_element(v.begin(), v.end()) ; ++i)
{
double mycount = std::count(v.begin() + position, v.end(), i);
mapv[i] = mycount;
position = position + mycount;
}
} catch(std::exception &ex) {
forward_exception_to_r(ex);
} catch(...) {
::Rf_error("c++ exception (unknown reason)");
}
return mapv;
}
// Pedestrian dataset imputation ....
// TODO :
// - perform better imputation
void Impute_snp_HDF5(H5File* file, DataSet* dataset, bool bycols, std::string stroutdataset)
{
IntegerVector stride = IntegerVector::create(1, 1);
IntegerVector block = IntegerVector::create(1, 1);
IntegerVector offset = IntegerVector::create(0, 0);
IntegerVector count = IntegerVector::create(0, 0);
DataSet* outdataset;
int ilimit;
int blocksize = 1000;
try{
// Real data set dimension
IntegerVector dims_out = get_HDF5_dataset_size(*dataset);
// id bycols == true : read all rows by group of columns ; else : all columns by group of rows
if (bycols == true) {
ilimit = dims_out[0];
count[1] = dims_out[1];
offset[1] = 0;
} else {
ilimit = dims_out[1];
count[0] = dims_out[0];
offset[0] = 0;
};
if( stroutdataset.compare("")!=0)
{
hsize_t dimsf[2]; // dataset dimensions
dimsf[0] = dims_out[0];
dimsf[1] = dims_out[1];
DataSpace dataspace( RANK2, dimsf );
outdataset = new DataSet(file->createDataSet(stroutdataset, PredType::NATIVE_DOUBLE, dataspace));
} else {
outdataset = dataset;
}
for( int i=0; i<=(ilimit/blocksize); i++)
{
int iread;
if( (i+1)*blocksize < ilimit) iread = blocksize;
else iread = ilimit - (i*blocksize);
if(bycols == true) {
count[0] = iread;
offset[0] = i*blocksize;
} else {
count[1] = iread;
offset[1] = i*blocksize;
}
// read block
Eigen::MatrixXd data = GetCurrentBlock_hdf5(file, dataset, offset[0], offset[1], count[0], count[1]);
if(bycols == true) // We have to do it by rows
{
for( int row = 0; row<data.rows(); row++) // COMPLETE EXECUTION
{
std::map<double, double> myMap;
myMap = VectortoOrderedMap_SNP_counts(data.row(row));
/*** ORIGINAL FUNCIONA PERFECTAMENT PERÒ ASSIGNA UN MATEIX VALOR A TOS... !!!
data.row(row) = (data.row(row).array() == 3).select( get_value_to_impute_discrete(myMap), data.row(row));
***/
//..// data.row(row) = (data.row(row).array() == 0).select( -5, data.row(row));
//..// data.row(row) = (data.row(row).array() == 1).select( 0, data.row(row));
//..// data.row(row) = (data.row(row).array() == 2).select( 5, data.row(row));
//..// data.row(row) = (data.row(row).array() == 3).select( 99, data.row(row));
Eigen::VectorXd ev = data.row(row);
std::vector<double> v(ev.data(), ev.data() + ev.size());
auto it = std::find_if(std::begin(v), std::end(v), [](int i){return i == 3;});
while (it != std::end(v)) {
//..// results.emplace_back(std::distance(std::begin(v), it));
if(*it==3) *it = get_value_to_impute_discrete(myMap);
it = std::find_if(std::next(it), std::end(v), [](int i){return i == 3;});
}
Eigen::VectorXd X = Eigen::Map<Eigen::VectorXd>(v.data(), v.size());
data.row(row) = X;
}
} else {
for( int col = 0; col<data.cols(); col++)
{
std::map<double, double> myMap;
myMap = VectortoOrderedMap_SNP_counts(data.col(col));
//..// data.col(col) = (data.col(col).array() == 3).select( get_value_to_impute_discrete(myMap), data.col(col));
Eigen::VectorXd ev = data.col(col);
std::vector<double> v(ev.data(), ev.data() + ev.size());
auto it = std::find_if(std::begin(v), std::end(v), [](int i){return i == 3;});
while (it != std::end(v)) {
//..// results.emplace_back(std::distance(std::begin(v), it));
if(*it==3) *it = get_value_to_impute_discrete(myMap);
it = std::find_if(std::next(it), std::end(v), [](int i){return i == 3;});
}
Eigen::VectorXd X = Eigen::Map<Eigen::VectorXd>(v.data(), v.size());
data.col(col) = X;
}
}
//..// write_HDF5_matrix_subset_v2(file, dataset, offset, count, stride, block, wrap(data) );
write_HDF5_matrix_subset_v2(file, outdataset, offset, count, stride, block, wrap(data) );
}
outdataset->close();
} catch(FileIException& error) { // catch failure caused by the H5File operations
outdataset->close();
file->close();
::Rf_error( "c++ exception Impute_snp_HDF5 (File IException)" );
} catch(DataSetIException& error) { // catch failure caused by the DataSet operations
outdataset->close();
file->close();
::Rf_error( "c++ exception Impute_snp_HDF5 (DataSet IException)" );
} catch(GroupIException& error) { // catch failure caused by the Group operations
outdataset->close();
file->close();
::Rf_error( "c++ exception Impute_snp_HDF5 (Group IException)" );
} catch(DataSpaceIException& error) { // catch failure caused by the DataSpace operations
outdataset->close();
file->close();
::Rf_error( "c++ exception Impute_snp_HDF5 (DataSpace IException)" );
} catch(DataTypeIException& error) { // catch failure caused by the DataSpace operations
outdataset->close();
file->close();
::Rf_error( "c++ exception Impute_snp_HDF5 (Data TypeIException)" );
}
}
//' Impute SNPs in hdf5 omic dataset
//'
//' Impute SNPs in hdf5 omic dataset
//'
//' @param filename, character array indicating the name of the file to create
//' @param group, character array indicating the input group where the data set to be imputed is.
//' @param dataset, character array indicating the input dataset to be imputed
//' @param bycols, boolean by default = true, true indicates that the imputation will be done by columns, otherwise, the imputation will be done by rows
//' @param outgroup, optional character array indicating group where the data set will be saved after imputation if `outgroup` is NULL, output dataset is stored in the same input group.
//' @param outdataset, optional character array indicating dataset to store the resulting data after imputation if `outdataset` is NULL, input dataset will be overwritten.
//' @return Original hdf5 data file with imputed data
//' @export
// [[Rcpp::export]]
Rcpp::RObject bdImpute_snps_hdf5(std::string filename, std::string group, std::string dataset,
Rcpp::Nullable<std::string> outgroup = R_NilValue, Rcpp::Nullable<std::string> outdataset = R_NilValue,
Rcpp::Nullable<bool> bycols = true )
{
H5File* file;
DataSet* pdataset = nullptr;
try
{
std::string strdataset = group +"/" + dataset;
std::string stroutgroup, stroutdataset, stroutdata;
std::string strdatasetout;
//.commented 20201120 - warning check().// int res;
bool bcols;
if(bycols.isNull()) bcols = true ;
else bcols = Rcpp::as<bool>(bycols);
if(outgroup.isNull()) stroutgroup = group ;
else stroutgroup = Rcpp::as<std::string>(outgroup);
if(outdataset.isNull()) stroutdataset = dataset ;
else stroutdataset = Rcpp::as<std::string>(outdataset);
stroutdata = stroutgroup +"/" + stroutdataset;
if(!ResFileExist_filestream(filename)){
throw std::range_error("File not exits, create file before access to dataset");
}
file = new H5File( filename, H5F_ACC_RDWR );
if(exists_HDF5_element_ptr(file, strdataset))
{
try
{
pdataset = new DataSet(file->openDataSet(strdataset));
if( strdataset.compare(stroutdata)!= 0)
{
// If output is different from imput --> Remve possible existing dataset and create new
if(exists_HDF5_element_ptr(file, stroutdata))
remove_HDF5_element_ptr(file, stroutdata);
// Create group if not exists
if(!exists_HDF5_element_ptr(file, stroutgroup))
file->createGroup(stroutgroup);
} else {
stroutdata = "";
}
Impute_snp_HDF5( file, pdataset, bcols, stroutdata);
}catch(FileIException& error) {
pdataset->close(); //.created 20201120 - warning check().//
file->close();
}
} else{
//.commented 20201120 - warning check().// pdataset->close();
file->close();
throw std::range_error("Dataset not exits");
}
}
catch( FileIException& error ) { // catch failure caused by the H5File operations
//.commented 20201120 - warning check().// pdataset->close();
file->close();
::Rf_error( "c++ exception (File IException)" );
return(wrap(-1));
}
pdataset->close();
file->close();
return(wrap(0));
}
/***R
*/ | 34.639241 | 187 | 0.578019 | [
"vector"
] |
7a21ffd6f466a6a5fdcb1afc3a26f05ce2745972 | 4,405 | cpp | C++ | LRUCache.cpp | liuslevis/leetcode | 3447b338cd4efc7d817e35e182dda3a53899b8c2 | [
"MIT"
] | null | null | null | LRUCache.cpp | liuslevis/leetcode | 3447b338cd4efc7d817e35e182dda3a53899b8c2 | [
"MIT"
] | null | null | null | LRUCache.cpp | liuslevis/leetcode | 3447b338cd4efc7d817e35e182dda3a53899b8c2 | [
"MIT"
] | null | null | null | /*
用时6h,2天,(我的方法思路对,但是出错case无法找到),参考ref实现accept, 100ms
=== Should learn how to analysis as below ===
ref: https://leetcode.com/discuss/13964/accepted-c-solution-296-ms
1. hash map holds iterators to linked list
2. linked list holds key and value, key to access hash map items
3. when item is accessed, it's promoted - moved to the tail of the list - O(1) operation
4. when item should be removed, we remove head of the list - O(1) operation
5. when item is not promoted long time, it's moved to the head of the list automatically
6. time complexity: based on unordered_map:
get() - avg. O(1) performance or worst O(n), set() - O(1) performance
*/
#include <iostream>
#include <vector>
#include <unordered_map>
#include <list>
#include <assert.h>
#include <algorithm>
using namespace std;
class LRUCache{
private:
struct item_t {
int key, val;
item_t(int k, int v) : key(k), val(v) {}
};
typedef list<item_t> list_t;
typedef std::unordered_map<int, list_t::iterator> dict_t; // { key: list_t::iterator}
dict_t m_dict; // {key : list_iter}
list_t m_list; // FIFO + LRU, front()==LRU, list<item_t(key,value)>
int capacity;
// remove LRU item at front of the list
void remove_LRU_item() {
int pop_key = m_list.front().key;
m_dict.erase(pop_key);
m_list.pop_front();
}
// add item at the end of the list
void add_new_item(int key, int value) {
m_list.push_back(item_t(key, value));
m_dict[key] = (--m_list.end());
}
// get value and promote item to the end of the list
int get_value_and_promote_key(int key) {
list_t::iterator it = m_dict[key];
item_t item = item_t(it->key, it->val);
m_list.erase(it);
m_list.push_back(item);
m_dict[key] = (--m_list.end());
return item.val;
}
public:
LRUCache(int capacity) {
this->capacity = capacity;
}
int get(int key) {
if (m_dict.find(key) == m_dict.end()) {
return -1;
} else {
return get_value_and_promote_key(key);
}
}
void set(int key, int value) {
// cout<<"set key:"<<key<<" value:"<<value<<endl;
if (capacity == 0) return;
// item not found
if (m_dict.find(key) == m_dict.end()) {
// remove LRU item if out of capacity
if (!m_dict.empty() && m_dict.size() == capacity) {
remove_LRU_item();
}
} else { // item found, move item to the end of the list
m_list.erase(m_dict[key]);
}
add_new_item(key, value);
}
};
void test() {
LRUCache lru = LRUCache(1);
lru.set(1,2);
assert(2 == lru.get(1));
assert(-1 == lru.get(2));
lru.set(2,3);
assert(-1 == lru.get(1));
assert(3 == lru.get(2));
LRUCache lru2 = LRUCache(2);
lru2.set(1,11);
lru2.set(2,22);
assert(11 == lru2.get(1));
lru2.set(3,33);
assert(11 == lru2.get(1));
assert(-1 == lru2.get(2));
assert(33 == lru2.get(3));
LRUCache lru3 = LRUCache(3);
lru3.set(1,11);
lru3.set(2,22);
lru3.set(3,33);
assert(22 == lru3.get(2));
lru3.set(4,44);
assert(-1 == lru3.get(1));
assert(33 == lru3.get(3));
LRUCache lru4 = LRUCache(0);
assert(-1 == lru4.get(-1));
assert(-1 == lru4.get(0));
assert(-1 == lru4.get(1));
lru4.set(1,11);
assert(-1 == lru4.get(0));
assert(-1 == lru4.get(1));
LRUCache lru5 = LRUCache(1);
assert(-1 == lru5.get(0));
lru5.set(1,11);
assert(-1 == lru5.get(0));
assert(-1 == lru5.get(2));
assert(11 == lru5.get(1));//failed
lru5.set(2,22);
assert(-1 == lru5.get(-1));
assert(-1 == lru5.get(0));
assert(-1 == lru5.get(1));
assert(22 == lru5.get(2));
LRUCache lru6 = LRUCache(2);
assert(-1 == lru6.get(2));
lru6.set(2,6);
assert(-1 == lru6.get(1));
lru6.set(1,5);
lru6.set(1,2);
assert(2 == lru6.get(1));
assert(6 == lru6.get(2));
LRUCache lru7 = LRUCache(2);
lru7.set(2,1);
lru7.set(1,1);
lru7.set(2,3);
lru7.set(4,1);
assert(-1 == lru7.get(1));
assert(3 == lru7.get(2));
assert(1 == lru7.get(4));
LRUCache lru8 = LRUCache(1);
assert(-1 == lru7.get(0));
printf("pass test!\n");
}
int main(int argc, char const *argv[])
{
test();
return 0;
} | 25.760234 | 89 | 0.563451 | [
"vector"
] |
7a2448048b6f7d94fcb9142a134bf73371727a82 | 1,827 | cpp | C++ | src/robot_manager_node.cpp | temoto-framework/temoto_robot_manager | 98d44dccaad83a466d7a01531bc8f125468e0887 | [
"Apache-2.0"
] | null | null | null | src/robot_manager_node.cpp | temoto-framework/temoto_robot_manager | 98d44dccaad83a466d7a01531bc8f125468e0887 | [
"Apache-2.0"
] | 2 | 2020-05-14T14:26:10.000Z | 2020-06-01T07:13:56.000Z | src/robot_manager_node.cpp | temoto-telerobotics/temoto_robot_manager | 98d44dccaad83a466d7a01531bc8f125468e0887 | [
"Apache-2.0"
] | null | null | null | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright 2019 TeMoto Telerobotics
*
* 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 "temoto_robot_manager/robot_manager.h"
#include <boost/program_options.hpp>
#include "temoto_resource_registrar/temoto_logging.h"
using namespace temoto_robot_manager;
int main(int argc, char** argv)
{
namespace po = boost::program_options;
po::variables_map vm;
po::options_description desc("Allowed options");
desc.add_options()
("config-base-path", po::value<std::string>(), "Base path to robot_description.yaml config file.");
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
// Get the config path
std::string config_base_path;
if (vm.count("config-base-path"))
{
config_base_path = vm["config-base-path"].as<std::string>();
}
else
{
std::cout << "Missing Component Manager config base path\n" << desc;
return 1;
}
TEMOTO_LOG_ATTR.initialize("robot_manager");
ros::init(argc, argv, TEMOTO_LOG_ATTR.getSubsystemName());
// Create a SensorManager object
RobotManager rm(config_base_path);
ros::AsyncSpinner spinner(4);
spinner.start();
ros::waitForShutdown();
}
| 32.052632 | 103 | 0.659551 | [
"object"
] |
7a255d6a086ed93c63926edc9b188d8bcf203e12 | 1,427 | cpp | C++ | Easy/Sleep Cycle/Sleep Cycle.cpp | anishsingh42/CodeChef | 50f5c0438516210895e513bc4ee959b9d99ef647 | [
"Apache-2.0"
] | 127 | 2020-10-13T18:04:35.000Z | 2022-02-17T10:56:27.000Z | Easy/Sleep Cycle/Sleep Cycle.cpp | anishsingh42/CodeChef | 50f5c0438516210895e513bc4ee959b9d99ef647 | [
"Apache-2.0"
] | 132 | 2020-10-13T18:06:53.000Z | 2021-10-17T18:44:26.000Z | Easy/Sleep Cycle/Sleep Cycle.cpp | anishsingh42/CodeChef | 50f5c0438516210895e513bc4ee959b9d99ef647 | [
"Apache-2.0"
] | 364 | 2020-10-13T18:04:52.000Z | 2022-03-04T14:34:53.000Z | #include <bits/stdc++.h>
typedef long long ll;
typedef long double ld;
#define fr(i, a, b) for (ll i = a; i < b; i++)
#define rf(i, a, b) for (ll i = a; i >= b; i--)
typedef std::vector<long long> vi;
#define F first
#define S second
#define fast \
ios_base::sync_with_stdio(0); \
cin.tie(0); \
cout.tie(0);
#define mod 1000000007
#define PB push_back
#define MP make_pair
#define PI 3.14159265358979323846
#define all(a) a.begin(), a.end()
#define mx(a) *max_element(all(a))
#define mn(a) *min_element(all(a))
const ll INF = LLONG_MAX / 2;
const ll N = 2e5 + 1;
using namespace std;
int main()
{
fast;
ll t = 1;
std::cin >> t;
while (t--)
{
ll l, h, b;
std::cin >> l >> h;
string s;
cin >> s;
ll co = 0, p = 0;
fr(i, 0, l)
{
if (s[i] == '0')
co++;
else
{
if (2 * (h - co) <= h)
h = 2 * (h - co);
co = 0;
}
if (h <= 0)
{
p = 1;
break;
}
}
if (p == 1)
{
cout << "YES\n";
continue;
}
if (2 * (h - co) <= h)
h = 2 * (h - co);
if (h <= 0)
{
cout << "YES\n";
}
else
cout << "NO\n";
}
} | 21.953846 | 47 | 0.384723 | [
"vector"
] |
7a2e37df3c4c02f70e77f246a23f0636e614a847 | 1,973 | cpp | C++ | aws-cpp-sdk-dlm/source/model/LocationValues.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-dlm/source/model/LocationValues.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-dlm/source/model/LocationValues.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/dlm/model/LocationValues.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace DLM
{
namespace Model
{
namespace LocationValuesMapper
{
static const int CLOUD_HASH = HashingUtils::HashString("CLOUD");
static const int OUTPOST_LOCAL_HASH = HashingUtils::HashString("OUTPOST_LOCAL");
LocationValues GetLocationValuesForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == CLOUD_HASH)
{
return LocationValues::CLOUD;
}
else if (hashCode == OUTPOST_LOCAL_HASH)
{
return LocationValues::OUTPOST_LOCAL;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<LocationValues>(hashCode);
}
return LocationValues::NOT_SET;
}
Aws::String GetNameForLocationValues(LocationValues enumValue)
{
switch(enumValue)
{
case LocationValues::CLOUD:
return "CLOUD";
case LocationValues::OUTPOST_LOCAL:
return "OUTPOST_LOCAL";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return {};
}
}
} // namespace LocationValuesMapper
} // namespace Model
} // namespace DLM
} // namespace Aws
| 27.788732 | 92 | 0.6148 | [
"model"
] |
7a331c951e2c28e0b72da43ecc914fb15d30ea75 | 2,940 | cc | C++ | ref_src/2009-Connected-Iterative-Scan/src-refactor/graph/temporal_network.cc | GraphProcessor/LocalityBasedGraphAlgo | de6e48498eb43a106312f14149a3060501b8a49c | [
"MIT"
] | null | null | null | ref_src/2009-Connected-Iterative-Scan/src-refactor/graph/temporal_network.cc | GraphProcessor/LocalityBasedGraphAlgo | de6e48498eb43a106312f14149a3060501b8a49c | [
"MIT"
] | null | null | null | ref_src/2009-Connected-Iterative-Scan/src-refactor/graph/temporal_network.cc | GraphProcessor/LocalityBasedGraphAlgo | de6e48498eb43a106312f14149a3060501b8a49c | [
"MIT"
] | 1 | 2021-01-06T14:03:59.000Z | 2021-01-06T14:03:59.000Z | #include "temporal_network.h"
/**
*@fn TemporalNetwork::AddNetwork ( const string& filename, const string& delimiters )
*
*Adds a network structure to the end of the temporal network represented by this structure.
*
*@TODO - Add parameter to notify if the network is directed or undirected.
* - Add option to add a network in any time point of the temporal network
*
*@param filename Name of the file to load the information from. Each line in the file
* should be a single edge - node1|node2|edge_weight. If the network
* is undirected, it doesn't matter if both directions are in the
* file. If directed, the edge format is fr|to|edge_weight.
*@param delimiters Characters to be used as the delimiter for the network file
*
*/
shared_ptr < network > temporal_network::AddNetwork ( const string& filename, const string& delimiters, const bool& directed ){
ifstream fin; //Open file
openFileHarsh(&fin, filename);
vector < string > fields; //Set up parameters
shared_ptr < network > result ( new network() );
while ( fline_tr( &fin, &fields, delimiters ) ){
if (fields.size() != 3) continue; //Simple format check
for (int i = 0; i < 2; i++){ //Add new edges to list
if ( vertex_set.find(fields[i]) == vertex_set.end() ){
vertex_set.insert(fields[i]);
}
}
pair < double, bool > ret = check_str_to<double>(fields[2]); //Get edge weight
if ( !ret.second ) continue; //Wrong format
result->addEdge(shared_ptr<string>( new string ( *(vertex_set.find(fields[0])) ) ),
shared_ptr<string>( new string ( *(vertex_set.find(fields[1])) ) ),
ret.first, directed ); //Add to network
}
networks.push_back(result); //Add to time series
fin.close(); //Clean up
return ( networks[networks.size() - 1] );
}
void temporal_network::AddCommunities ( const string& filename, const string& delimiters ){
ifstream fin; //Open file
openFileHarsh(&fin, filename);
vector < string > fields; //Set up parameters
set < community, cmp_set_str > structure;
while ( fline_tr( &fin, &fields, delimiters ) ){
community next;
for (int i = 0; i < fields.size(); i++){ //Add new edges to list
if ( vertex_set.find(fields[i]) == vertex_set.end() ){
vertex_set.insert(fields[i]);
}
next.insert( shared_ptr < string > ( new string ( *(vertex_set.find(fields[i]) ) ) ) );
}
structure.insert(next);
}
communities.push_back( structure );
fin.close(); //Clean up
}
| 40.273973 | 127 | 0.565646 | [
"vector"
] |
7a34d8affd67528fa4b73b8811140abc6f963e26 | 2,009 | cpp | C++ | src/ConvNet/RegressionLayer.cpp | OuluLinux/ConvNetCpp | 48854357b49b35d6599fb8ae42be01f4ba1903a6 | [
"MIT"
] | 7 | 2017-05-04T17:20:10.000Z | 2019-10-02T13:08:33.000Z | src/ConvNet/RegressionLayer.cpp | sppp/ConvNetC- | 48854357b49b35d6599fb8ae42be01f4ba1903a6 | [
"MIT"
] | null | null | null | src/ConvNet/RegressionLayer.cpp | sppp/ConvNetC- | 48854357b49b35d6599fb8ae42be01f4ba1903a6 | [
"MIT"
] | 3 | 2017-04-13T06:29:23.000Z | 2018-01-09T07:44:09.000Z | #include "LayerBase.h"
namespace ConvNet {
void LayerBase::InitRegression(int input_width, int input_height, int input_depth) {
int input_count = input_width * input_height * input_depth;
output_depth = input_count;
output_width = 1;
output_height = 1;
}
Volume& LayerBase::ForwardRegression(Volume& input, bool is_training) {
input_activation = &input;
output_activation = input;
return input; // identity function
}
double LayerBase::BackwardRegression(const Vector<double>& y) {
// compute and accumulate gradient wrt weights and bias of this layer
Volume& input = *input_activation;
input.ZeroGradients(); // zero out the gradient of input Vol
double loss = 0.0;
for (int i = 0; i < output_depth; i++) {
double dy = input.Get(i) - y[i];
input.SetGradient(i, dy);
loss += 0.5 * dy * dy;
}
return loss;
}
double LayerBase::BackwardRegression(int pos, double y) {
// compute and accumulate gradient wrt weights and bias of this layer
Volume& input = *input_activation;
input.ZeroGradients(); // zero out the gradient of input Vol
double loss = 0.0;
// lets hope that only one number is being regressed
double dy = input.Get(pos) - y;
if (!IsFin(dy)) return 0;
input.SetGradient(pos, dy);
loss += 0.5 * dy * dy;
return loss;
}
double LayerBase::BackwardRegression(int cols, const Vector<int>& posv, const Vector<double>& yv) {
// compute and accumulate gradient wrt weights and bias of this layer
Volume& input = *input_activation;
input.ZeroGradients(); // zero out the gradient of input Vol
double loss = 0.0;
ASSERT(posv.GetCount() == yv.GetCount());
for(int i = 0; i < posv.GetCount(); i++) {
int p = posv[i];
ASSERT(p >= 0 && p < cols);
int pos = i * cols + p;
double y = yv[i];
double dy = input.Get(pos) - y;
input.SetGradient(pos, dy);
loss += 0.5 * dy * dy;
}
return loss;
}
String LayerBase::ToStringRegression() const {
return Format("Regression: w:%d, h:%d, d:%d",
output_width, output_height, output_depth);
}
}
| 25.43038 | 99 | 0.687904 | [
"vector"
] |
7a3791e5b339169ab0f0574b31266f8ae6c5cde1 | 110,319 | cpp | C++ | CPP2D/DPrinter.cpp | Geod24/CPP2D | 3ca5c4b85f587bcac897ab74a8d9195811a8bcba | [
"BSL-1.0"
] | 94 | 2016-05-28T11:20:44.000Z | 2021-08-24T13:27:33.000Z | CPP2D/DPrinter.cpp | Geod24/CPP2D | 3ca5c4b85f587bcac897ab74a8d9195811a8bcba | [
"BSL-1.0"
] | 31 | 2016-05-12T20:30:01.000Z | 2021-03-07T22:19:16.000Z | CPP2D/DPrinter.cpp | Geod24/CPP2D | 3ca5c4b85f587bcac897ab74a8d9195811a8bcba | [
"BSL-1.0"
] | 11 | 2016-09-06T19:47:18.000Z | 2021-04-26T14:19:44.000Z | //
// Copyright (c) 2016 Loïc HAMOT
//
// 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 "DPrinter.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <locale>
#include <ciso646>
#include <cstdio>
#include <regex>
#pragma warning(push, 0)
#include <llvm/ADT/SmallString.h>
#include <llvm/ADT/APFloat.h>
#include <llvm/Support/Path.h>
#include <llvm/Support/ConvertUTF.h>
#include <clang/AST/RecursiveASTVisitor.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Lex/Preprocessor.h>
#include <clang/Lex/MacroArgs.h>
#include <clang/AST/Comment.h>
#include <clang/AST/Expr.h>
#pragma warning(pop)
#include "MatchContainer.h"
#include "CPP2DTools.h"
#include "Spliter.h"
#include "CPP2DTools.h"
using namespace llvm;
using namespace clang;
std::vector<std::unique_ptr<std::stringstream> > outStack;
bool output_enabled = true;
std::stringstream& out()
{
static std::stringstream empty_ss;
empty_ss.str("");
if(output_enabled)
return *outStack.back();
else
return empty_ss;
}
void pushStream()
{
outStack.emplace_back(std::make_unique<std::stringstream>());
}
std::string popStream()
{
std::string const str = outStack.back()->str();
outStack.pop_back();
return str;
}
#define CHECK_LOC if (checkFilename(Decl)) {} else return true
static std::map<std::string, std::string> type2type =
{
{ "boost::optional", "std.typecons.Nullable" },
{ "std::vector", "cpp_std.vector" },
{ "std::set", "cpp_std.set" },
{ "boost::shared_mutex", "core.sync.rwmutex.ReadWriteMutex" },
{ "boost::mutex", "core.sync.mutex.Mutex" },
{ "std::allocator", "cpp_std.allocator" },
{ "time_t", "core.stdc.time.time_t" },
{ "intptr_t", "core.stdc.stdint.intptr_t" },
{ "int8_t", "core.stdc.stdint.int8_t" },
{ "uint8_t", "core.stdc.stdint.uint8_t" },
{ "int16_t", "core.stdc.stdint.int16_t" },
{ "uint16_t", "core.stdc.stdint.uint16_t" },
{ "int32_t", "core.stdc.stdint.int32_t" },
{ "uint32_t", "core.stdc.stdint.uint32_t" },
{ "int64_t", "core.stdc.stdint.int64_t" },
{ "uint64_t", "core.stdc.stdint.uint64_t" },
{ "size_t", "size_t" },
{ "SafeInt", "std.experimental.safeint.SafeInt" },
{ "RedBlackTree", "std.container.rbtree" },
{ "std::string", "string" },
{ "std::__cxx11::string", "string" },
{ "std::ostream", "std.stdio.File" },
{ "std::rand", "core.stdc.rand" },
{ "::rand", "core.stdc.stdlib.rand" },
};
static const std::set<Decl::Kind> noSemiCommaDeclKind =
{
Decl::Kind::CXXRecord,
Decl::Kind::Record,
Decl::Kind::ClassTemplate,
Decl::Kind::Function,
Decl::Kind::CXXConstructor,
Decl::Kind::CXXDestructor,
Decl::Kind::CXXConversion,
Decl::Kind::CXXMethod,
Decl::Kind::Namespace,
Decl::Kind::NamespaceAlias,
Decl::Kind::UsingDirective,
Decl::Kind::Empty,
Decl::Kind::Friend,
Decl::Kind::FunctionTemplate,
Decl::Kind::Enum,
};
static const std::set<Stmt::StmtClass> noSemiCommaStmtKind =
{
Stmt::StmtClass::ForStmtClass,
Stmt::StmtClass::IfStmtClass,
Stmt::StmtClass::CXXForRangeStmtClass,
Stmt::StmtClass::WhileStmtClass,
Stmt::StmtClass::CompoundStmtClass,
Stmt::StmtClass::CXXCatchStmtClass,
Stmt::StmtClass::CXXTryStmtClass,
Stmt::StmtClass::NullStmtClass,
Stmt::StmtClass::SwitchStmtClass,
//Stmt::StmtClass::DeclStmtClass,
};
bool needSemiComma(Decl* decl)
{
auto const kind = decl->getKind();
if (auto record = dyn_cast<RecordDecl>(decl))
return !record->isCompleteDefinition();
else if (auto tmp = dyn_cast<ClassTemplateDecl>(decl))
return !tmp->hasBody();
else
return noSemiCommaDeclKind.count(kind) == 0;
}
bool needSemiComma(Stmt* stmt)
{
if (auto* declStmt = dyn_cast<DeclStmt>(stmt))
{
if (declStmt->isSingleDecl()) //May be in for or catch
return needSemiComma(declStmt->getSingleDecl());
else
return false;//needSemiComma(*(declStmt->children().end()--));
}
else
{
auto const kind = stmt->getStmtClass();
return noSemiCommaStmtKind.count(kind) == 0;
}
}
std::string mangleName(std::string const& name)
{
if(name == "version")
return "version_";
if(name == "out")
return "out_";
if(name == "in")
return "in_";
if(name == "ref")
return "ref_";
if(name == "debug")
return "debug_";
if(name == "function")
return "function_";
if(name == "cast")
return "cast_";
if(name == "align")
return "align_";
else if(name == "Exception")
return "Exception_";
else
return name;
}
static char const* AccessSpecifierStr[] =
{
"public",
"protected",
"private",
"private" // ...the special value "none" which means different things in different contexts.
// (from the clang doxy)
};
void DPrinter::setIncludes(std::set<std::string> const& includes)
{
includesInFile = includes;
}
void DPrinter::includeFile(std::string const& inclFile, std::string const& typeName)
{
if(isInMacro)
return;
// For each #include find in the cpp
for(std::string include : includesInFile)
{
auto const pos = inclFile.find(include);
// TODO : Use llvm::path
// If the include is found in the file inclFile, import it
if(pos != std::string::npos &&
pos == (inclFile.size() - include.size()) &&
(pos == 0 || inclFile[pos - 1] == '/' || inclFile[pos - 1] == '\\'))
{
static std::string const hExt = ".h";
static std::string const hppExt = ".hpp";
if(include.find(hExt) == include.size() - hExt.size())
include = include.substr(0, include.size() - hExt.size());
if(include.find(hppExt) == include.size() - hppExt.size())
include = include.substr(0, include.size() - hppExt.size());
std::transform(std::begin(include), std::end(include),
std::begin(include),
[](char c) {return static_cast<char>(tolower(c)); });
std::replace(std::begin(include), std::end(include), '/', '.');
std::replace(std::begin(include), std::end(include), '\\', '.');
std::replace(std::begin(include), std::end(include), '-', '_');
externIncludes[include].insert(typeName);
break;
}
}
}
void DPrinter::printDeclContext(DeclContext* DC)
{
if(DC->isTranslationUnit()) return;
if(DC->isFunctionOrMethod()) return;
printDeclContext(DC->getParent());
if(NamespaceDecl* NS = dyn_cast<NamespaceDecl>(DC))
return;
else if(ClassTemplateSpecializationDecl* Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC))
{
if(passDecl(Spec) == false)
{
auto* type = Spec->getTypeForDecl();
QualType qtype = type->getCanonicalTypeInternal();
TraverseType(qtype);
}
out() << ".";
}
else if(TagDecl* Tag = dyn_cast<TagDecl>(DC))
{
if(TypedefNameDecl* Typedef = Tag->getTypedefNameForAnonDecl())
out() << Typedef->getIdentifier()->getName().str() << ".";
else if(Tag->getIdentifier())
out() << Tag->getIdentifier()->getName().str() << ".";
else
return;
}
}
std::string DPrinter::printDeclName(NamedDecl* decl)
{
NamedDecl* canDecl = nullptr;
std::string const& name = decl->getNameAsString();
if(name.empty())
return std::string();
std::string qualName = name;
std::string result;
if(DeclContext* ctx = decl->getDeclContext())
{
pushStream();
printDeclContext(ctx);
result = popStream();
qualName = decl->getQualifiedNameAsString();
}
auto qualTypeToD = type2type.find(qualName);
if(qualTypeToD != type2type.end())
{
//There is a convertion to D
auto const& dQualType = qualTypeToD->second;
auto const dotPos = dQualType.find_last_of('.');
auto const module = dotPos == std::string::npos ?
std::string() :
dQualType.substr(0, dotPos);
if(not module.empty()) //Need an import
externIncludes[module].insert(qualName);
if(dotPos == std::string::npos)
return result + dQualType;
else
return result + dQualType.substr(dotPos + 1);
}
else
{
NamedDecl const* usedDecl = canDecl ? canDecl : decl;
includeFile(CPP2DTools::getFile(Context->getSourceManager(), usedDecl), qualName);
return result + mangleName(name);
}
}
std::string getName(DeclarationName const& dn)
{
std::string name = dn.getAsString();
if(name.empty())
{
std::stringstream ss;
ss << "var" << dn.getAsOpaqueInteger();
name = ss.str();
}
return name;
}
void DPrinter::printCommentBefore(Decl* t)
{
SourceManager& sm = Context->getSourceManager();
const RawComment* rc = Context->getRawCommentForDeclNoCache(t);
if(rc && not rc->isTrailingComment())
{
using namespace std;
out() << std::endl << indentStr();
string comment = rc->getRawText(sm).str();
auto end = std::remove(std::begin(comment), std::end(comment), '\r');
comment.erase(end, comment.end());
out() << comment << std::endl << indentStr();
}
else
out() << std::endl << indentStr();
}
void DPrinter::printCommentAfter(Decl* t)
{
SourceManager& sm = Context->getSourceManager();
const RawComment* rc = Context->getRawCommentForDeclNoCache(t);
if(rc && rc->isTrailingComment())
out() << '\t' << rc->getRawText(sm).str();
}
std::string DPrinter::trim(std::string const& s)
{
auto const pos1 = s.find_first_not_of("\r\n\t ");
auto const pos2 = s.find_last_not_of("\r\n\t ");
return pos1 == std::string::npos ?
std::string() :
s.substr(pos1, (pos2 - pos1) + 1);
}
std::vector<std::string> DPrinter::split_lines(std::string const& instr)
{
std::vector<std::string> result;
auto prevIter = std::begin(instr);
auto iter = std::begin(instr);
do
{
iter = std::find(prevIter, std::end(instr), '\n');
result.push_back(std::string(prevIter, iter));
if (iter != std::end(instr))
{
result.back() += "\n";
prevIter = iter + 1;
}
}
while(iter != std::end(instr));
return result;
}
bool DPrinter::printStmtComment(SourceLocation& locStart,
SourceLocation const& locEnd,
SourceLocation const& nextStart,
bool doIndent)
{
if(locStart.isInvalid() || locEnd.isInvalid() || locStart.isMacroID() || locEnd.isMacroID())
{
locStart = nextStart;
return false;
}
auto& sm = Context->getSourceManager();
std::string comment =
Lexer::getSourceText(CharSourceRange(SourceRange(locStart, locEnd), true),
sm,
LangOptions()
).str();
// Uniformize end of lines
comment = std::regex_replace(comment, std::regex(R"(\r)"), std::string(""));
// Extract comments
enum State
{
StartOfLine,
Line,
Slash,
MultilineComment,
MultilineComment_star,
SinglelineComment,
Pragma,
Pragma_antislash,
};
State state = StartOfLine;
struct StringWithState
{
StringWithState(State s) :state(s) {}
State state = Line;
std::string str;
};
std::vector<StringWithState> comments;
comments.emplace_back(StartOfLine);
auto splitComment = [&](State newState)
{
if (comments.back().state == Pragma)
{
std::string& pragma = comments.back().str;
pragma = std::regex_replace(pragma, std::regex(R"(^\s*\#define\s+(\w+)\s+(\w+)(\s*)$)"), std::string("auto const $1 = $2;$3"));
pragma = std::regex_replace(pragma, std::regex(R"(^\s*\#define\s+(\w+)(\s*)$)"), std::string("version = $1;$2")); // OK
pragma = std::regex_replace(pragma, std::regex(R"(^\s*\#ifdef\s*([^\z]*?[^\\])(\s*)$)"), std::string("version($1)\n{$2"));
pragma = std::regex_replace(pragma, std::regex(R"(^\s*\#ifndef\s*([^\z]*?[^\\])(\s*)$)"), std::string("version(!($1))\n{$2"));
pragma = std::regex_replace(pragma, std::regex(R"(^\s*\#if\s*([^\z]*?[^\\])(\s*)$)"), std::string("$1\n{$2"));
pragma = std::regex_replace(pragma, std::regex(R"(^\s*\#elif\s*([^\z]*?[^\\])(\s*)$)"), std::string("}\nelse $1\n{$2"));
pragma = std::regex_replace(pragma, std::regex(R"(^\s*\#else(\s*))"), std::string("}\nelse\n{$1"));
pragma = std::regex_replace(pragma, std::regex(R"(^\s*\#endif(\s*))"), std::string("}$1"));
pragma = std::regex_replace(pragma, std::regex(R"(^\s*(\#undef\s+\w+\s*$))"), std::string("//$1"));
pragma = std::regex_replace(pragma, std::regex(R"(^\s*\#error\s*([^\z]*?[^\\])(\s*)$)"), std::string("static_assert(false, $1);$2"));
pragma = std::regex_replace(pragma, std::regex(R"(defined(\(\w+\)))"), std::string("version$1"));
if (pragma.find("#define") == 0)
pragma = "//" + std::regex_replace(pragma, std::regex(R"((\\))"), std::string("\n//"));
}
else if (comments.back().state == MultilineComment)
comments.back().str += '\n';
comments.emplace_back(newState);
};
auto push = [&](char c)
{
comments.back().str.push_back(c);
};
for (char c : comment)
{
switch (state)
{
case StartOfLine:
{
switch (c)
{
case '/': state = Slash; break;
case '#': state = Pragma; splitComment(Pragma); push(c); break;
case ' ': state = StartOfLine; push(c); break;
case '\t': state = StartOfLine; push(c); break;
case '\n': state = StartOfLine; push(c); splitComment(StartOfLine); break;
default: state = Line; push(c);
}
break;
}
case Line:
{
switch (c)
{
case '/': state = Slash; break;
case '\n': state = StartOfLine; push(c); splitComment(StartOfLine); break;
default: push(c);
}
break;
}
case Slash:
{
switch (c)
{
case '*': state = MultilineComment; splitComment(MultilineComment); push('/'); push(c); break;
case '/': state = SinglelineComment; splitComment(SinglelineComment); push('/'); push(c); break;
default: state = Line; push(c);
}
break;
}
case MultilineComment:
{
switch (c)
{
case '*': state = MultilineComment_star; break;
default: push(c);
}
break;
}
case MultilineComment_star:
{
switch (c)
{
case '/': state = Line; push('*'); push(c); splitComment(Line); break;
default: state = MultilineComment; push(c);
}
break;
}
case SinglelineComment:
{
switch (c)
{
case '\n': state = StartOfLine; push(c); splitComment(Line); break;
default: push(c);
}
break;
}
case Pragma:
{
switch (c)
{
case '\n': state = StartOfLine; push(c); splitComment(Line); break;
case '\\': state = Pragma_antislash; push(c); break;
default: push(c);
}
break;
}
case Pragma_antislash:
{
state = Pragma;
}
}
}
if(not comments.empty())
comments.erase(comments.begin());
if (not comments.empty())
comments.erase(comments.end() - 1);
bool printedSomething = false;
Spliter split(*this, "");
if(not comments.empty())
{
for(StringWithState const& ss : comments)
{
std::string const& c = ss.str;
size_t incPos = c.find("#include");
if (not c.empty() && incPos == std::string::npos && ss.state != StartOfLine)
{
split.split();
if (doIndent)
out() << indentStr();
out() << c;
printedSomething = true;
}
}
}
locStart = nextStart;
return printedSomething;
}
void DPrinter::printMacroArgs(CallExpr* macro_args)
{
Spliter split(*this, ", ");
for(Expr* arg : macro_args->arguments())
{
split.split();
out() << "q{";
if(auto* matTmpExpr = dyn_cast<MaterializeTemporaryExpr>(arg))
{
Stmt* tmpExpr = matTmpExpr->getTemporary();
if(auto* callExpr = dyn_cast<CallExpr>(tmpExpr))
{
if(auto* impCast = dyn_cast<ImplicitCastExpr>(callExpr->getCallee()))
{
if(auto* func = dyn_cast<DeclRefExpr>(impCast->getSubExpr()))
{
std::string const func_name = func->getNameInfo().getAsString();
if(func_name == "cpp2d_type")
{
TraverseTemplateArgument(func->getTemplateArgs()->getArgument());
}
else if(func_name == "cpp2d_name")
{
auto* impCast2 = dyn_cast<ImplicitCastExpr>(callExpr->getArg(0));
auto* str = dyn_cast<clang::StringLiteral>(impCast2->getSubExpr());
out() << str->getString().str();
}
else
TraverseStmt(arg);
}
else
TraverseStmt(arg);
}
else
TraverseStmt(arg);
}
else
TraverseStmt(arg);
}
else
TraverseStmt(arg);
out() << "}";
}
}
void DPrinter::printStmtMacro(std::string const& varName, Expr* init)
{
if (varName.find("CPP2D_MACRO_STMT_END") == 0)
--isInMacro;
else if(varName.find("CPP2D_MACRO_STMT") == 0)
{
auto get_binop = [](Expr * paren)
{
auto cleanups = dyn_cast<ExprWithCleanups>(paren);
if (cleanups)
paren = cleanups->getSubExpr();
auto parenExpr = dyn_cast<ParenExpr>(paren);
assert(parenExpr);
auto binOp = dyn_cast<BinaryOperator>(parenExpr->getSubExpr());
assert(binOp);
return binOp;
};
BinaryOperator* name_and_args = get_binop(init);
auto* macro_name = dyn_cast<clang::StringLiteral>(name_and_args->getLHS());
auto* macro_args = dyn_cast<CallExpr>(name_and_args->getRHS());
out() << "mixin(" << macro_name->getString().str() << "!(";
printMacroArgs(macro_args);
out() << "))";
++isInMacro;
}
}
static PrintingPolicy getPrintingPolicy()
{
LangOptions lo;
lo.CPlusPlus14 = true;
lo.DelayedTemplateParsing = false;
PrintingPolicy printingPolicy(lo);
printingPolicy.ConstantArraySizeAsWritten = true;
return printingPolicy;
}
clang::PrintingPolicy DPrinter::printingPolicy = getPrintingPolicy();
DPrinter::DPrinter(
ASTContext* Context,
MatchContainer const& receiver,
StringRef file)
: Context(Context)
, receiver(receiver)
, modulename(llvm::sys::path::stem(file))
{
}
std::string DPrinter::indentStr() const
{
return std::string(indent * 4, ' '); //-V112
}
bool DPrinter::isA(CXXRecordDecl* decl, std::string const& baseName)
{
std::string declName = decl->getQualifiedNameAsString();
if(declName == baseName)
return true;
for(CXXBaseSpecifier const& baseSpec : decl->bases())
{
CXXRecordDecl* base = baseSpec.getType()->getAsCXXRecordDecl();
assert(base);
if(isA(base, baseName))
return true;
}
for(CXXBaseSpecifier const& baseSpec : decl->vbases())
{
CXXRecordDecl* base = baseSpec.getType()->getAsCXXRecordDecl();
assert(base);
if(isA(base, baseName))
return true;
}
return false;
}
bool DPrinter::TraverseTranslationUnitDecl(TranslationUnitDecl* Decl)
{
if(passDecl(Decl)) return true;
outStack.clear();
outStack.emplace_back(std::make_unique<std::stringstream>());
std::error_code ec;
llvm::raw_fd_ostream file(StringRef(modulename + ".print.cpp"), ec, sys::fs::OpenFlags());
Decl->print(file);
SourceLocation locStart = Decl->getLocStart();
std::ofstream file2(modulename + ".source.cpp");
auto& sm = Context->getSourceManager();
for(clang::Decl* c : Decl->decls())
{
std::string decl_str =
Lexer::getSourceText(CharSourceRange(c->getSourceRange(), true),
sm,
LangOptions()
).str();
file2 << decl_str;
if (CPP2DTools::checkFilename(Context->getSourceManager(), modulename, c))
{
pushStream();
if (locStart.isInvalid())
locStart = sm.getLocForStartOfFile(sm.getMainFileID());
printStmtComment(locStart,
c->getSourceRange().getBegin(),
c->getSourceRange().getEnd(),
true
);
TraverseDecl(c);
std::string const decl = popStream();
if (not decl.empty())
{
printCommentBefore(c);
out() << indentStr() << decl;
if (needSemiComma(c))
out() << ';';
printCommentAfter(c);
}
output_enabled = (isInMacro == 0);
}
}
printStmtComment(locStart, sm.getLocForEndOfFile(sm.getMainFileID()), clang::SourceLocation(), true);
return true;
}
bool DPrinter::TraverseTypedefDecl(TypedefDecl* Decl)
{
if(passDecl(Decl)) return true;
pushStream();
printType(Decl->getUnderlyingType());
std::string const rhs = popStream();
std::string const lhs = mangleName(Decl->getNameAsString());
if (lhs != rhs && rhs.empty() == false)
out() << "alias " << lhs << " = " << rhs;
return true;
}
bool DPrinter::TraverseTypeAliasDecl(TypeAliasDecl* Decl)
{
if(passDecl(Decl)) return true;
pushStream();
printType(Decl->getUnderlyingType());
std::string const rhs = popStream();
std::string const lhs = mangleName(Decl->getNameAsString());
if (lhs != rhs && rhs.empty() == false)
out() << "alias " << lhs << " = " << rhs;
return true;
}
bool DPrinter::TraverseTypeAliasTemplateDecl(TypeAliasTemplateDecl* Decl)
{
if(passDecl(Decl)) return true;
out() << "alias " << mangleName(Decl->getNameAsString());
printTemplateParameterList(Decl->getTemplateParameters(), "");
out() << " = ";
printType(Decl->getTemplatedDecl()->getUnderlyingType());
return true;
}
bool DPrinter::TraverseFieldDecl(FieldDecl* Decl)
{
if(passDecl(Decl)) return true;
std::string const varName = Decl->getNameAsString();
if(varName.find("CPP2D_MACRO_STMT") == 0)
{
if (Decl->hasInClassInitializer())
{
printStmtMacro(varName, Decl->getInClassInitializer());
return true;
}
else
out() << varName << " // NO InClassInitializer! (2)" << std::endl;
}
if(passDecl(Decl)) return true;
if(Decl->isMutable())
out() << "/*mutable*/";
if(Decl->isBitField())
{
out() << "\t";
printType(Decl->getType());
out() << ", \"" << mangleName(varName) << "\", ";
TraverseStmt(Decl->getBitWidth());
out() << ',';
externIncludes["std.bitmanip"].insert("bitfields");
}
else
{
printType(Decl->getType());
out() << " " << mangleName(Decl->getNameAsString());
}
QualType const type = Decl->getType();
if(Decl->hasInClassInitializer())
{
out() << " = ";
TraverseStmt(Decl->getInClassInitializer());
}
else if(!type.getTypePtr()->isPointerType() && getSemantic(Decl->getType()) == TypeOptions::Reference)
{
out() << " = new ";
printType(Decl->getType());
}
return true;
}
bool DPrinter::TraverseDependentNameType(DependentNameType* Type)
{
if(passType(Type)) return false;
if(NestedNameSpecifier* nns = Type->getQualifier())
TraverseNestedNameSpecifier(nns);
out() << Type->getIdentifier()->getName().str();
return true;
}
bool DPrinter::TraverseAttributedType(AttributedType* Type)
{
if(passType(Type)) return false;
printType(Type->getEquivalentType());
return true;
}
bool DPrinter::TraverseDecayedType(DecayedType* Type)
{
if(passType(Type)) return false;
printType(Type->getOriginalType());
return true;
}
bool DPrinter::TraverseElaboratedType(ElaboratedType* Type)
{
if(passType(Type)) return false;
printType(Type->getNamedType());
return true;
}
bool DPrinter::TraverseInjectedClassNameType(InjectedClassNameType* Type)
{
if(passType(Type)) return false;
printType(Type->getInjectedSpecializationType());
return true;
}
bool DPrinter::TraverseSubstTemplateTypeParmType(SubstTemplateTypeParmType* Type)
{
if(passType(Type)) return false;
return true;
}
bool DPrinter::TraverseNestedNameSpecifier(NestedNameSpecifier* NNS)
{
NestedNameSpecifier::SpecifierKind const kind = NNS->getKind();
switch(kind)
{
//case NestedNameSpecifier::Namespace:
//case NestedNameSpecifier::NamespaceAlias:
//case NestedNameSpecifier::Global:
//case NestedNameSpecifier::Super:
case NestedNameSpecifier::TypeSpec:
case NestedNameSpecifier::TypeSpecWithTemplate:
printType(QualType(NNS->getAsType(), 0));
out() << ".";
break;
case NestedNameSpecifier::Identifier:
if(NNS->getPrefix())
TraverseNestedNameSpecifier(NNS->getPrefix());
out() << NNS->getAsIdentifier()->getName().str() << ".";
break;
}
return true;
}
void DPrinter::printTmpArgList(std::string const& tmpArgListStr)
{
out() << "!(" << tmpArgListStr << ')';
}
bool DPrinter::customTypePrinter(NamedDecl* decl)
{
if(decl == nullptr)
return false;
std::string typeName = decl->getQualifiedNameAsString();
for(auto const& name_printer : receiver.customTypePrinters)
{
llvm::Regex RE(name_printer.first);
if(RE.match("::" + typeName))
{
name_printer.second(*this, decl);// TemplateName().getAsTemplateDecl());
return true;
}
}
return false;
}
bool DPrinter::TraverseTemplateSpecializationType(TemplateSpecializationType* Type)
{
if(passType(Type)) return false;
if(customTypePrinter(Type->getAsTagDecl()))
return true;
if(isStdArray(Type->desugar()))
{
printTemplateArgument(Type->getArg(0));
out() << '[';
printTemplateArgument(Type->getArg(1));
out() << ']';
return true;
}
else if(isStdUnorderedMap(Type->desugar()))
{
printTemplateArgument(Type->getArg(1));
out() << '[';
printTemplateArgument(Type->getArg(0));
out() << ']';
return true;
}
out() << printDeclName(Type->getTemplateName().getAsTemplateDecl());
auto const argNum = Type->getNumArgs();
Spliter spliter(*this, ", ");
pushStream();
for(unsigned int i = 0; i < argNum; ++i)
{
spliter.split();
printTemplateArgument(Type->getArg(i));
}
printTmpArgList(popStream());
return true;
}
bool DPrinter::TraverseTypedefType(TypedefType* Type)
{
if(passType(Type)) return false;
if(customTypePrinter(Type->getDecl()))
return true;
out() << printDeclName(Type->getDecl());
return true;
}
template<typename InitList, typename AddBeforeEnd>
void DPrinter::traverseCompoundStmtImpl(CompoundStmt* Stmt, InitList initList, AddBeforeEnd addBeforEnd)
{
SourceLocation locStart = Stmt->getLBracLoc().getLocWithOffset(1);
out() << "{" << std::endl;
++indent;
initList();
for(auto child : Stmt->children())
{
printStmtComment(locStart,
child->getLocStart(),
child->getLocEnd(),
true
);
out() << indentStr();
TraverseStmt(child);
if(needSemiComma(child))
out() << ";";
out() << std::endl;
output_enabled = (isInMacro == 0);
}
printStmtComment(
locStart,
Stmt->getRBracLoc(),
clang::SourceLocation(),
true
);
addBeforEnd();
--indent;
out() << indentStr();
out() << "}";
out() << std::endl;
out() << indentStr();
}
bool DPrinter::TraverseCompoundStmt(CompoundStmt* Stmt)
{
if(passStmt(Stmt)) return false;
traverseCompoundStmtImpl(Stmt, [] {}, [] {});
return true;
}
template<typename InitList>
void DPrinter::traverseCXXTryStmtImpl(CXXTryStmt* Stmt, InitList initList)
{
out() << "try" << std::endl << indentStr();
auto tryBlock = Stmt->getTryBlock();
traverseCompoundStmtImpl(tryBlock, initList, [] {});
auto handlerCount = Stmt->getNumHandlers();
for(decltype(handlerCount) i = 0; i < handlerCount; ++i)
{
out() << std::endl << indentStr();
TraverseStmt(Stmt->getHandler(i));
}
}
bool DPrinter::TraverseCXXTryStmt(CXXTryStmt* Stmt)
{
if(passStmt(Stmt)) return false;
traverseCXXTryStmtImpl(Stmt, [] {});
return true;
}
bool DPrinter::passDecl(Decl* decl)
{
auto printer = receiver.getPrinter(decl);
if(printer)
{
printer(*this, decl);
return true;
}
else
return false;
}
bool DPrinter::passStmt(Stmt* stmt)
{
auto printer = receiver.getPrinter(stmt);
if(printer)
{
printer(*this, stmt);
return true;
}
else
return false;
}
bool DPrinter::passType(clang::Type* type)
{
auto printer = receiver.getPrinter(type);
if(printer)
{
printer(*this, type);
return true;
}
else
return false;
}
bool DPrinter::TraverseNamespaceDecl(NamespaceDecl* Decl)
{
if(passDecl(Decl)) return true;
out() << "// -> module " << mangleName(Decl->getNameAsString()) << ';' << std::endl;
for(auto decl : Decl->decls())
{
pushStream();
TraverseDecl(decl);
std::string const declstr = popStream();
if(not declstr.empty())
{
printCommentBefore(decl);
out() << indentStr() << declstr;
if(needSemiComma(decl))
out() << ';';
printCommentAfter(decl);
out() << std::endl << std::endl;
}
output_enabled = (isInMacro == 0);
}
out() << "// <- module " << mangleName(Decl->getNameAsString()) << " end" << std::endl;
return true;
}
bool DPrinter::TraverseCXXCatchStmt(CXXCatchStmt* Stmt)
{
if(passStmt(Stmt)) return false;
out() << "catch";
if(Stmt->getExceptionDecl())
{
out() << '(';
catchedExceptNames.push(getName(Stmt->getExceptionDecl()->getDeclName()));
traverseVarDeclImpl(Stmt->getExceptionDecl());
out() << ')';
}
else
{
out() << "(Throwable ex)";
catchedExceptNames.push("ex");
}
out() << std::endl;
out() << indentStr();
TraverseStmt(Stmt->getHandlerBlock());
catchedExceptNames.pop();
return true;
}
bool DPrinter::TraverseAccessSpecDecl(AccessSpecDecl* Decl)
{
if(passDecl(Decl)) return true;
return true;
}
void DPrinter::printBasesClass(CXXRecordDecl* decl)
{
Spliter splitBase(*this, ", ");
if(decl->getNumBases() + decl->getNumVBases() != 0)
{
pushStream();
auto printBaseSpec = [&](CXXBaseSpecifier & base)
{
splitBase.split();
TagDecl* tagDecl = base.getType()->getAsTagDecl();
NamedDecl* named = tagDecl ? dyn_cast<NamedDecl>(tagDecl) : nullptr;
if(named && named->getNameAsString() == "noncopyable")
return;
AccessSpecifier const as = base.getAccessSpecifier();
if(as != AccessSpecifier::AS_public)
{
llvm::errs()
<< "error : class " << decl->getNameAsString()
<< " use of base class protection private and protected is no supported\n";
out() << "/*" << AccessSpecifierStr[as] << "*/ ";
}
TraverseType(base.getType());
};
for(CXXBaseSpecifier& base : decl->bases())
printBaseSpec(base);
for(CXXBaseSpecifier& base : decl->vbases())
printBaseSpec(base);
std::string const bases = popStream();
if(not bases.empty())
out() << " : " << bases;
}
}
bool DPrinter::TraverseCXXRecordDecl(CXXRecordDecl* decl)
{
if(passDecl(decl)) return true;
if(decl->isClass())
{
for(auto* ctor : decl->ctors())
{
if(ctor->isImplicit()
&& ctor->isCopyConstructor()
&& not ctor->isDeleted()
&& not isA(decl, "std::exception"))
{
llvm::errs() << "error : class " << decl->getNameAsString() <<
" is copy constructible which is not dlang compatible.\n";
break;
}
}
}
traverseCXXRecordDeclImpl(decl, [] {}, [this, decl] {printBasesClass(decl); });
return true;
}
bool DPrinter::TraverseRecordDecl(RecordDecl* Decl)
{
if(passDecl(Decl)) return true;
traverseCXXRecordDeclImpl(Decl, [] {}, [] {});
return true;
}
template<typename TmpSpecFunc, typename PrintBasesClass>
void DPrinter::traverseCXXRecordDeclImpl(
RecordDecl* decl,
TmpSpecFunc traverseTmpSpecs,
PrintBasesClass printBasesClass)
{
if(decl->isImplicit())
return;
if(decl->isCompleteDefinition() == false && decl->getDefinition() != nullptr)
return;
const bool isClass = decl->isClass();
char const* struct_class =
decl->isClass() ? "class" :
decl->isUnion() ? "union" :
"struct";
TypedefNameDecl* typedefDecl = decl->getTypedefNameForAnonDecl();
if (typedefDecl)
out() << struct_class << " " << mangleName(typedefDecl->getNameAsString());
else
out() << struct_class << " " << mangleName(decl->getNameAsString());
traverseTmpSpecs();
if(decl->isCompleteDefinition() == false)
return;
printBasesClass();
out() << std::endl << indentStr() << "{";
++indent;
auto isBitField = [this](Decl * decl2) -> int
{
if(FieldDecl* field = llvm::dyn_cast<FieldDecl>(decl2))
{
if(field->isBitField())
return static_cast<int>(field->getBitWidthValue(*Context));
else
return - 1;
}
else
return -1;
};
auto roundPow2 = [](int bit_count)
{
return
bit_count <= 0 ? 0 :
bit_count <= 8 ? 8 :
bit_count <= 16 ? 16 :
bit_count <= 32 ? 32 : //-V112
64;
};
int bit_count = 0;
bool inBitField = false;
AccessSpecifier access = AccessSpecifier::AS_public;
for(Decl* decl2 : decl->decls())
{
pushStream();
int const bc = isBitField(decl2);
bool const nextIsBitField = (bc >= 0);
if(nextIsBitField)
bit_count += bc;
else if(bit_count != 0)
out() << "\tuint, \"\", " << (roundPow2(bit_count) - bit_count) << "));\n"
<< indentStr();
TraverseDecl(decl2);
std::string const declstr = popStream();
if(not declstr.empty())
{
AccessSpecifier newAccess = decl2->getAccess();
if(newAccess == AccessSpecifier::AS_none)
newAccess = AccessSpecifier::AS_public;
if(newAccess == AccessSpecifier::AS_private)
{
// A private method can't be virtual in D => change them to protected
if(auto* meth = dyn_cast<CXXMethodDecl>(decl2))
{
if(meth->isVirtual())
newAccess = AccessSpecifier::AS_protected;
}
}
if(newAccess != access && (isInMacro == 0))
{
--indent;
out() << std::endl << indentStr() << AccessSpecifierStr[newAccess] << ":";
++indent;
access = newAccess;
}
printCommentBefore(decl2);
if(inBitField == false && nextIsBitField && (isInMacro == 0))
out() << "mixin(bitfields!(\n" << indentStr();
out() << declstr;
if(needSemiComma(decl2) && nextIsBitField == false)
out() << ";";
printCommentAfter(decl2);
}
inBitField = nextIsBitField;
if(nextIsBitField == false)
bit_count = 0;
output_enabled = (isInMacro == 0);
}
if(inBitField)
out() << "\n" << indentStr() << "\tuint, \"\", "
<< (roundPow2(bit_count) - bit_count) << "));";
out() << std::endl;
//Print all free operator inside the class scope
auto record_name = decl->getTypeForDecl()->getCanonicalTypeInternal().getAsString();
for(auto rng = receiver.freeOperator.equal_range(record_name);
rng.first != rng.second;
++rng.first)
{
out() << indentStr();
traverseFunctionDeclImpl(const_cast<FunctionDecl*>(rng.first->second), 0);
out() << std::endl;
}
for(auto rng = receiver.freeOperatorRight.equal_range(record_name);
rng.first != rng.second;
++rng.first)
{
out() << indentStr();
traverseFunctionDeclImpl(const_cast<FunctionDecl*>(rng.first->second), 1);
out() << std::endl;
}
// print the opCmd operator
if(auto* cxxRecordDecl = dyn_cast<CXXRecordDecl>(decl))
{
ClassInfo const& classInfo = classInfoMap[cxxRecordDecl];
for(auto && type_info : classInfoMap[cxxRecordDecl].relations)
{
clang::Type const* type = type_info.first;
RelationInfo& info = type_info.second;
if(info.hasOpLess and info.hasOpEqual)
{
out() << indentStr() << "int opCmp(ref in ";
printType(type->getPointeeType());
out() << " other)";
if(portConst)
out() << " const";
out() << "\n";
out() << indentStr() << "{\n";
++indent;
out() << indentStr() << "return _opLess(other) ? -1: ((this == other)? 0: 1);\n";
--indent;
out() << indentStr() << "}\n";
}
}
if(classInfo.hasOpExclaim and not classInfo.hasBoolConv)
{
out() << indentStr() << "bool opCast(T : bool)()";
if(portConst)
out() << " const";
out() << "\n";
out() << indentStr() << "{\n";
++indent;
out() << indentStr() << "return !_opExclaim();\n";
--indent;
out() << indentStr() << "}\n";
}
}
--indent;
out() << indentStr() << "}";
}
void DPrinter::printTemplateParameterList(TemplateParameterList* tmpParams,
std::string const& prevTmplParmsStr)
{
out() << "(";
Spliter spliter1(*this, ", ");
if(prevTmplParmsStr.empty() == false)
{
spliter1.split();
out() << prevTmplParmsStr;
}
for(unsigned int i = 0, size = tmpParams->size(); i != size; ++i)
{
spliter1.split();
NamedDecl* param = tmpParams->getParam(i);
inTemplateParamList = true;
TraverseDecl(param);
inTemplateParamList = false;
// Print default template arguments
if(auto* FTTP = dyn_cast<TemplateTypeParmDecl>(param))
{
if(FTTP->hasDefaultArgument())
{
out() << " = ";
printType(FTTP->getDefaultArgument());
}
}
else if(auto* FNTTP = dyn_cast<NonTypeTemplateParmDecl>(param))
{
if(FNTTP->hasDefaultArgument())
{
out() << " = ";
TraverseStmt(FNTTP->getDefaultArgument());
}
}
else if(auto* FTTTP = dyn_cast<TemplateTemplateParmDecl>(param))
{
if(FTTTP->hasDefaultArgument())
{
out() << " = ";
printTemplateArgument(FTTTP->getDefaultArgument().getArgument());
}
}
}
out() << ')';
}
bool DPrinter::TraverseClassTemplateDecl(ClassTemplateDecl* Decl)
{
if(passDecl(Decl)) return true;
traverseCXXRecordDeclImpl(Decl->getTemplatedDecl(), [Decl, this]
{
printTemplateParameterList(Decl->getTemplateParameters(), "");
},
[this, Decl] {printBasesClass(Decl->getTemplatedDecl()); });
return true;
}
TemplateParameterList* DPrinter::getTemplateParameters(ClassTemplateSpecializationDecl*)
{
return nullptr;
}
TemplateParameterList* DPrinter::getTemplateParameters(
ClassTemplatePartialSpecializationDecl* Decl)
{
return Decl->getTemplateParameters();
}
bool DPrinter::TraverseClassTemplatePartialSpecializationDecl(
ClassTemplatePartialSpecializationDecl* Decl)
{
if(passDecl(Decl)) return true;
traverseClassTemplateSpecializationDeclImpl(Decl, Decl->getTemplateArgsAsWritten());
return true;
}
bool DPrinter::TraverseClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl* Decl)
{
if(passDecl(Decl)) return true;
traverseClassTemplateSpecializationDeclImpl(Decl, nullptr);
return true;
}
void DPrinter::printTemplateArgument(TemplateArgument const& ta)
{
switch(ta.getKind())
{
case TemplateArgument::Null: break;
case TemplateArgument::Declaration: TraverseDecl(ta.getAsDecl()); break;
case TemplateArgument::Integral: out() << ta.getAsIntegral().toString(10); break;
case TemplateArgument::NullPtr: out() << "null"; break;
case TemplateArgument::Type: printType(ta.getAsType()); break;
case TemplateArgument::Pack:
{
Spliter split(*this, ", ");
for(TemplateArgument const& arg : ta.pack_elements())
split.split(), printTemplateArgument(arg);
break;
}
default: TraverseTemplateArgument(ta);
}
}
void DPrinter::printTemplateSpec_TmpArgsAndParms(
TemplateParameterList& primaryTmpParams,
TemplateArgumentList const& tmpArgs,
const ASTTemplateArgumentListInfo* tmpArgsInfo,
TemplateParameterList* newTmpParams,
std::string const& prevTmplParmsStr
)
{
assert(tmpArgs.size() == primaryTmpParams.size());
out() << '(';
Spliter spliter2(*this, ", ");
if(prevTmplParmsStr.empty() == false)
{
spliter2.split();
out() << prevTmplParmsStr;
}
if(newTmpParams)
{
for(decltype(newTmpParams->size()) i = 0, size = newTmpParams->size(); i != size; ++i)
{
NamedDecl* parmDecl = newTmpParams->getParam(i);
IdentifierInfo* info = parmDecl->getIdentifier();
std::string name = info->getName().str() + "_";
renamedIdentifiers[info] = name;
}
}
auto printRedefinedTmp = [&](NamedDecl * tmpl, TemplateArgument const & tmplDef)
{
spliter2.split();
renameIdentifiers = false;
TraverseDecl(tmpl);
renameIdentifiers = true;
out() << " : ";
printTemplateArgument(tmplDef);
};
if(tmpArgsInfo)
{
for(unsigned i = 0, size = tmpArgsInfo->NumTemplateArgs; i != size; ++i)
printRedefinedTmp(primaryTmpParams.getParam(i), (*tmpArgsInfo)[i].getArgument());
}
else
{
for(decltype(tmpArgs.size()) i = 0, size = tmpArgs.size(); i != size; ++i)
printRedefinedTmp(primaryTmpParams.getParam(i), tmpArgs.get(i));
}
if(newTmpParams)
{
for(decltype(newTmpParams->size()) i = 0, size = newTmpParams->size(); i != size; ++i)
{
spliter2.split();
TraverseDecl(newTmpParams->getParam(i));
}
}
out() << ')';
}
template<typename D>
void DPrinter::traverseClassTemplateSpecializationDeclImpl(
D* Decl,
const ASTTemplateArgumentListInfo* tmpArgsInfo
)
{
if(Decl->getSpecializationKind() == TSK_ExplicitInstantiationDeclaration
|| Decl->getSpecializationKind() == TSK_ExplicitInstantiationDefinition
|| Decl->getSpecializationKind() == TSK_ImplicitInstantiation)
return;
TemplateParameterList* tmpParams = getTemplateParameters(Decl);
if(tmpParams)
{
unsigned Depth = tmpParams->getDepth();
for(decltype(tmpParams->size()) i = 0, size = tmpParams->size(); i != size; ++i)
templateArgsStack[Depth][i] = tmpParams->getParam(i);
}
TemplateParameterList& specializedTmpParams =
*Decl->getSpecializedTemplate()->getTemplateParameters();
TemplateArgumentList const& tmpArgs = Decl->getTemplateArgs();
traverseCXXRecordDeclImpl(Decl, [&]
{
printTemplateSpec_TmpArgsAndParms(specializedTmpParams, tmpArgs, tmpArgsInfo, tmpParams, "");
},
[this, Decl] {printBasesClass(Decl); });
if(tmpParams)
templateArgsStack[tmpParams->getDepth()].clear();
}
bool DPrinter::TraverseCXXConversionDecl(CXXConversionDecl* Decl)
{
if(passDecl(Decl)) return true;
traverseFunctionDeclImpl(Decl);
return true;
}
bool DPrinter::TraverseCXXConstructorDecl(CXXConstructorDecl* Decl)
{
if(passDecl(Decl)) return true;
traverseFunctionDeclImpl(Decl);
return true;
}
bool DPrinter::TraverseCXXDestructorDecl(CXXDestructorDecl* Decl)
{
if(passDecl(Decl)) return true;
traverseFunctionDeclImpl(Decl);
return true;
}
bool DPrinter::TraverseCXXMethodDecl(CXXMethodDecl* Decl)
{
if(passDecl(Decl)) return true;
if(Decl->getLexicalParent() == Decl->getParent())
traverseFunctionDeclImpl(Decl);
return true;
}
bool DPrinter::TraversePredefinedExpr(PredefinedExpr* expr)
{
if(passStmt(expr)) return true;
out() << "__PRETTY_FUNCTION__";
return true;
}
bool DPrinter::TraverseCXXDefaultArgExpr(CXXDefaultArgExpr* expr)
{
if(passStmt(expr)) return true;
TraverseStmt(expr->getExpr());
return true;
}
bool DPrinter::TraverseCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr* Expr)
{
if(passStmt(Expr)) return true;
printType(Expr->getTypeAsWritten());
Spliter spliter(*this, ", ");
out() << "(";
for(decltype(Expr->arg_size()) i = 0; i < Expr->arg_size(); ++i)
{
auto arg = Expr->getArg(i);
if(arg->getStmtClass() != Stmt::StmtClass::CXXDefaultArgExprClass)
{
spliter.split();
TraverseStmt(arg);
}
}
out() << ")";
return true;
}
bool DPrinter::TraverseCXXForRangeStmt(CXXForRangeStmt* Stmt)
{
if(passStmt(Stmt)) return false;
out() << "foreach(";
refAccepted = true;
inForRangeInit = true;
traverseVarDeclImpl(dyn_cast<VarDecl>(Stmt->getLoopVarStmt()->getSingleDecl()));
inForRangeInit = false;
refAccepted = false;
out() << "; ";
Expr* rangeInit = Stmt->getRangeInit();
TraverseStmt(rangeInit);
if(TagDecl* rangeInitDecl = rangeInit->getType()->getAsTagDecl())
{
if(isStdUnorderedMap(QualType(rangeInitDecl->getTypeForDecl(), 0)))
out() << ".byKeyValue";
}
out() << ")" << std::endl;
traverseCompoundStmtOrNot(Stmt->getBody());
return true;
}
bool DPrinter::TraverseDoStmt(DoStmt* Stmt)
{
if(passStmt(Stmt)) return false;
out() << "do" << std::endl;
traverseCompoundStmtOrNot(Stmt->getBody());
out() << "while(";
TraverseStmt(Stmt->getCond());
out() << ")";
return true;
}
bool DPrinter::TraverseSwitchStmt(SwitchStmt* Stmt)
{
if(passStmt(Stmt)) return false;
out() << "switch(";
TraverseStmt(Stmt->getCond());
out() << ")" << std::endl << indentStr();
if (auto* body = dyn_cast<CompoundStmt>(Stmt->getBody()))
{
auto* last = dyn_cast<DefaultStmt>(body->body_back());
if(last)
traverseCompoundStmtImpl(body, [] {}, [] {});
else
traverseCompoundStmtImpl(
body, [] {}, [this] {out() << indentStr() << "default: break;\n"; });
}
return true;
}
bool DPrinter::TraverseCaseStmt(CaseStmt* Stmt)
{
if(passStmt(Stmt)) return false;
out() << "case ";
TraverseStmt(Stmt->getLHS());
out() << ":" << std::endl;
++indent;
out() << indentStr();
TraverseStmt(Stmt->getSubStmt());
--indent;
return true;
}
bool DPrinter::TraverseBreakStmt(BreakStmt* Stmt)
{
if(passStmt(Stmt)) return false;
out() << "break";
return true;
}
bool DPrinter::TraverseContinueStmt(ContinueStmt* Stmt)
{
if(passStmt(Stmt)) return false;
out() << "continue";
return true;
}
bool DPrinter::TraverseStaticAssertDecl(StaticAssertDecl* Decl)
{
if(passDecl(Decl)) return true;
out() << "static assert(";
TraverseStmt(Decl->getAssertExpr());
out() << ", ";
TraverseStmt(Decl->getMessage());
out() << ")";
return true;
}
bool DPrinter::TraverseDefaultStmt(DefaultStmt* Stmt)
{
if(passStmt(Stmt)) return false;
out() << "default:" << std::endl;
++indent;
out() << indentStr();
TraverseStmt(Stmt->getSubStmt());
--indent;
return true;
}
bool DPrinter::TraverseCXXDeleteExpr(CXXDeleteExpr* Expr)
{
if(passStmt(Expr)) return true;
TraverseStmt(Expr->getArgument());
out() << " = null";
return true;
}
bool DPrinter::TraverseCXXNewExpr(CXXNewExpr* Expr)
{
if(passStmt(Expr)) return true;
out() << "new ";
if(Expr->isArray())
{
printType(Expr->getAllocatedType());
out() << '[';
TraverseStmt(Expr->getArraySize());
out() << ']';
}
else
{
switch(Expr->getInitializationStyle())
{
case CXXNewExpr::NoInit:
printType(Expr->getAllocatedType());
break;
case CXXNewExpr::CallInit:
printType(Expr->getAllocatedType());
out() << '(';
TraverseStmt(const_cast<CXXConstructExpr*>(Expr->getConstructExpr()));
out() << ')';
break;
case CXXNewExpr::ListInit:
TraverseStmt(Expr->getInitializer());
break;
}
}
return true;
}
void DPrinter::printCXXConstructExprParams(CXXConstructExpr* Init)
{
if(Init->getNumArgs() == 1) //Handle Copy ctor
{
QualType recordType = Init->getType();
recordType.addConst();
if(recordType == Init->getArg(0)->getType())
{
TraverseStmt(Init->getArg(0));
return;
}
}
printType(Init->getType());
out() << '(';
Spliter spliter(*this, ", ");
size_t counter = 0;
TypeOptions::Semantic const sem = getSemantic(Init->getType());
for(auto arg : Init->arguments())
{
if(arg->getStmtClass() == Stmt::StmtClass::CXXDefaultArgExprClass
&& ((counter != 0) || sem != TypeOptions::Value))
break;
spliter.split();
TraverseStmt(arg);
++counter;
}
out() << ')';
}
bool DPrinter::TraverseCXXConstructExpr(CXXConstructExpr* Init)
{
if(passStmt(Init)) return true;
if(Init->isListInitialization() && !Init->isStdInitListInitialization())
out() << '{';
Spliter spliter(*this, ", ");
size_t count = 0;
for(unsigned i = 0, e = Init->getNumArgs(); i != e; ++i)
{
if(isa<CXXDefaultArgExpr>(Init->getArg(i)) && (count != 0))
break; // Don't print any defaulted arguments
spliter.split();
TraverseStmt(Init->getArg(i));
++count;
}
if(Init->isListInitialization() && !Init->isStdInitListInitialization())
out() << '}';
return true;
}
void DPrinter::printType(QualType const& type)
{
if(type.getTypePtr()->getTypeClass() == clang::Type::TypeClass::Auto)
{
if(type.isConstQualified() && portConst)
out() << "const ";
TraverseType(type);
}
else
{
bool printConst = portConst || isa<BuiltinType>(type->getCanonicalTypeUnqualified());
if(type.isConstQualified() && printConst)
out() << "const(";
TraverseType(type);
if(type.isConstQualified() && printConst)
out() << ')';
}
}
template<typename T>
T* dynCastAcrossCleanup(Expr* expr)
{
if(auto* cleanup = dyn_cast<ExprWithCleanups>(expr))
expr = cleanup->getSubExpr();
return dyn_cast<T>(expr);
}
bool DPrinter::TraverseConstructorInitializer(CXXCtorInitializer* Init)
{
if(Init->isAnyMemberInitializer())
{
if(Init->getInit()->getStmtClass() == Stmt::StmtClass::CXXDefaultInitExprClass)
return true;
FieldDecl* fieldDecl = Init->getAnyMember();
TypeOptions::Semantic const sem = getSemantic(fieldDecl->getType());
out() << fieldDecl->getNameAsString();
out() << " = ";
if(sem == TypeOptions::Value)
{
Expr* init = Init->getInit();
if(auto* parenListExpr = dyn_cast<ParenListExpr>(init))
{
if(parenListExpr->getNumExprs() > 1)
{
printType(fieldDecl->getType());
out() << '(';
}
TraverseStmt(Init->getInit());
if(parenListExpr->getNumExprs() > 1)
out() << ')';
}
else if(auto* ctorExpr = dyn_cast<CXXConstructExpr>(init))
{
if(ctorExpr->getNumArgs() > 1)
{
printType(fieldDecl->getType());
out() << '(';
}
TraverseStmt(Init->getInit());
if(ctorExpr->getNumArgs() > 1)
out() << ')';
}
else
TraverseStmt(Init->getInit());
}
else
{
isThisFunctionUsefull = true;
Expr* init = Init->getInit();
if(auto* ctor = dynCastAcrossCleanup<CXXConstructExpr>(init))
{
if(ctor->getNumArgs() == 1)
{
QualType initType = ctor->getArg(0)->getType().getCanonicalType();
QualType fieldType = fieldDecl->getType().getCanonicalType();
initType.removeLocalConst();
fieldType.removeLocalConst();
if(fieldType == initType)
{
TraverseStmt(init);
out() << ".dup()";
return true;
}
}
if(sem == TypeOptions::AssocArray)
{
if(ctor->getNumArgs() == 0 || isa<CXXDefaultArgExpr>(*ctor->arg_begin()))
return true;
}
}
if (fieldDecl->getType()->isPointerType())
TraverseStmt(init);
else
{
out() << "new ";
printType(fieldDecl->getType());
out() << '(';
TraverseStmt(init);
out() << ')';
}
}
}
else if(Init->isWritten())
{
assert(Init->isBaseInitializer());
Expr* decl = Init->getInit();
CXXConstructorDecl* ctorDecl = llvm::dyn_cast<CXXConstructExpr>(decl)->getConstructor();
if (ctorDecl->isDefaulted() == false)
{
out() << "super(";
TraverseStmt(Init->getInit());
out() << ")";
}
}
return true;
}
void DPrinter::startCtorBody(FunctionDecl*) {}
void DPrinter::startCtorBody(CXXConstructorDecl* Decl)
{
auto ctor_init_count = Decl->getNumCtorInitializers();
if(ctor_init_count != 0)
{
for(CXXCtorInitializer* init : Decl->inits())
{
pushStream();
TraverseConstructorInitializer(init);
std::string const initStr = popStream();
if(initStr.empty() == false)
{
// If nothing to print, default init is enought.
if(initStr.substr(initStr.size() - 2) != "= ")
{
out() << std::endl << indentStr();
out() << initStr;
out() << ";";
}
}
}
}
}
void DPrinter::printFuncEnd(FunctionDecl*) {}
void DPrinter::printFuncEnd(CXXMethodDecl* Decl)
{
if(Decl->isConst() && portConst)
out() << " const";
}
void DPrinter::printSpecialMethodAttribute(CXXMethodDecl* Decl)
{
if(Decl->isStatic())
out() << "static ";
CXXRecordDecl* record = Decl->getParent();
if(record->isClass())
{
if(Decl->isPure())
out() << "abstract ";
if(Decl->size_overridden_methods() != 0)
out() << "override ";
if(Decl->isVirtual() == false)
out() << "final ";
}
else
{
if(Decl->isPure())
{
llvm::errs() << "struct " << record->getName()
<< " has abstract function, which is forbiden.\n";
out() << "abstract ";
}
if(Decl->isVirtual())
{
llvm::errs() << "struct " << record->getName()
<< " has virtual function, which is forbiden.\n";
out() << "virtual ";
}
if(Decl->size_overridden_methods() != 0)
out() << "override ";
}
}
bool DPrinter::printFuncBegin(CXXMethodDecl* Decl, std::string& tmpParams, int arg_become_this)
{
if(not Decl->isPure() && Decl->getBody() == nullptr)
return false;
if(Decl->isImplicit())
return false;
if(Decl->isMoveAssignmentOperator())
return false;
if(Decl->isOverloadedOperator()
&& Decl->getOverloadedOperator() == OverloadedOperatorKind::OO_ExclaimEqual)
return false;
printSpecialMethodAttribute(Decl);
printFuncBegin((FunctionDecl*)Decl, tmpParams, arg_become_this);
return true;
}
bool DPrinter::printFuncBegin(FunctionDecl* Decl, std::string& tmpParams, int arg_become_this)
{
if(Decl->isImplicit())
return false;
if(Decl->isOverloadedOperator()
&& Decl->getOverloadedOperator() == OverloadedOperatorKind::OO_ExclaimEqual)
return false;
std::string const name = Decl->getNameAsString();
if(name == "cpp2d_dummy_variadic")
return false;
printType(Decl->getReturnType());
out() << " ";
if(Decl->isOverloadedOperator())
{
QualType arg1Type;
QualType arg2Type;
CXXRecordDecl* arg1Record = nullptr;
CXXRecordDecl* arg2Record = nullptr;
auto getRecordType = [](QualType qt)
{
if(auto const* lval = dyn_cast<LValueReferenceType>(qt.getTypePtr()))
{
return lval->getPointeeType()->getAsCXXRecordDecl();
}
else
{
return qt->getAsCXXRecordDecl();
}
};
if(auto* methodDecl = dyn_cast<CXXMethodDecl>(Decl))
{
arg1Type = methodDecl->getThisType(*Context);
arg1Record = methodDecl->getParent();
if(methodDecl->getNumParams() > 0)
{
arg2Type = methodDecl->getParamDecl(0)->getType();
arg2Record = getRecordType(arg2Type);
}
}
else
{
if(Decl->getNumParams() > 0)
{
arg1Type = Decl->getParamDecl(0)->getType();
arg1Record = getRecordType(arg1Type);
}
if(Decl->getNumParams() > 1)
{
arg2Type = Decl->getParamDecl(1)->getType();
arg2Record = getRecordType(arg2Type);
}
}
auto const nbArgs = (arg_become_this == -1 ? 1 : 0) + Decl->getNumParams();
std::string const right = (arg_become_this == 1) ? "Right" : "";
OverloadedOperatorKind const opKind = Decl->getOverloadedOperator();
if(opKind == OverloadedOperatorKind::OO_EqualEqual)
{
out() << "opEquals" + right;
if(arg1Record)
classInfoMap[arg1Record].relations[arg2Type.getTypePtr()].hasOpEqual = true;
if(arg2Record)
classInfoMap[arg2Record].relations[arg1Type.getTypePtr()].hasOpEqual = true;
}
else if(opKind == OverloadedOperatorKind::OO_Exclaim)
{
out() << "_opExclaim" + right;
if(arg1Record)
classInfoMap[arg1Record].hasOpExclaim = true;
}
else if(opKind == OverloadedOperatorKind::OO_Call)
out() << "opCall" + right;
else if(opKind == OverloadedOperatorKind::OO_Subscript)
out() << "opIndex" + right;
else if(opKind == OverloadedOperatorKind::OO_Equal)
out() << "opAssign" + right;
else if(opKind == OverloadedOperatorKind::OO_Less)
{
out() << "_opLess" + right;
if(arg1Record)
classInfoMap[arg1Record].relations[arg2Type.getTypePtr()].hasOpLess = true;
}
else if(opKind == OverloadedOperatorKind::OO_LessEqual)
out() << "_opLessEqual" + right;
else if(opKind == OverloadedOperatorKind::OO_Greater)
out() << "_opGreater" + right;
else if(opKind == OverloadedOperatorKind::OO_GreaterEqual)
out() << "_opGreaterEqual" + right;
else if(opKind == OverloadedOperatorKind::OO_PlusPlus && nbArgs == 2)
out() << "_opPostPlusplus" + right;
else if(opKind == OverloadedOperatorKind::OO_MinusMinus && nbArgs == 2)
out() << "_opPostMinusMinus" + right;
else
{
std::string spelling = getOperatorSpelling(opKind);
if(nbArgs == 1)
out() << "opUnary" + right;
else // Two args
{
if(spelling.back() == '=') //Handle self assign operators
{
out() << "opOpAssign";
spelling.resize(spelling.size() - 1);
}
else
out() << "opBinary" + right;
}
tmpParams = "string op: \"" + spelling + "\"";
}
}
else
out() << mangleName(name);
return true;
}
bool DPrinter::printFuncBegin(CXXConversionDecl* Decl, std::string& tmpParams, int)
{
printSpecialMethodAttribute(Decl);
printType(Decl->getConversionType());
out() << " opCast";
pushStream();
out() << "T : ";
if(Decl->getConversionType().getAsString() == "bool")
classInfoMap[Decl->getParent()].hasBoolConv = true;
printType(Decl->getConversionType());
tmpParams = popStream();
return true;
}
bool DPrinter::printFuncBegin(CXXConstructorDecl* Decl,
std::string&, //tmpParams
int //arg_become_this = -1
)
{
if(Decl->isMoveConstructor() || Decl->getBody() == nullptr)
return false;
CXXRecordDecl* record = Decl->getParent();
if(record->isStruct() || record->isUnion())
{
if(Decl->isDefaultConstructor() && Decl->getNumParams() == 0)
{
if(Decl->isExplicit() && Decl->isDefaulted() == false)
{
llvm::errs() << "error : " << Decl->getNameAsString()
<< " struct has an explicit default ctor.\n";
llvm::errs() << "\tThis is illegal in D language.\n";
llvm::errs() << "\tRemove it, default it or replace it by a factory method.\n";
}
return false; //If default struct ctor : don't print
}
}
else
{
if(Decl->isImplicit() && !Decl->isDefaultConstructor())
return false;
}
out() << "this";
return true;
}
bool DPrinter::printFuncBegin(CXXDestructorDecl* decl,
std::string&, //tmpParams,
int //arg_become_this = -1
)
{
if(decl->isImplicit() || decl->getBody() == nullptr)
return false;
//if(Decl->isPure() && !Decl->hasBody())
// return false; //ctor and dtor can't be abstract
//else
out() << "~this";
return true;
}
template<typename Decl>
TypeOptions::Semantic getThisSemantic(Decl* decl, ASTContext& context)
{
if(decl->isStatic())
return TypeOptions::Reference;
auto* recordPtrType = dyn_cast<clang::PointerType>(decl->getThisType(context));
return DPrinter::getSemantic(recordPtrType->getPointeeType());
}
TypeOptions::Semantic getThisSemantic(FunctionDecl*, ASTContext&)
{
return TypeOptions::Reference;
}
template<typename D>
void DPrinter::traverseFunctionDeclImpl(
D* Decl,
int arg_become_this)
{
if(Decl->isDeleted())
return;
if(Decl->isImplicit() && Decl->getBody() == nullptr)
return;
if(Decl != Decl->getCanonicalDecl() &&
not(Decl->getTemplatedKind() == FunctionDecl::TK_FunctionTemplateSpecialization
&& Decl->isThisDeclarationADefinition()))
return;
pushStream();
refAccepted = true;
std::string const name = Decl->getQualifiedNameAsString();
bool const isMain = name == "main";
std::string tmplParamsStr;
if(printFuncBegin(Decl, tmplParamsStr, arg_become_this) == false)
{
refAccepted = false;
popStream();
return;
}
bool tmplPrinted = false;
switch(Decl->getTemplatedKind())
{
case FunctionDecl::TK_MemberSpecialization:
case FunctionDecl::TK_NonTemplate:
break;
case FunctionDecl::TK_FunctionTemplate:
if(FunctionTemplateDecl* tDecl = Decl->getDescribedFunctionTemplate())
{
printTemplateParameterList(tDecl->getTemplateParameters(), tmplParamsStr);
tmplPrinted = true;
}
break;
case FunctionDecl::TK_FunctionTemplateSpecialization:
case FunctionDecl::TK_DependentFunctionTemplateSpecialization:
if(FunctionTemplateDecl* tDecl = Decl->getPrimaryTemplate())
{
TemplateParameterList* primaryTmpParams = tDecl->getTemplateParameters();
TemplateArgumentList const* tmpArgs = Decl->getTemplateSpecializationArgs();
assert(primaryTmpParams && tmpArgs);
printTemplateSpec_TmpArgsAndParms(
*primaryTmpParams,
*tmpArgs,
Decl->getTemplateSpecializationArgsAsWritten(),
nullptr,
tmplParamsStr);
tmplPrinted = true;
}
break;
default: assert(false && "Inconststent clang::FunctionDecl::TemplatedKind");
}
if(not tmplPrinted and not tmplParamsStr.empty())
out() << '(' << tmplParamsStr << ')';
out() << "(";
inFuncParams = true;
bool isConstMethod = false;
auto* ctorDecl = dyn_cast<CXXConstructorDecl>(Decl);
bool const isCopyCtor = ctorDecl && ctorDecl->isCopyConstructor();
TypeOptions::Semantic const sem = getThisSemantic(Decl, *Context);
if(Decl->getNumParams() != 0)
{
TypeSourceInfo* declSourceInfo = Decl->getTypeSourceInfo();
FunctionTypeLoc funcTypeLoc;
SourceLocation locStart;
auto isConst = [](QualType type)
{
if(auto* ref = dyn_cast<LValueReferenceType>(type.getTypePtr()))
return ref->getPointeeType().isConstQualified();
else
return type.isConstQualified();
};
++indent;
size_t index = 0;
size_t const numParam =
Decl->getNumParams() +
(Decl->isVariadic() ? 1 : 0) +
((arg_become_this == -1) ? 0 : -1);
FunctionDecl* bodyDecl = Decl;
for(FunctionDecl* decl : Decl->redecls()) //Print params of the function definition
if(decl != bodyDecl) // rather than the function declaration
{
bodyDecl = decl;
declSourceInfo = bodyDecl->getTypeSourceInfo();
}
if(declSourceInfo)
{
TypeLoc declTypeLoc = declSourceInfo->getTypeLoc();
TypeLoc::TypeLocClass tlClass = declTypeLoc.getTypeLocClass();
if(tlClass == TypeLoc::TypeLocClass::FunctionProto)
{
funcTypeLoc = declTypeLoc.castAs<FunctionTypeLoc>();
locStart = funcTypeLoc.getLParenLoc().getLocWithOffset(1);
}
}
for(ParmVarDecl* decl : bodyDecl->parameters())
{
if (isMain && Decl->getNumParams() == 2 && decl == bodyDecl->parameters()[0])
{ // Remove the first parameter (argc) of the main function
locStart = decl->getLocEnd();
++index;
continue;
}
if (arg_become_this == static_cast<int>(index))
{
isConstMethod = isConst(decl->getType());
locStart = decl->getLocEnd();
}
else
{
SourceLocation endLoc = decl->getLocEnd();
if (numParam != 1)
{
bool isComment = printStmtComment(locStart,
decl->getLocStart(),
endLoc);
if(not isComment)
out() << std::endl;
out() << indentStr();
}
else
locStart = endLoc;
if(isCopyCtor && sem == TypeOptions::Value)
out() << "this";
else
{
if(index == 0
&& sem == TypeOptions::Value
&& (ctorDecl != nullptr))
printDefaultValue = false;
TraverseDecl(decl);
printDefaultValue = true;
}
if(index < numParam - 1)
out() << ", ";
}
++index;
}
if(Decl->isVariadic())
{
if(numParam != 1)
out() << "\n" << indentStr();
out() << "...";
addExternInclude("core.vararg", "...");
locStart = funcTypeLoc.getRParenLoc(); // the dots doesn't have Decl, but we have to go foreward
}
if (funcTypeLoc.isNull() == false)
{
bool isComment = printStmtComment(locStart, funcTypeLoc.getRParenLoc());
if (not isComment)
out() << std::endl;
}
--indent;
}
if(Decl->getNumParams() != 0)
out() << indentStr() << ')';
else
out() << ')';
if(isConstMethod && portConst)
out() << " const";
printFuncEnd(Decl);
refAccepted = false;
inFuncParams = false;
isThisFunctionUsefull = false;
if(Stmt* body = Decl->getBody())
{
//Stmt* body = Decl->getBody();
out() << std::endl << std::flush;
if(isCopyCtor && sem == TypeOptions::Value)
arg_become_this = 0;
auto alias_this = [Decl, arg_become_this, this]
{
if(arg_become_this >= 0)
{
ParmVarDecl* param = *(Decl->param_begin() + arg_become_this);
std::string const this_name = getName(param->getDeclName());
if(this_name.empty() == false)
out() << indentStr() << "alias " << this_name << " = this;" << std::endl;
}
};
if(body->getStmtClass() == Stmt::CXXTryStmtClass)
{
out() << indentStr() << '{' << std::endl;
++indent;
out() << indentStr();
traverseCXXTryStmtImpl(static_cast<CXXTryStmt*>(body),
[&] {alias_this(); startCtorBody(Decl); });
out() << std::endl;
--indent;
out() << indentStr() << '}';
}
else
{
out() << indentStr();
assert(body->getStmtClass() == Stmt::CompoundStmtClass);
traverseCompoundStmtImpl(static_cast<CompoundStmt*>(body),
[&] {alias_this(); startCtorBody(Decl); },
[] {});
}
}
else
out() << ";";
std::string printedFunction = popStream();
if(not Decl->isImplicit() || isThisFunctionUsefull)
out() << printedFunction;
return;
}
bool DPrinter::TraverseUsingDecl(UsingDecl* Decl)
{
if(passDecl(Decl)) return true;
out() << "//using " << Decl->getNameAsString();
return true;
}
bool DPrinter::TraverseFunctionDecl(FunctionDecl* Decl)
{
if(passDecl(Decl)) return true;
traverseFunctionDeclImpl(Decl);
return true;
}
bool DPrinter::TraverseUsingDirectiveDecl(UsingDirectiveDecl* Decl)
{
if(passDecl(Decl)) return true;
return true;
}
bool DPrinter::TraverseFunctionTemplateDecl(FunctionTemplateDecl* Decl)
{
if(passDecl(Decl)) return true;
FunctionDecl* FDecl = Decl->getTemplatedDecl();
switch(FDecl->getKind())
{
case Decl::Function:
traverseFunctionDeclImpl(FDecl);
return true;
case Decl::CXXMethod:
traverseFunctionDeclImpl(llvm::cast<CXXMethodDecl>(FDecl));
return true;
case Decl::CXXConstructor:
traverseFunctionDeclImpl(llvm::cast<CXXConstructorDecl>(FDecl));
return true;
case Decl::CXXConversion:
traverseFunctionDeclImpl(llvm::cast<CXXConversionDecl>(FDecl));
return true;
case Decl::CXXDestructor:
traverseFunctionDeclImpl(llvm::cast<CXXDestructorDecl>(FDecl));
return true;
default: assert(false && "Inconsistent FunctionDecl kind in FunctionTemplateDecl");
}
return true;
}
bool DPrinter::TraverseBuiltinType(BuiltinType* Type)
{
if(passType(Type)) return false;
out() << [this, Type]
{
BuiltinType::Kind k = Type->getKind();
switch(k)
{
case BuiltinType::Void: return "void";
case BuiltinType::Bool: return "bool";
case BuiltinType::Char_S: return "char";
case BuiltinType::Char_U: return "char";
case BuiltinType::SChar: return "char";
case BuiltinType::Short: return "short";
case BuiltinType::Int: return "int";
case BuiltinType::Long: return "long";
case BuiltinType::LongLong: return "long";
case BuiltinType::Int128: return "cent";
case BuiltinType::UChar: return "ubyte";
case BuiltinType::UShort: return "ushort";
case BuiltinType::UInt: return "uint";
case BuiltinType::ULong: return "ulong";
case BuiltinType::ULongLong: return "ulong";
case BuiltinType::UInt128: return "ucent";
case BuiltinType::Half: return "half";
case BuiltinType::Float: return "float";
case BuiltinType::Double: return "double";
case BuiltinType::LongDouble: return "real";
case BuiltinType::WChar_S:
case BuiltinType::WChar_U: return "wchar";
case BuiltinType::Char16: return "wchar";
case BuiltinType::Char32: return "dchar";
case BuiltinType::NullPtr: return "nullptr_t";
case BuiltinType::Overload: return "<overloaded function type>";
case BuiltinType::BoundMember: return "<bound member function type>";
case BuiltinType::PseudoObject: return "<pseudo-object type>";
case BuiltinType::Dependent: return "<dependent type>";
case BuiltinType::UnknownAny: return "<unknown type>";
case BuiltinType::ARCUnbridgedCast: return "<ARC unbridged cast type>";
case BuiltinType::BuiltinFn: return "<builtin fn type>";
case BuiltinType::ObjCId: return "id";
case BuiltinType::ObjCClass: return "Class";
case BuiltinType::ObjCSel: return "SEL";
default: return Type->getNameAsCString(printingPolicy);
}
}();
return true;
}
TypeOptions::Semantic DPrinter::getSemantic(QualType qt)
{
clang::Type const* type = qt.getTypePtr();
std::string empty;
raw_string_ostream os(empty);
qt.getCanonicalType().getUnqualifiedType().print(os, printingPolicy);
std::string const name = os.str();
// TODO : Externalize the semantic customization
if(name.find("class SafeInt<") == 0)
return TypeOptions::Value;
if(isStdArray(qt))
return TypeOptions::Value;
if(name.find("class std::basic_string<") == 0)
return TypeOptions::Value;
if(name.find("class std::__cxx11::basic_string<") == 0)
return TypeOptions::Value;
if(name.find("class boost::optional<") == 0)
return TypeOptions::Value;
if(name.find("class boost::property_tree::basic_ptree<") == 0)
return TypeOptions::Value;
if(name.find("class std::vector<") == 0)
return TypeOptions::Value;
if(name.find("class std::shared_ptr<") == 0)
return TypeOptions::Value;
if(name.find("class boost::scoped_ptr<") == 0)
return TypeOptions::Value;
if(name.find("class std::unique_ptr<") == 0)
return TypeOptions::Value;
if(isStdUnorderedMap(qt))
return TypeOptions::AssocArray;
if(name.find("class std::set<") == 0)
return TypeOptions::Value;
if(name.find("class std::unordered_set<") == 0)
return TypeOptions::Value;
if(name.find("class std::map<") == 0)
return TypeOptions::Value;
if(name.find("class std::multiset<") == 0)
return TypeOptions::Value;
if(name.find("class std::unordered_multiset<") == 0)
return TypeOptions::Value;
if(name.find("class std::multimap<") == 0)
return TypeOptions::Value;
if(name.find("class std::unordered_multimap<") == 0)
return TypeOptions::Value;
for(auto& nvp : Options::getInstance().types)
{
if(name.find(nvp.first) == 0)
return nvp.second.semantic;
}
if (auto *pt = dyn_cast<clang::PointerType>(type))
return getSemantic(pt->getPointeeType());
else
return (type->isClassType() || type->isFunctionType()) ?
TypeOptions::Reference : TypeOptions::Value;
}
bool DPrinter::isPointer(QualType const& type)
{
if(type->isPointerType())
return true;
QualType const rawType = type.isCanonical() ?
type :
type.getCanonicalType();
std::string const name = rawType.getAsString();
static std::string const arrayNames[] =
{
"class std::shared_ptr<",
"class std::unique_ptr<",
"struct std::shared_ptr<",
"struct std::unique_ptr<",
"class boost::shared_ptr<",
"class boost::scoped_ptr<",
"struct boost::shared_ptr<",
"struct boost::scoped_ptr<",
};
return std::any_of(std::begin(arrayNames), std::end(arrayNames), [&](auto && arrayName)
{
return name.find(arrayName) == 0;
});
}
template<typename PType>
void DPrinter::traversePointerTypeImpl(PType* Type)
{
QualType const pointee = Type->getPointeeType();
clang::Type::TypeClass const tc = pointee->getTypeClass();
if(tc == clang::Type::Paren) //function pointer do not need '*'
{
auto innerType = static_cast<ParenType const*>(pointee.getTypePtr())->getInnerType();
if(innerType->getTypeClass() == clang::Type::FunctionProto)
{
TraverseType(innerType);
return;
}
}
printType(pointee);
out() << ((getSemantic(pointee) == TypeOptions::Value) ? "[]" : ""); //'*';
}
bool DPrinter::TraverseMemberPointerType(MemberPointerType* Type)
{
if(passType(Type)) return false;
traversePointerTypeImpl(Type);
return true;
}
bool DPrinter::TraversePointerType(clang::PointerType* Type)
{
if(passType(Type)) return false;
traversePointerTypeImpl(Type);
return true;
}
bool DPrinter::TraverseCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr* Expr)
{
if(passStmt(Expr)) return true;
out() << "null";
return true;
}
bool DPrinter::TraverseEnumConstantDecl(EnumConstantDecl* Decl)
{
if(passDecl(Decl)) return true;
out() << mangleName(Decl->getNameAsString());
if(Decl->getInitExpr())
{
out() << " = ";
TraverseStmt(Decl->getInitExpr());
}
return true;
}
bool DPrinter::TraverseEnumDecl(EnumDecl* Decl)
{
if(passDecl(Decl)) return true;
out() << "enum";
if (Decl->getDeclName()) {
out() << " " << mangleName(Decl->getNameAsString());
}
if(Decl->isFixed())
{
out() << " : ";
TraverseType(Decl->getIntegerType());
}
out() << std::endl << indentStr() << "{" << std::endl;
++indent;
size_t count = 0;
for(auto e : Decl->enumerators())
{
++count;
out() << indentStr();
TraverseDecl(e);
out() << "," << std::endl;
}
if(count == 0)
out() << indentStr() << "Default" << std::endl;
--indent;
out() << indentStr() << "}";
return true;
}
bool DPrinter::TraverseEnumType(EnumType* Type)
{
if(passType(Type)) return false;
out() << printDeclName(Type->getDecl());
return true;
}
bool DPrinter::TraverseIntegerLiteral(IntegerLiteral* Stmt)
{
if(passStmt(Stmt)) return true;
out() << Stmt->getValue().toString(10, true);
return true;
}
bool DPrinter::TraverseDecltypeType(DecltypeType* Type)
{
if(passType(Type)) return false;
out() << "typeof(";
TraverseStmt(Type->getUnderlyingExpr());
out() << ')';
return true;
}
bool DPrinter::TraverseAutoType(AutoType* Type)
{
if(passType(Type)) return false;
if(not inForRangeInit)
out() << "auto";
return true;
}
bool DPrinter::TraverseLinkageSpecDecl(LinkageSpecDecl* Decl)
{
if(passDecl(Decl)) return true;
switch(Decl->getLanguage())
{
case LinkageSpecDecl::LanguageIDs::lang_c: out() << "extern (C) "; break;
case LinkageSpecDecl::LanguageIDs::lang_cxx: out() << "extern (C++) "; break;
default: assert(false && "Inconsistant LinkageSpecDecl::LanguageIDs");
}
DeclContext* declContext = LinkageSpecDecl::castToDeclContext(Decl);;
if(Decl->hasBraces())
{
out() << "\n" << indentStr() << "{\n";
++indent;
for(auto* decl : declContext->decls())
{
out() << indentStr();
TraverseDecl(decl);
if(needSemiComma(decl))
out() << ";";
out() << "\n";
}
--indent;
out() << indentStr() << "}";
}
else
TraverseDecl(*declContext->decls_begin());
return true;
}
bool DPrinter::TraverseFriendDecl(FriendDecl* Decl)
{
if(passDecl(Decl)) return true;
out() << "//friend ";
if(Decl->getFriendType())
TraverseType(Decl->getFriendType()->getType());
else
TraverseDecl(Decl->getFriendDecl());
return true;
}
bool DPrinter::TraverseParmVarDecl(ParmVarDecl* Decl)
{
if(passDecl(Decl)) return true;
printType(Decl->getType());
std::string const name = getName(Decl->getDeclName());//getNameAsString();
if(name.empty() == false)
out() << " " << mangleName(name);
if(Decl->hasDefaultArg())
{
if(not printDefaultValue)
out() << "/*";
out() << " = ";
TraverseStmt(
Decl->hasUninstantiatedDefaultArg() ?
Decl->getUninstantiatedDefaultArg() :
Decl->getDefaultArg());
if(not printDefaultValue)
out() << "*/";
}
return true;
}
bool DPrinter::TraverseRValueReferenceType(RValueReferenceType* Type)
{
if(passType(Type)) return false;
printType(Type->getPointeeType());
out() << "/*&&*/";
return true;
}
bool DPrinter::TraverseLValueReferenceType(LValueReferenceType* Type)
{
if(passType(Type)) return false;
if(refAccepted)
{
if(getSemantic(Type->getPointeeType()) == TypeOptions::Value)
{
if(inFuncParams)
{
// In D, we can't take a rvalue by const ref. So we need to pass by copy.
// (But the copy will be elided when possible)
if(Type->getPointeeType().isConstant(*Context) == false)
out() << "ref ";
}
else
out() << "ref ";
}
printType(Type->getPointeeType());
}
else
{
QualType const pt = Type->getPointeeType();
if(getSemantic(Type->getPointeeType()) == TypeOptions::Value)
{
out() << "Ref!(";
if(auto* at = dyn_cast<AutoType>(pt))
printType(at->getDeducedType());
else
printType(pt);
out() << ")";
}
else
printType(pt);
}
return true;
}
bool DPrinter::TraverseTemplateTypeParmType(TemplateTypeParmType* Type)
{
if(passType(Type)) return false;
if(Type->getDecl())
TraverseDecl(Type->getDecl());
else
{
IdentifierInfo* identifier = Type->getIdentifier();
if(identifier == nullptr)
{
if(static_cast<size_t>(Type->getDepth()) >= templateArgsStack.size())
out() << "/* getDepth : " << Type->getDepth() << "*/";
else if(static_cast<size_t>(Type->getIndex()) >= templateArgsStack[Type->getDepth()].size())
out() << "/* getIndex : " << Type->getIndex() << "*/";
else
{
auto param = templateArgsStack[Type->getDepth()][Type->getIndex()];
identifier = param->getIdentifier();
if(identifier == nullptr)
TraverseDecl(param);
}
}
auto iter = renamedIdentifiers.find(identifier);
if(iter != renamedIdentifiers.end())
out() << iter->second;
else if(identifier != nullptr)
out() << identifier->getName().str();
else
out() << "cant_find_name";
}
return true;
}
bool DPrinter::TraversePackExpansionType(clang::PackExpansionType* type)
{
printType(type->getPattern());
return true;
}
bool DPrinter::TraversePackExpansionExpr(clang::PackExpansionExpr* expr)
{
TraverseStmt(expr->getPattern());
return true;
}
bool DPrinter::TraverseTemplateTypeParmDecl(TemplateTypeParmDecl* Decl)
{
if(passDecl(Decl)) return true;
IdentifierInfo* identifier = Decl->getIdentifier();
if(identifier)
{
auto iter = renamedIdentifiers.find(identifier);
if(renameIdentifiers && iter != renamedIdentifiers.end())
out() << iter->second;
else
out() << identifier->getName().str();
}
if(Decl->isParameterPack() && inTemplateParamList)
out() << "...";
// A template type without name is a auto param of a lambda
// Add "else" to handle it
return true;
}
bool DPrinter::TraverseNonTypeTemplateParmDecl(NonTypeTemplateParmDecl* Decl)
{
if(passDecl(Decl)) return true;
printType(Decl->getType());
out() << " ";
IdentifierInfo* identifier = Decl->getIdentifier();
if(identifier)
out() << mangleName(identifier->getName());
return true;
}
bool DPrinter::TraverseDeclStmt(DeclStmt* Stmt)
{
if(passStmt(Stmt)) return false;
if(Stmt->isSingleDecl()) //May be in for or catch
TraverseDecl(Stmt->getSingleDecl());
else
{
// Better to split multi line decl, but in for init, we can't do it
if(splitMultiLineDecl)
{
int count = 0;
for(auto d : Stmt->decls())
{
pushStream();
TraverseDecl(d);
std::string const line = popStream();
if (line.empty() == false)
{
if (count != 0)
out() << "\n" << indentStr();
++count;
out() << line;
if (needSemiComma(d))
out() << ";";
}
}
}
else
{
Spliter split(*this, ", ");
for(auto d : Stmt->decls())
{
doPrintType = split.first;
split.split();
TraverseDecl(d);
if(isa<RecordDecl>(d))
{
out() << "\n" << indentStr();
split.first = true;
}
doPrintType = true;
}
}
}
return true;
}
bool DPrinter::TraverseNamespaceAliasDecl(NamespaceAliasDecl* Decl)
{
if(passDecl(Decl)) return true;
return true;
}
bool DPrinter::TraverseReturnStmt(ReturnStmt* Stmt)
{
if(passStmt(Stmt)) return false;
out() << "return";
if(Stmt->getRetValue())
{
out() << " ";
TraverseStmt(Stmt->getRetValue());
}
return true;
out() << "return";
if(Stmt->getRetValue())
{
out() << ' ';
TraverseStmt(Stmt->getRetValue());
}
return true;
}
bool DPrinter::TraverseCXXOperatorCallExpr(CXXOperatorCallExpr* Stmt)
{
if(passStmt(Stmt)) return true;
auto const numArgs = Stmt->getNumArgs();
const OverloadedOperatorKind kind = Stmt->getOperator();
char const* opStr = getOperatorSpelling(kind);
if(kind == OverloadedOperatorKind::OO_Call || kind == OverloadedOperatorKind::OO_Subscript)
{
auto iter = Stmt->arg_begin(), end = Stmt->arg_end();
TraverseStmt(*iter);
Spliter spliter(*this, ", ");
out() << opStr[0];
for(++iter; iter != end; ++iter)
{
if((*iter)->getStmtClass() != Stmt::StmtClass::CXXDefaultArgExprClass)
{
spliter.split();
TraverseStmt(*iter);
}
}
out() << opStr[1];
}
else if(kind == OverloadedOperatorKind::OO_Arrow)
TraverseStmt(*Stmt->arg_begin());
else if(kind == OverloadedOperatorKind::OO_Equal)
{
Expr* lo = *Stmt->arg_begin();
Expr* ro = *(Stmt->arg_end() - 1);
bool const lo_ptr = isPointer(lo->getType());
bool const ro_ptr = isPointer(ro->getType());
TypeOptions::Semantic const lo_sem = getSemantic(lo->getType());
TypeOptions::Semantic const ro_sem = getSemantic(ro->getType());
bool const dup = //both operands will be transformed to pointer
(ro_ptr == false && ro_sem != TypeOptions::Value) &&
(lo_ptr == false && lo_sem != TypeOptions::Value);
if(dup)
{
// Always use dup, because
// - It is OK on hashmap
// - opAssign is not possible on classes
// - copy ctor is possible but can cause slicing
TraverseStmt(lo);
out() << " = ";
TraverseStmt(ro);
out() << ".dup()";
isThisFunctionUsefull = true;
}
else
{
TraverseStmt(lo);
out() << " = ";
TraverseStmt(ro);
}
}
else if(kind == OverloadedOperatorKind::OO_PlusPlus ||
kind == OverloadedOperatorKind::OO_MinusMinus)
{
if(numArgs == 2)
{
TraverseStmt(*Stmt->arg_begin());
out() << opStr;
}
else
{
out() << opStr;
TraverseStmt(*Stmt->arg_begin());
}
}
else
{
if(numArgs == 2)
{
TraverseStmt(*Stmt->arg_begin());
out() << " ";
}
out() << opStr;
if(numArgs == 2)
out() << " ";
TraverseStmt(*(Stmt->arg_end() - 1));
}
return true;
}
bool DPrinter::TraverseExprWithCleanups(ExprWithCleanups* Stmt)
{
if(passStmt(Stmt)) return true;
TraverseStmt(Stmt->getSubExpr());
return true;
}
void DPrinter::traverseCompoundStmtOrNot(Stmt* Stmt) //Impl
{
if(Stmt->getStmtClass() == Stmt::StmtClass::CompoundStmtClass)
{
out() << indentStr();
TraverseStmt(Stmt);
}
else
{
++indent;
out() << indentStr();
if(isa<NullStmt>(Stmt))
out() << "{}";
TraverseStmt(Stmt);
if(needSemiComma(Stmt))
out() << ";";
--indent;
}
}
bool DPrinter::TraverseArraySubscriptExpr(ArraySubscriptExpr* Expr)
{
if(passStmt(Expr)) return true;
TraverseStmt(Expr->getLHS());
out() << '[';
TraverseStmt(Expr->getRHS());
out() << ']';
return true;
}
bool DPrinter::TraverseFloatingLiteral(FloatingLiteral* Expr)
{
if(passStmt(Expr)) return true;
const llvm::fltSemantics& sem = Expr->getSemantics();
llvm::SmallString<1000> str;
if(APFloat::semanticsSizeInBits(sem) < 64)
{
Expr->getValue().toString(str, std::numeric_limits<float>::digits10);
out() << str.c_str() << 'f';
}
else if(APFloat::semanticsSizeInBits(sem) > 64)
{
Expr->getValue().toString(str, std::numeric_limits<long double>::digits10);
out() << str.c_str() << 'l';
}
else
{
Expr->getValue().toString(str, std::numeric_limits<double>::digits10);
out() << str.c_str();
}
return true;
}
bool DPrinter::TraverseForStmt(ForStmt* Stmt)
{
if(passStmt(Stmt)) return false;
out() << "for(";
splitMultiLineDecl = false;
TraverseStmt(Stmt->getInit());
splitMultiLineDecl = true;
out() << "; ";
TraverseStmt(Stmt->getCond());
out() << "; ";
TraverseStmt(Stmt->getInc());
out() << ")" << std::endl;
traverseCompoundStmtOrNot(Stmt->getBody());
return true;
}
bool DPrinter::TraverseWhileStmt(WhileStmt* Stmt)
{
if(passStmt(Stmt)) return false;
out() << "while(";
TraverseStmt(Stmt->getCond());
out() << ")" << std::endl;
traverseCompoundStmtOrNot(Stmt->getBody());
return true;
}
bool DPrinter::TraverseIfStmt(IfStmt* Stmt)
{
if(passStmt(Stmt)) return false;
out() << "if(";
TraverseStmt(Stmt->getCond());
out() << ")" << std::endl;
traverseCompoundStmtOrNot(Stmt->getThen());
if(Stmt->getElse())
{
out() << std::endl << indentStr() << "else ";
if(Stmt->getElse()->getStmtClass() == Stmt::IfStmtClass)
TraverseStmt(Stmt->getElse());
else
{
out() << std::endl;
traverseCompoundStmtOrNot(Stmt->getElse());
}
}
return true;
}
bool DPrinter::TraverseCXXBindTemporaryExpr(CXXBindTemporaryExpr* Stmt)
{
if(passStmt(Stmt)) return true;
TraverseStmt(Stmt->getSubExpr());
return true;
}
bool DPrinter::TraverseCXXThrowExpr(CXXThrowExpr* Stmt)
{
if(passStmt(Stmt)) return true;
out() << "throw ";
if(Stmt->getSubExpr() == nullptr)
out() << catchedExceptNames.top();
else
TraverseStmt(Stmt->getSubExpr());
return true;
}
bool DPrinter::TraverseMaterializeTemporaryExpr(MaterializeTemporaryExpr* Stmt)
{
if(passStmt(Stmt)) return true;
TraverseStmt(Stmt->GetTemporaryExpr());
return true;
}
bool DPrinter::TraverseCXXFunctionalCastExpr(CXXFunctionalCastExpr* Stmt)
{
if(passStmt(Stmt)) return true;
QualType qt = Stmt->getTypeInfoAsWritten()->getType();
if(getSemantic(qt) == TypeOptions::Reference)
{
out() << "new ";
printType(qt);
out() << '(';
TraverseStmt(Stmt->getSubExpr());
out() << ')';
}
else
{
out() << "cast(";
printType(qt);
out() << ")(";
TraverseStmt(Stmt->getSubExpr());
out() << ")";
}
return true;
}
bool DPrinter::TraverseParenType(ParenType* Type)
{
if(passType(Type)) return false;
// Parenthesis are useless (and illegal) on function types
printType(Type->getInnerType());
return true;
}
bool DPrinter::TraverseFunctionProtoType(FunctionProtoType* Type)
{
if(passType(Type)) return false;
printType(Type->getReturnType());
out() << " function(";
Spliter spliter(*this, ", ");
for(auto const& p : Type->getParamTypes())
{
spliter.split();
printType(p);
}
if(Type->isVariadic())
{
spliter.split();
out() << "...";
addExternInclude("core.vararg", "...");
}
out() << ')';
return true;
}
bool DPrinter::TraverseCXXTemporaryObjectExpr(CXXTemporaryObjectExpr* Stmt)
{
if(passStmt(Stmt)) return true;
printType(Stmt->getType());
out() << '(';
TraverseCXXConstructExpr(Stmt);
out() << ')';
return true;
}
bool DPrinter::TraverseNullStmt(NullStmt* Stmt)
{
if(passStmt(Stmt)) return false;
return true;
}
bool DPrinter::TraverseCharacterLiteral(CharacterLiteral* Stmt)
{
if(passStmt(Stmt)) return true;
out() << '\'';
auto c = Stmt->getValue();
switch(c)
{
case '\0': out() << "\\0"; break;
case '\n': out() << "\\n"; break;
case '\t': out() << "\\t"; break;
case '\r': out() << "\\r"; break;
default: out() << (char)c;
}
out() << '\'';
return true;
}
bool DPrinter::TraverseStringLiteral(clang::StringLiteral* Stmt)
{
if(passStmt(Stmt)) return true;
out() << "\"";
std::string literal;
StringRef str = Stmt->getString();
if(not str.empty())
{
if(Stmt->isUTF16() || Stmt->isWide())
{
const UTF16* source = reinterpret_cast<const UTF16*>(str.begin());
const UTF16* sourceEnd = reinterpret_cast<const UTF16*>(str.end());
literal.resize(size_t((sourceEnd - source) * UNI_MAX_UTF8_BYTES_PER_CODE_POINT + 1));
auto* dest = reinterpret_cast<UTF8*>(&literal[0]);
ConvertUTF16toUTF8(&source, source + str.size(), &dest, dest + literal.size(), ConversionFlags());
literal.resize(size_t(reinterpret_cast<char*>(dest) - &literal[0]));
}
else if(Stmt->isUTF32())
{
const UTF32* source = reinterpret_cast<const UTF32*>(str.begin());
const UTF32* sourceEnd = reinterpret_cast<const UTF32*>(str.end());
literal.resize(size_t((sourceEnd - source) * UNI_MAX_UTF8_BYTES_PER_CODE_POINT + 1));
auto* dest = reinterpret_cast<UTF8*>(&literal[0]);
ConvertUTF32toUTF8(&source, source + str.size(), &dest, dest + literal.size(), ConversionFlags());
literal.resize(size_t(reinterpret_cast<char*>(dest) - &literal[0]));
}
else
{
for (char _c : str)
{
unsigned char c = (unsigned char)_c;
if (c < 128)
literal.push_back(_c);
else
{
static char buffer[20];
std::sprintf(buffer, "\\x%x", c);
literal += buffer;
}
}
}
}
size_t pos = 0;
while((pos = literal.find('\\', pos)) != std::string::npos)
{
char next = ' ';
if (literal.size() > (pos + 1))
next = literal[pos + 1];
if (next != 'n' && next != 'x')
{
literal = literal.substr(0, pos) + "\\\\" + literal.substr(pos + 1);
pos += 2;
}
else
++pos;
}
pos = std::string::npos;
while((pos = literal.find('\n')) != std::string::npos)
literal = literal.substr(0, pos) + "\\n" + literal.substr(pos + 1);
pos = 0;
while((pos = literal.find('"', pos)) != std::string::npos)
{
if(pos > 0 && literal[pos - 1] == '\\')
++pos;
else
{
literal = literal.substr(0, pos) + "\\\"" + literal.substr(pos + 1);
pos += 2;
}
}
out() << literal;
out() << "\"";
return true;
}
bool DPrinter::TraverseCXXBoolLiteralExpr(CXXBoolLiteralExpr* Stmt)
{
if(passStmt(Stmt)) return true;
out() << (Stmt->getValue() ? "true" : "false");
return true;
}
bool DPrinter::TraverseUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr* Expr)
{
if(passStmt(Expr)) return true;
out() << '(';
if(Expr->isArgumentType())
printType(Expr->getArgumentType());
else
TraverseStmt(Expr->getArgumentExpr());
UnaryExprOrTypeTrait const kind = Expr->getKind();
out() << (
kind == UETT_AlignOf ? ").alignof" :
kind == UETT_SizeOf ? ").sizeof" :
kind == UETT_OpenMPRequiredSimdAlign ? ").OpenMPRequiredSimdAlign" :
kind == UETT_VecStep ? ").VecStep" :
")");
return true;
}
bool DPrinter::TraverseEmptyDecl(EmptyDecl* Decl)
{
if(passDecl(Decl)) return true;
return true;
}
bool DPrinter::TraverseLambdaExpr(LambdaExpr* Node)
{
if(passStmt(Node)) return true;
CXXMethodDecl* Method = Node->getCallOperator();
// Has some auto type?
bool hasAuto = false;
if(Node->hasExplicitParameters())
{
for(ParmVarDecl* P : Method->parameters())
{
if(P->getType()->getTypeClass() == clang::Type::TypeClass::TemplateTypeParm)
{
hasAuto = true;
break;
}
else if(auto* lvalueRef = dyn_cast<LValueReferenceType>(P->getType()))
{
if(lvalueRef->getPointeeType()->getTypeClass() == clang::Type::TypeClass::TemplateTypeParm)
{
hasAuto = true;
break;
}
}
}
}
if(hasAuto)
{
externIncludes["cpp_std"].insert("toFunctor");
out() << "toFunctor!(";
}
const FunctionProtoType* Proto = Method->getType()->getAs<FunctionProtoType>();
if(Node->hasExplicitResultType())
{
out() << "function ";
printType(Proto->getReturnType());
}
if(Node->hasExplicitParameters())
{
out() << "(";
inFuncParams = true;
refAccepted = true;
Spliter split(*this, ", ");
for(ParmVarDecl* P : Method->parameters())
{
split.split();
TraverseDecl(P);
}
if(Method->isVariadic())
{
split.split();
out() << "...";
addExternInclude("core.vararg", "...");
}
out() << ')';
inFuncParams = false;
refAccepted = false;
}
// Print the body.
out() << "\n" << indentStr();
CompoundStmt* Body = Node->getBody();
TraverseStmt(Body);
if(hasAuto)
out() << ")()";
return true;
}
void DPrinter::printCallExprArgument(CallExpr* Stmt)
{
out() << "(";
Spliter spliter(*this, ", ");
for(Expr* arg : Stmt->arguments())
{
if(arg->getStmtClass() == Stmt::StmtClass::CXXDefaultArgExprClass)
break;
spliter.split();
TraverseStmt(arg);
}
out() << ")";
}
bool DPrinter::TraverseCallExpr(CallExpr* Stmt)
{
auto matchesName = [&](std::string const calleeName)
{
for(auto const& name_printer : receiver.globalFuncPrinters)
{
llvm::Regex RE(name_printer.first);
if(RE.match("::" + calleeName))
{
name_printer.second(*this, Stmt);
return true;
}
}
return false;
};
if(Decl* calleeDecl = Stmt->getCalleeDecl())
{
if(auto* func = dyn_cast<FunctionDecl>(calleeDecl))
{
if(matchesName(func->getQualifiedNameAsString()))
return true;
}
}
Expr* callee = Stmt->getCallee();
if(auto* lockup = dyn_cast<UnresolvedLookupExpr>(callee))
{
std::string name;
llvm::raw_string_ostream ss(name);
lockup->printPretty(ss, nullptr, printingPolicy);
if(matchesName(ss.str()))
return true;
}
if(passStmt(Stmt)) return true;
dontTakePtr.insert(callee);
TraverseStmt(callee);
dontTakePtr.erase(callee);
// Are parentezis on zero argument needed?
//if (Stmt->getNumArgs() == 0)
// return true;
printCallExprArgument(Stmt);
return true;
}
bool DPrinter::TraverseImplicitCastExpr(ImplicitCastExpr* Stmt)
{
if(passStmt(Stmt)) return true;
if(Stmt->getCastKind() == CK_FunctionToPointerDecay && dontTakePtr.count(Stmt) == 0)
out() << "&";
if(Stmt->getCastKind() == CK_ConstructorConversion)
{
QualType const type = Stmt->getType();
if(getSemantic(type) == TypeOptions::Reference)
out() << "new ";
printType(type);
out() << '(';
}
TraverseStmt(Stmt->getSubExpr());
if(Stmt->getCastKind() == CK_ConstructorConversion)
out() << ')';
return true;
}
bool DPrinter::TraverseCXXThisExpr(CXXThisExpr* expr)
{
if(passStmt(expr)) return true;
QualType pointee = expr->getType()->getPointeeType();
if(getSemantic(pointee) == TypeOptions::Value)
out() << "(&this)[0..1]";
else
out() << "this";
return true;
}
bool DPrinter::isStdArray(QualType const& type)
{
QualType const rawType = type.isCanonical() ?
type :
type.getCanonicalType();
std::string const name = rawType.getAsString();
static std::string const arrayNames[] =
{
"class boost::array<",
"class std::array<",
"struct boost::array<",
"struct std::array<"
};
return std::any_of(std::begin(arrayNames), std::end(arrayNames), [&](auto && arrayName)
{
return name.find(arrayName) == 0;
});
}
bool DPrinter::isStdUnorderedMap(QualType const& type)
{
QualType const rawType = type.isCanonical() ?
type :
type.getCanonicalType();
std::string const name = rawType.getAsString();
static std::string const arrayNames[] =
{
"class std::unordered_map<",
"class boost::unordered_map<",
"struct std::unordered_map<",
"struct boost::unordered_map<",
};
return std::any_of(std::begin(arrayNames), std::end(arrayNames), [&](auto && arrayName)
{
return name.find(arrayName) == 0;
});
}
bool DPrinter::TraverseCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr* expr)
{
if(passStmt(expr)) return true;
return traverseMemberExprImpl(expr);
}
bool DPrinter::TraverseMemberExpr(MemberExpr* Stmt)
{
if(passStmt(Stmt)) return true;
return traverseMemberExprImpl(Stmt);
}
template<typename ME>
bool DPrinter::traverseMemberExprImpl(ME* Stmt)
{
DeclarationName const declName = Stmt->getMemberNameInfo().getName();
auto const kind = declName.getNameKind();
std::string const memberName = Stmt->getMemberNameInfo().getName().getAsString();
Expr* base = Stmt->isImplicitAccess() ? nullptr : Stmt->getBase();
bool const isThis = not(base && base->getStmtClass() != Stmt::StmtClass::CXXThisExprClass);
if(not isThis)
TraverseStmt(base);
if(kind == DeclarationName::NameKind::CXXConversionFunctionName)
{
if(memberName.empty() == false && not isThis)
out() << '.';
out() << "opCast!(";
printType(declName.getCXXNameType());
out() << ')';
}
else if(kind == DeclarationName::NameKind::CXXOperatorName)
{
out() << " " << memberName.substr(8) << " "; //8 is size of "operator"
}
else
{
if (memberName.empty() == false && not isThis)
{
if (Stmt->isArrow() &&
base->getStmtClass() != clang::Stmt::CXXOperatorCallExprClass &&
getSemantic(base->getType()) == TypeOptions::Semantic::Value)
{
out() << ".front.";
addExternInclude("std.range", "front");
}
else
out() << '.';
}
out() << memberName;
}
auto TAL = Stmt->getTemplateArgs();
auto const tmpArgCount = Stmt->getNumTemplateArgs();
Spliter spliter(*this, ", ");
if(tmpArgCount != 0)
{
pushStream();
for(size_t I = 0; I < tmpArgCount; ++I)
{
spliter.split();
printTemplateArgument(TAL[I].getArgument());
}
printTmpArgList(popStream());
}
return true;
}
//! @brief Is decl or parent of decl present in classes
//! @return The printer method found in classes
MatchContainer::ClassPrinter::const_iterator::value_type::second_type
isAnyOfThoseTypes(CXXRecordDecl* decl, MatchContainer::ClassPrinter const& classes)
{
std::string declName = decl->getQualifiedNameAsString();
size_t pos = declName.find('<');
if(pos != std::string::npos)
declName = declName.substr(0, pos);
auto classIter = classes.find(declName);
if(classIter != classes.end())
return classIter->second;
for(CXXBaseSpecifier const& baseSpec : decl->bases())
{
CXXRecordDecl* base = baseSpec.getType()->getAsCXXRecordDecl();
assert(base);
if(auto func = isAnyOfThoseTypes(base, classes))
return func;
}
for(CXXBaseSpecifier const& baseSpec : decl->vbases())
{
CXXRecordDecl* base = baseSpec.getType()->getAsCXXRecordDecl();
assert(base);
if(auto func = isAnyOfThoseTypes(base, classes))
return func;
}
return nullptr;
};
bool DPrinter::TraverseCXXMemberCallExpr(CXXMemberCallExpr* expr)
{
if(passStmt(expr)) return true;
if(auto* meth = dyn_cast<CXXMethodDecl>(expr->getCalleeDecl()))
{
std::string methName = meth->getNameAsString();
CXXRecordDecl* thisType = expr->getRecordDecl();
auto methIter = receiver.methodPrinters.find(methName);
if(methIter != receiver.methodPrinters.end())
{
if(auto func = isAnyOfThoseTypes(thisType, methIter->second))
{
func(*this, expr);
return true;
}
}
}
if(auto* dtor = dyn_cast<CXXDestructorDecl>(expr->getCalleeDecl()))
{
out() << "object.destroy(";
if(auto* memExpr = dyn_cast<MemberExpr>(expr->getCallee()))
{
Expr* base = memExpr->isImplicitAccess() ? nullptr : memExpr->getBase();
TraverseStmt(base);
}
out() << ")";
}
else
{
TraverseStmt(expr->getCallee());
printCallExprArgument(expr);
}
return true;
}
bool DPrinter::TraverseCXXStaticCastExpr(CXXStaticCastExpr* Stmt)
{
if(passStmt(Stmt)) return true;
out() << "cast(";
printType(Stmt->getTypeInfoAsWritten()->getType());
out() << ')';
TraverseStmt(Stmt->getSubExpr());
return true;
}
bool DPrinter::TraverseCStyleCastExpr(CStyleCastExpr* Stmt)
{
if(passStmt(Stmt)) return true;
out() << "cast(";
printType(Stmt->getTypeInfoAsWritten()->getType());
out() << ')';
TraverseStmt(Stmt->getSubExpr());
return true;
}
bool DPrinter::TraverseConditionalOperator(ConditionalOperator* op)
{
if(passStmt(op)) return true;
TraverseStmt(op->getCond());
out() << "? ";
TraverseStmt(op->getTrueExpr());
out() << ": ";
TraverseStmt(op->getFalseExpr());
return true;
}
bool DPrinter::TraverseCompoundAssignOperator(CompoundAssignOperator* op)
{
if(passStmt(op)) return true;
DPrinter::TraverseBinaryOperator(op);
return true;
}
bool DPrinter::TraverseBinAddAssign(CompoundAssignOperator* expr)
{
if(passStmt(expr)) return true;
if(isPointer(expr->getLHS()->getType()))
{
TraverseStmt(expr->getLHS());
out() << ".popFrontN(";
TraverseStmt(expr->getRHS());
out() << ')';
externIncludes["std.range.primitives"].insert("popFrontN");
return true;
}
else
return TraverseCompoundAssignOperator(expr);
}
#define OPERATOR(NAME) \
bool DPrinter::TraverseBin##NAME##Assign(CompoundAssignOperator *S) \
{if (passStmt(S)) return true; return TraverseCompoundAssignOperator(S);}
OPERATOR(Mul) OPERATOR(Div) OPERATOR(Rem) OPERATOR(Sub)
OPERATOR(Shl) OPERATOR(Shr) OPERATOR(And) OPERATOR(Or) OPERATOR(Xor)
#undef OPERATOR
bool DPrinter::TraverseSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr* Expr)
{
if(passStmt(Expr)) return true;
TraverseStmt(Expr->getReplacement());
return true;
}
bool DPrinter::TraverseBinaryOperator(BinaryOperator* Stmt)
{
if(passStmt(Stmt)) return true;
Expr* lhs = Stmt->getLHS();
Expr* rhs = Stmt->getRHS();
if(isPointer(lhs->getType()) and isPointer(rhs->getType()))
{
TraverseStmt(Stmt->getLHS());
switch(Stmt->getOpcode())
{
case BinaryOperatorKind::BO_EQ: out() << " is "; break;
case BinaryOperatorKind::BO_NE: out() << " !is "; break;
default: out() << " " << Stmt->getOpcodeStr().str() << " ";
}
TraverseStmt(Stmt->getRHS());
}
else
{
TraverseStmt(lhs);
out() << " " << Stmt->getOpcodeStr().str() << " ";
TraverseStmt(rhs);
}
return true;
}
bool DPrinter::TraverseBinAdd(BinaryOperator* expr)
{
if(passStmt(expr)) return true;
if(isPointer(expr->getLHS()->getType()))
{
TraverseStmt(expr->getLHS());
out() << '[';
TraverseStmt(expr->getRHS());
out() << "..$]";
return true;
}
else
return TraverseBinaryOperator(expr);
}
#define OPERATOR(NAME) \
bool DPrinter::TraverseBin##NAME(BinaryOperator* Stmt) \
{if (passStmt(Stmt)) return true; return TraverseBinaryOperator(Stmt);}
OPERATOR(PtrMemD) OPERATOR(PtrMemI) OPERATOR(Mul) OPERATOR(Div)
OPERATOR(Rem) OPERATOR(Sub) OPERATOR(Shl) OPERATOR(Shr)
OPERATOR(LT) OPERATOR(GT) OPERATOR(LE) OPERATOR(GE) OPERATOR(EQ)
OPERATOR(NE) OPERATOR(And) OPERATOR(Xor) OPERATOR(Or) OPERATOR(LAnd)
OPERATOR(LOr) OPERATOR(Assign) OPERATOR(Comma)
#undef OPERATOR
bool DPrinter::TraverseUnaryOperator(UnaryOperator* Stmt)
{
if(passStmt(Stmt)) return true;
if(Stmt->isIncrementOp())
{
if(isPointer(Stmt->getSubExpr()->getType()))
{
TraverseStmt(Stmt->getSubExpr());
out() << ".popFront";
externIncludes["std.range.primitives"].insert("popFront");
return true;
}
}
if(Stmt->isPostfix())
{
TraverseStmt(Stmt->getSubExpr());
out() << Stmt->getOpcodeStr(Stmt->getOpcode()).str();
}
else
{
std::string preOp = Stmt->getOpcodeStr(Stmt->getOpcode()).str();
std::string postOp = "";
if(Stmt->getOpcode() == UnaryOperatorKind::UO_AddrOf)
{
preOp = "(&";
postOp = ")[0..1]";
}
else if(Stmt->getOpcode() == UnaryOperatorKind::UO_Deref)
{
if(auto* t = dyn_cast<CXXThisExpr>(Stmt->getSubExpr()))
{
// (*this) in C++ mean (this) in D
out() << "this";
return true;
}
preOp.clear();
postOp = "[0]";
}
// Avoid to deref struct this
Expr* expr = static_cast<Expr*>(*Stmt->child_begin());
bool showOp = true;
QualType exprType = expr->getType();
TypeOptions::Semantic operSem =
exprType->hasPointerRepresentation() ?
getSemantic(exprType->getPointeeType()) :
getSemantic(exprType);
if(operSem != TypeOptions::Value)
{
if(Stmt->getOpcode() == UnaryOperatorKind::UO_AddrOf
|| Stmt->getOpcode() == UnaryOperatorKind::UO_Deref)
showOp = false;
}
if(showOp)
out() << preOp;
for(auto c : Stmt->children())
TraverseStmt(c);
if(showOp)
out() << postOp;
}
return true;
}
#define OPERATOR(NAME) \
bool DPrinter::TraverseUnary##NAME(UnaryOperator* Stmt) \
{if (passStmt(Stmt)) return true; return TraverseUnaryOperator(Stmt);}
OPERATOR(PostInc) OPERATOR(PostDec) OPERATOR(PreInc) OPERATOR(PreDec)
OPERATOR(AddrOf) OPERATOR(Deref) OPERATOR(Plus) OPERATOR(Minus)
OPERATOR(Not) OPERATOR(LNot) OPERATOR(Real) OPERATOR(Imag)
OPERATOR(Extension) OPERATOR(Coawait)
#undef OPERATOR
template<typename TDeclRefExpr>
void DPrinter::traverseDeclRefExprImpl(TDeclRefExpr* Expr)
{
size_t const argNum = Expr->getNumTemplateArgs();
if(argNum != 0)
{
TemplateArgumentLoc const* tmpArgs = Expr->getTemplateArgs();
Spliter split(*this, ", ");
pushStream();
for(size_t i = 0; i < argNum; ++i)
{
split.split();
printTemplateArgument(tmpArgs[i].getArgument());
}
printTmpArgList(popStream());
}
}
bool DPrinter::TraverseDeclRefExpr(DeclRefExpr* Expr)
{
if(passStmt(Expr)) return true;
QualType nnsQualType;
NestedNameSpecifier* nns = Expr->getQualifier();
if(nns != nullptr)
{
if(nns->getKind() == NestedNameSpecifier::SpecifierKind::TypeSpec)
nnsQualType = nns->getAsType()->getCanonicalTypeUnqualified();
}
auto decl = Expr->getDecl();
bool nestedNamePrined = false;
if(decl->getKind() == Decl::Kind::EnumConstant)
{
nestedNamePrined = true;
if(nnsQualType != decl->getType().getUnqualifiedType())
{
printType(decl->getType().getUnqualifiedType());
out() << '.';
}
else if(nns)
TraverseNestedNameSpecifier(nns);
}
else if(nns)
{
nestedNamePrined = true;
TraverseNestedNameSpecifier(nns);
}
else
{ // If it refer the param argc, print argv.length
ValueDecl* valdecl = Expr->getDecl();
ParmVarDecl* pVarDecl = llvm::dyn_cast<ParmVarDecl>(valdecl);
if (pVarDecl && pVarDecl->getNameAsString() == "argc")
{
out() << "(cast(int)argv.length)";
return true;
}
}
std::string name = getName(Expr->getNameInfo().getName());
if(nestedNamePrined == false)
if(char const* filename = CPP2DTools::getFile(Context->getSourceManager(), Expr->getDecl()))
includeFile(filename, name);
out() << mangleName(name);
traverseDeclRefExprImpl(Expr);
return true;
}
bool DPrinter::TraverseDependentScopeDeclRefExpr(DependentScopeDeclRefExpr* Expr)
{
if(passStmt(Expr)) return true;
if(NestedNameSpecifier* nns = Expr->getQualifier())
TraverseNestedNameSpecifier(nns);
out() << mangleName(getName(Expr->getNameInfo().getName()));
traverseDeclRefExprImpl(Expr);
return true;
}
bool DPrinter::TraverseUnresolvedLookupExpr(UnresolvedLookupExpr* Expr)
{
if(passStmt(Expr)) return true;
if(NestedNameSpecifier* nns = Expr->getQualifier())
TraverseNestedNameSpecifier(nns);
out() << mangleName(getName(Expr->getNameInfo().getName()));
traverseDeclRefExprImpl(Expr);
return true;
}
bool DPrinter::TraverseRecordType(RecordType* Type)
{
if(passType(Type)) return false;
if(customTypePrinter(Type->getDecl()))
return true;
out() << printDeclName(Type->getDecl());
RecordDecl* decl = Type->getDecl();
switch(decl->getKind())
{
case Decl::Kind::Record: break;
case Decl::Kind::CXXRecord: break;
case Decl::Kind::ClassTemplateSpecialization:
{
// Print template arguments in template type of template specialization
auto* tmpSpec = llvm::dyn_cast<ClassTemplateSpecializationDecl>(decl);
TemplateArgumentList const& tmpArgsSpec = tmpSpec->getTemplateInstantiationArgs();
pushStream();
Spliter spliter2(*this, ", ");
for(unsigned int i = 0, size = tmpArgsSpec.size(); i != size; ++i)
{
spliter2.split();
TemplateArgument const& tmpArg = tmpArgsSpec.get(i);
printTemplateArgument(tmpArg);
}
printTmpArgList(popStream());
break;
}
default: assert(false && "Unconsustent RecordDecl kind");
}
return true;
}
bool DPrinter::TraverseConstantArrayType(ConstantArrayType* Type)
{
if(passType(Type)) return false;
printType(Type->getElementType());
out() << '[' << Type->getSize().toString(10, false) << ']';
return true;
}
bool DPrinter::TraverseIncompleteArrayType(IncompleteArrayType* Type)
{
if(passType(Type)) return false;
printType(Type->getElementType());
out() << "[]";
return true;
}
bool DPrinter::TraverseDependentSizedArrayType(DependentSizedArrayType* type)
{
if(passType(type)) return false;
printType(type->getElementType());
out() << '[';
TraverseStmt(type->getSizeExpr());
out() << ']';
return true;
}
bool DPrinter::TraverseInitListExpr(InitListExpr* expr)
{
if(passStmt(expr)) return true;
Expr* expr2 = expr->IgnoreImplicit();
if(expr2 != expr)
return TraverseStmt(expr2);
bool isExplicitBracket = true;
if(expr->getNumInits() == 1)
isExplicitBracket = not isa<InitListExpr>(expr->getInit(0));
bool const isArray =
(expr->ClassifyLValue(*Context) == Expr::LV_ArrayTemporary);
if(isExplicitBracket)
out() << (isArray ? '[' : '{') << " " << std::endl;
++indent;
size_t argIndex = 0;
for(Expr* c : expr->inits())
{
++argIndex;
pushStream();
TraverseStmt(c);
std::string const valInit = popStream();
if(valInit.empty() == false)
{
out() << indentStr() << valInit;
if(isExplicitBracket)
out() << ',' << std::endl;
}
output_enabled = (isInMacro == 0);
}
--indent;
if(isExplicitBracket)
out() << indentStr() << (isArray ? ']' : '}');
return true;
}
bool DPrinter::TraverseParenExpr(ParenExpr* expr)
{
if(passStmt(expr)) return true;
if(auto* binOp = dyn_cast<BinaryOperator>(expr->getSubExpr()))
{
Expr* lhs = binOp->getLHS();
Expr* rhs = binOp->getRHS();
clang::StringLiteral const* strLit = dyn_cast<clang::StringLiteral>(lhs);
if(strLit && (binOp->getOpcode() == BinaryOperatorKind::BO_Comma))
{
StringRef const str = strLit->getString();
if(str == "CPP2D_MACRO_EXPR")
{
auto get_binop = [](Expr * paren)
{
return dyn_cast<BinaryOperator>(dyn_cast<ParenExpr>(paren)->getSubExpr());
};
BinaryOperator* macro_and_cpp = get_binop(rhs);
BinaryOperator* macro_name_and_args = get_binop(macro_and_cpp->getLHS());
auto* macro_name = dyn_cast<clang::StringLiteral>(macro_name_and_args->getLHS());
auto* macro_args = dyn_cast<CallExpr>(macro_name_and_args->getRHS());
std::string macroName = macro_name->getString().str();
if(macroName == "assert")
{
out() << "assert(";
TraverseStmt(*macro_args->arg_begin());
out() << ")";
}
else
{
out() << "(mixin(" << macroName << "!(";
printMacroArgs(macro_args);
out() << ")))";
}
pushStream();
TraverseStmt(macro_and_cpp->getRHS()); //Add the required import
popStream();
return true;
}
}
}
out() << '(';
TraverseStmt(expr->getSubExpr());
out() << ')';
return true;
}
bool DPrinter::TraverseImplicitValueInitExpr(ImplicitValueInitExpr* expr)
{
if(passStmt(expr)) return true;
return true;
}
bool DPrinter::TraverseParenListExpr(clang::ParenListExpr* expr)
{
if(passStmt(expr)) return true;
Spliter split(*this, ", ");
for(Expr* arg : expr->exprs())
{
split.split();
TraverseStmt(arg);
}
return true;
}
bool DPrinter::TraverseCXXScalarValueInitExpr(CXXScalarValueInitExpr* expr)
{
QualType type;
if(TypeSourceInfo* TSInfo = expr->getTypeSourceInfo())
type = TSInfo->getType();
else
type = expr->getType();
if(type->isPointerType())
out() << "null";
else
{
printType(type);
out() << "()";
}
return true;
}
bool DPrinter::TraverseUnresolvedMemberExpr(UnresolvedMemberExpr* expr)
{
if(!expr->isImplicitAccess())
{
TraverseStmt(expr->getBase());
out() << '.';
}
if(NestedNameSpecifier* Qualifier = expr->getQualifier())
TraverseNestedNameSpecifier(Qualifier);
out() << expr->getMemberNameInfo().getAsString();
traverseDeclRefExprImpl(expr);
return true;
}
void DPrinter::traverseVarDeclImpl(VarDecl* Decl)
{
std::string const varName = getName(Decl->getDeclName());
if(varName.find("CPP2D_MACRO_STMT") == 0)
{
printStmtMacro(varName, Decl->getInit());
return;
}
if(passDecl(Decl)) return;
if(Decl->getCanonicalDecl() != Decl)
return;
if (Decl->isOutOfLine())
return;
else if (Decl->isOutOfLine())
Decl = Decl->getDefinition();
QualType varType = Decl->getType();
bool const isRef = [&]()
{
if(auto* refType = varType->getAs<LValueReferenceType>())
{
if(not refAccepted && getSemantic(refType->getPointeeType()) == TypeOptions::Value)
return true; //Have to call "makeRef" to handle to storage of a ref
}
return false;
}();
if(doPrintType)
{
if(Decl->isStaticDataMember() || Decl->isStaticLocal())
out() << "static ";
if(isRef)
out() << "auto";
else
printType(varType);
out() << " ";
}
out() << mangleName(varName);
bool const in_foreach_decl = inForRangeInit;
VarDecl* definition = Decl->hasInit() ? Decl : Decl->getDefinition();
if(definition && definition->hasInit() && !in_foreach_decl)
{
Expr* init = definition->getInit();
if(definition->isDirectInit())
{
if(auto* constr = dynCastAcrossCleanup<CXXConstructExpr>(init))
{
if(getSemantic(varType) == TypeOptions::Value)
{
if(constr->getNumArgs() != 0)
{
out() << " = ";
if(isRef)
out() << "makeRef(";
printCXXConstructExprParams(constr);
if(isRef)
out() << ")";
}
}
else if(getSemantic(varType) == TypeOptions::AssocArray)
{
if(constr->getNumArgs() != 0 && not isa<CXXDefaultArgExpr>(*constr->arg_begin()))
{
out() << " = ";
printCXXConstructExprParams(constr);
}
}
else
{
out() << " = new ";
printCXXConstructExprParams(constr);
}
}
else
{
out() << " = ";
TraverseStmt(init);
}
}
else
{
out() << " = ";
if(isRef)
out() << "makeRef(";
TraverseStmt(init);
if(isRef)
out() << ")";
}
}
}
bool DPrinter::TraverseVarDecl(VarDecl* Decl)
{
if(passDecl(Decl)) return true;
traverseVarDeclImpl(Decl);
return true;
}
bool DPrinter::TraverseIndirectFieldDecl(IndirectFieldDecl*)
{
return true;
}
bool DPrinter::VisitDecl(Decl* Decl)
{
out() << indentStr() << "/*" << Decl->getDeclKindName() << " Decl*/";
return true;
}
bool DPrinter::VisitStmt(Stmt* Stmt)
{
out() << indentStr() << "/*" << Stmt->getStmtClassName() << " Stmt*/";
return true;
}
bool DPrinter::VisitType(clang::Type* Type)
{
out() << indentStr() << "/*" << Type->getTypeClassName() << " Type*/";
return true;
}
void DPrinter::addExternInclude(std::string const& include, std::string const& typeName)
{
externIncludes[include].insert(typeName);
}
std::ostream& DPrinter::stream()
{
return out();
}
std::map<std::string, std::set<std::string> > const& DPrinter::getExternIncludes() const
{
return externIncludes;
}
std::string DPrinter::getDCode() const
{
return out().str();
}
bool DPrinter::shouldVisitImplicitCode() const
{
return true;
}
| 25.787518 | 136 | 0.659442 | [
"object",
"vector",
"transform"
] |
7a3a6c1502f4e291a0f4df2d65adad1859ce4255 | 5,446 | cpp | C++ | rootex/core/input/input_manager.cpp | meetcshah19/Rootex | 002725f80ee6ce02a01e1d18630f5635ad2a5b0c | [
"MIT"
] | null | null | null | rootex/core/input/input_manager.cpp | meetcshah19/Rootex | 002725f80ee6ce02a01e1d18630f5635ad2a5b0c | [
"MIT"
] | null | null | null | rootex/core/input/input_manager.cpp | meetcshah19/Rootex | 002725f80ee6ce02a01e1d18630f5635ad2a5b0c | [
"MIT"
] | null | null | null | #include "input_manager.h"
#include "event_manager.h"
#include <functional>
void InputManager::initialize(unsigned int width, unsigned int height)
{
m_GainputManager.SetDisplaySize(width, height);
m_Width = width;
m_Height = height;
DeviceIDs[Device::Mouse] = m_GainputManager.CreateDevice<gainput::InputDeviceMouse>();
DeviceIDs[Device::Keyboard] = m_GainputManager.CreateDevice<gainput::InputDeviceKeyboard>();
DeviceIDs[Device::Pad1] = m_GainputManager.CreateDevice<gainput::InputDevicePad>();
DeviceIDs[Device::Pad2] = m_GainputManager.CreateDevice<gainput::InputDevicePad>();
m_Listener.setID(1);
setEnabled(true);
}
void InputManager::setEnabled(bool enabled)
{
if (enabled)
{
PRINT("Input enabled");
setScheme(m_CurrentInputScheme);
m_GainputMap.AddListener(&m_Listener);
}
else
{
PRINT("Input disabled");
m_GainputMap.Clear();
m_GainputManager.RemoveListener(m_Listener.getID());
}
m_IsEnabled = enabled;
}
void InputManager::loadSchemes(const JSON::json& inputSchemes)
{
m_InputSchemes.clear();
for (auto& inputScheme : inputSchemes)
{
Vector<InputButtonBindingData> scheme;
InputButtonBindingData button;
for (auto& keys : inputScheme["bools"])
{
button.m_Type = InputButtonBindingData::Type::Bool;
button.m_InputEvent = keys["inputEvent"];
button.m_Device = keys["device"];
button.m_ButtonID = keys["button"];
scheme.emplace_back(button);
}
for (auto& axis : inputScheme["floats"])
{
button.m_Type = InputButtonBindingData::Type::Float;
button.m_InputEvent = axis["inputEvent"];
button.m_Device = axis["device"];
button.m_ButtonID = axis["button"];
scheme.emplace_back(button);
}
m_InputSchemes[inputScheme["name"]] = scheme;
}
}
void InputManager::setScheme(const String& schemeName)
{
m_GainputMap.Clear();
const Vector<InputButtonBindingData>& scheme = m_InputSchemes[schemeName];
for (auto& binding : scheme)
{
switch (binding.m_Type)
{
case InputButtonBindingData::Type::Bool:
mapBool(binding.m_InputEvent, binding.m_Device, binding.m_ButtonID);
break;
case InputButtonBindingData::Type::Float:
mapFloat(binding.m_InputEvent, binding.m_Device, binding.m_ButtonID);
break;
default:
break;
}
}
m_CurrentInputScheme = schemeName;
}
void InputManager::mapBool(const Event::Type& action, Device device, DeviceButtonID button)
{
m_InputEventNameIDs[action] = getNextID();
m_InputEventIDNames[m_InputEventNameIDs[action]] = action;
if (!m_GainputMap.MapBool((gainput::UserButtonId)m_InputEventNameIDs[action], DeviceIDs[device], button))
{
WARN("Bool mapping could not done: " + action);
}
}
void InputManager::mapFloat(const Event::Type& action, Device device, DeviceButtonID button)
{
m_InputEventNameIDs[action] = getNextID();
m_InputEventIDNames[m_InputEventNameIDs[action]] = action;
if (!m_GainputMap.MapFloat((gainput::UserButtonId)m_InputEventNameIDs[action], DeviceIDs[device], button))
{
WARN("Float mapping could not done: " + action);
}
}
void InputManager::unmap(const Event::Type& action)
{
m_GainputMap.Unmap(m_InputEventNameIDs[action]);
}
bool InputManager::isPressed(const Event::Type& action)
{
if (m_IsEnabled)
{
return m_GainputMap.GetBool((gainput::UserButtonId)m_InputEventNameIDs[action]);
}
return false;
}
bool InputManager::wasPressed(const Event::Type& action)
{
if (m_IsEnabled)
{
return m_GainputMap.GetBoolWasDown((gainput::UserButtonId)m_InputEventNameIDs[action]);
}
return false;
}
float InputManager::getFloat(const Event::Type& action)
{
if (m_IsEnabled)
{
return m_GainputMap.GetFloat((gainput::UserButtonId)m_InputEventNameIDs[action]);
}
return 0;
}
float InputManager::getFloatDelta(const Event::Type& action)
{
if (m_IsEnabled)
{
return m_GainputMap.GetFloatDelta((gainput::UserButtonId)m_InputEventNameIDs[action]);
}
return 0;
}
void InputManager::update()
{
m_GainputManager.Update();
}
unsigned int InputManager::getNextID()
{
static unsigned int count = 0;
return count++;
}
void InputManager::RegisterAPI(sol::state& rootex)
{
sol::usertype<InputManager> inputManager = rootex.new_usertype<InputManager>("InputManager");
inputManager["Get"] = &InputManager::GetSingleton;
inputManager["setEnabled"] = &InputManager::setEnabled;
inputManager["mapBool"] = &InputManager::mapBool;
inputManager["mapFloat"] = &InputManager::mapFloat;
inputManager["isPressed"] = &InputManager::isPressed;
inputManager["wasPressed"] = &InputManager::wasPressed;
inputManager["getFloat"] = &InputManager::getFloat;
inputManager["getFloatDelta"] = &InputManager::getFloatDelta;
inputManager["unmap"] = &InputManager::unmap;
}
InputManager* InputManager::GetSingleton()
{
static InputManager singleton;
return &singleton;
}
bool InputManager::BoolListen(int userButton, bool oldValue, bool newValue)
{
EventManager::GetSingleton()->call("BoolInputEvent", GetSingleton()->m_InputEventIDNames[userButton], Vector2(oldValue, newValue));
return true;
}
bool InputManager::FloatListen(int userButton, float oldValue, float newValue)
{
EventManager::GetSingleton()->call("FloatInputEvent", GetSingleton()->m_InputEventIDNames[userButton], Vector2(oldValue, newValue));
return true;
}
InputManager::InputManager()
: m_GainputMap(m_GainputManager)
, m_Listener(BoolListen, FloatListen)
, m_Width(0)
, m_Height(0)
{
}
void InputManager::forwardMessage(const MSG& msg)
{
m_GainputManager.HandleMessage(msg);
}
| 26.309179 | 133 | 0.752295 | [
"vector"
] |
7a3ab7ef1412bb9f6d7a40adaaeed923e6da9ea2 | 1,056 | cpp | C++ | 12. Stack/SortAstack.cpp | LikhithaTadikonda/DSA-cpp | 51ba2e1fe2cc832d55d2f6316498581efac65581 | [
"MIT"
] | 149 | 2021-09-17T17:11:06.000Z | 2021-10-01T17:32:18.000Z | 12. Stack/SortAstack.cpp | LikhithaTadikonda/DSA-cpp | 51ba2e1fe2cc832d55d2f6316498581efac65581 | [
"MIT"
] | 138 | 2021-09-29T14:04:05.000Z | 2021-10-01T17:43:18.000Z | 12. Stack/SortAstack.cpp | LikhithaTadikonda/DSA-cpp | 51ba2e1fe2cc832d55d2f6316498581efac65581 | [
"MIT"
] | 410 | 2021-09-27T03:13:55.000Z | 2021-10-01T17:59:42.000Z |
#include<bits/stdc++.h>
using namespace std;
class SortedStack{
public:
stack<int> s;
void sort();
};
void printStack(stack<int> s)
{
while (!s.empty())
{
printf("%d ", s.top());
s.pop();
}
printf("\n");
}
int main()
{
int t;
cin>>t;
while(t--)
{
SortedStack *ss = new SortedStack();
int n;
cin>>n;
for(int i=0;i<n;i++)
{
int k;
cin>>k;
ss->s.push(k);
}
ss->sort();
printStack(ss->s);
}
}
/*The structure of the class is
class SortedStack{
public:
stack<int> s;
void sort();
};
*/
/* The below method sorts the stack s */
void SortedStack :: sort()
{
priority_queue<int,vector<int>,greater<int>> q; //max priority queue to store the elements of the stack from top to bottom one by one(decreasing order)
while(!s.empty())
{
q.push(s.top());
s.pop();
}
while(!q.empty())
{
s.push(q.top()); //pushing back the elements from the queue in the stack (now increasing order sorted)
q.pop();
}
}
| 15.529412 | 157 | 0.544508 | [
"vector"
] |
7a3b6a235c730fcd152e7bc1d09b48002eeac282 | 359 | cpp | C++ | Day 1/Q.2]/Ravi.cpp | gopalshendge18/Practice-Question | c0dfefb4b6d7c3c5344d09b23d311f07a4444149 | [
"MIT"
] | 1 | 2022-01-03T14:04:26.000Z | 2022-01-03T14:04:26.000Z | Day 1/Q.2]/Ravi.cpp | gopalshendge18/Practice-Question | c0dfefb4b6d7c3c5344d09b23d311f07a4444149 | [
"MIT"
] | null | null | null | Day 1/Q.2]/Ravi.cpp | gopalshendge18/Practice-Question | c0dfefb4b6d7c3c5344d09b23d311f07a4444149 | [
"MIT"
] | 8 | 2021-11-03T04:12:17.000Z | 2021-12-11T09:28:54.000Z | void nextPermutation(vector<int>& nums) {
int n = nums.size();
int i = n-2, j = n-1;
while(i>=0 && nums[i]>=nums[i+1]) i--;
if(i<0)
{
reverse(nums.begin(), nums.end());
}
else
{
while(nums[j]<=nums[i]) j--;
swap(nums[i],nums[j]);
reverse(nums.begin() + i + 1, nums.end());
}
}
| 18.894737 | 50 | 0.440111 | [
"vector"
] |
7a3f45e962ab2c6d0904952f8f760c56cf141515 | 22,549 | cpp | C++ | Engine/Source/Runtime/GameplayTasks/Private/GameplayTasksComponent.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Runtime/GameplayTasks/Private/GameplayTasksComponent.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Runtime/GameplayTasks/Private/GameplayTasksComponent.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "GameplayTasksComponent.h"
#include "UObject/Package.h"
#include "Net/UnrealNetwork.h"
#include "Engine/ActorChannel.h"
#include "GameFramework/Actor.h"
#include "VisualLogger/VisualLoggerTypes.h"
#include "VisualLogger/VisualLogger.h"
#include "GameplayTasksPrivate.h"
#include "Logging/MessageLog.h"
#define LOCTEXT_NAMESPACE "GameplayTasksComponent"
namespace
{
FORCEINLINE const TCHAR* GetGameplayTaskEventName(EGameplayTaskEvent Event)
{
/*static const UEnum* GameplayTaskEventEnum = FindObject<UEnum>(ANY_PACKAGE, TEXT("EGameplayTaskEvent"));
return GameplayTaskEventEnum->GetDisplayNameTextByValue(static_cast<int64>(Event)).ToString();*/
return Event == EGameplayTaskEvent::Add ? TEXT("Add") : TEXT("Remove");
}
}
UGameplayTasksComponent::FEventLock::FEventLock(UGameplayTasksComponent* InOwner) : Owner(InOwner)
{
if (Owner)
{
Owner->EventLockCounter++;
}
}
UGameplayTasksComponent::FEventLock::~FEventLock()
{
if (Owner)
{
Owner->EventLockCounter--;
if (Owner->TaskEvents.Num() && Owner->CanProcessEvents())
{
Owner->ProcessTaskEvents();
}
}
}
UGameplayTasksComponent::UGameplayTasksComponent(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
PrimaryComponentTick.TickGroup = TG_DuringPhysics;
PrimaryComponentTick.bStartWithTickEnabled = false;
PrimaryComponentTick.bCanEverTick = true;
bReplicates = true;
bInEventProcessingInProgress = false;
TopActivePriority = 0;
}
void UGameplayTasksComponent::OnGameplayTaskActivated(UGameplayTask& Task)
{
// process events after finishing all operations
FEventLock ScopeEventLock(this);
KnownTasks.Add(&Task);
if (Task.IsTickingTask())
{
check(TickingTasks.Contains(&Task) == false);
TickingTasks.Add(&Task);
// If this is our first ticking task, set this component as active so it begins ticking
if (TickingTasks.Num() == 1)
{
UpdateShouldTick();
}
}
if (Task.IsSimulatedTask())
{
check(SimulatedTasks.Contains(&Task) == false);
SimulatedTasks.Add(&Task);
}
IGameplayTaskOwnerInterface* TaskOwner = Task.GetTaskOwner();
if (!Task.IsOwnedByTasksComponent() && TaskOwner)
{
TaskOwner->OnGameplayTaskActivated(Task);
}
}
void UGameplayTasksComponent::OnGameplayTaskDeactivated(UGameplayTask& Task)
{
// process events after finishing all operations
FEventLock ScopeEventLock(this);
const bool bIsFinished = (Task.GetState() == EGameplayTaskState::Finished);
if (Task.GetChildTask() && bIsFinished)
{
if (Task.HasOwnerFinished())
{
Task.GetChildTask()->TaskOwnerEnded();
}
else
{
Task.GetChildTask()->EndTask();
}
}
if (Task.IsTickingTask())
{
// If we are removing our last ticking task, set this component as inactive so it stops ticking
TickingTasks.RemoveSingleSwap(&Task);
}
if (bIsFinished)
{
// using RemoveSwap rather than RemoveSingleSwap since a Task can be added
// to KnownTasks both when activating as well as unpausing
// while removal happens only once. It's cheaper to handle it here.
KnownTasks.RemoveSwap(&Task);
}
if (Task.IsSimulatedTask())
{
SimulatedTasks.RemoveSingleSwap(&Task);
}
// Resource-using task
if (Task.RequiresPriorityOrResourceManagement() && bIsFinished)
{
OnTaskEnded(Task);
}
IGameplayTaskOwnerInterface* TaskOwner = Task.GetTaskOwner();
if (!Task.IsOwnedByTasksComponent() && !Task.HasOwnerFinished() && TaskOwner)
{
TaskOwner->OnGameplayTaskDeactivated(Task);
}
UpdateShouldTick();
}
void UGameplayTasksComponent::OnTaskEnded(UGameplayTask& Task)
{
ensure(Task.RequiresPriorityOrResourceManagement() == true);
RemoveResourceConsumingTask(Task);
}
void UGameplayTasksComponent::GetLifetimeReplicatedProps(TArray< FLifetimeProperty >& OutLifetimeProps) const
{
// Intentionally not calling super: We do not want to replicate bActive which controls ticking. We sometimes need to tick on client predictively.
DOREPLIFETIME_CONDITION(UGameplayTasksComponent, SimulatedTasks, COND_SkipOwner);
}
bool UGameplayTasksComponent::ReplicateSubobjects(UActorChannel* Channel, class FOutBunch *Bunch, FReplicationFlags *RepFlags)
{
bool WroteSomething = Super::ReplicateSubobjects(Channel, Bunch, RepFlags);
if (!RepFlags->bNetOwner)
{
for (UGameplayTask* SimulatedTask : SimulatedTasks)
{
if (SimulatedTask && !SimulatedTask->IsPendingKill())
{
WroteSomething |= Channel->ReplicateSubobject(SimulatedTask, *Bunch, *RepFlags);
}
}
}
return WroteSomething;
}
void UGameplayTasksComponent::OnRep_SimulatedTasks()
{
for (UGameplayTask* SimulatedTask : SimulatedTasks)
{
// Temp check
if (SimulatedTask && SimulatedTask->IsTickingTask() && TickingTasks.Contains(SimulatedTask) == false)
{
SimulatedTask->InitSimulatedTask(*this);
if (TickingTasks.Num() == 0)
{
UpdateShouldTick();
}
TickingTasks.Add(SimulatedTask);
}
}
}
void UGameplayTasksComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction)
{
SCOPE_CYCLE_COUNTER(STAT_TickGameplayTasks);
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
// Because we have no control over what a task may do when it ticks, we must be careful.
// Ticking a task may kill the task right here. It could also potentially kill another task
// which was waiting on the original task to do something. Since when a tasks is killed, it removes
// itself from the TickingTask list, we will make a copy of the tasks we want to service before ticking any
int32 NumTickingTasks = TickingTasks.Num();
int32 NumActuallyTicked = 0;
switch (NumTickingTasks)
{
case 0:
break;
case 1:
if (TickingTasks[0])
{
TickingTasks[0]->TickTask(DeltaTime);
NumActuallyTicked++;
}
break;
default:
{
static TArray<UGameplayTask*> LocalTickingTasks;
LocalTickingTasks.Reset();
LocalTickingTasks.Append(TickingTasks);
for (UGameplayTask* TickingTask : LocalTickingTasks)
{
if (TickingTask)
{
TickingTask->TickTask(DeltaTime);
NumActuallyTicked++;
}
}
}
break;
};
// Stop ticking if no more active tasks
if (NumActuallyTicked == 0)
{
TickingTasks.SetNum(0, false);
UpdateShouldTick();
}
}
bool UGameplayTasksComponent::GetShouldTick() const
{
return TickingTasks.Num() > 0;
}
void UGameplayTasksComponent::RequestTicking()
{
if (bIsActive == false)
{
SetActive(true);
}
}
void UGameplayTasksComponent::UpdateShouldTick()
{
const bool bShouldTick = GetShouldTick();
if (bIsActive != bShouldTick)
{
SetActive(bShouldTick);
}
}
//----------------------------------------------------------------------//
// Priority and resources handling
//----------------------------------------------------------------------//
void UGameplayTasksComponent::AddTaskReadyForActivation(UGameplayTask& NewTask)
{
UE_VLOG(this, LogGameplayTasks, Log, TEXT("AddTaskReadyForActivation %s"), *NewTask.GetName());
ensure(NewTask.RequiresPriorityOrResourceManagement() == true);
TaskEvents.Add(FGameplayTaskEventData(EGameplayTaskEvent::Add, NewTask));
// trigger the actual processing only if it was the first event added to the list
if (TaskEvents.Num() == 1 && CanProcessEvents())
{
ProcessTaskEvents();
}
}
void UGameplayTasksComponent::RemoveResourceConsumingTask(UGameplayTask& Task)
{
UE_VLOG(this, LogGameplayTasks, Log, TEXT("RemoveResourceConsumingTask %s"), *Task.GetName());
TaskEvents.Add(FGameplayTaskEventData(EGameplayTaskEvent::Remove, Task));
// trigger the actual processing only if it was the first event added to the list
if (TaskEvents.Num() == 1 && CanProcessEvents())
{
ProcessTaskEvents();
}
}
void UGameplayTasksComponent::EndAllResourceConsumingTasksOwnedBy(const IGameplayTaskOwnerInterface& TaskOwner)
{
FEventLock ScopeEventLock(this);
for (int32 Idx = 0; Idx < TaskPriorityQueue.Num(); Idx++)
{
if (TaskPriorityQueue[Idx] && TaskPriorityQueue[Idx]->GetTaskOwner() == &TaskOwner)
{
// finish task, remove event will be processed after all locks are cleared
TaskPriorityQueue[Idx]->TaskOwnerEnded();
}
}
}
bool UGameplayTasksComponent::FindAllResourceConsumingTasksOwnedBy(const IGameplayTaskOwnerInterface& TaskOwner, TArray<UGameplayTask*>& FoundTasks) const
{
int32 NumFound = 0;
for (int32 TaskIndex = 0; TaskIndex < TaskPriorityQueue.Num(); TaskIndex++)
{
if (TaskPriorityQueue[TaskIndex] && TaskPriorityQueue[TaskIndex]->GetTaskOwner() == &TaskOwner)
{
FoundTasks.Add(TaskPriorityQueue[TaskIndex]);
NumFound++;
}
}
return (NumFound > 0);
}
UGameplayTask* UGameplayTasksComponent::FindResourceConsumingTaskByName(const FName TaskInstanceName) const
{
for (int32 TaskIndex = 0; TaskIndex < TaskPriorityQueue.Num(); TaskIndex++)
{
if (TaskPriorityQueue[TaskIndex] && TaskPriorityQueue[TaskIndex]->GetInstanceName() == TaskInstanceName)
{
return TaskPriorityQueue[TaskIndex];
}
}
return nullptr;
}
bool UGameplayTasksComponent::HasActiveTasks(UClass* TaskClass) const
{
for (int32 Idx = 0; Idx < KnownTasks.Num(); Idx++)
{
if (KnownTasks[Idx] && KnownTasks[Idx]->IsA(TaskClass))
{
return true;
}
}
return false;
}
void UGameplayTasksComponent::ProcessTaskEvents()
{
static const int32 MaxIterations = 16;
bInEventProcessingInProgress = true;
int32 IterCounter = 0;
while (TaskEvents.Num() > 0)
{
IterCounter++;
if (IterCounter > MaxIterations)
{
UE_VLOG(this, LogGameplayTasks, Error, TEXT("UGameplayTasksComponent::ProcessTaskEvents has exceeded allowes number of iterations. Check your GameplayTasks for logic loops!"));
TaskEvents.Reset();
break;
}
for (int32 EventIndex = 0; EventIndex < TaskEvents.Num(); ++EventIndex)
{
UE_VLOG(this, LogGameplayTasks, Verbose, TEXT("UGameplayTasksComponent::ProcessTaskEvents: %s event %s")
, *TaskEvents[EventIndex].RelatedTask.GetName(), GetGameplayTaskEventName(TaskEvents[EventIndex].Event));
if (TaskEvents[EventIndex].RelatedTask.IsPendingKill())
{
UE_VLOG(this, LogGameplayTasks, Verbose, TEXT("%s is PendingKill"), *TaskEvents[EventIndex].RelatedTask.GetName());
// we should ignore it, but just in case run the removal code.
RemoveTaskFromPriorityQueue(TaskEvents[EventIndex].RelatedTask);
continue;
}
switch (TaskEvents[EventIndex].Event)
{
case EGameplayTaskEvent::Add:
if (TaskEvents[EventIndex].RelatedTask.TaskState != EGameplayTaskState::Finished)
{
AddTaskToPriorityQueue(TaskEvents[EventIndex].RelatedTask);
}
else
{
UE_VLOG(this, LogGameplayTasks, Error, TEXT("UGameplayTasksComponent::ProcessTaskEvents trying to add a finished task to priority queue!"));
}
break;
case EGameplayTaskEvent::Remove:
RemoveTaskFromPriorityQueue(TaskEvents[EventIndex].RelatedTask);
break;
default:
checkNoEntry();
break;
}
}
TaskEvents.Reset();
UpdateTaskActivations();
// task activation changes may create new events, loop over to check it
}
bInEventProcessingInProgress = false;
}
void UGameplayTasksComponent::AddTaskToPriorityQueue(UGameplayTask& NewTask)
{
const bool bStartOnTopOfSamePriority = (NewTask.GetResourceOverlapPolicy() == ETaskResourceOverlapPolicy::StartOnTop);
int32 InsertionPoint = INDEX_NONE;
for (int32 Idx = 0; Idx < TaskPriorityQueue.Num(); ++Idx)
{
if (TaskPriorityQueue[Idx] == nullptr)
{
continue;
}
if ((bStartOnTopOfSamePriority && TaskPriorityQueue[Idx]->GetPriority() <= NewTask.GetPriority())
|| (!bStartOnTopOfSamePriority && TaskPriorityQueue[Idx]->GetPriority() < NewTask.GetPriority()))
{
TaskPriorityQueue.Insert(&NewTask, Idx);
InsertionPoint = Idx;
break;
}
}
if (InsertionPoint == INDEX_NONE)
{
TaskPriorityQueue.Add(&NewTask);
}
}
void UGameplayTasksComponent::RemoveTaskFromPriorityQueue(UGameplayTask& Task)
{
const int32 RemovedTaskIndex = TaskPriorityQueue.Find(&Task);
if (RemovedTaskIndex != INDEX_NONE)
{
TaskPriorityQueue.RemoveAt(RemovedTaskIndex, 1, /*bAllowShrinking=*/false);
}
else
{
// take a note and ignore
UE_VLOG(this, LogGameplayTasks, Verbose, TEXT("RemoveTaskFromPriorityQueue for %s called, but it's not in the queue. Might have been already removed"), *Task.GetName());
}
}
void UGameplayTasksComponent::UpdateTaskActivations()
{
FGameplayResourceSet ResourcesClaimed;
bool bHasNulls = false;
if (TaskPriorityQueue.Num() > 0)
{
TArray<UGameplayTask*> ActivationList;
ActivationList.Reserve(TaskPriorityQueue.Num());
FGameplayResourceSet ResourcesBlocked;
for (int32 TaskIndex = 0; TaskIndex < TaskPriorityQueue.Num(); ++TaskIndex)
{
if (TaskPriorityQueue[TaskIndex])
{
const FGameplayResourceSet RequiredResources = TaskPriorityQueue[TaskIndex]->GetRequiredResources();
const FGameplayResourceSet ClaimedResources = TaskPriorityQueue[TaskIndex]->GetClaimedResources();
if (RequiredResources.GetOverlap(ResourcesBlocked).IsEmpty())
{
// postpone activations, it's some tasks (like MoveTo) require pausing old ones first
ActivationList.Add(TaskPriorityQueue[TaskIndex]);
ResourcesClaimed.AddSet(ClaimedResources);
}
else
{
TaskPriorityQueue[TaskIndex]->PauseInTaskQueue();
}
ResourcesBlocked.AddSet(ClaimedResources);
}
else
{
bHasNulls = true;
UE_VLOG(this, LogGameplayTasks, Warning, TEXT("UpdateTaskActivations found null entry in task queue at index:%d!"), TaskIndex);
}
}
for (int32 Idx = 0; Idx < ActivationList.Num(); Idx++)
{
// check if task wasn't already finished as a result of activating previous elements of this list
if (ActivationList[Idx] != nullptr
&& ActivationList[Idx]->IsFinished() == false
&& ActivationList[Idx]->IsPendingKill() == false)
{
ActivationList[Idx]->ActivateInTaskQueue();
}
}
}
SetCurrentlyClaimedResources(ResourcesClaimed);
// remove all null entries after processing activation changes
if (bHasNulls)
{
TaskPriorityQueue.RemoveAll([](UGameplayTask* Task) { return Task == nullptr; });
}
}
void UGameplayTasksComponent::SetCurrentlyClaimedResources(FGameplayResourceSet NewClaimedSet)
{
if (CurrentlyClaimedResources != NewClaimedSet)
{
FGameplayResourceSet ReleasedResources = FGameplayResourceSet(CurrentlyClaimedResources).RemoveSet(NewClaimedSet);
FGameplayResourceSet ClaimedResources = FGameplayResourceSet(NewClaimedSet).RemoveSet(CurrentlyClaimedResources);
CurrentlyClaimedResources = NewClaimedSet;
OnClaimedResourcesChange.Broadcast(ClaimedResources, ReleasedResources);
}
}
//----------------------------------------------------------------------//
// debugging
//----------------------------------------------------------------------//
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
FString UGameplayTasksComponent::GetTickingTasksDescription() const
{
FString TasksDescription;
for (auto& Task : TickingTasks)
{
if (Task)
{
TasksDescription += FString::Printf(TEXT("\n%s %s"), *GetTaskStateName(Task->GetState()), *Task->GetDebugDescription());
}
else
{
TasksDescription += TEXT("\nNULL");
}
}
return TasksDescription;
}
FString UGameplayTasksComponent::GetKnownTasksDescription() const
{
FString TasksDescription;
for (auto& Task : KnownTasks)
{
if (Task)
{
TasksDescription += FString::Printf(TEXT("\n%s %s"), *GetTaskStateName(Task->GetState()), *Task->GetDebugDescription());
}
else
{
TasksDescription += TEXT("\nNULL");
}
}
return TasksDescription;
}
FString UGameplayTasksComponent::GetTasksPriorityQueueDescription() const
{
FString TasksDescription;
for (auto Task : TaskPriorityQueue)
{
if (Task != nullptr)
{
TasksDescription += FString::Printf(TEXT("\n%s %s"), *GetTaskStateName(Task->GetState()), *Task->GetDebugDescription());
}
else
{
TasksDescription += TEXT("\nNULL");
}
}
return TasksDescription;
}
FString UGameplayTasksComponent::GetTaskStateName(EGameplayTaskState Value)
{
static const UEnum* Enum = FindObject<UEnum>(ANY_PACKAGE, TEXT("EGameplayTaskState"));
check(Enum);
return Enum->GetNameStringByValue(int64(Value));
}
#endif // !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
FConstGameplayTaskIterator UGameplayTasksComponent::GetTickingTaskIterator() const
{
return TickingTasks.CreateConstIterator();
}
FConstGameplayTaskIterator UGameplayTasksComponent::GetKnownTaskIterator() const
{
return KnownTasks.CreateConstIterator();
}
FConstGameplayTaskIterator UGameplayTasksComponent::GetPriorityQueueIterator() const
{
return TaskPriorityQueue.CreateConstIterator();
}
#if ENABLE_VISUAL_LOG
void UGameplayTasksComponent::DescribeSelfToVisLog(FVisualLogEntry* Snapshot) const
{
static const FString CategoryName = TEXT("GameplayTasks");
static const FString PriorityQueueName = TEXT("Priority Queue");
static const FString OtherTasksName = TEXT("Other tasks");
if (IsPendingKill())
{
return;
}
FString NotInQueueDesc;
for (auto& Task : KnownTasks)
{
if (Task)
{
if (!Task->RequiresPriorityOrResourceManagement())
{
NotInQueueDesc += FString::Printf(TEXT("\n%s %s %s %s"),
*GetTaskStateName(Task->GetState()), *Task->GetDebugDescription(),
Task->IsTickingTask() ? TEXT("[TICK]") : TEXT(""),
Task->IsSimulatedTask() ? TEXT("[REP]") : TEXT(""));
}
}
else
{
NotInQueueDesc += TEXT("\nNULL");
}
}
FVisualLogStatusCategory StatusCategory(CategoryName);
StatusCategory.Add(OtherTasksName, NotInQueueDesc);
StatusCategory.Add(PriorityQueueName, GetTasksPriorityQueueDescription());
Snapshot->Status.Add(StatusCategory);
}
#endif // ENABLE_VISUAL_LOG
EGameplayTaskRunResult UGameplayTasksComponent::RunGameplayTask(IGameplayTaskOwnerInterface& TaskOwner, UGameplayTask& Task, uint8 Priority, FGameplayResourceSet AdditionalRequiredResources, FGameplayResourceSet AdditionalClaimedResources)
{
const FText NoneText = FText::FromString(TEXT("None"));
if (Task.GetState() == EGameplayTaskState::Paused || Task.GetState() == EGameplayTaskState::Active)
{
// return as success if already running for the same owner, failure otherwise
return Task.GetTaskOwner() == &TaskOwner
? (Task.GetState() == EGameplayTaskState::Paused ? EGameplayTaskRunResult::Success_Paused : EGameplayTaskRunResult::Success_Active)
: EGameplayTaskRunResult::Error;
}
// this is a valid situation if the task has been created via "Construct Object" mechanics
if (Task.GetState() == EGameplayTaskState::Uninitialized)
{
Task.InitTask(TaskOwner, Priority);
}
Task.AddRequiredResourceSet(AdditionalRequiredResources);
Task.AddClaimedResourceSet(AdditionalClaimedResources);
Task.ReadyForActivation();
switch (Task.GetState())
{
case EGameplayTaskState::AwaitingActivation:
case EGameplayTaskState::Paused:
return EGameplayTaskRunResult::Success_Paused;
break;
case EGameplayTaskState::Active:
return EGameplayTaskRunResult::Success_Active;
break;
case EGameplayTaskState::Finished:
return EGameplayTaskRunResult::Success_Active;
break;
}
return EGameplayTaskRunResult::Error;
}
//----------------------------------------------------------------------//
// BP API
//----------------------------------------------------------------------//
EGameplayTaskRunResult UGameplayTasksComponent::K2_RunGameplayTask(TScriptInterface<IGameplayTaskOwnerInterface> TaskOwner, UGameplayTask* Task, uint8 Priority, TArray<TSubclassOf<UGameplayTaskResource> > AdditionalRequiredResources, TArray<TSubclassOf<UGameplayTaskResource> > AdditionalClaimedResources)
{
const FText NoneText = FText::FromString(TEXT("None"));
if (TaskOwner.GetInterface() == nullptr)
{
FMessageLog("PIE").Error(FText::Format(
LOCTEXT("RunGameplayTaskNullOwner", "Tried running a gameplay task {0} while owner is None!"),
Task ? FText::FromName(Task->GetFName()) : NoneText));
return EGameplayTaskRunResult::Error;
}
IGameplayTaskOwnerInterface& OwnerInstance = *TaskOwner;
if (Task == nullptr)
{
FMessageLog("PIE").Error(FText::Format(
LOCTEXT("RunNullGameplayTask", "Tried running a None task for {0}"),
FText::FromString(Cast<UObject>(&OwnerInstance)->GetName())
));
return EGameplayTaskRunResult::Error;
}
if (Task->GetState() == EGameplayTaskState::Paused || Task->GetState() == EGameplayTaskState::Active)
{
FMessageLog("PIE").Warning(FText::Format(
LOCTEXT("RunNullGameplayTask", "Tried running a None task for {0}"),
FText::FromString(Cast<UObject>(&OwnerInstance)->GetName())
));
// return as success if already running for the same owner, failure otherwise
return Task->GetTaskOwner() == &OwnerInstance
? (Task->GetState() == EGameplayTaskState::Paused ? EGameplayTaskRunResult::Success_Paused : EGameplayTaskRunResult::Success_Active)
: EGameplayTaskRunResult::Error;
}
// this is a valid situation if the task has been created via "Construct Object" mechanics
if (Task->GetState() == EGameplayTaskState::Uninitialized)
{
Task->InitTask(OwnerInstance, Priority);
}
Task->AddRequiredResourceSet(AdditionalRequiredResources);
Task->AddClaimedResourceSet(AdditionalClaimedResources);
Task->ReadyForActivation();
switch (Task->GetState())
{
case EGameplayTaskState::AwaitingActivation:
case EGameplayTaskState::Paused:
return EGameplayTaskRunResult::Success_Paused;
break;
case EGameplayTaskState::Active:
return EGameplayTaskRunResult::Success_Active;
break;
case EGameplayTaskState::Finished:
return EGameplayTaskRunResult::Success_Active;
break;
}
return EGameplayTaskRunResult::Error;
}
//----------------------------------------------------------------------//
// FGameplayResourceSet
//----------------------------------------------------------------------//
FString FGameplayResourceSet::GetDebugDescription() const
{
static const int32 FlagsCount = sizeof(FFlagContainer) * 8;
FFlagContainer FlagsCopy = Flags;
int32 FlagIndex = 0;
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
FString Description;
for (; FlagIndex < FlagsCount && FlagsCopy != 0; ++FlagIndex)
{
if (FlagsCopy & (1 << FlagIndex))
{
Description += UGameplayTaskResource::GetDebugDescription(FlagIndex);
Description += TEXT(' ');
}
FlagsCopy &= ~(1 << FlagIndex);
}
return Description;
#else
TCHAR Description[FlagsCount + 1];
for (; FlagIndex < FlagsCount && FlagsCopy != 0; ++FlagIndex)
{
Description[FlagIndex] = (FlagsCopy & (1 << FlagIndex)) ? TCHAR('1') : TCHAR('0');
FlagsCopy &= ~(1 << FlagIndex);
}
Description[FlagIndex] = TCHAR('\0');
return FString(Description);
#endif // !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
}
#undef LOCTEXT_NAMESPACE
| 29.208549 | 305 | 0.728369 | [
"object"
] |
7a5f958b75f35071c0844b9f142f339e61097fa2 | 6,117 | cpp | C++ | MACHINATH/MACHINATH/pickup.cpp | susajin/MACHINATH | 1e75097f86218f143411885240bbcf211a6e9c99 | [
"MIT"
] | null | null | null | MACHINATH/MACHINATH/pickup.cpp | susajin/MACHINATH | 1e75097f86218f143411885240bbcf211a6e9c99 | [
"MIT"
] | null | null | null | MACHINATH/MACHINATH/pickup.cpp | susajin/MACHINATH | 1e75097f86218f143411885240bbcf211a6e9c99 | [
"MIT"
] | null | null | null | #include <vector>
#include "sound.h"
#include "common.h"
#include "pickup.h"
#include "customMath.h"
#include "mydirect3d.h"
#include "player.h"
#include "effect.h"
#include "score.h"
// globals
static std::vector<Pickup*> g_pickup;
static float g_zRotSpeed = 0;
void SpawnPickupAtRandom(Map* map);
void Pickup::Draw()
{
#if _DEBUG
if(enableDraw)
BoxCollider::DrawCollider(col, D3DCOLOR(D3DCOLOR_RGBA(0, 255, 255, 255)));
#endif
MeshObject::Draw();
}
void InitPickup()
{
// init
g_zRotSpeed = 10;
g_pickup = std::vector<Pickup*>();
// spawn pickups at random
for (Map* map : *GetMap())
{
SpawnPickupAtRandom(map);
}
}
void UninitPickup()
{
// free memory
for (int i = 0; i < g_pickup.size(); ++i)
SAFE_DELETE(g_pickup[i]);
g_pickup.clear();
}
void UpdatePickup()
{
// loop for every pickup
for (int i = 0; i < g_pickup.size(); i++)
{
if (!g_pickup[i]->enableDraw) break;
// rotate pickup
g_pickup[i]->transform.localRotation.y += g_zRotSpeed;
// check for collision with player
if (GetCurrentMapId() == g_pickup[i]->mapId && g_pickup[i]->col.CheckCollision(GetPlayer()->col))
{
// collided, play effect and delete pickup
PlayEffect(EFFECT_GOLD, g_pickup[i]->GetCombinedPosition(), { 0, 0, 0 }, {0.2F,0.2F,0.2F});
PlaySound(AUIDO_SE_PICKUP);
SAFE_DELETE(g_pickup[i]);
AddScore(100);
g_pickup.erase(g_pickup.begin() + i);
}
}
}
void CleanPickup(int mapId)
{
// delete all pickups with the given mapId
for (int i = 0; i < g_pickup.size(); ++i)
{
if (g_pickup[i]->mapId > mapId) return;
if (g_pickup[i]->mapId == mapId)
{
delete g_pickup[i];
g_pickup.erase(g_pickup.begin() + i);
--i;
}
}
}
void SpawnPickupAtRandom(Map* map)
{
if (map->mapType == MapType::STRAIGHT)
{
if (map->exit == Direction::NORTH || map->exit == Direction::SOUTH)
{
float r = (rand() % 31) - 15;
SpawnPickup({ r,2,-10 }, map);
SpawnPickup({ r,2,0 }, map);
SpawnPickup({ r,2,10 }, map);
return;
}
if (map->exit == Direction::EAST || map->exit == Direction::WEST)
{
float r = (rand() % 31) - 15;
SpawnPickup({ -10,2,r }, map);
SpawnPickup({ 0,2,r }, map);
SpawnPickup({ 10,2,r }, map);
return;
}
}
if (map->mapType == MapType::FALLHOLE)
{
if (map->exit == Direction::NORTH || map->exit == Direction::SOUTH)
{
float r = (rand() % 31) - 15;
SpawnPickup({ r,15,-30 }, map);
SpawnPickup({ r,17,-20 }, map);
SpawnPickup({ r,19,-10 }, map);
SpawnPickup({ r,21,0 }, map);
SpawnPickup({ r,19,10 }, map);
SpawnPickup({ r,17,20 }, map);
SpawnPickup({ r,15,30 }, map);
return;
}
if (map->exit == Direction::EAST || map->exit == Direction::WEST)
{
float r = (rand() % 31) - 15;
SpawnPickup({ -30,15,r }, map);
SpawnPickup({ -20,17,r }, map);
SpawnPickup({ -10,19,r }, map);
SpawnPickup({ 0, 21,r }, map);
SpawnPickup({ 10, 19,r }, map);
SpawnPickup({ 20, 17,r }, map);
SpawnPickup({ 30, 15,r }, map);
return;
}
}
if (map->mapType == MapType::SLOPE)
{
if (map->exit == Direction::NORTH)
{
int inv = rand() % 2 ? 1 : -1;
SpawnPickup({ -10.0F * inv, 10, -30 }, map);
SpawnPickup({ 0, 20, 0 }, map);
SpawnPickup({ 10.0F * inv, 30, 30 }, map);
return;
}
if (map->exit == Direction::SOUTH)
{
int inv = rand() % 2 ? 1 : -1;
SpawnPickup({ -10.0F * inv, 30, -30 }, map);
SpawnPickup({ 0, 20, 0 }, map);
SpawnPickup({ 10.0F * inv, 10, 30 }, map);
return;
}
if (map->exit == Direction::EAST)
{
int inv = rand() % 2 ? 1 : -1;
SpawnPickup({ -30, 10, -10.0F * inv }, map);
SpawnPickup({ 0, 20, 0 }, map);
SpawnPickup({ 30, 30, 10.0F * inv }, map);
return;
}
if (map->exit == Direction::WEST)
{
int inv = rand() % 2 ? 1 : -1;
SpawnPickup({ 30, 10, -10.0F * inv }, map);
SpawnPickup({ 0, 20, 0 }, map);
SpawnPickup({ -30, 30, 10.0F * inv }, map);
return;
}
}
if (map->mapType == MapType::TUNNEL)
{
if (map->exit == Direction::NORTH)
{
float r = (rand() % 21) - 10;
SpawnPickup({ r, 1, 0 }, map);
SpawnPickup({ r, -2.5F, 10 }, map);
SpawnPickup({ r, -6, 20 }, map);
r = (rand() % 21) - 10;
SpawnPickup({ r, -35, 100 }, map);
SpawnPickup({ r, -38.5F, 110 }, map);
SpawnPickup({ r, -42, 120 }, map);
return;
}
if (map->exit == Direction::SOUTH)
{
float r = (rand() % 21) - 10;
SpawnPickup({ r, 1, 0 }, map);
SpawnPickup({ r, -2.5F, -10 }, map);
SpawnPickup({ r, -6, -20 }, map);
r = (rand() % 21) - 10;
SpawnPickup({ r, -35, -100 }, map);
SpawnPickup({ r, -38.5F, -110 }, map);
SpawnPickup({ r, -42, -120 }, map);
return;
}
if (map->exit == Direction::EAST)
{
float r = (rand() % 21) - 10;
SpawnPickup({ 0, 1, r }, map);
SpawnPickup({ 10, -2.5F, r }, map);
SpawnPickup({ 20, -6, r}, map);
r = (rand() % 21) - 10;
SpawnPickup({ 100, -35, r }, map);
SpawnPickup({ 110, -38.5F, r }, map);
SpawnPickup({ 120, -42, r }, map);
return;
}
if (map->exit == Direction::WEST)
{
float r = (rand() % 21) - 10;
SpawnPickup({ 0, 1, r }, map);
SpawnPickup({ -10, -2.5F, r }, map);
SpawnPickup({ -20, -6, r }, map);
r = (rand() % 21) - 10;
SpawnPickup({ -100, -35, r }, map);
SpawnPickup({ -110, -38.5F, r }, map);
SpawnPickup({ -120, -42, r }, map);
return;
}
}
}
void SpawnPickup(D3DXVECTOR3 position, Map* parent)
{
SpawnPickup(position.x, position.y, position.z, parent);
}
void SpawnPickup(float posX, float posY, float posZ, Map* parent)
{
Transform trans(D3DXVECTOR3(posX, posY, posZ), D3DXVECTOR3(0, 0, 0), D3DXVECTOR3(0, 90, 0), D3DXVECTOR3(0.2F, 0.2F, 0.2F));
g_pickup.emplace_back(new Pickup(parent->id, trans, MESH_COIN, SHADER_DEFAULT, 12, 12, 12, true, parent));
g_pickup.back()->enableDraw = parent->enableDraw;
}
std::vector<Pickup*>* GetPickup()
{
return &g_pickup;
}
| 23.709302 | 125 | 0.547 | [
"vector",
"transform"
] |
7a703e769aaff1d9111601503cb6d7d6d462b6de | 18,332 | cpp | C++ | src/io/hdf5functions_blosc.cpp | mosaic-group/LibAPR | 69097a662bf671d77a548fc47dae2c590675bfac | [
"Apache-2.0"
] | 27 | 2018-12-03T20:38:44.000Z | 2022-03-23T17:53:51.000Z | src/io/hdf5functions_blosc.cpp | mosaic-group/LibAPR | 69097a662bf671d77a548fc47dae2c590675bfac | [
"Apache-2.0"
] | 49 | 2018-11-28T09:10:56.000Z | 2022-01-12T20:42:11.000Z | src/io/hdf5functions_blosc.cpp | mosaic-group/LibAPR | 69097a662bf671d77a548fc47dae2c590675bfac | [
"Apache-2.0"
] | 7 | 2018-12-07T19:30:53.000Z | 2020-10-03T14:38:07.000Z | ///////////////////////////////////////////
//
// ImageGen 2016
//
// Bevan Cheeseman 2016
//
// Header file with some specific hdf5 functions
//
//////////////////////////////////////////
#include "hdf5functions_blosc.h"
/**
* Register the 'blosc' filter with the HDF5 library
*/
void hdf5_register_blosc(){
register_blosc(nullptr, nullptr);
}
/**
* reads data from hdf5
*/
void hdf5_load_data_blosc(hid_t obj_id, hid_t dataType, void* buff, const char* data_name) {
hid_t data_id = H5Dopen2(obj_id, data_name ,H5P_DEFAULT);
H5Dread(data_id, dataType, H5S_ALL, H5S_ALL, H5P_DEFAULT, buff);
H5Dclose(data_id);
}
/**
* reads data from hdf5 (data type auto-detection)
*/
void hdf5_load_data_blosc(hid_t obj_id, void* buff, const char* data_name) {
hid_t data_id = H5Dopen2(obj_id, data_name ,H5P_DEFAULT);
hid_t dataType = H5Dget_type(data_id);
H5Dread(data_id, dataType, H5S_ALL, H5S_ALL, H5P_DEFAULT, buff);
H5Tclose(dataType);
H5Dclose(data_id);
}
/**
* reads only a set number of elements
*/
void hdf5_load_data_blosc_partial(hid_t obj_id, void* buff, const char* data_name,uint64_t elements_start,uint64_t elements_end) {
hid_t data_id = H5Dopen2(obj_id, data_name ,H5P_DEFAULT);
hid_t memspace_id=0;
hid_t dataspace_id=0;
hid_t dataType = H5Dget_type(data_id);
hsize_t dims = elements_end - elements_start;
memspace_id = H5Screate_simple (1, &dims, NULL);
hsize_t offset = elements_start;
hsize_t count = dims;
hsize_t stride = 1;
hsize_t block = 1;
dataspace_id = H5Dget_space (data_id);
H5Sselect_hyperslab (dataspace_id, H5S_SELECT_SET, &offset,
&stride, &count, &block);
H5Dread(data_id, dataType, memspace_id, dataspace_id, H5P_DEFAULT, buff);
H5Sclose (memspace_id);
H5Sclose (dataspace_id);
H5Tclose(dataType);
H5Dclose(data_id);
}
/**
* writes only a set number of elements
*/
void hdf5_write_data_blosc_partial(hid_t obj_id, void* buff, const char* data_name,uint64_t elements_start,uint64_t elements_end) {
hid_t data_id = H5Dopen2(obj_id, data_name ,H5P_DEFAULT);
hid_t memspace_id=0;
hid_t dataspace_id=0;
hid_t dataType = H5Dget_type(data_id);
hsize_t dims = elements_end - elements_start;
memspace_id = H5Screate_simple (1, &dims, NULL);
hsize_t offset = elements_start;
hsize_t count = dims;
hsize_t stride = 1;
hsize_t block = 1;
dataspace_id = H5Dget_space (data_id);
H5Sselect_hyperslab (dataspace_id, H5S_SELECT_SET, &offset,
&stride, &count, &block);
H5Dwrite(data_id, dataType, memspace_id, dataspace_id, H5P_DEFAULT, buff);
H5Sclose (memspace_id);
H5Sclose (dataspace_id);
H5Tclose(dataType);
H5Dclose(data_id);
}
/**
* writes data to the hdf5 file or group identified by obj_id of hdf5 datatype data_type
*/
void hdf5_create_dataset_blosc(hid_t obj_id, hid_t type_id, const char *ds_name, hsize_t rank, hsize_t *dims,unsigned int comp_type,unsigned int comp_level,unsigned int shuffle) {
hid_t plist_id = H5Pcreate(H5P_DATASET_CREATE);
// Dataset must be chunked for compression
const uint64_t max_size = 100000;
hsize_t cdims = (dims[0] < max_size) ? dims[0] : max_size;
rank = 1;
H5Pset_chunk(plist_id, rank, &cdims);
/////SET COMPRESSION TYPE /////
// But you can also taylor Blosc parameters to your needs
// 0 to 3 (inclusive) param slots are reserved.
const int numOfParams = 7;
unsigned int cd_values[numOfParams];
cd_values[4] = comp_level; // compression level
cd_values[5] = shuffle; // 0: shuffle not active, 1: shuffle active
cd_values[6] = comp_type; // the actual compressor to use
H5Pset_filter(plist_id, FILTER_BLOSC, H5Z_FLAG_OPTIONAL, numOfParams, cd_values);
//create write and close
hid_t space_id = H5Screate_simple(rank, dims, NULL);
hid_t dset_id = H5Dcreate2(obj_id, ds_name, type_id, space_id, H5P_DEFAULT, plist_id, H5P_DEFAULT);
H5Dclose(dset_id);
H5Pclose(plist_id);
}
/**
* writes data to the hdf5 file or group identified by obj_id of hdf5 datatype data_type
*/
void hdf5_write_data_blosc(hid_t obj_id, hid_t type_id, const char *ds_name, hsize_t rank, hsize_t *dims, void *data ,unsigned int comp_type,unsigned int comp_level,unsigned int shuffle) {
hid_t plist_id = H5Pcreate(H5P_DATASET_CREATE);
// Dataset must be chunked for compression
const uint64_t max_size = 100000;
hsize_t cdims = (dims[0] < max_size) ? dims[0] : max_size;
rank = 1;
H5Pset_chunk(plist_id, rank, &cdims);
/////SET COMPRESSION TYPE /////
// But you can also taylor Blosc parameters to your needs
// 0 to 3 (inclusive) param slots are reserved.
const int numOfParams = 7;
unsigned int cd_values[numOfParams];
cd_values[4] = comp_level; // compression level
cd_values[5] = shuffle; // 0: shuffle not active, 1: shuffle active
cd_values[6] = comp_type; // the actual compressor to use
H5Pset_filter(plist_id, FILTER_BLOSC, H5Z_FLAG_OPTIONAL, numOfParams, cd_values);
//create write and close
hid_t space_id = H5Screate_simple(rank, dims, nullptr);
hid_t dset_id = H5Dcreate2(obj_id, ds_name, type_id, space_id, H5P_DEFAULT, plist_id, H5P_DEFAULT);
H5Dwrite(dset_id,type_id,H5S_ALL,H5S_ALL,H5P_DEFAULT,data);
H5Dclose(dset_id);
H5Pclose(plist_id);
}
void
hdf5_write_data_blosc_create(hid_t obj_id, hid_t type_id, const char *ds_name, hsize_t rank, hsize_t *dims, void *data,
unsigned int comp_type, unsigned int comp_level, unsigned int shuffle) {
hid_t plist_id = H5Pcreate(H5P_DATASET_CREATE);
// Dataset must be chunked for compression
const uint64_t max_size = 100000;
hsize_t cdims = (dims[0] < max_size) ? dims[0] : max_size;
cdims = max_size;
rank = 1;
H5Pset_chunk(plist_id, rank, &cdims);
/////SET COMPRESSION TYPE /////
// But you can also taylor Blosc parameters to your needs
// 0 to 3 (inclusive) param slots are reserved.
const int numOfParams = 7;
unsigned int cd_values[numOfParams];
cd_values[4] = comp_level; // compression level
cd_values[5] = shuffle; // 0: shuffle not active, 1: shuffle active
cd_values[6] = comp_type; // the actual compressor to use
H5Pset_filter(plist_id, FILTER_BLOSC, H5Z_FLAG_OPTIONAL, numOfParams, cd_values);
hsize_t max_dims = H5S_UNLIMITED;
//create write and close
hid_t space_id = H5Screate_simple(rank, dims, &max_dims);
hid_t dset_id = H5Dcreate2(obj_id, ds_name, type_id, space_id, H5P_DEFAULT, plist_id, H5P_DEFAULT);
H5Dwrite(dset_id,type_id,H5S_ALL,H5S_ALL,H5P_DEFAULT,data);
H5Sclose (space_id);
H5Dclose(dset_id);
H5Pclose(plist_id);
}
uint64_t hdf5_write_data_blosc_append(hid_t obj_id, hid_t type_id, const char *ds_name, void *data, hsize_t* num_2_add) {
//
// Appends data to the end of an existing dataset
//
hid_t dset_id = H5Dopen2(obj_id, ds_name ,H5P_DEFAULT);
hid_t dspace = H5Dget_space(dset_id);
hsize_t current_dim;
H5Sget_simple_extent_dims(dspace, ¤t_dim, NULL);
hsize_t new_dim = current_dim+ num_2_add[0];
H5Dset_extent(dset_id, &new_dim);
hid_t memspace_id=0;
hid_t dataspace_id=0;
hid_t dataType = H5Dget_type(dset_id);
//extends the current file
H5Dset_extent(dset_id,&new_dim);
memspace_id = H5Screate_simple (1, num_2_add, NULL);
hsize_t offset = current_dim;
hsize_t count = num_2_add[0];
//hsize_t stride = 1;
//hsize_t block = 1;
dataspace_id = H5Dget_space (dset_id);
H5Sselect_hyperslab (dataspace_id, H5S_SELECT_SET, &offset,
NULL, &count, NULL);
if(new_dim > 0) {
//H5Dwrite(dset, H5T_NATIVE_FLOAT, mem_space, file_space, H5P_DEFAULT, buffer);
H5Dwrite(dset_id, type_id, memspace_id, dataspace_id, H5P_DEFAULT, data);
}
H5Sclose (memspace_id);
H5Sclose (dataspace_id);
H5Sclose (dspace);
H5Tclose(dataType);
H5Dclose(dset_id);
return new_dim;
// H5Dwrite(dset_id,type_id,H5S_ALL,H5S_ALL,H5P_DEFAULT,data);
// H5Dclose(dset_id);
}
/**
* writes data to the hdf5 file or group identified by obj_id of hdf5 datatype data_type without using blosc
*/
void hdf5_write_data_standard(hid_t obj_id, hid_t type_id, const char *ds_name, hsize_t rank, hsize_t *dims, void *data) {
hid_t plist_id = H5Pcreate(H5P_DATASET_CREATE);
// Dataset must be chunked for compression
const uint64_t max_size = 100000;
hsize_t cdims = (dims[0] < max_size) ? dims[0] : max_size;
rank = 1;
H5Pset_chunk(plist_id, rank, &cdims);
//compression parameters
int deflate_level = 9;
/////SET COMPRESSION TYPE /////
//DEFLATE ENCODING (GZIP)
H5Pset_deflate (plist_id, deflate_level);
//create write and close
hid_t space_id = H5Screate_simple(rank, dims, NULL);
hid_t dset_id = H5Dcreate2(obj_id, ds_name, type_id, space_id, H5P_DEFAULT, plist_id, H5P_DEFAULT);
H5Dwrite(dset_id,type_id,H5S_ALL,H5S_ALL,H5P_DEFAULT,data);
H5Dclose(dset_id);
H5Pclose(plist_id);
}
/**
* writes data to the hdf5 file or group identified by obj_id of hdf5 datatype data_type
*/
bool attribute_exists(hid_t obj_id,const char* attr_name){
/* Save old error handler */
herr_t (*old_func)(void*);
void *old_client_data;
H5Eget_auto1(&old_func, &old_client_data);
hid_t attr_id;
/* Turn off error handling */
H5Eset_auto1(NULL, NULL);
attr_id = H5Aopen_name(obj_id,attr_name);
/* Restore previous error handler */
H5Eset_auto1(old_func, old_client_data);
bool exists = (bool)(attr_id > 0);
//if the attribute is not being used, we need to close it.
if(exists){
H5Aclose(attr_id);
}
return exists;
}
bool group_exists(hid_t fileId,const char * attr_name){
/* Save old error handler */
herr_t (*old_func)(void*);
void *old_client_data;
H5Eget_auto1(&old_func, &old_client_data);
hid_t attr_id;
/* Turn off error handling */
H5Eset_auto1(NULL, NULL);
attr_id = H5Gopen2(fileId, attr_name, H5P_DEFAULT);
/* Restore previous error handler */
H5Eset_auto1(old_func, old_client_data);
bool exists = (bool)(attr_id > 0);
//if the attribute is not being used, we need to close it.
if(exists){
H5Gclose(attr_id);
}
return exists;
}
bool data_exists(hid_t fileId,const char * attr_name){
/* Save old error handler */
herr_t (*old_func)(void*);
void *old_client_data;
H5Eget_auto1(&old_func, &old_client_data);
hid_t attr_id;
/* Turn off error handling */
H5Eset_auto1(NULL, NULL);
attr_id = H5Dopen2(fileId, attr_name, H5P_DEFAULT);
/* Restore previous error handler */
H5Eset_auto1(old_func, old_client_data);
bool exists = (bool)(attr_id > 0);
//if the attribute is not being used, we need to close it.
if(exists){
H5Dclose(attr_id);
}
return exists;
}
void hdf5_write_attribute_blosc(hid_t obj_id,hid_t type_id,const char* attr_name,hsize_t rank,hsize_t* dims, const void * const data ){
hid_t exists;
herr_t (*old_func)(void*);
void *old_client_data;
H5Eget_auto1(&old_func, &old_client_data);
/* Turn off error handling */
H5Eset_auto1(NULL, NULL);
exists = H5Aopen_name(obj_id,attr_name);
/* Restore previous error handler */
H5Eset_auto1(old_func, old_client_data);
//does it already exist
//if it already exists then over-write
if(exists<0) {
hid_t attr_id;
//doesn't exist
hid_t space_id = H5Screate_simple(rank, dims, NULL);
attr_id = H5Acreate2(obj_id, attr_name, type_id, space_id, H5P_DEFAULT, H5P_DEFAULT);
H5Awrite(attr_id, type_id, data);
H5Aclose(attr_id);
H5Sclose(space_id);
} else {
//
H5Awrite(exists, type_id, data);
H5Aclose(exists);
}
}
/**
* creates the hdf5 file before you can then write to it
*/
hid_t hdf5_create_file_blosc(std::string file_name){
//hid_t fcpl_id=H5Pcreate(H5P_FILE_CREATE);
//H5Pset_file_space(fcpl_id,H5F_FILE_SPACE_ALL_PERSIST,(hsize_t)0);
//return H5Fcreate(file_name.c_str(),H5F_ACC_TRUNC, fcpl_id, H5P_DEFAULT); //this writes over the current file
return H5Fcreate(file_name.c_str(),H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT); //this writes over the current file
}
void write_main_paraview_xdmf_xml(const std::string &aDestinationDir,const std::string &aHdf5FileName, const std::string &aParaviewFileName, uint64_t aNumOfParticles){
std::ofstream myfile(aDestinationDir + aParaviewFileName + "_paraview.xmf");
myfile << "<?xml version=\"1.0\" ?>\n";
myfile << "<!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\" []>\n";
myfile << "<Xdmf Version=\"2.0\" xmlns:xi=\"[http://www.w3.org/2001/XInclude]\">\n";
myfile << " <Domain>\n";
myfile << " <Grid Name=\"parts\" GridType=\"Uniform\">\n";
myfile << " <Topology TopologyType=\"Polyvertex\" Dimensions=\"" << aNumOfParticles << "\"/>\n";
myfile << " <Geometry GeometryType=\"X_Y_Z\">\n";
myfile << " <DataItem Dimensions=\""<< aNumOfParticles <<"\" NumberType=\"UInt\" Precision=\"2\" Format=\"HDF\">\n";
myfile << " " << aHdf5FileName << ":/ParticleRepr/t/x\n";
myfile << " </DataItem>\n";
myfile << " <DataItem Dimensions=\""<< aNumOfParticles <<"\" NumberType=\"UInt\" Precision=\"2\" Format=\"HDF\">\n";
myfile << " " << aHdf5FileName << ":/ParticleRepr/t/y\n";
myfile << " </DataItem>\n";
myfile << " <DataItem Dimensions=\""<< aNumOfParticles <<"\" NumberType=\"UInt\" Precision=\"2\" Format=\"HDF\">\n";
myfile << " " << aHdf5FileName << ":/ParticleRepr/t/z\n";
myfile << " </DataItem>\n";
myfile << " </Geometry>\n";
myfile << " <Attribute Name=\"particle property\" AttributeType=\"Scalar\" Center=\"Node\">\n";
myfile << " <DataItem Dimensions=\""<< aNumOfParticles <<"\" NumberType=\"UInt\" Precision=\"2\" Format=\"HDF\">\n";
myfile << " " << aHdf5FileName << ":/ParticleRepr/t/particle property\n";
myfile << " </DataItem>\n";
myfile << " </Attribute>\n";
myfile << " <Attribute Name=\"level\" AttributeType=\"Scalar\" Center=\"Node\">\n";
myfile << " <DataItem Dimensions=\""<< aNumOfParticles <<"\" NumberType=\"UInt\" Precision=\"1\" Format=\"HDF\">\n";
myfile << " " << aHdf5FileName << ":/ParticleRepr/t/level\n";
myfile << " </DataItem>\n";
myfile << " </Attribute>\n";
// myfile << " <Attribute Name=\"type\" AttributeType=\"Scalar\" Center=\"Node\">\n";
// myfile << " <DataItem Dimensions=\""<< aNumOfParticles <<"\" NumberType=\"UInt\" Precision=\"1\" Format=\"HDF\">\n";
// myfile << " " << aHdf5FileName << ":/ParticleRepr/t/type\n";
// myfile << " </DataItem>\n";
// myfile << " </Attribute>\n";
myfile << " </Grid>\n";
myfile << " </Domain>\n";
myfile << "</Xdmf>\n";
myfile.close();
}
void write_main_paraview_xdmf_xml_time(const std::string &aDestinationDir,const std::string &aHdf5FileName, const std::string &aParaviewFileName, std::vector<uint64_t> aNumOfParticles){
std::ofstream myfile(aDestinationDir + aParaviewFileName + "_paraview.xmf");
myfile << "<?xml version=\"1.0\" ?>\n";
myfile << "<!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\" []>\n";
myfile << "<Xdmf Version=\"2.0\" xmlns:xi=\"[http://www.w3.org/2001/XInclude]\">\n";
myfile << " <Domain>\n";
myfile << " <Grid Name=\"partsTime\" GridType=\"Collection\" CollectionType=\"Temporal\">\n";
for (int time_step = 0; time_step < (int) aNumOfParticles.size(); ++time_step) {
std::string t_string;
if(time_step==0){
t_string = "t";
} else{
t_string = "t" +std::to_string(time_step);
}
myfile << " <Grid Name=\"parts\" GridType=\"Uniform\">\n";
myfile << " <Time Value=\"" << time_step << "\" />\n";
myfile << " <Topology TopologyType=\"Polyvertex\" Dimensions=\"" << aNumOfParticles[time_step] << "\"/>\n";
myfile << " <Geometry GeometryType=\"X_Y_Z\">\n";
myfile << " <DataItem Dimensions=\"" << aNumOfParticles[time_step] << "\" NumberType=\"UInt\" Precision=\"2\" Format=\"HDF\">\n";
myfile << " " << aHdf5FileName << ":/ParticleRepr/" << t_string <<"/x\n";
myfile << " </DataItem>\n";
myfile << " <DataItem Dimensions=\"" << aNumOfParticles[time_step]
<< "\" NumberType=\"UInt\" Precision=\"2\" Format=\"HDF\">\n";
myfile << " " << aHdf5FileName << ":/ParticleRepr/" << t_string <<"/y\n";
myfile << " </DataItem>\n";
myfile << " <DataItem Dimensions=\"" << aNumOfParticles[time_step]
<< "\" NumberType=\"UInt\" Precision=\"2\" Format=\"HDF\">\n";
myfile << " " << aHdf5FileName << ":/ParticleRepr/" << t_string <<"/z\n";
myfile << " </DataItem>\n";
myfile << " </Geometry>\n";
myfile << " <Attribute Name=\"particle property\" AttributeType=\"Scalar\" Center=\"Node\">\n";
myfile << " <DataItem Dimensions=\"" << aNumOfParticles[time_step]
<< "\" NumberType=\"UInt\" Precision=\"2\" Format=\"HDF\">\n";
myfile << " " << aHdf5FileName << ":/ParticleRepr/" << t_string <<"/particle property\n";
myfile << " </DataItem>\n";
myfile << " </Attribute>\n";
myfile << " <Attribute Name=\"level\" AttributeType=\"Scalar\" Center=\"Node\">\n";
myfile << " <DataItem Dimensions=\"" << aNumOfParticles[time_step]
<< "\" NumberType=\"UInt\" Precision=\"1\" Format=\"HDF\">\n";
myfile << " " << aHdf5FileName << ":/ParticleRepr/" << t_string <<"/level\n";
myfile << " </DataItem>\n";
myfile << " </Attribute>\n";
myfile << " </Grid>\n";
}
myfile << " </Grid>\n";
myfile << " </Domain>\n";
myfile << "</Xdmf>\n";
myfile.close();
}
| 35.253846 | 188 | 0.638283 | [
"geometry",
"vector"
] |
7a717c07688239195bbc6569826f25a7744359e5 | 467 | cpp | C++ | A_problems/translatrion.cpp | tarek99samy/code_forces_problems | a2e6fd1ad762843a4fa1e4a2561299a21ec2bb2e | [
"MIT"
] | null | null | null | A_problems/translatrion.cpp | tarek99samy/code_forces_problems | a2e6fd1ad762843a4fa1e4a2561299a21ec2bb2e | [
"MIT"
] | null | null | null | A_problems/translatrion.cpp | tarek99samy/code_forces_problems | a2e6fd1ad762843a4fa1e4a2561299a21ec2bb2e | [
"MIT"
] | null | null | null | #include<iostream>
using namespace std;
//#include<windows.h>
#include<cstring>
#include<string>
#include<algorithm>
#include<stack>
#include<vector>
#include<cmath>
#include<list>
int main()
{
string s1, s2;
cin >> s1 >> s2;
if (s1.size() != s2.size())
{
cout << "NO\n ";
return 0;
}
int size = s1.size();
for (int i = 0; i < size; i++)
{
if (s1[i] != s2[size - 1 - i])
{
cout << "NO\n ";
return 0;
}
}
cout << "YES\n ";
return 0;
}
| 13.735294 | 34 | 0.554604 | [
"vector"
] |
7a7477d5d795672c06a3ae12e47c4564079cdf4f | 4,008 | cc | C++ | third_party/blink/renderer/core/frame/csp/media_list_directive.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | third_party/blink/renderer/core/frame/csp/media_list_directive.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | third_party/blink/renderer/core/frame/csp/media_list_directive.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/frame/csp/media_list_directive.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/platform/network/content_security_policy_parsers.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
#include "third_party/blink/renderer/platform/wtf/text/parsing_utilities.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
MediaListDirective::MediaListDirective(const String& name,
const String& value,
ContentSecurityPolicy* policy)
: CSPDirective(name, value, policy) {
Vector<UChar> characters;
value.AppendTo(characters);
Parse(characters.data(), characters.data() + characters.size());
}
bool MediaListDirective::Allows(const String& type) const {
return plugin_types_.Contains(type);
}
void MediaListDirective::Parse(const UChar* begin, const UChar* end) {
// TODO(amalika): Revisit parsing algorithm. Right now plugin types are not
// validated when they are added to m_pluginTypes.
const UChar* position = begin;
// 'plugin-types ____;' OR 'plugin-types;'
if (position == end) {
Policy()->ReportInvalidPluginTypes(String());
return;
}
while (position < end) {
// _____ OR _____mime1/mime1
// ^ ^
SkipWhile<UChar, IsASCIISpace>(position, end);
if (position == end)
return;
// mime1/mime1 mime2/mime2
// ^
begin = position;
if (!SkipExactly<UChar, IsMediaTypeCharacter>(position, end)) {
SkipWhile<UChar, IsNotASCIISpace>(position, end);
Policy()->ReportInvalidPluginTypes(String(begin, position - begin));
continue;
}
SkipWhile<UChar, IsMediaTypeCharacter>(position, end);
// mime1/mime1 mime2/mime2
// ^
if (!SkipExactly<UChar>(position, end, '/')) {
SkipWhile<UChar, IsNotASCIISpace>(position, end);
Policy()->ReportInvalidPluginTypes(String(begin, position - begin));
continue;
}
// mime1/mime1 mime2/mime2
// ^
if (!SkipExactly<UChar, IsMediaTypeCharacter>(position, end)) {
SkipWhile<UChar, IsNotASCIISpace>(position, end);
Policy()->ReportInvalidPluginTypes(String(begin, position - begin));
continue;
}
SkipWhile<UChar, IsMediaTypeCharacter>(position, end);
// mime1/mime1 mime2/mime2 OR mime1/mime1 OR mime1/mime1/error
// ^ ^ ^
if (position < end && IsNotASCIISpace(*position)) {
SkipWhile<UChar, IsNotASCIISpace>(position, end);
Policy()->ReportInvalidPluginTypes(String(begin, position - begin));
continue;
}
plugin_types_.insert(String(begin, position - begin));
DCHECK(position == end || IsASCIISpace(*position));
}
}
bool MediaListDirective::Subsumes(
const HeapVector<Member<MediaListDirective>>& other) const {
if (!other.size())
return false;
// Find the effective set of plugins allowed by `other`.
HashSet<String> normalized_b = other[0]->plugin_types_;
for (size_t i = 1; i < other.size(); i++)
normalized_b = other[i]->GetIntersect(normalized_b);
// Empty list of plugins is equivalent to no plugins being allowed.
if (!plugin_types_.size())
return !normalized_b.size();
// Check that each element of `normalizedB` is allowed by `m_pluginTypes`.
for (auto it = normalized_b.begin(); it != normalized_b.end(); ++it) {
if (!Allows(*it))
return false;
}
return true;
}
HashSet<String> MediaListDirective::GetIntersect(
const HashSet<String>& other) const {
HashSet<String> normalized;
for (const auto& type : plugin_types_) {
if (other.Contains(type))
normalized.insert(type);
}
return normalized;
}
} // namespace blink
| 33.123967 | 88 | 0.673154 | [
"vector"
] |
7a822d48316d973a48ca850cb4cf3364885b563e | 6,006 | cpp | C++ | herald-tests-zephyr/src/main.cpp | theheraldproject/herald-for-cpp | 571e92f5c3bb363df40dba98b7e88ffe4609cdc2 | [
"Apache-2.0"
] | 8 | 2021-04-02T22:39:50.000Z | 2022-03-05T21:50:54.000Z | herald-tests-zephyr/src/main.cpp | adamfowleruk/herald-for-cpp | 6268834298462caa26bec84c3ab887e624928304 | [
"Apache-2.0"
] | 49 | 2021-04-02T10:59:42.000Z | 2021-12-30T16:44:46.000Z | herald-tests-zephyr/src/main.cpp | adamfowleruk/herald-for-cpp | 6268834298462caa26bec84c3ab887e624928304 | [
"Apache-2.0"
] | 8 | 2021-03-31T18:57:49.000Z | 2021-09-19T08:53:11.000Z | /*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr/types.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <sys/printk.h>
#include <sys/byteorder.h>
#include <zephyr.h>
#include <kernel_structs.h>
// #include <sys/thread_stack.h> // Cannot be found in NCS v1.6.0
// #include <drivers/gpio.h>
// #include <drivers/hwinfo.h>
#include <logging/log.h>
LOG_MODULE_REGISTER(app, CONFIG_APP_LOG_LEVEL);
// See https://github.com/catchorg/Catch2/blob/devel/docs/own-main.md#top
#define CATCH_CONFIG_RUNNER
#define SA_ONSTACK 0
#define CATCH_CONFIG_NO_POSIX_SIGNALS
#define CATCH_CONFIG_NOSTDOUT
// #define CATCH_CONFIG_DISABLE_EXCEPTIONS
#include "../../herald-tests/catch.hpp"
#include <sstream>
#include <cstdio>
struct k_thread herald_thread;
constexpr int stackMaxSize =
// #ifdef CONFIG_BT_MAX_CONN
// 2048 + (CONFIG_BT_MAX_CONN * 512)
// // Was 12288 + (CONFIG_BT_MAX_CONN * 512), but this starved newlibc of HEAP (used in handling BLE connections/devices)
// #else
// 9192
// #endif
// // Since v2.1 - MEMORY ARENA extra stack reservation - See herald/datatype/data.h
// #ifdef HERALD_MEMORYARENA_MAX
// + HERALD_MEMORYARENA_MAX
// #else
// + 8192
// #endif
// + 4508 // Since v2.1 test for debug
// // + 5120 // Since v2.1 AllocatableArray and removal of vector and map
// // Note +0 crashes at Herald entry, +1024 crashes at PAST DATE, +2048 crashes at creating sensor array
// // +3072 crashes at herald entry with Illegal load of EXC_RETURN into PC
// // +4096 crashes at BEFORE DATE with Stacking error (context area might be not valid)... Data Access Violation... MMFAR Address: 0x20006304
// // +5120 crashes at sensor array running with Stacking error (context area might be not valid)... Data Access Violation... MMFAR Address: 0x20008ae0
// // +6144 crashes at sensor array running with Stacking error (context area might be not valid)... Data Access Violation... MMFAR Address: 0x20008ee0
// // +7168 crashes at sensor array running with Stacking error (context area might be not valid)... Data Access Violation... MMFAR Address: 0x200092e0
// // +8192 crashes at sensor array running with Stacking error (context area might be not valid)... Data Access Violation... MMFAR Address: 0x200096e0
// // +9216 crashes at sensor array running with Stacking error (context area might be not valid)... Data Access Violation... MMFAR Address: 0x20009ae0
// // +10240 crashes zephyr in main thread loop - likely due to memory exhaustion for the heap (over 96% SRAM used at this level)
// // Changed heap for nRF52832 to 1024, max conns to 4 from 2
// // +0 crashes BEFORE DATE with Stacking error (context area might be not valid)... Data Access Violation... MMFAR Address: 0x20006504
// // Changed heap for nRF52832 to 2048. max conns back to 2
// // +4096 crashes BEFORE DATE with Stacking error (context area might be not valid)... Data Access Violation... MMFAR Address: 0x20006904
// // +5120 crashes at sensor array running with Stacking error (context area might be not valid)... Data Access Violation... MMFAR Address: 0x200090e0
// // Additions for catch2
// // + 16384
// ;
65536;
K_THREAD_STACK_DEFINE(herald_stack, stackMaxSize);
// Catch normally uses std::cout but Zephyr doesn't use that - so we need this:-
// from https://github.com/catchorg/Catch2/issues/1290
class out_buff : public std::stringbuf {
std::FILE* m_stream;
public:
out_buff(std::FILE* stream):m_stream(stream) {}
~out_buff();
int sync() override {
int ret = 0;
// for (unsigned char c : str()) {
// if (putc(c, m_stream) == EOF) {
// ret = -1;
// break;
// }
// }
LOG_ERR("Catch2: %s",log_strdup(str().c_str()));
// Reset the buffer to avoid printing it multiple times
str("");
return ret;
}
};
out_buff::~out_buff() { pubsync(); }
#if defined(__clang__)
#pragma clang diagnostic ignored "-Wexit-time-destructors" // static variables in cout/cerr/clog
#endif
namespace Catch {
std::ostream& cout() {
static std::ostream ret(new out_buff(stdout));
return ret;
}
std::ostream& clog() {
static std::ostream ret(new out_buff(stderr));
return ret;
}
std::ostream& cerr() {
return clog();
}
}
// Fatal thread failure error handler in Zephyr
void k_sys_fatal_error_handler(unsigned int reason, const z_arch_esf_t *esf) {
LOG_DBG("Kernel fatal thread failure with reason: %d", reason);
// Always return to allow main thread to proceed (Don't halt via k_fatal_halt like the default)
}
void _exit(int status)
{
LOG_ERR("FAILURE: exit called with status %d", status);
while (1) {
k_sleep(K_SECONDS(10));
}
}
void herald_entry() {
LOG_DBG("Catch thread entry");
k_sleep(K_SECONDS(10));
try {
LOG_DBG("In try");
k_sleep(K_SECONDS(10));
Catch::Session session;
LOG_DBG("Session created. Calling run in 2 seconds");
k_sleep(K_SECONDS(10));
int result = session.run();
LOG_DBG("Catch returned a value of: %d",result);
} catch (const std::exception& e) {
LOG_ERR("Tests reported problem: %s",log_strdup(e.what()));
}
while (1) {
k_sleep(K_SECONDS(2));
LOG_DBG("test thread still running");
}
}
void main(void)
{
int nameOk = k_thread_name_set(NULL,"main");
// Wait for a few seconds for remote to connect
LOG_DBG("Waiting for 10 seconds for tests to start (so we see thread analyser output)");
k_sleep(K_SECONDS(10));
// Now manually initialise catch
LOG_DBG("Initialising catch");
k_sleep(K_SECONDS(10));
[[maybe_unused]]
k_tid_t herald_pid = k_thread_create(&herald_thread, herald_stack, stackMaxSize,
(k_thread_entry_t)herald_entry, NULL, NULL, NULL,
-1, K_USER,
K_SECONDS(2));
nameOk = k_thread_name_set(herald_pid,"herald");
LOG_DBG("Catch thread started");
while (1) {
k_sleep(K_SECONDS(2));
LOG_DBG("main thread still running");
}
} | 34.517241 | 153 | 0.686813 | [
"vector"
] |
7a83dfae8a0d24a58d775b37c89332af9df5bd61 | 386 | cpp | C++ | solutions/1370.increasing-decreasing-string.326239841.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | 78 | 2020-10-22T11:31:53.000Z | 2022-02-22T13:27:49.000Z | solutions/1370.increasing-decreasing-string.326239841.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | null | null | null | solutions/1370.increasing-decreasing-string.326239841.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | 26 | 2020-10-23T15:10:44.000Z | 2021-11-07T16:13:50.000Z | class Solution {
public:
string sortString(string s) {
vector<int> mp(256);
string result;
for (char c : s)
mp[c]++;
while (result.size() < s.size()) {
for (char i = 'a'; i <= 'z'; i++)
if (mp[i]-- > 0)
result += i;
for (char i = 'z'; i >= 'a'; i--)
if (mp[i]-- > 0)
result += i;
}
return result;
}
};
| 18.380952 | 39 | 0.419689 | [
"vector"
] |
185237b0d8aace7c786e00cd46ea1fa14698daea | 243 | hpp | C++ | PatternMatch/generic/pattern_match_types.hpp | suiyili/Algorithms | d6ddc8262c5d681ecc78938b6140510793a29d91 | [
"MIT"
] | null | null | null | PatternMatch/generic/pattern_match_types.hpp | suiyili/Algorithms | d6ddc8262c5d681ecc78938b6140510793a29d91 | [
"MIT"
] | null | null | null | PatternMatch/generic/pattern_match_types.hpp | suiyili/Algorithms | d6ddc8262c5d681ecc78938b6140510793a29d91 | [
"MIT"
] | null | null | null | #pragma once
#include "generic/resource_manager/resource_manager.hpp"
#include <unordered_set>
namespace pattern_match{
//pmr::vector and its resource allocator
template<typename T>
using pmr_hash_set = std::pmr::unordered_set<T>;
} | 22.090909 | 56 | 0.769547 | [
"vector"
] |
185bb0d589b461e5c655451556e78ab675f43268 | 4,623 | cc | C++ | vcs/src/model/ListDevicesResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | vcs/src/model/ListDevicesResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | vcs/src/model/ListDevicesResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/vcs/model/ListDevicesResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Vcs;
using namespace AlibabaCloud::Vcs::Model;
ListDevicesResult::ListDevicesResult() :
ServiceResult()
{}
ListDevicesResult::ListDevicesResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
ListDevicesResult::~ListDevicesResult()
{}
void ListDevicesResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
if(!dataNode["PageNumber"].isNull())
data_.pageNumber = std::stoi(dataNode["PageNumber"].asString());
if(!dataNode["PageSize"].isNull())
data_.pageSize = std::stoi(dataNode["PageSize"].asString());
if(!dataNode["TotalCount"].isNull())
data_.totalCount = std::stoi(dataNode["TotalCount"].asString());
if(!dataNode["TotalPage"].isNull())
data_.totalPage = std::stoi(dataNode["TotalPage"].asString());
auto allRecordsNode = dataNode["Records"]["Record"];
for (auto dataNodeRecordsRecord : allRecordsNode)
{
Data::Record recordObject;
if(!dataNodeRecordsRecord["AccessProtocolType"].isNull())
recordObject.accessProtocolType = dataNodeRecordsRecord["AccessProtocolType"].asString();
if(!dataNodeRecordsRecord["BitRate"].isNull())
recordObject.bitRate = dataNodeRecordsRecord["BitRate"].asString();
if(!dataNodeRecordsRecord["CoverImageUrl"].isNull())
recordObject.coverImageUrl = dataNodeRecordsRecord["CoverImageUrl"].asString();
if(!dataNodeRecordsRecord["GbId"].isNull())
recordObject.gbId = dataNodeRecordsRecord["GbId"].asString();
if(!dataNodeRecordsRecord["DeviceAddress"].isNull())
recordObject.deviceAddress = dataNodeRecordsRecord["DeviceAddress"].asString();
if(!dataNodeRecordsRecord["DeviceDirection"].isNull())
recordObject.deviceDirection = dataNodeRecordsRecord["DeviceDirection"].asString();
if(!dataNodeRecordsRecord["DeviceSite"].isNull())
recordObject.deviceSite = dataNodeRecordsRecord["DeviceSite"].asString();
if(!dataNodeRecordsRecord["Latitude"].isNull())
recordObject.latitude = dataNodeRecordsRecord["Latitude"].asString();
if(!dataNodeRecordsRecord["Longitude"].isNull())
recordObject.longitude = dataNodeRecordsRecord["Longitude"].asString();
if(!dataNodeRecordsRecord["DeviceName"].isNull())
recordObject.deviceName = dataNodeRecordsRecord["DeviceName"].asString();
if(!dataNodeRecordsRecord["Resolution"].isNull())
recordObject.resolution = dataNodeRecordsRecord["Resolution"].asString();
if(!dataNodeRecordsRecord["SipGBId"].isNull())
recordObject.sipGBId = dataNodeRecordsRecord["SipGBId"].asString();
if(!dataNodeRecordsRecord["SipPassword"].isNull())
recordObject.sipPassword = dataNodeRecordsRecord["SipPassword"].asString();
if(!dataNodeRecordsRecord["SipServerIp"].isNull())
recordObject.sipServerIp = dataNodeRecordsRecord["SipServerIp"].asString();
if(!dataNodeRecordsRecord["SipServerPort"].isNull())
recordObject.sipServerPort = dataNodeRecordsRecord["SipServerPort"].asString();
if(!dataNodeRecordsRecord["Status"].isNull())
recordObject.status = std::stoi(dataNodeRecordsRecord["Status"].asString());
if(!dataNodeRecordsRecord["DeviceType"].isNull())
recordObject.deviceType = dataNodeRecordsRecord["DeviceType"].asString();
if(!dataNodeRecordsRecord["Vendor"].isNull())
recordObject.vendor = dataNodeRecordsRecord["Vendor"].asString();
if(!dataNodeRecordsRecord["CreateTime"].isNull())
recordObject.createTime = dataNodeRecordsRecord["CreateTime"].asString();
data_.records.push_back(recordObject);
}
if(!value["Code"].isNull())
code_ = value["Code"].asString();
if(!value["Message"].isNull())
message_ = value["Message"].asString();
}
std::string ListDevicesResult::getMessage()const
{
return message_;
}
ListDevicesResult::Data ListDevicesResult::getData()const
{
return data_;
}
std::string ListDevicesResult::getCode()const
{
return code_;
}
| 39.512821 | 92 | 0.754272 | [
"model"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.