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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6f30f8866e10646651936829e03ec8c884d94946 | 1,868 | cpp | C++ | CodeForces/CF 670 Div 2/C/main.cpp | MuhamedAbdalla/My-CForAtCoder-Round-Solutions | ad66158da86d00f32a58974c8bed29a7407c08e9 | [
"MIT"
] | 1 | 2021-04-26T00:17:23.000Z | 2021-04-26T00:17:23.000Z | CodeForces/CF 670 Div 2/C/main.cpp | MuhamedAbdalla/MyProblemSolving-Contest-Solutions | ad66158da86d00f32a58974c8bed29a7407c08e9 | [
"MIT"
] | null | null | null | CodeForces/CF 670 Div 2/C/main.cpp | MuhamedAbdalla/MyProblemSolving-Contest-Solutions | ad66158da86d00f32a58974c8bed29a7407c08e9 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
int n, mx[N], dep[N], u, maxi;
map<pair<int, int>, bool> pq;
vector<int> e[N];
void init() {
for (int i = 0; i <= n; i++) {
e[i].clear();
}
fill(dep, dep + n + 1, 0);
fill(mx, mx + n + 1, 0);
pq.clear();
}
void rdfs(int c, int p, int lvl) {
dep[c] = 1;
for (auto i : e[c]) {
if(i != p && !pq[{c, i}]) {
rdfs(i, c, lvl + 1);
dep[c] += dep[i];
}
}
if (dep[c] == 1 && lvl < maxi) {
u = c;
maxi = lvl;
}
}
void dfs(int c, int p) {
dep[c] = 1;
for (auto i : e[c]) {
if(i != p) {
dfs(i, c);
dep[c] += dep[i];
mx[c] = max(mx[c], dep[i]);
}
}
mx[c] = max(mx[c], n - dep[c]);
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(NULL);
int t;
cin >> t;
while (t--) {
cin >> n;
for (int i = 0; i < n - 1; i++) {
int x, y;
cin >> x >> y;
e[x].push_back(y);
e[y].push_back(x);
}
dfs(1, 1);
int mn = 1e9;
vector<int> v;
for (int i = 1; i <= n; i++) {
if (mx[i] < mn) {
mn = mx[i];
v.clear();
v.push_back(i);
}
else if (mx[i] == mn) {
v.push_back(i);
}
}
if (v.size() == 1) {
cout << v[0] << " " << e[v[0]][0] << endl;
cout << v[0] << " " << e[v[0]][0] << endl;
}
else {
pq[{v[0], v[1]}] = 1;
pq[{v[1], v[0]}] = 1;
maxi = 2e18;
rdfs(v[0], v[0], 0);
cout << u << " " << e[u][0] << endl;
cout << u << " " << v[1] << endl;
}
init();
}
return 0;
}
| 20.755556 | 54 | 0.32334 | [
"vector"
] |
6f31fecdf2cdbbf8e06de9a830fda2396409ee45 | 16,361 | cpp | C++ | src/drivers/AHCI/AHCIDriver.cpp | LittleCodingFox/ToastOS | 28475cbde3bd358460e070575e91496bf211f1d5 | [
"BSD-2-Clause"
] | 5 | 2021-12-21T19:17:00.000Z | 2022-03-10T17:56:59.000Z | src/drivers/AHCI/AHCIDriver.cpp | LittleCodingFox/ToastOS | 28475cbde3bd358460e070575e91496bf211f1d5 | [
"BSD-2-Clause"
] | null | null | null | src/drivers/AHCI/AHCIDriver.cpp | LittleCodingFox/ToastOS | 28475cbde3bd358460e070575e91496bf211f1d5 | [
"BSD-2-Clause"
] | null | null | null | #include <string.h>
#include "AHCIDriver.hpp"
#include "../../low-level/paging/PageFrameAllocator.hpp"
#include "../../low-level/paging/PageTableManager.hpp"
namespace Drivers
{
namespace AHCI
{
#define ATA_DEV_BUSY 0x80
#define ATA_DEV_DRQ 0x08
#define ATA_CMD_READ_DMA_EX 0x25
#define ATA_CMD_WRITE_DMA_EX 0x35
#define ATA_CMD_IDENTIFY 0xEC
#define HBA_PxIS_TFES (1 << 30)
#define HBA_PORT_DEV_PRESENT 0x3
#define HBA_PORT_IPM_ACTIVE 0x1
#define SATA_SIG_ATAPI 0xEB140101
#define SATA_SIG_ATA 0x00000101
#define SATA_SIG_SEMB 0xC33C0101
#define SATA_SIG_PM 0x96690101
#define HBA_PxCMD_CR 0x8000
#define HBA_PxCMD_FRE 0x0010
#define HBA_PxCMD_ST 0x0001
#define HBA_PxCMD_FR 0x4000
class AHCIHolder
{
public:
AHCIHolder() : portCount(0) {}
void ProbePorts();
PCIDevice *device;
volatile HBAMemory *ABAR;
AHCIDriver *ports[32];
uint8_t portCount;
};
void InitializeCommandHeader(volatile HBACommandHeader *commandHeader, bool write)
{
volatile HBACommandHeader *higherCommandHeader = (volatile HBACommandHeader *)TranslateToHighHalfMemoryAddress((uint64_t)commandHeader);
higherCommandHeader->commandFISLength = sizeof(FISREGHost2Device) / sizeof(uint32_t);
higherCommandHeader->write = write;
higherCommandHeader->prdtLength = 1;
}
void InitializeCommandTable(volatile HBACommandTable *commandTable, volatile HBACommandHeader *commandHeader,
uintptr_t dataAddress, size_t count)
{
volatile HBACommandTable *higherCommandTable = (volatile HBACommandTable *)TranslateToHighHalfMemoryAddress((uint64_t)commandTable);
volatile HBACommandHeader *higherCommandHeader = (volatile HBACommandHeader *)TranslateToHighHalfMemoryAddress((uint64_t)commandHeader);
memset((void *)higherCommandTable, 0, sizeof(HBACommandTable) + (higherCommandHeader->prdtLength - 1) * sizeof(HBAPRDEntry));
if(IsKernelHigherHalf(dataAddress))
{
dataAddress = TranslateToKernelPhysicalMemoryAddress(dataAddress);
}
else if(IsHigherHalf(dataAddress))
{
dataAddress = TranslateToPhysicalMemoryAddress(dataAddress);
}
higherCommandTable->prdtEntry[0].dataBaseAddress = (uint64_t)dataAddress;
higherCommandTable->prdtEntry[0].dataBaseAddressUpper = ((uint64_t)dataAddress >> 32);
higherCommandTable->prdtEntry[0].interruptOnCompletion = 1;
higherCommandTable->prdtEntry[0].byteCount = (count * 512) - 1;
}
void InitializeFISRegCommand(volatile FISREGHost2Device *command, bool write, uintptr_t sector, size_t count)
{
volatile FISREGHost2Device *higherCommand = (volatile FISREGHost2Device *)TranslateToHighHalfMemoryAddress((uint64_t)command);
memset((void *)higherCommand, 0, sizeof(FISREGHost2Device));
higherCommand->fisType = FIS_TYPE_REG_H2D;
higherCommand->commandControl = 1;
if(write)
{
higherCommand->command = ATA_CMD_WRITE_DMA_EX;
}
else
{
higherCommand->command = ATA_CMD_READ_DMA_EX;
}
higherCommand->lba0 = (uint8_t)((sector & 0x000000000000FF));
higherCommand->lba1 = (uint8_t)((sector & 0x0000000000FF00) >> 8);
higherCommand->lba2 = (uint8_t)((sector & 0x00000000FF0000) >> 16);
higherCommand->deviceRegister = 1 << 6;
higherCommand->lba3 = (uint8_t)((sector & 0x000000FF000000) >> 24);
higherCommand->lba4 = (uint8_t)((sector & 0x0000FF00000000) >> 32);
higherCommand->lba5 = (uint8_t)((sector & 0x00FF0000000000) >> 40);
higherCommand->countLow = count & 0xFF;
higherCommand->countHigh = (count >> 8) & 0xFF;
}
bool ATABusyWait(volatile HBAPort *port)
{
size_t spinTimeout = 0;
while((port->taskFileData & (ATA_DEV_BUSY | ATA_DEV_DRQ)) && spinTimeout < 1000000)
{
spinTimeout++;
}
if(spinTimeout == 1000000)
{
return false;
}
return true;
}
int32_t FindCommandSlot(volatile HBAPort *port)
{
uint32_t slots = (port->sataControl | port->commandIssue);
for(int i = 0; i < 32; i++, slots >>= 1)
{
if((slots & 1) == 0)
{
return i;
}
}
return -1;
}
PortType CheckPortType(volatile HBAPort *port)
{
uint32_t sataStatus = port->sataStatus;
uint8_t interfacePowerManagement = (sataStatus >> 8) & 0x0F;
uint8_t deviceDetection = sataStatus & 0x0F;
if(deviceDetection != HBA_PORT_DEV_PRESENT ||
interfacePowerManagement != HBA_PORT_IPM_ACTIVE)
{
return AHCI_PORT_TYPE_NONE;
}
switch(port->signature)
{
case SATA_SIG_ATAPI:
return AHCI_PORT_TYPE_SATAPI;
case SATA_SIG_ATA:
return AHCI_PORT_TYPE_SATA;
case SATA_SIG_PM:
return AHCI_PORT_TYPE_PM;
case SATA_SIG_SEMB:
return AHCI_PORT_TYPE_SEMB;
default:
return AHCI_PORT_TYPE_SATA;
}
}
void AHCIHolder::ProbePorts()
{
uint32_t implementedPorts = ABAR->implementedPorts;
for(uint32_t i = 0; i < 32; i++, implementedPorts >>= 1)
{
if(implementedPorts & 1)
{
PortType type = CheckPortType(&ABAR->ports[i]);
if(type == AHCI_PORT_TYPE_SATA || type == AHCI_PORT_TYPE_SATAPI)
{
AHCIDriver *port = new AHCIDriver();
ports[portCount] = port;
port->device = device;
port->portType = type;
port->port = (volatile HBAPort *)&ABAR->ports[i];
port->portNumber = portCount;
portCount++;
}
}
}
}
void FISIdentify::ReadModel(char *buffer) const
{
memcpy(buffer, model, sizeof(model));
buffer[40] = 0;
for(uint32_t i = 0; i < 40; i+=2)
{
char c = buffer[i + 1];
buffer[i + 1] = buffer[i];
buffer[i] = c;
}
char before = '\0';
for(uint32_t i = 0; i < 40; i++)
{
if(buffer[i] == ' ')
{
if(before == ' ')
{
buffer[i] = '\0';
break;
}
else
{
before = buffer[i];
}
}
}
}
AHCIDriver::AHCIDriver()
{
memset(&identify, 0, sizeof(identify));
memset(model, 0, sizeof(model));
}
bool AHCIDriver::Configure()
{
void *newBase = globalAllocator.RequestPage();
globalPageTableManager->MapMemory((void *)TranslateToHighHalfMemoryAddress((uint64_t)newBase),
newBase, PAGING_FLAG_PRESENT | PAGING_FLAG_WRITABLE);
memset((void *)TranslateToHighHalfMemoryAddress((uint64_t)newBase), 0, 0x1000);
port->commandListBase = (uint64_t)newBase;
HBAFIS *fis = new HBAFIS();
memset(fis, 0, sizeof(HBAFIS));
fis->dmaFIS.type = FIS_TYPE_DMA_SETUP;
fis->linkFIS.type = FIS_TYPE_REG_D2H;
fis->pioFIS.type = FIS_TYPE_PIO_SETUP;
port->fisBaseAddress = (uint64_t)TranslateToPhysicalMemoryAddress((uint64_t)fis);
volatile HBACommandHeader *commandHeader = (HBACommandHeader *)TranslateToHighHalfMemoryAddress((uint64_t)newBase);
for(uint32_t i = 0; i < 32; i++)
{
commandHeader[i].prdtLength = 8;
void *commandTableAddress = globalAllocator.RequestPage();
globalPageTableManager->MapMemory((void *)TranslateToHighHalfMemoryAddress((uint64_t)commandTableAddress),
commandTableAddress, PAGING_FLAG_PRESENT | PAGING_FLAG_WRITABLE);
commandHeader[i].commandTableBaseAddress = (uint64_t)commandTableAddress;
}
if(!Identify())
{
memset(&identify, 0, sizeof(identify));
return false;
}
return true;
}
bool AHCIDriver::Identify()
{
port->interruptStatus = (uint32_t)-1;
int32_t slot = FindCommandSlot(port);
if(slot == -1)
{
return false;
}
volatile HBACommandHeader *commandHeader = (HBACommandHeader *)((uint64_t)port->commandListBase);
commandHeader += slot;
InitializeCommandHeader(commandHeader, false);
volatile HBACommandTable *commandTable = (HBACommandTable *)(uint64_t)((uint64_t)((volatile HBACommandHeader *)
TranslateToHighHalfMemoryAddress((uint64_t)commandHeader))->commandTableBaseAddress);
InitializeCommandTable(commandTable, commandHeader, (uintptr_t)&identify, 0);
volatile FISREGHost2Device *commandFIS = (FISREGHost2Device *)((uint64_t)TranslateToPhysicalMemoryAddress((uint64_t)((volatile HBACommandTable *)
TranslateToHighHalfMemoryAddress((uint64_t)commandTable))->commandFIS));
InitializeFISRegCommand(commandFIS, false, 0, 0);
((volatile FISREGHost2Device *)TranslateToHighHalfMemoryAddress((uint64_t)commandFIS))->command = ATA_CMD_IDENTIFY;
if(!ATABusyWait(port))
{
return false;
}
StartCommand();
port->commandIssue = 1 << slot;
for(;;)
{
if((port->commandIssue & (1 << slot)) == 0)
{
break;
}
if(port->interruptStatus & HBA_PxIS_TFES)
{
return false;
}
}
if(port->interruptStatus & HBA_PxIS_TFES)
{
return false;
}
StopCommand();
identify.ReadModel(model);
return true;
}
void AHCIDriver::StartCommand()
{
port->commandStatus &= ~HBA_PxCMD_ST;
for(;;)
{
if((port->commandStatus & HBA_PxCMD_CR))
{
continue;
}
break;
}
port->commandStatus |= HBA_PxCMD_FRE;
port->commandStatus |= HBA_PxCMD_ST;
}
void AHCIDriver::StopCommand()
{
port->commandStatus &= ~HBA_PxCMD_ST;
for(;;)
{
if((port->commandStatus & HBA_PxCMD_CR))
{
continue;
}
break;
}
port->commandStatus &= ~HBA_PxCMD_FRE;
}
bool AHCIDriver::Read(void *buffer, uint64_t sector, uint64_t sectorCount)
{
port->interruptStatus = (uint32_t)-1;
int32_t slot = FindCommandSlot(port);
if(slot == -1)
{
return false;
}
volatile HBACommandHeader *commandHeader = (HBACommandHeader *)((uint64_t)port->commandListBase);
commandHeader += slot;
InitializeCommandHeader(commandHeader, false);
volatile HBACommandTable *commandTable = (HBACommandTable *)(uint64_t)((uint64_t)((volatile HBACommandHeader *)
TranslateToHighHalfMemoryAddress((uint64_t)commandHeader))->commandTableBaseAddress);
InitializeCommandTable(commandTable, commandHeader, (uintptr_t)buffer, sectorCount);
volatile FISREGHost2Device *commandFIS = (FISREGHost2Device *)((uint64_t)TranslateToPhysicalMemoryAddress((uint64_t)((volatile HBACommandTable *)
TranslateToHighHalfMemoryAddress((uint64_t)commandTable))->commandFIS));
InitializeFISRegCommand(commandFIS, false, sector, sectorCount);
if(!ATABusyWait(port))
{
return false;
}
StartCommand();
port->commandIssue = 1 << slot;
for(;;)
{
if((port->commandIssue & (1 << slot)) == 0)
{
break;
}
if(port->interruptStatus & HBA_PxIS_TFES)
{
return false;
}
}
if(port->interruptStatus & HBA_PxIS_TFES)
{
return false;
}
StopCommand();
return true;
}
bool AHCIDriver::Write(const void *buffer, uint64_t sector, uint64_t sectorCount)
{
port->interruptStatus = (uint32_t)-1;
int32_t slot = FindCommandSlot(port);
if(slot == -1)
{
return false;
}
volatile HBACommandHeader *commandHeader = (volatile HBACommandHeader *)(uint64_t)(port->commandListBase);
commandHeader += slot;
InitializeCommandHeader(commandHeader, true);
volatile HBACommandTable *commandTable = (HBACommandTable *)(uint64_t)((uint64_t)((volatile HBACommandHeader *)
TranslateToHighHalfMemoryAddress((uint64_t)commandHeader))->commandTableBaseAddress);
InitializeCommandTable(commandTable, commandHeader, (uintptr_t)buffer, sectorCount);
volatile FISREGHost2Device *commandFIS = (FISREGHost2Device *)((uint64_t)TranslateToPhysicalMemoryAddress((uint64_t)((volatile HBACommandTable *)
TranslateToHighHalfMemoryAddress((uint64_t)commandTable))->commandFIS));
InitializeFISRegCommand(commandFIS, true, sector, sectorCount);
if(!ATABusyWait(port))
{
return false;
}
StartCommand();
port->commandIssue = 1 << slot;
for(;;)
{
if((port->commandIssue & (1 << slot)) == 0)
{
break;
}
if(port->interruptStatus & HBA_PxIS_TFES)
{
return false;
}
}
if(port->interruptStatus & HBA_PxIS_TFES)
{
return false;
}
StopCommand();
return true;
}
void HandleMassStorageDevice(PCIDevice *device)
{
auto name = PCIDeviceName(device->vendorID, device->deviceID);
auto vendor = PCIVendorName(device->vendorID);
printf("Initializing AHCI device %s (vendor: %s)\n",
name,
vendor);
AHCIHolder holder;
holder.device = device;
holder.ABAR = (volatile HBAMemory *)(device->bars[5].address);
holder.ProbePorts();
for(uint32_t i = 0; i < holder.portCount; i++)
{
AHCIDriver *port = holder.ports[i];
if(port->Configure())
{
globalDeviceManager.AddDevice(port);
}
}
}
}
} | 31.403071 | 157 | 0.526313 | [
"model"
] |
6f350cc89e6272304ee43b95aefc660794d03d55 | 993 | cpp | C++ | modules/randomwalk/ext/RandomWalksLib/SparseSolverEigenCG.cpp | hmsgit/campvis | d97de6a86323866d6a8f81d2a641e3e0443a6b39 | [
"ECL-2.0",
"Apache-2.0"
] | 5 | 2018-06-19T06:20:01.000Z | 2021-07-31T05:54:25.000Z | modules/randomwalk/ext/RandomWalksLib/SparseSolverEigenCG.cpp | hmsgit/campvis | d97de6a86323866d6a8f81d2a641e3e0443a6b39 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | modules/randomwalk/ext/RandomWalksLib/SparseSolverEigenCG.cpp | hmsgit/campvis | d97de6a86323866d6a8f81d2a641e3e0443a6b39 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | #include "SparseSolverEigenCG.h"
SparseSolverEigenCG::SparseSolverEigenCG(int iterations, double tolerance)
{
this->iterations = iterations;
this->tolerance = tolerance;
}
std::vector<double> SparseSolverEigenCG::solve_Ax_b(SparseMatrix<double> A, SparseVector<double> b, int numel, std::vector<int> & uidx, const std::vector<int> * labels, const std::vector<int> * seeds, int active_label)
{
VectorXd b_dense = b;
// Eigen Conjugate Gradient Solver, by default Jacobi Preconditioning is used
ConjugateGradient<SparseMatrix<double> > cg;
cg.setMaxIterations(iterations);
cg.setTolerance(tolerance);
cg.compute(A);
VectorXd x_dense = cg.solve(b_dense);
std::vector<double> xmat(numel);
for (int i=0; i<x_dense.rows(); i++)
{
double val = x_dense(i);
xmat[uidx[i]] = val;
}
for (size_t i=0; i<seeds->size(); i++)
{
if((*labels)[i] == active_label)
xmat[(*seeds)[i]] = 1.0;
else
xmat[(*seeds)[i]] = 0.0;
}
return xmat;
} | 26.131579 | 219 | 0.671702 | [
"vector"
] |
6f3eacafbe683ae972e66c99dddc2406e31b451c | 1,728 | cpp | C++ | oreon.engine/oreon.engine/engine/CoreEngine.cpp | antarezz/Oreon.Engine-OpenGL-Cpp | 6a36a3138fe291f114be25ee69a0d5ac96edd2f0 | [
"MIT"
] | 4 | 2017-08-27T07:44:05.000Z | 2018-09-02T07:27:31.000Z | oreon.engine/oreon.engine/engine/CoreEngine.cpp | antarezz/Oreon.Engine-OpenGL-Cpp | 6a36a3138fe291f114be25ee69a0d5ac96edd2f0 | [
"MIT"
] | null | null | null | oreon.engine/oreon.engine/engine/CoreEngine.cpp | antarezz/Oreon.Engine-OpenGL-Cpp | 6a36a3138fe291f114be25ee69a0d5ac96edd2f0 | [
"MIT"
] | 2 | 2020-02-18T15:44:23.000Z | 2020-12-13T19:49:25.000Z | #include "CoreEngine.h"
using namespace std::chrono_literals;
int CoreEngine::fps;
CoreEngine::CoreEngine() : isRunning(false),frametime(1/100.0f){}
void CoreEngine::createWindow(int width, int height, char* title) {
Window::getInstance().create(width,height,title);
}
void CoreEngine::init() {
}
void CoreEngine::start() {
if (isRunning)
return;
run();
}
void CoreEngine::run() {
isRunning = true;
int frames = 0;
long frameCounter = 0;
auto lastTime = std::chrono::high_resolution_clock::now();
double unprocessedTime = 0;
// Rendering Loop
while (isRunning)
{
bool renderFrame = false;
auto startTime = std::chrono::high_resolution_clock::now();
long passedTime = (startTime - lastTime).count();
lastTime = startTime;
unprocessedTime += passedTime / (double)1000000000;
frameCounter += passedTime;
while (unprocessedTime > frametime)
{
// kommt hier nie raus
renderFrame = true;
unprocessedTime -= frametime;
if (glfwWindowShouldClose(Window::getInstance().getWindow()))
stop();
update();
if (frameCounter >= (double)1000000000)
{
fps = frames;
frames = 0;
frameCounter = 0;
std::cout << fps << std::endl;
}
}
if (renderFrame)
{
this->render();
this->update();
frames++;
}
else
{
std::this_thread::sleep_for(10ms);
}
}
cleanUp();
}
void CoreEngine::stop() {
if (!isRunning)
return;
isRunning = false;
}
void CoreEngine::render() {
glClearColor(0.1, 0.7, 0.1, 1);
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(Window::getInstance().getWindow());
}
void CoreEngine::update() {
InputHandler::getInstance().update();
}
void CoreEngine::cleanUp() {
}
int CoreEngine::getFps() {
return fps;
}
| 16.776699 | 67 | 0.662616 | [
"render"
] |
6f3fc520f6fb6c940311a13209c95a3a4d6d96f8 | 5,941 | cpp | C++ | modules/fbx/data/fbx_bone.cpp | MichaelBelousov/godot | ad64d5de1170109a53a5d0cfd8101824c2c4d77c | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | modules/fbx/data/fbx_bone.cpp | MichaelBelousov/godot | ad64d5de1170109a53a5d0cfd8101824c2c4d77c | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | modules/fbx/data/fbx_bone.cpp | MichaelBelousov/godot | ad64d5de1170109a53a5d0cfd8101824c2c4d77c | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | /*************************************************************************/
/* fbx_bone.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "fbx_bone.h"
#include "fbx_node.h"
#include "import_state.h"
Ref<FBXNode> FBXBone::get_link(const ImportState &state) const {
print_verbose("bone name: " + bone_name);
// safe for when deformers must be polyfilled when skin has different count of binds to bones in the scene ;)
if (!cluster) {
return nullptr;
}
ERR_FAIL_COND_V_MSG(cluster->TargetNode() == nullptr, nullptr, "bone has invalid target node");
Ref<FBXNode> link_node;
uint64_t id = cluster->TargetNode()->ID();
if (state.fbx_target_map.has(id)) {
link_node = state.fbx_target_map[id];
} else {
print_error("link node not found for " + itos(id));
}
// the node in space this is for, like if it's FOR a target.
return link_node;
}
/* right now we just get single skin working and we can patch in the multiple tomorrow - per skin not per bone. */
// this will work for multiple meshes :) awesomeness.
// okay so these formula's are complex and need proper understanding of
// shear, pivots, geometric pivots, pre rotation and post rotation
// additionally DO NOT EDIT THIS if your blender file isn't working.
// Contact RevoluPowered Gordon MacPherson if you are contemplating making edits to this.
Transform FBXBone::get_vertex_skin_xform(const ImportState &state, Transform mesh_global_position, bool &r_valid_pose) {
r_valid_pose = false;
print_verbose("get_vertex_skin_xform: " + bone_name);
// safe to do, this means we have 'remove unused deformer' checked.
if (!cluster) {
print_verbose("bone [" + itos(bone_id) + "] " + bone_name + ": has no skin offset poly-filling the skin to make rasterizer happy with unused deformers not being skinned");
r_valid_pose = true;
return Transform();
}
ERR_FAIL_COND_V_MSG(cluster == nullptr, Transform(), "[serious] unable to resolve the fbx cluster for this bone " + bone_name);
// these methods will ONLY work for Maya.
if (cluster->TransformAssociateModelValid()) {
//print_error("additive skinning in use");
Transform associate_global_init_position = cluster->TransformAssociateModel();
Transform associate_global_current_position = Transform();
Transform reference_global_init_position = cluster->GetTransform();
Transform cluster_global_init_position = cluster->TransformLink();
Ref<FBXNode> link_node = get_link(state);
ERR_FAIL_COND_V_MSG(link_node.is_null(), Transform(), "invalid link corrupt file detected");
r_valid_pose = true;
Transform cluster_global_current_position = link_node.is_valid() && link_node->pivot_transform.is_valid() ? link_node->pivot_transform->GlobalTransform : Transform();
vertex_transform_matrix = reference_global_init_position.affine_inverse() * associate_global_init_position * associate_global_current_position.affine_inverse() *
cluster_global_current_position * cluster_global_init_position.affine_inverse() * reference_global_init_position;
} else {
//print_error("non additive skinning is in use");
Transform reference_global_position = cluster->GetTransform();
Transform reference_global_current_position = mesh_global_position;
//Transform geometric_pivot = Transform(); // we do not use this - 3ds max only
Transform global_init_position = cluster->TransformLink();
if (global_init_position.basis.determinant() == 0) {
global_init_position = Transform(Basis(), global_init_position.origin);
}
Transform cluster_relative_init_position = global_init_position.affine_inverse() * reference_global_position;
Transform cluster_relative_position_inverse = reference_global_current_position.affine_inverse() * global_init_position;
vertex_transform_matrix = cluster_relative_position_inverse * cluster_relative_init_position;
r_valid_pose = true;
}
return vertex_transform_matrix;
}
| 55.523364 | 173 | 0.651069 | [
"transform"
] |
6f4171ce135a16edb1eae36baf87bca890d6c8ff | 5,661 | cpp | C++ | tests/ieventemitter.test.cpp | futoin/core-cpp-api | 20ae11bf39de03fa64da800ba1c60a953cf5c122 | [
"Apache-2.0"
] | 7 | 2018-09-25T19:32:16.000Z | 2018-10-05T14:29:34.000Z | tests/ieventemitter.test.cpp | futoin/core-cpp-api | 20ae11bf39de03fa64da800ba1c60a953cf5c122 | [
"Apache-2.0"
] | null | null | null | tests/ieventemitter.test.cpp | futoin/core-cpp-api | 20ae11bf39de03fa64da800ba1c60a953cf5c122 | [
"Apache-2.0"
] | null | null | null | //-----------------------------------------------------------------------------
// Copyright 2018 FutoIn Project
// Copyright 2018 Andrey Galkin
//
// 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 <boost/test/unit_test.hpp>
#include <futoin/ieventemitter.hpp>
class TestEventEmitter : public futoin::IEventEmitter
{
public:
TestEventEmitter() noexcept = default;
void on(const EventType& event, EventHandler& handler) noexcept override
{
BOOST_CHECK_EQUAL(Accessor::event_emitter(event), this);
BOOST_CHECK_EQUAL(Accessor::event_id(event), 1);
Accessor::event_type(handler) = event;
}
void once(const EventType& event, EventHandler& handler) noexcept override
{
BOOST_CHECK_EQUAL(Accessor::event_emitter(event), this);
BOOST_CHECK_EQUAL(Accessor::event_id(event), 1);
Accessor::event_type(handler) = event;
}
void off(const EventType& event, EventHandler& handler) noexcept override
{
BOOST_CHECK_EQUAL(Accessor::event_emitter(event), this);
BOOST_CHECK_EQUAL(Accessor::event_id(event), 1);
Accessor::event_id(handler) = NO_EVENT_ID;
}
void emit(const EventType& event) noexcept override
{
BOOST_CHECK_EQUAL(Accessor::event_emitter(event), this);
BOOST_CHECK_EQUAL(Accessor::event_id(event), 1);
}
void emit(const EventType& event, NextArgs&& args) noexcept override
{
BOOST_CHECK_EQUAL(Accessor::event_emitter(event), this);
BOOST_CHECK_EQUAL(Accessor::event_id(event), 1);
test_cast_(args);
}
using IEventEmitter::register_event;
protected:
void register_event_impl(
EventType& event,
TestCast test_cast,
const NextArgs& model_args) noexcept override
{
BOOST_CHECK_EQUAL(Accessor::event_id(event), (NO_EVENT_ID + 0));
BOOST_CHECK_EQUAL(Accessor::raw_event_type(event), "TestEvent");
Accessor::event_emitter(event) = this;
Accessor::event_id(event) = 1;
test_cast_ = test_cast;
test_cast(model_args);
}
std::size_t handle_hash_;
IEventEmitter::EventHandler::TestCast test_cast_;
};
BOOST_AUTO_TEST_SUITE(ieventemitter) // NOLINT
BOOST_AUTO_TEST_CASE(instance) // NOLINT
{
TestEventEmitter tee;
}
BOOST_AUTO_TEST_CASE(register_event) // NOLINT
{
TestEventEmitter tee;
TestEventEmitter::EventType test_event("TestEvent");
tee.register_event(test_event);
}
BOOST_AUTO_TEST_CASE(on) // NOLINT
{
TestEventEmitter tee;
futoin::IEventEmitter& ee = tee;
TestEventEmitter::EventType test_event("TestEvent");
tee.register_event(test_event);
TestEventEmitter::EventHandler handler([]() {});
ee.on(test_event, handler);
ee.off(test_event, handler);
}
BOOST_AUTO_TEST_CASE(once) // NOLINT
{
TestEventEmitter tee;
futoin::IEventEmitter& ee = tee;
TestEventEmitter::EventType test_event("TestEvent");
tee.register_event(test_event);
TestEventEmitter::EventHandler handler([]() {});
ee.once(test_event, handler);
ee.off(test_event, handler);
}
BOOST_AUTO_TEST_CASE(emit) // NOLINT
{
TestEventEmitter tee;
futoin::IEventEmitter& ee = tee;
TestEventEmitter::EventType test_event("TestEvent");
tee.register_event(test_event);
ee.emit(test_event);
}
BOOST_AUTO_TEST_CASE(with_args) // NOLINT
{
TestEventEmitter tee;
futoin::IEventEmitter& ee = tee;
TestEventEmitter::EventType test_event1("TestEvent");
tee.register_event<int>(test_event1);
TestEventEmitter::EventHandler handler1([](int) {});
ee.on(test_event1, handler1);
ee.once(test_event1, handler1);
ee.emit(test_event1, 123);
ee.off(test_event1, handler1);
TestEventEmitter::EventType test_event2("TestEvent");
tee.register_event<int, futoin::string>(test_event2);
TestEventEmitter::EventHandler handler2([](int, const futoin::string&) {});
ee.on(test_event2, handler2);
ee.once(test_event2, handler2);
ee.emit(test_event2, 123, "str");
ee.emit(test_event2, 123, futoin::string{"str"});
ee.off(test_event2, handler2);
TestEventEmitter::EventType test_event3("TestEvent");
tee.register_event<int, futoin::string, std::vector<int>>(test_event3);
TestEventEmitter::EventHandler handler3(
[](int, const futoin::string&, const std::vector<int>&) {});
ee.on(test_event3, handler3);
ee.once(test_event3, handler3);
ee.emit(test_event3, 123, "str", std::vector<int>{1, 2, 3});
ee.off(test_event3, handler3);
TestEventEmitter::EventType test_event4("TestEvent");
tee.register_event<int, futoin::string, std::vector<int>, bool>(
test_event4);
TestEventEmitter::EventHandler handler4(
[](int, const futoin::string&, const std::vector<int>&, bool) {});
ee.on(test_event4, handler4);
ee.once(test_event4, handler4);
ee.emit(test_event4, 123, "str", std::vector<int>{1, 2, 3}, true);
ee.off(test_event4, handler4);
}
BOOST_AUTO_TEST_SUITE_END() // NOLINT
| 32.348571 | 79 | 0.673379 | [
"vector"
] |
6f4204c1a02fef0af8ec6c6f1f7e0f70d0746949 | 1,706 | cpp | C++ | nudg++/trunk/Src/Codes3D/TopTheta.cpp | Notargets/nodal-dg | 1866dbdfeeff34b7586e70d308dbfe42a2b59844 | [
"MIT"
] | 93 | 2015-01-26T17:48:24.000Z | 2022-03-16T10:26:07.000Z | nudg++/trunk/Src/Codes3D/TopTheta.cpp | Notargets/nodal-dg | 1866dbdfeeff34b7586e70d308dbfe42a2b59844 | [
"MIT"
] | 4 | 2016-01-27T02:45:40.000Z | 2021-11-26T11:50:08.000Z | nudg++/trunk/Src/Codes3D/TopTheta.cpp | Notargets/nodal-dg | 1866dbdfeeff34b7586e70d308dbfe42a2b59844 | [
"MIT"
] | 80 | 2015-04-03T18:44:50.000Z | 2022-03-30T19:25:22.000Z | // TopTheta.cpp
// function topu = TopTheta(u, theta)
// 2007/10/11
//---------------------------------------------------------
#include "NDGLib_headers.h"
#include "NDG3D.h"
// template <class T> void Sort_Index(const Vector<T>& A, Vector<T>& S, IVec& IX, eDir dir); // =eAscend
void Sort_Index(const DVec& A, DVec& S, IVec& IX, eDir dir); // =eAscend
//---------------------------------------------------------
IVec& TopTheta(const DVec& u, double theta, bool do_print)
//---------------------------------------------------------
{
DVec sortu("sortu"); IVec indu("indu");
IVec* tmp = new IVec("topu", OBJ_temp); IVec& topu=(*tmp);
// [sortu,indu] = sort(u(:), eDescend);
//sort (u, sortu, indu, eDescend);
//Sort_Index<double>(u, sortu, indu, eDescend);
Sort_Index (u, sortu, indu, eDescend);
//#######################################################
// FIXME: ask Tim if this should be u.sum_abs();
// NBN: check for numerical noise:
double u_sum = u.sum();
if (fabs(u_sum)<5e-14)
//if (0.0 == u_sum)
{
return topu; // return empty vector
}
//#######################################################
DVec cumsortu = cumsum(sortu) / u_sum;
topu = find(cumsortu, '<', theta);
if (topu.size()<1) {
if (cumsortu(1)>1e-10) {
// topu.resize(1); topu(1)=indu(1);
topu.append(indu(1));
}
} else {
topu = indu.get_map(topu);
}
if (do_print)
{
//static int cntx=0; char buf[20]={""};
//sprintf(buf, "topu_%d", ++cntx);
//dumpDVec(u, "u");
//dumpDVec(sortu, "sortu");
//dumpIVec(indu, "indu");
//dumpDVec(cumsortu, "cumsortu");
//dumpIVec(topu, buf);
}
return topu;
}
| 25.848485 | 104 | 0.478312 | [
"vector"
] |
6f4240707e4085475a8945f1d284104883f4939b | 1,351 | cpp | C++ | src/process.cpp | malaca3/Project2SystemMonitor | 2375b94f572a6a646e15ca426144db105ee7014e | [
"MIT"
] | null | null | null | src/process.cpp | malaca3/Project2SystemMonitor | 2375b94f572a6a646e15ca426144db105ee7014e | [
"MIT"
] | null | null | null | src/process.cpp | malaca3/Project2SystemMonitor | 2375b94f572a6a646e15ca426144db105ee7014e | [
"MIT"
] | null | null | null | #include <unistd.h>
#include <cctype>
#include <sstream>
#include <string>
#include <vector>
#include <unistd.h>
#include "process.h"
#include "linux_parser.h"
using std::string;
using std::to_string;
using std::vector;
Process::Process(int i): pid(i){
CalcCpuUtilization();
}
int Process::Pid() { return pid; }
float Process::CpuUtilization() {
return cpu;
}
void Process::CalcCpuUtilization() {
vector<float> times = LinuxParser::CpuUtilization(pid);
float uptime = LinuxParser::UpTime(pid);
total_time = times[0] + times[1] + times[2] + times[3];
seconds = uptime;
cpu = (((total_time-prev_total_time)/sysconf(_SC_CLK_TCK))/(seconds-prev_seconds));
if(seconds-prev_seconds > 5){
prev_total_time = total_time;
prev_seconds = seconds;
}
}
string Process::Command() { return LinuxParser::Command(pid); }
string Process::Ram() { return LinuxParser::Ram(pid); }
string Process::User() { return LinuxParser::User(pid); }
long int Process::UpTime() { return LinuxParser::UpTime(pid); }
bool Process::InList(std::vector<int>& ids) {
for(unsigned int i = 0; i < ids.size(); i++){
if(ids[i] == pid){
ids.erase(ids.begin()+i);
return true;
}
}
return false;
}
bool Process::operator<(Process const& a) const { return cpu > a.cpu; } | 23.701754 | 87 | 0.641747 | [
"vector"
] |
6f4371f0aad4749d3a8f4fe1b23ae49a9a4f7e5a | 1,951 | hpp | C++ | pwiz/utility/math/Parabola.hpp | edyp-lab/pwiz-mzdb | d13ce17f4061596c7e3daf9cf5671167b5996831 | [
"Apache-2.0"
] | 11 | 2015-01-08T08:33:44.000Z | 2019-07-12T06:14:54.000Z | pwiz/utility/math/Parabola.hpp | shze/pwizard-deb | 4822829196e915525029a808470f02d24b8b8043 | [
"Apache-2.0"
] | 61 | 2015-05-27T11:20:11.000Z | 2019-12-20T15:06:21.000Z | pwiz/utility/math/Parabola.hpp | shze/pwizard-deb | 4822829196e915525029a808470f02d24b8b8043 | [
"Apache-2.0"
] | 4 | 2016-02-03T09:41:16.000Z | 2021-08-01T18:42:36.000Z | //
// $Id: Parabola.hpp 1195 2009-08-14 22:12:04Z chambm $
//
//
// Original author: Darren Kessner <darren@proteowizard.org>
//
// Copyright 2006 Louis Warschaw Prostate Cancer Center
// Cedars Sinai Medical Center, Los Angeles, California 90048
//
// 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 _PARABOLA_HPP_
#define _PARABOLA_HPP_
#include "pwiz/utility/misc/Export.hpp"
#include <vector>
#include <iosfwd>
namespace pwiz {
namespace math {
class PWIZ_API_DECL Parabola
{
public:
// construct by giving 3 coefficients
Parabola(double a=0, double b=0, double c=0);
Parabola(std::vector<double> a);
// construct by giving 3 or more sample points
Parabola(const std::vector< std::pair<double,double> >& samples);
// construct by weighted least squares
Parabola(const std::vector< std::pair<double,double> >& samples,
const std::vector<double>& weights);
std::vector<double>& coefficients() {return a_;}
const std::vector<double>& coefficients() const {return a_;}
double operator()(double x) const {return a_[0]*x*x + a_[1]*x + a_[2];}
double center() const {return -a_[1]/(2*a_[0]);}
private:
std::vector<double> a_;
};
PWIZ_API_DECL std::ostream& operator<<(std::ostream& os, const Parabola& p);
} // namespace math
} // namespace pwiz
#endif // _PARABOLA_HPP_
| 27.097222 | 77 | 0.670425 | [
"vector"
] |
6f47979e0e926bc052d26e0551926152bb300c38 | 1,163 | cpp | C++ | GeeksForGeeks/Convert array into Zig-Zag fashion.cpp | tanishq1g/cp_codes | 80b8ccc9e195a66d6d317076fdd54a02cd21275b | [
"MIT"
] | null | null | null | GeeksForGeeks/Convert array into Zig-Zag fashion.cpp | tanishq1g/cp_codes | 80b8ccc9e195a66d6d317076fdd54a02cd21275b | [
"MIT"
] | null | null | null | GeeksForGeeks/Convert array into Zig-Zag fashion.cpp | tanishq1g/cp_codes | 80b8ccc9e195a66d6d317076fdd54a02cd21275b | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
#include <locale>
#include <algorithm>
#include <cmath>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <bitset>
#include <climits>
#include <list>
#include <queue>
#include <stack>
#include <utility>
using namespace std;
#define INF 1e7
// array
int main(){
int t;
cin >> t;
while(t--){
int n;
cin >> n;
vector<int> ve(n);
for(int i = 0; i < n; i++){
cin >> ve[i];
}
// Flag true indicates relation "<" is expected,
// else ">" is expected. The first expected relation
// is "<"
bool flag = true;
for(int i = 0; i < n - 1; i++){
if(flag){
if(ve[i] > ve[i + 1]){
swap(ve[i], ve[i + 1]);
}
}
else{
if(ve[i] < ve[i + 1]){
swap(ve[i], ve[i + 1]);
}
}
flag = !flag;
}
for(int i = 0; i < n; i++){
cout << ve[i] << ' ';
} cout << endl;
}
return 0;
} | 21.537037 | 62 | 0.421324 | [
"vector"
] |
6f51d419e072e8338b1c5c675b5ed19568f4e085 | 19,600 | cpp | C++ | src/OrbitCaptureClient/GpuQueueSubmissionProcessor.cpp | Mu-L/orbit | 9a3338d1fda66c4c3723333023dd039acc3c40a0 | [
"BSD-2-Clause"
] | null | null | null | src/OrbitCaptureClient/GpuQueueSubmissionProcessor.cpp | Mu-L/orbit | 9a3338d1fda66c4c3723333023dd039acc3c40a0 | [
"BSD-2-Clause"
] | null | null | null | src/OrbitCaptureClient/GpuQueueSubmissionProcessor.cpp | Mu-L/orbit | 9a3338d1fda66c4c3723333023dd039acc3c40a0 | [
"BSD-2-Clause"
] | null | null | null | // Copyright (c) 2020 The Orbit 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 "OrbitCaptureClient/GpuQueueSubmissionProcessor.h"
#include "OrbitBase/Logging.h"
using orbit_client_protos::Color;
using orbit_client_protos::TimerInfo;
using orbit_grpc_protos::GpuCommandBuffer;
using orbit_grpc_protos::GpuJob;
using orbit_grpc_protos::GpuQueueSubmission;
std::vector<TimerInfo> GpuQueueSubmissionProcessor::ProcessGpuQueueSubmission(
const orbit_grpc_protos::GpuQueueSubmission& gpu_queue_submission,
const absl::flat_hash_map<uint64_t, std::string>& string_intern_pool,
const std::function<uint64_t(const std::string& str)>&
get_string_hash_and_send_to_listener_if_necessary) {
int32_t thread_id = gpu_queue_submission.meta_info().tid();
uint64_t pre_submission_cpu_timestamp =
gpu_queue_submission.meta_info().pre_submission_cpu_timestamp();
uint64_t post_submission_cpu_timestamp =
gpu_queue_submission.meta_info().post_submission_cpu_timestamp();
const GpuJob* matching_gpu_job =
FindMatchingGpuJob(thread_id, pre_submission_cpu_timestamp, post_submission_cpu_timestamp);
// If we haven't found the matching "GpuJob" or the submission contains "begin" markers (which
// might have the "end" markers in a later submission), we save the "GpuSubmission" for later.
// Note that as soon as all "begin" markers have been processed, the "GpuSubmission" will be
// deleted again.
if (matching_gpu_job == nullptr || gpu_queue_submission.num_begin_markers() > 0) {
tid_to_post_submission_time_to_gpu_submission_[thread_id][post_submission_cpu_timestamp] =
gpu_queue_submission;
}
if (gpu_queue_submission.num_begin_markers() > 0) {
tid_to_post_submission_time_to_num_begin_markers_[thread_id][post_submission_cpu_timestamp] =
gpu_queue_submission.num_begin_markers();
}
if (matching_gpu_job == nullptr) {
return {};
}
std::vector<TimerInfo> result = ProcessGpuQueueSubmissionWithMatchingGpuJob(
gpu_queue_submission, *matching_gpu_job, string_intern_pool,
get_string_hash_and_send_to_listener_if_necessary);
if (!HasUnprocessedBeginMarkers(thread_id, post_submission_cpu_timestamp)) {
DeleteSavedGpuJob(thread_id, matching_gpu_job->amdgpu_cs_ioctl_time_ns());
}
return result;
}
std::vector<orbit_client_protos::TimerInfo> GpuQueueSubmissionProcessor::ProcessGpuJob(
const orbit_grpc_protos::GpuJob& gpu_job,
const absl::flat_hash_map<uint64_t, std::string>& string_intern_pool,
const std::function<uint64_t(const std::string& str)>&
get_string_hash_and_send_to_listener_if_necessary) {
int32_t thread_id = gpu_job.tid();
uint64_t amdgpu_cs_ioctl_time_ns = gpu_job.amdgpu_cs_ioctl_time_ns();
const GpuQueueSubmission* matching_gpu_submission =
FindMatchingGpuQueueSubmission(thread_id, amdgpu_cs_ioctl_time_ns);
// If we haven't found the matching "GpuSubmission" or the submission contains "begin" markers
// (which might have the "end" markers in a later submission), we save the "GpuJob" for later.
// Note that as soon as all "begin" markers have been processed, the "GpuJob" will be deleted
// again.
if (matching_gpu_submission == nullptr || matching_gpu_submission->num_begin_markers() > 0) {
tid_to_submission_time_to_gpu_job_[thread_id][amdgpu_cs_ioctl_time_ns] = gpu_job;
}
if (matching_gpu_submission == nullptr) {
return {};
}
uint64_t post_submission_cpu_timestamp =
matching_gpu_submission->meta_info().post_submission_cpu_timestamp();
std::vector<TimerInfo> result = ProcessGpuQueueSubmissionWithMatchingGpuJob(
*matching_gpu_submission, gpu_job, string_intern_pool,
get_string_hash_and_send_to_listener_if_necessary);
if (!HasUnprocessedBeginMarkers(thread_id, post_submission_cpu_timestamp)) {
DeleteSavedGpuSubmission(thread_id, post_submission_cpu_timestamp);
}
return result;
}
const GpuQueueSubmission* GpuQueueSubmissionProcessor::FindMatchingGpuQueueSubmission(
int32_t thread_id, uint64_t submit_time) {
const auto& post_submission_time_to_gpu_submission_it =
tid_to_post_submission_time_to_gpu_submission_.find(thread_id);
if (post_submission_time_to_gpu_submission_it ==
tid_to_post_submission_time_to_gpu_submission_.end()) {
return nullptr;
}
const auto& post_submission_time_to_gpu_submission =
post_submission_time_to_gpu_submission_it->second;
// Find the first Gpu submission with a "post submission" timestamp greater or equal to the Gpu
// job's timestamp. If the "pre submission" timestamp is not greater (i.e. less or equal) than the
// job's timestamp, we have found the matching submission.
auto lower_bound_gpu_submission_it =
post_submission_time_to_gpu_submission.lower_bound(submit_time);
if (lower_bound_gpu_submission_it == post_submission_time_to_gpu_submission.end()) {
return nullptr;
}
const GpuQueueSubmission* matching_gpu_submission = &lower_bound_gpu_submission_it->second;
if (matching_gpu_submission->meta_info().pre_submission_cpu_timestamp() > submit_time) {
return nullptr;
}
return matching_gpu_submission;
}
const GpuJob* GpuQueueSubmissionProcessor::FindMatchingGpuJob(
int32_t thread_id, uint64_t pre_submission_cpu_timestamp,
uint64_t post_submission_cpu_timestamp) {
const auto& submission_time_to_gpu_job_it = tid_to_submission_time_to_gpu_job_.find(thread_id);
if (submission_time_to_gpu_job_it == tid_to_submission_time_to_gpu_job_.end()) {
return nullptr;
}
const auto& submission_time_to_gpu_job = submission_time_to_gpu_job_it->second;
// Find the first Gpu job that has a timestamp greater or equal to the "pre submission" timestamp:
auto gpu_job_matching_pre_submission_it =
submission_time_to_gpu_job.lower_bound(pre_submission_cpu_timestamp);
if (gpu_job_matching_pre_submission_it == submission_time_to_gpu_job.end()) {
return nullptr;
}
// Find the first Gpu job that has a timestamp greater to the "post submission" timestamp
// (which would be the next job) and decrease the iterator by one.
auto gpu_job_matching_post_submission_it =
submission_time_to_gpu_job.upper_bound(post_submission_cpu_timestamp);
if (gpu_job_matching_post_submission_it == submission_time_to_gpu_job.begin()) {
return nullptr;
}
--gpu_job_matching_post_submission_it;
if (&gpu_job_matching_pre_submission_it->second != &gpu_job_matching_post_submission_it->second) {
return nullptr;
}
return &gpu_job_matching_pre_submission_it->second;
}
std::vector<TimerInfo> GpuQueueSubmissionProcessor::ProcessGpuQueueSubmissionWithMatchingGpuJob(
const GpuQueueSubmission& gpu_queue_submission, const GpuJob& matching_gpu_job,
const absl::flat_hash_map<uint64_t, std::string>& string_intern_pool,
const std::function<uint64_t(const std::string& str)>&
get_string_hash_and_send_to_listener_if_necessary) {
std::vector<TimerInfo> result;
std::string timeline;
if (matching_gpu_job.timeline_or_key_case() == GpuJob::kTimelineKey) {
CHECK(string_intern_pool.contains(matching_gpu_job.timeline_key()));
timeline = string_intern_pool.at(matching_gpu_job.timeline_key());
} else {
timeline = matching_gpu_job.timeline();
}
uint64_t timeline_hash = get_string_hash_and_send_to_listener_if_necessary(timeline);
std::optional<GpuCommandBuffer> first_command_buffer =
ExtractFirstCommandBuffer(gpu_queue_submission);
std::vector<TimerInfo> command_buffer_timers =
ProcessGpuCommandBuffers(gpu_queue_submission, matching_gpu_job, first_command_buffer,
timeline_hash, get_string_hash_and_send_to_listener_if_necessary);
result.insert(result.end(), command_buffer_timers.begin(), command_buffer_timers.end());
std::vector<TimerInfo> debug_marker_timers =
ProcessGpuDebugMarkers(gpu_queue_submission, matching_gpu_job, first_command_buffer, timeline,
string_intern_pool, get_string_hash_and_send_to_listener_if_necessary);
result.insert(result.end(), debug_marker_timers.begin(), debug_marker_timers.end());
return result;
}
bool GpuQueueSubmissionProcessor::HasUnprocessedBeginMarkers(
int32_t thread_id, uint64_t post_submission_timestamp) const {
if (!tid_to_post_submission_time_to_num_begin_markers_.contains(thread_id)) {
return false;
}
if (!tid_to_post_submission_time_to_num_begin_markers_.at(thread_id).contains(
post_submission_timestamp)) {
return false;
}
CHECK(tid_to_post_submission_time_to_num_begin_markers_.at(thread_id).at(
post_submission_timestamp) > 0);
return true;
}
void GpuQueueSubmissionProcessor::DecrementUnprocessedBeginMarkers(
int32_t thread_id, uint64_t submission_timestamp, uint64_t post_submission_timestamp) {
CHECK(tid_to_post_submission_time_to_num_begin_markers_.contains(thread_id));
auto& post_submission_time_to_num_begin_markers =
tid_to_post_submission_time_to_num_begin_markers_.at(thread_id);
CHECK(post_submission_time_to_num_begin_markers.contains(post_submission_timestamp));
uint64_t new_num = post_submission_time_to_num_begin_markers.at(post_submission_timestamp) - 1;
post_submission_time_to_num_begin_markers.at(post_submission_timestamp) = new_num;
if (new_num == 0) {
post_submission_time_to_num_begin_markers.erase(post_submission_timestamp);
if (post_submission_time_to_num_begin_markers.empty()) {
tid_to_post_submission_time_to_num_begin_markers_.erase(thread_id);
DeleteSavedGpuJob(thread_id, submission_timestamp);
DeleteSavedGpuSubmission(thread_id, post_submission_timestamp);
}
}
}
void GpuQueueSubmissionProcessor::DeleteSavedGpuJob(int32_t thread_id,
uint64_t submission_timestamp) {
if (!tid_to_submission_time_to_gpu_job_.contains(thread_id)) {
return;
}
auto& submission_time_to_gpu_job = tid_to_submission_time_to_gpu_job_.at(thread_id);
submission_time_to_gpu_job.erase(submission_timestamp);
if (submission_time_to_gpu_job.empty()) {
tid_to_submission_time_to_gpu_job_.erase(thread_id);
}
}
void GpuQueueSubmissionProcessor::DeleteSavedGpuSubmission(int32_t thread_id,
uint64_t post_submission_timestamp) {
if (!tid_to_post_submission_time_to_gpu_submission_.contains(thread_id)) {
return;
}
auto& post_submission_time_to_gpu_submission =
tid_to_post_submission_time_to_gpu_submission_.at(thread_id);
post_submission_time_to_gpu_submission.erase(post_submission_timestamp);
if (post_submission_time_to_gpu_submission.empty()) {
tid_to_post_submission_time_to_gpu_submission_.erase(thread_id);
}
}
std::vector<TimerInfo> GpuQueueSubmissionProcessor::ProcessGpuCommandBuffers(
const orbit_grpc_protos::GpuQueueSubmission& gpu_queue_submission,
const orbit_grpc_protos::GpuJob& matching_gpu_job,
const std::optional<orbit_grpc_protos::GpuCommandBuffer>& first_command_buffer,
uint64_t timeline_hash,
const std::function<uint64_t(const std::string& str)>&
get_string_hash_and_send_to_listener_if_necessary) {
constexpr const char* kCommandBufferLabel = "command buffer";
uint64_t command_buffer_text_key =
get_string_hash_and_send_to_listener_if_necessary(kCommandBufferLabel);
int32_t thread_id = gpu_queue_submission.meta_info().tid();
std::vector<TimerInfo> result;
for (const auto& submit_info : gpu_queue_submission.submit_infos()) {
for (const auto& command_buffer : submit_info.command_buffers()) {
CHECK(first_command_buffer != std::nullopt);
TimerInfo command_buffer_timer;
if (command_buffer.begin_gpu_timestamp_ns() != 0) {
command_buffer_timer.set_start(command_buffer.begin_gpu_timestamp_ns() -
first_command_buffer->begin_gpu_timestamp_ns() +
matching_gpu_job.gpu_hardware_start_time_ns());
} else {
command_buffer_timer.set_start(begin_capture_time_ns_);
}
command_buffer_timer.set_end(command_buffer.end_gpu_timestamp_ns() -
first_command_buffer->begin_gpu_timestamp_ns() +
matching_gpu_job.gpu_hardware_start_time_ns());
command_buffer_timer.set_depth(matching_gpu_job.depth());
command_buffer_timer.set_timeline_hash(timeline_hash);
command_buffer_timer.set_processor(-1);
command_buffer_timer.set_thread_id(thread_id);
command_buffer_timer.set_type(TimerInfo::kGpuCommandBuffer);
command_buffer_timer.set_user_data_key(command_buffer_text_key);
result.push_back(command_buffer_timer);
}
}
return result;
}
std::vector<TimerInfo> GpuQueueSubmissionProcessor::ProcessGpuDebugMarkers(
const GpuQueueSubmission& gpu_queue_submission, const GpuJob& matching_gpu_job,
const std::optional<GpuCommandBuffer>& first_command_buffer, const std::string& timeline,
const absl::flat_hash_map<uint64_t, std::string>& string_intern_pool,
const std::function<uint64_t(const std::string& str)>&
get_string_hash_and_send_to_listener_if_necessary) {
if (gpu_queue_submission.completed_markers_size() == 0) {
return {};
}
std::vector<TimerInfo> result;
std::string timeline_marker = timeline + "_marker";
uint64_t timeline_marker_hash =
get_string_hash_and_send_to_listener_if_necessary(timeline_marker);
const auto& submission_meta_info = gpu_queue_submission.meta_info();
const int32_t submission_thread_id = submission_meta_info.tid();
uint64_t submission_pre_submission_cpu_timestamp =
submission_meta_info.pre_submission_cpu_timestamp();
uint64_t submission_post_submission_cpu_timestamp =
submission_meta_info.post_submission_cpu_timestamp();
static constexpr int32_t kUnknownThreadId = -1;
for (const auto& completed_marker : gpu_queue_submission.completed_markers()) {
CHECK(first_command_buffer != std::nullopt);
TimerInfo marker_timer;
// If we've recorded the submission that contains the begin marker, we'll retrieve this
// submission from our mappings, and set the markers begin time accordingly.
// Otherwise, we will use the capture start time as begin.
if (completed_marker.has_begin_marker()) {
const auto& begin_marker_info = completed_marker.begin_marker();
const auto& begin_marker_meta_info = begin_marker_info.meta_info();
const int32_t begin_marker_thread_id = begin_marker_meta_info.tid();
uint64_t begin_marker_post_submission_cpu_timestamp =
begin_marker_meta_info.post_submission_cpu_timestamp();
uint64_t begin_marker_pre_submission_cpu_timestamp =
begin_marker_meta_info.pre_submission_cpu_timestamp();
// Note that the "begin" and "end" of a debug marker may not happen on the same submission.
// For those cases, we save the meta information of the "begin" marker's submission in the
// marker information. We will always send the marker on the "end" marker's submission though.
// So let's check if the meta data is the same as the current submission (i.e. the marker
// begins and ends on this submission). If this is the case, use that submission. Otherwise,
// find the submission that matches the given meta data (that we must have received before,
// and must still be saved).
const GpuQueueSubmission* matching_begin_submission = nullptr;
if (submission_pre_submission_cpu_timestamp == begin_marker_pre_submission_cpu_timestamp &&
submission_post_submission_cpu_timestamp == begin_marker_post_submission_cpu_timestamp &&
submission_thread_id == begin_marker_thread_id) {
matching_begin_submission = &gpu_queue_submission;
} else {
matching_begin_submission = FindMatchingGpuQueueSubmission(
begin_marker_thread_id, begin_marker_post_submission_cpu_timestamp);
}
// Note that we receive submissions of a single queue in order (by CPU submission time). So if
// there is no matching "begin submission", the "begin" was submitted before the "end" and
// we lost the record of the "begin submission" (which should not happen).
CHECK(matching_begin_submission != nullptr);
std::optional<GpuCommandBuffer> begin_submission_first_command_buffer =
ExtractFirstCommandBuffer(*matching_begin_submission);
CHECK(begin_submission_first_command_buffer.has_value());
const GpuJob* matching_begin_job = FindMatchingGpuJob(
begin_marker_thread_id, begin_marker_meta_info.pre_submission_cpu_timestamp(),
begin_marker_post_submission_cpu_timestamp);
CHECK(matching_begin_job != nullptr);
// Convert the GPU time to CPU time, based on the CPU time of the HW execution begin and the
// GPU timestamp of the begin of the first command buffer. Note that we will assume that the
// first command buffer starts execution right away as an approximation.
marker_timer.set_start(completed_marker.begin_marker().gpu_timestamp_ns() +
matching_begin_job->gpu_hardware_start_time_ns() -
begin_submission_first_command_buffer->begin_gpu_timestamp_ns());
if (begin_marker_thread_id == gpu_queue_submission.meta_info().tid()) {
marker_timer.set_thread_id(begin_marker_thread_id);
} else {
marker_timer.set_thread_id(kUnknownThreadId);
}
DecrementUnprocessedBeginMarkers(begin_marker_thread_id,
matching_begin_job->amdgpu_cs_ioctl_time_ns(),
begin_marker_post_submission_cpu_timestamp);
} else {
marker_timer.set_start(begin_capture_time_ns_);
marker_timer.set_thread_id(kUnknownThreadId);
}
marker_timer.set_depth(completed_marker.depth());
marker_timer.set_timeline_hash(timeline_marker_hash);
marker_timer.set_processor(-1);
marker_timer.set_type(TimerInfo::kGpuDebugMarker);
marker_timer.set_end(completed_marker.end_gpu_timestamp_ns() -
first_command_buffer->begin_gpu_timestamp_ns() +
matching_gpu_job.gpu_hardware_start_time_ns());
CHECK(string_intern_pool.contains(completed_marker.text_key()));
const std::string& text = string_intern_pool.at(completed_marker.text_key());
uint64_t text_key = get_string_hash_and_send_to_listener_if_necessary(text);
if (completed_marker.has_color()) {
Color* color = marker_timer.mutable_color();
color->set_red(static_cast<uint32_t>(completed_marker.color().red() * 255));
color->set_green(static_cast<uint32_t>(completed_marker.color().green() * 255));
color->set_blue(static_cast<uint32_t>(completed_marker.color().blue() * 255));
color->set_alpha(static_cast<uint32_t>(completed_marker.color().alpha() * 255));
}
marker_timer.set_user_data_key(text_key);
result.push_back(marker_timer);
}
return result;
}
std::optional<orbit_grpc_protos::GpuCommandBuffer>
GpuQueueSubmissionProcessor::ExtractFirstCommandBuffer(
const orbit_grpc_protos::GpuQueueSubmission& gpu_queue_submission) {
for (const auto& submit_info : gpu_queue_submission.submit_infos()) {
for (const auto& command_buffer : submit_info.command_buffers()) {
return command_buffer;
}
}
return std::nullopt;
} | 48.395062 | 100 | 0.764847 | [
"vector"
] |
6f56edd365d97cc50fcff9544f6a3f7c56c75c15 | 9,848 | cpp | C++ | legacy/eva-to-be-ported/gims/src/DataProcessor/LineIntersection.cpp | lucid-at-dream/citylife | d0313536027e25c000cb8ed6146bdf67e1ed5c33 | [
"MIT"
] | 2 | 2022-02-15T18:09:06.000Z | 2022-02-15T22:37:26.000Z | legacy/eva-to-be-ported/gims/src/DataProcessor/LineIntersection.cpp | futuo/citylife | f9b855e740d970ab6a0a7204348b40849b3b9ac3 | [
"MIT"
] | 1 | 2022-02-18T16:58:39.000Z | 2022-02-18T16:58:39.000Z | legacy/eva-to-be-ported/gims/src/DataProcessor/LineIntersection.cpp | lucid-at-dream/citylife | d0313536027e25c000cb8ed6146bdf67e1ed5c33 | [
"MIT"
] | null | null | null | #include "LineIntersection.hpp"
//helper functions for the linestring intersection matrix construction
void DE9IM_mls_ls(DE9IM *resultset, GIMS_MultiLineString *query, GIMS_LineString *other)
{
BentleySolver bs;
GIMS_MultiLineString *other_mls = new GIMS_MultiLineString(1);
other_mls->append(other);
list<GIMS_Geometry *> intersections = bs.solve(query, other_mls);
delete other_mls;
matrix_t::iterator matrix_index = resultset->getMatrixIndex(other->id);
if (intersections.size() == 0)
{
//then they're disjoint...
resultset->setIE(matrix_index, 1);
resultset->setBE(matrix_index, 0);
resultset->setEI(matrix_index, 1);
resultset->setEB(matrix_index, 0);
return;
}
GIMS_LineString *other_original = (GIMS_LineString *)(*(idIndex.find(other)));
GIMS_Point *otherBorder[2] = { other_original->list[0], other_original->list[other_original->size - 1] };
GIMS_Geometry *query_original = (GIMS_LineString *)(*(idIndex.find(query)));
GIMS_MultiPoint queryBorder;
if (query_original->type == LINESTRING)
{
GIMS_LineString *aux_ls = (GIMS_LineString *)query_original;
queryBorder.append(aux_ls->list[0]);
queryBorder.append(aux_ls->list[aux_ls->size - 1]);
}
else if (query_original->type == MULTILINESTRING)
{
GIMS_MultiLineString *aux_mls = (GIMS_MultiLineString *)query_original;
for (int i = 0; i < aux_mls->size; i++)
{
queryBorder.append(aux_mls->list[i]->list[0]);
queryBorder.append(aux_mls->list[i]->list[aux_mls->list[i]->size - 1]);
}
}
int intersectedBorders = 0;
list<GIMS_LineSegment *> linesegments;
int shift_inc = queryBorder.size;
for (list<GIMS_Geometry *>::iterator it = intersections.begin(); it != intersections.end(); it++)
{
if ((*it)->type == LINESEGMENT)
{
linesegments.push_back((GIMS_LineSegment *)(*it));
for (int i = 0; i < queryBorder.size; i++)
{
if (((GIMS_LineSegment *)(*it))->coversPoint(queryBorder.list[i]))
intersectedBorders |= 1 << i;
}
for (int i = 0; i < 2; i++)
{
if (((GIMS_LineSegment *)(*it))->coversPoint(otherBorder[i]))
intersectedBorders |= 1 << (shift_inc + i);
}
resultset->setIntersect(matrix_index, 1);
resultset->setII(matrix_index, 1);
}
else
{
resultset->setIntersect(matrix_index, 0);
bool isBorder = false;
for (int i = 0; i < queryBorder.size; i++)
{
if (((GIMS_Point *)(*it))->equals(queryBorder.list[i]))
{
intersectedBorders |= 1 << i;
isBorder = true;
}
}
for (int i = 0; i < 2; i++)
{
if (((GIMS_Point *)(*it))->equals(otherBorder[i]))
{
intersectedBorders |= 1 << (shift_inc + i);
isBorder = true;
}
}
if (!isBorder)
resultset->setII(matrix_index, 0);
}
}
/*Here we check intersections of Borders with exteriors*/
if ((intersectedBorders & (1 << shift_inc)) == 0 || (intersectedBorders & (1 << (shift_inc + 1))) == 0)
{
resultset->setEB(matrix_index, 0);
}
for (int i = 0; i < queryBorder.size; i++)
{
if ((intersectedBorders & (1 << i)) == 0)
{
resultset->setBE(matrix_index, 0);
break;
}
}
/*Here we check intersections of exteriors with interiors*/
bool queryContained = false, otherContained = false;
if (linesegments.size() >= (unsigned)(query->size))
{
//check if linesegments cover the query geometry entirely
queryContained = query->isCoveredBy(linesegments);
}
if (linesegments.size() >= (unsigned)(other->size))
{
//check if linesegments cover the other geometry entirely
otherContained = other->isCoveredBy(linesegments, false);
}
if (!queryContained && !otherContained)
{
resultset->setEI(matrix_index, 1);
resultset->setIE(matrix_index, 1);
}
else if (!queryContained && otherContained)
{
resultset->setIE(matrix_index, 1);
}
else if (queryContained && !otherContained)
{
resultset->setEI(matrix_index, 1);
}
for (list<GIMS_Geometry *>::iterator it = intersections.begin(); it != intersections.end(); it++)
(*it)->deepDelete();
}
void DE9IM_mls_mls(DE9IM *resultset, GIMS_MultiLineString *query, GIMS_MultiLineString *other)
{
BentleySolver bs;
list<GIMS_Geometry *> intersections = bs.solve(query, other);
matrix_t::iterator matrix_index = resultset->getMatrixIndex(other->id);
if (intersections.size() == 0)
{
//then they're disjoint...
resultset->setIE(matrix_index, 1);
resultset->setBE(matrix_index, 0);
resultset->setEI(matrix_index, 1);
resultset->setEB(matrix_index, 0);
return;
}
//retrieve other's border
GIMS_Geometry *original = (*(idIndex.find(other)));
GIMS_MultiPoint otherBorder;
if (original->type == LINESTRING)
{
GIMS_LineString *orig_ls = (GIMS_LineString *)original;
otherBorder.append(orig_ls->list[0]);
otherBorder.append(orig_ls->list[orig_ls->size - 1]);
}
else if (original->type == MULTILINESTRING)
{
GIMS_MultiLineString *orig_mls = (GIMS_MultiLineString *)original;
for (int i = 0; i < orig_mls->size; i++)
{
otherBorder.append(orig_mls->list[i]->list[0]);
otherBorder.append(orig_mls->list[i]->list[orig_mls->list[i]->size - 1]);
}
}
//retrieve query's border
original = (*(idIndex.find(query)));
GIMS_MultiPoint queryBorder;
if (original->type == LINESTRING)
{
GIMS_LineString *orig_ls = (GIMS_LineString *)original;
queryBorder.append(orig_ls->list[0]);
queryBorder.append(orig_ls->list[orig_ls->size - 1]);
}
else if (original->type == MULTILINESTRING)
{
GIMS_MultiLineString *orig_mls = (GIMS_MultiLineString *)original;
for (int i = 0; i < orig_mls->size; i++)
{
queryBorder.append(orig_mls->list[i]->list[0]);
queryBorder.append(orig_mls->list[i]->list[orig_mls->list[i]->size - 1]);
}
}
int intersectedBorders = 0;
list<GIMS_LineSegment *> linesegments;
int shift_inc = queryBorder.size;
for (list<GIMS_Geometry *>::iterator it = intersections.begin(); it != intersections.end(); it++)
{
if ((*it)->type == LINESEGMENT)
{
linesegments.push_back((GIMS_LineSegment *)(*it));
for (int i = 0; i < queryBorder.size; i++)
{
if (((GIMS_LineSegment *)(*it))->coversPoint(queryBorder.list[i]))
intersectedBorders |= 1 << i;
}
for (int i = 0; i < otherBorder.size; i++)
{
if (((GIMS_LineSegment *)(*it))->coversPoint(otherBorder.list[i]))
intersectedBorders |= 1 << (shift_inc + i);
}
resultset->setIntersect(matrix_index, 1);
resultset->setII(matrix_index, 1);
}
else
{
resultset->setIntersect(matrix_index, 0);
bool isBorder = false;
for (int i = 0; i < queryBorder.size; i++)
{
if (((GIMS_Point *)(*it))->equals(queryBorder.list[i]))
{
intersectedBorders |= 1 << i;
isBorder = true;
}
}
for (int i = 0; i < otherBorder.size; i++)
{
if (((GIMS_Point *)(*it))->equals(otherBorder.list[i]))
{
intersectedBorders |= 1 << (shift_inc + i);
isBorder = true;
}
}
if (!isBorder)
resultset->setII(matrix_index, 0);
}
}
/*Here we check intersections of Borders with exteriors*/
for (int i = 0; i < otherBorder.size; i++)
{
if ((intersectedBorders & (1 << (shift_inc + i))) == 0)
{
resultset->setEB(matrix_index, 0);
break;
}
}
for (int i = 0; i < queryBorder.size; i++)
{
if ((intersectedBorders & (1 << i)) == 0)
{
resultset->setBE(matrix_index, 0);
break;
}
}
/*Here we check intersections of exteriors with interiors*/
bool queryContained = false, otherContained = false;
if (linesegments.size() >= (unsigned)(query->size))
{
//check if linesegments cover the query geometry entirely
queryContained = query->isCoveredBy(linesegments);
}
int total = 0;
for (int i = 0; i < other->size; i++)
total += other->list[i]->size;
if (linesegments.size() >= (unsigned)(total))
{
//check if linesegments cover the other geometry entirely
otherContained = other->isCoveredBy(linesegments, false);
}
if (!queryContained && !otherContained)
{
resultset->setEI(matrix_index, 1);
resultset->setIE(matrix_index, 1);
}
else if (!queryContained && otherContained)
{
resultset->setIE(matrix_index, 1);
}
else if (queryContained && !otherContained)
{
resultset->setEI(matrix_index, 1);
}
for (list<GIMS_Geometry *>::iterator it = intersections.begin(); it != intersections.end(); it++)
(*it)->deepDelete();
}
| 31.87055 | 109 | 0.555544 | [
"geometry"
] |
6f597765e28c6e47b7d905559af810e9a49c7d7b | 9,356 | hpp | C++ | Include/MH/Geometry/Math.hpp | n-suudai/MHLib | 1f67d696f1147d8f4df56f9531f91eae8913ab9a | [
"MIT"
] | null | null | null | Include/MH/Geometry/Math.hpp | n-suudai/MHLib | 1f67d696f1147d8f4df56f9531f91eae8913ab9a | [
"MIT"
] | null | null | null | Include/MH/Geometry/Math.hpp | n-suudai/MHLib | 1f67d696f1147d8f4df56f9531f91eae8913ab9a | [
"MIT"
] | null | null | null |
#pragma once
#include "MH/External/Eigen.hpp"
#include "MH/OS/Types.hpp"
#include "MH/OS/Assert.hpp"
namespace MH {
namespace Geometry {
typedef f32 Radius;
typedef Eigen::Matrix4f Matrix4x4;
typedef Eigen::Matrix3f Matrix3x3;
typedef Eigen::Matrix2f Matrix2x2;
typedef Eigen::Vector4f Vector4;
typedef Eigen::Vector3f Vector3;
typedef Eigen::Vector2f Vector2;
typedef Eigen::DiagonalMatrix<f32, 3> Scaling3;
typedef Eigen::DiagonalMatrix<f32, 2> Scaling2;
typedef Eigen::Affine3f Affine3;
typedef Eigen::Affine2f Affine2;
typedef Eigen::Translation3f Translation3;
typedef Eigen::Translation2f Translation2;
typedef Eigen::Quaternionf Quaternion;
typedef Eigen::Rotation2Df Rotation2;
static constexpr f32 PIH = 1.5707963267948966192313216916398f;
static constexpr f32 PI = 3.1415926535897932384626433832795f;
static constexpr f32 PI2 = 6.2831853071795864769252867665590f;
static constexpr f32 DIV_PI = 0.31830988618379067153776752674503f;
static constexpr f32 DIV_PI2 = 0.15915494309189533576888376337251f;
static constexpr f32 F32_EPSILON = 1.192093e-07f;
template<typename T>
inline T& Lerp(T& out, T const& value1, T const& value2, f32 t)
{
out = value1 + (value2 - value1) * t;
return out;
}
inline f32 DegreeToRadian(f32 degree)
{
return degree * 0.01745329251994329576923690768489f;
}
inline f32 RadianToDegree(f32 radian)
{
return radian * 57.295779513082320876798154814105f;
}
inline f32 Clamp(f32 value, f32 min, f32 max)
{
if (value < min) { return min; }
if (value > max) { return max; }
return value;
}
inline f32 Min(f32 value1, f32 value2)
{
return value1 > value2 ? value2 : value1;
}
inline f32 Max(f32 value1, f32 value2)
{
return value1 < value2 ? value2 : value1;
}
inline f32 Saturate(f32 value)
{
if (value > 1.0f) { return 1.0f; }
if (value < 0.0f) { return 0.0f; }
return value;
}
inline f32 Smoothstep(f32 edge0, f32 edge1, f32 x)
{
x = Saturate((x - edge0) / (edge1 - edge0));
return x * x * (3.0f - 2.0f * x);
}
inline bool NearEqual(f32 S1, f32 S2, f32 epsilon = F32_EPSILON)
{
float Delta = S1 - S2;
return (fabsf(Delta) <= epsilon);
}
inline f32 Cos(f32 x)
{
return std::cos(x);
}
inline f32 Sin(f32 x)
{
return std::sin(x);
}
inline void SinCos(f32* pSin, f32* pCos, f32 value)
{
MH_ASSERT(pSin);
MH_ASSERT(pCos);
// Map Value to y in [-pi,pi], x = 2*pi*quotient + remainder.
f32 quotient = DIV_PI2 * value;
if (value >= 0.0f)
{
quotient = (f32)((int)(quotient + 0.5f));
}
else
{
quotient = (f32)((int)(quotient - 0.5f));
}
f32 y = value - PI2 * quotient;
// Map y to [-pi/2,pi/2] with sin(y) = sin(Value).
f32 sign;
if (y > PIH)
{
y = PI - y;
sign = -1.0f;
}
else if (y < -PIH)
{
y = -PI - y;
sign = -1.0f;
}
else
{
sign = +1.0f;
}
f32 y2 = y * y;
// 11-degree minimax approximation
*pSin = (((((-2.3889859e-08f * y2 + 2.7525562e-06f) * y2 - 0.00019840874f) * y2 + 0.0083333310f) * y2 - 0.16666667f) * y2 + 1.0f) * y;
// 10-degree minimax approximation
f32 p = ((((-2.6051615e-07f * y2 + 2.4760495e-05f) * y2 - 0.0013888378f) * y2 + 0.041666638f) * y2 - 0.5f) * y2 + 1.0f;
*pCos = sign * p;
}
inline void SinCos(f32* pSin, f32* pCos, f32 value, f32 scale)
{
SinCos(pSin, pCos, value);
*pSin *= scale;
*pCos *= scale;
}
inline Matrix4x4& Translate(Matrix4x4& mat, Matrix4x4 const& m, Vector3 const& v)
{
mat = m;
mat.col(3) = m.col(0) * v(0) + m.col(1) * v(1) + m.col(2) * v(2) + m.col(3);
return mat;
}
inline Matrix4x4& Rotate(Matrix4x4& mat, Matrix4x4 const& m, f32 angle, Vector3 const& v)
{
f32 s, c;
SinCos(&s, &c, angle);
Vector3 axis(v.normalized());
Vector3 temp((1.0f - c) * axis);
Matrix4x4 Rotate;
Rotate(0, 0) = c + temp(0) * axis(0);
Rotate(0, 1) = temp(0) * axis(1) + s * axis(2);
Rotate(0, 2) = temp(0) * axis(2) - s * axis(1);
Rotate(1, 0) = temp(1) * axis(0) - s * axis(2);
Rotate(1, 1) = c + temp(1) * axis(1);
Rotate(1, 2) = temp(1) * axis(2) + s * axis(0);
Rotate(2, 0) = temp(2) * axis(0) + s * axis(1);
Rotate(2, 1) = temp(2) * axis(1) - s * axis(0);
Rotate(2, 2) = c + temp(2) * axis(2);
mat.col(0) = m.col(0) * Rotate(0, 0) + m.col(1) * Rotate(0, 1) + m.col(2) * Rotate(0, 2);
mat.col(1) = m.col(0) * Rotate(1, 0) + m.col(1) * Rotate(1, 1) + m.col(2) * Rotate(1, 2);
mat.col(2) = m.col(0) * Rotate(2, 0) + m.col(1) * Rotate(2, 1) + m.col(2) * Rotate(2, 2);
mat.col(3) = m.col(3);
return mat;
}
inline Matrix4x4& Scale(Matrix4x4& mat, Matrix4x4 const& m, Vector3 const& v)
{
mat.col(0) = m.col(0) * v(0);
mat.col(1) = m.col(1) * v(1);
mat.col(2) = m.col(2) * v(2);
mat.col(3) = m.col(3);
return mat;
}
inline Matrix4x4& OrthoLH(Matrix4x4& mat, f32 left, f32 right, f32 bottom, f32 top, f32 zNear, f32 zFar)
{
mat = Matrix4x4::Identity();
mat(0, 0) = 2.0f / (right - left);
mat(1, 1) = 2.0f / (top - bottom);
mat(2, 2) = 2.0f / (zFar - zNear);
mat(3, 0) = -(right + left) / (right - left);
mat(3, 1) = -(top + bottom) / (top - bottom);
mat(3, 2) = -(zFar + zNear) / (zFar - zNear);
return mat;
}
inline Matrix4x4& OrthoRH(Matrix4x4& mat, f32 left, f32 right, f32 bottom, f32 top, f32 zNear, f32 zFar)
{
mat = Matrix4x4::Identity();
mat(0, 0) = 2.0f / (right - left);
mat(1, 1) = 2.0f / (top - bottom);
mat(2, 2) = -2.0f / (zFar - zNear);
mat(3, 0) = -(right + left) / (right - left);
mat(3, 1) = -(top + bottom) / (top - bottom);
mat(3, 2) = -(zFar + zNear) / (zFar - zNear);
return mat;
}
inline Matrix4x4& FrustumLH(Matrix4x4& mat, f32 left, f32 right, f32 bottom, f32 top, f32 nearVal, f32 farVal)
{
mat = Matrix4x4::Zero();
mat(0, 0) = (2.0f * nearVal) / (right - left);
mat(1, 1) = (2.0f * nearVal) / (top - bottom);
mat(2, 0) = (right + left) / (right - left);
mat(2, 1) = (top + bottom) / (top - bottom);
mat(2, 2) = (farVal + nearVal) / (farVal - nearVal);
mat(2, 3) = 1.0f;
mat(3, 2) = -(2.0f * farVal * nearVal) / (farVal - nearVal);
return mat;
}
inline Matrix4x4& FrustumRH(Matrix4x4& mat, f32 left, f32 right, f32 bottom, f32 top, f32 nearVal, f32 farVal)
{
mat = Matrix4x4::Zero();
mat(0, 0) = (2.0f * nearVal) / (right - left);
mat(1, 1) = (2.0f * nearVal) / (top - bottom);
mat(2, 0) = (right + left) / (right - left);
mat(2, 1) = (top + bottom) / (top - bottom);
mat(2, 2) = -(farVal + nearVal) / (farVal - nearVal);
mat(2, 3) = -1.0f;
mat(3, 2) = -(2.0f * farVal * nearVal) / (farVal - nearVal);
return mat;
}
inline Matrix4x4& PerspectiveFovLH(Matrix4x4& mat, f32 fov, f32 width, f32 height, f32 zNear, f32 zFar)
{
MH_ASSERT(width > 0.0f);
MH_ASSERT(height > 0.0f);
MH_ASSERT(fov > 0.0f);
f32 s, c;
SinCos(&s, &c, 0.5f * fov);
f32 const h = c / s;
f32 const w = h * height / width; ///todo max(width , Height) / min(width , Height)?
mat = Matrix4x4::Zero();
mat(0, 0) = w;
mat(1, 1) = h;
mat(2, 2) = (zFar + zNear) / (zFar - zNear);
mat(2, 3) = 1.0f;
mat(3, 2) = -(2.0f * zFar * zNear) / (zFar - zNear);
return mat;
}
inline Matrix4x4& PerspectiveFovRH(Matrix4x4& mat, f32 fov, f32 width, f32 height, f32 zNear, f32 zFar)
{
MH_ASSERT(width > 0.0f);
MH_ASSERT(height > 0.0f);
MH_ASSERT(fov > 0.0f);
f32 s, c;
SinCos(&s, &c, 0.5f * fov);
f32 const h = c / s;
f32 const w = h * height / width; ///todo max(width , Height) / min(width , Height)?
mat = Matrix4x4::Zero();
mat(0, 0) = w;
mat(1, 1) = h;
mat(2, 2) = -(zFar + zNear) / (zFar - zNear);
mat(2, 3) = -1.0f;
mat(3, 2) = -(2.0f * zFar * zNear) / (zFar - zNear);
return mat;
}
inline Matrix4x4& LookAtLH(Matrix4x4& mat, Vector3 const& eye, Vector3 const& center, Vector3 const& up)
{
Vector3 const f((center - eye).normalized());
Vector3 const s(up.cross(f).normalized());
Vector3 const u(f.cross(s));
mat = Matrix4x4::Identity();
mat(0, 0) = s.x();
mat(1, 0) = s.y();
mat(2, 0) = s.z();
mat(0, 1) = u.x();
mat(1, 1) = u.y();
mat(2, 1) = u.z();
mat(0, 2) = f.x();
mat(1, 2) = f.y();
mat(2, 2) = f.z();
mat(3, 0) = -s.dot(eye);
mat(3, 1) = -u.dot(eye);
mat(3, 2) = -f.dot(eye);
return mat;
}
inline Matrix4x4& LookAtRH(Matrix4x4& mat, Vector3 const& eye, Vector3 const& center, Vector3 const& up)
{
Vector3 const f((center - eye).normalized());
Vector3 const s(f.cross(up).normalized());
Vector3 const u(s.cross(f));
mat = Matrix4x4::Identity();
mat(0, 0) = s.x();
mat(1, 0) = s.y();
mat(2, 0) = s.z();
mat(0, 1) = u.x();
mat(1, 1) = u.y();
mat(2, 1) = u.z();
mat(0, 2) = -f.x();
mat(1, 2) = -f.y();
mat(2, 2) = -f.z();
mat(3, 0) = -s.dot(eye);
mat(3, 1) = -u.dot(eye);
mat(3, 2) = f.dot(eye);
return mat;
}
} // namespace Geometry
} // namespace MH
| 26.134078 | 138 | 0.55451 | [
"geometry"
] |
6f5983b9b1d1bb29668552aa3bd8d068f7f47193 | 1,373 | cc | C++ | components/dom_distiller/core/dom_distiller_service.cc | nagineni/chromium-crosswalk | 5725642f1c67d0f97e8613ec1c3e8107ab53fdf8 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 4 | 2017-04-05T01:51:34.000Z | 2018-02-15T03:11:54.000Z | components/dom_distiller/core/dom_distiller_service.cc | nagineni/chromium-crosswalk | 5725642f1c67d0f97e8613ec1c3e8107ab53fdf8 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-12-13T19:44:12.000Z | 2021-12-13T19:44:12.000Z | components/dom_distiller/core/dom_distiller_service.cc | nagineni/chromium-crosswalk | 5725642f1c67d0f97e8613ec1c3e8107ab53fdf8 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 4 | 2017-04-05T01:52:03.000Z | 2022-02-13T17:58:45.000Z | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/dom_distiller/core/dom_distiller_service.h"
#include "components/dom_distiller/core/dom_distiller_store.h"
namespace dom_distiller {
ViewerHandle::ViewerHandle() {}
ViewerHandle::~ViewerHandle() {}
DomDistillerService::DomDistillerService(
scoped_ptr<DomDistillerStoreInterface> store,
scoped_ptr<DistillerFactory> distiller_factory)
: store_(store.Pass()), distiller_factory_(distiller_factory.Pass()) {}
DomDistillerService::~DomDistillerService() {}
syncer::SyncableService* DomDistillerService::GetSyncableService() const {
return store_->GetSyncableService();
}
void DomDistillerService::AddToList(const GURL& url) { NOTIMPLEMENTED(); }
std::vector<ArticleEntry> DomDistillerService::GetEntries() const {
return store_->GetEntries();
}
scoped_ptr<ViewerHandle> DomDistillerService::ViewEntry(
ViewerContext* context,
const std::string& entry_id) {
NOTIMPLEMENTED();
return scoped_ptr<ViewerHandle>();
}
scoped_ptr<ViewerHandle> DomDistillerService::ViewUrl(ViewerContext* context,
const GURL& url) {
NOTIMPLEMENTED();
return scoped_ptr<ViewerHandle>();
}
} // namespace dom_distiller
| 31.204545 | 77 | 0.74654 | [
"vector"
] |
6f59d26cd12651b8f96ff4f494b7ef92cdfd4c2e | 2,906 | cpp | C++ | modules/unitest/encode/test_encoder.cpp | zhaoying9105/CNStream | 22c8e26ac5f2db613d33aaf636b1a96dba5e3417 | [
"Apache-2.0"
] | 1 | 2020-07-20T10:46:40.000Z | 2020-07-20T10:46:40.000Z | modules/unitest/encode/test_encoder.cpp | zhaoying9105/CNStream | 22c8e26ac5f2db613d33aaf636b1a96dba5e3417 | [
"Apache-2.0"
] | null | null | null | modules/unitest/encode/test_encoder.cpp | zhaoying9105/CNStream | 22c8e26ac5f2db613d33aaf636b1a96dba5e3417 | [
"Apache-2.0"
] | null | null | null | /*************************************************************************
* Copyright (C) [2019] by Cambricon, Inc. All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 <glog/logging.h>
#include <gtest/gtest.h>
#include <cstdlib>
#include <ctime>
#include <memory>
#include <string>
#include <vector>
#include "cnstream_frame_va.hpp"
#include "encoder.hpp"
#include "test_base.hpp"
namespace cnstream {
static constexpr const char *gname = "encoder";
TEST(EncoderModule, OpenClose) {
Encoder module(gname);
ModuleParamSet params;
params.clear();
EXPECT_TRUE(module.Open(params));
params["dump_dir"] = GetExePath();
EXPECT_TRUE(module.Open(params));
module.Close();
// module.Process(nullptr);
}
TEST(EncoderModule, Process) {
std::shared_ptr<Module> ptr = std::make_shared<Encoder>(gname);
ModuleParamSet params;
params["dump_dir"] = GetExePath();
EXPECT_TRUE(ptr->Open(params));
// prepare data
int width = 1920;
int height = 1080;
cv::Mat img(height, width, CV_8UC3, cv::Scalar(0, 0, 0));
auto data = cnstream::CNFrameInfo::Create(std::to_string(0));
std::shared_ptr<CNDataFrame> frame(new (std::nothrow) CNDataFrame());
data->SetStreamIndex(0);
frame->frame_id = 1;
data->timestamp = 1000;
frame->width = width;
frame->height = height;
frame->ptr_cpu[0] = img.data;
frame->stride[0] = width;
frame->ctx.dev_type = DevContext::DevType::CPU;
frame->fmt = CN_PIXEL_FORMAT_BGR24;
frame->CopyToSyncMem();
data->datas[CNDataFramePtrKey] = frame;
EXPECT_EQ(ptr->Process(data), 0);
ptr->Close();
params["dump_type"] = "image";
EXPECT_TRUE(ptr->Open(params));
EXPECT_EQ(ptr->Process(data), 0);
ptr->Close();
}
TEST(EncoderModule, CheckParamSet) {
Encoder module(gname);
ModuleParamSet params;
params["dump_dir"] = GetExePath();
params["dump_type"] = "image";
EXPECT_TRUE(module.CheckParamSet(params));
params["fake_key"] = "fake_value";
EXPECT_TRUE(module.CheckParamSet(params));
}
} // namespace cnstream
| 31.247312 | 80 | 0.676875 | [
"vector"
] |
6f5a50c9ed6bc855e0fa5b10b00eae718e161650 | 77,319 | cc | C++ | lib/deckard/src/ptgen/gcc/lex.yy.cc | mir597/ml_safe | e0da1d9c564b0e8850e75db1d3d976b959bf61cb | [
"BSD-3-Clause"
] | 1 | 2018-03-19T13:57:35.000Z | 2018-03-19T13:57:35.000Z | lib/deckard/src/ptgen/gcc/lex.yy.cc | mir597/ml_safe | e0da1d9c564b0e8850e75db1d3d976b959bf61cb | [
"BSD-3-Clause"
] | null | null | null | lib/deckard/src/ptgen/gcc/lex.yy.cc | mir597/ml_safe | e0da1d9c564b0e8850e75db1d3d976b959bf61cb | [
"BSD-3-Clause"
] | 3 | 2020-10-21T10:50:23.000Z | 2021-12-27T21:34:50.000Z | #line 2 "lex.yy.cc"
#line 4 "lex.yy.cc"
#define YY_INT_ALIGNED short int
/* A lexical scanner generated by flex */
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 5
#define YY_FLEX_SUBMINOR_VERSION 35
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
/* First, we deal with platform-specific or compiler-specific issues. */
/* begin standard C headers. */
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
/* end standard C headers. */
/* flex integer type definitions */
#ifndef FLEXINT_H
#define FLEXINT_H
/* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
* if you want the limit (max/min) macros for int types.
*/
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS 1
#endif
#include <inttypes.h>
typedef int8_t flex_int8_t;
typedef uint8_t flex_uint8_t;
typedef int16_t flex_int16_t;
typedef uint16_t flex_uint16_t;
typedef int32_t flex_int32_t;
typedef uint32_t flex_uint32_t;
#else
typedef signed char flex_int8_t;
typedef short int flex_int16_t;
typedef int flex_int32_t;
typedef unsigned char flex_uint8_t;
typedef unsigned short int flex_uint16_t;
typedef unsigned int flex_uint32_t;
#endif /* ! C99 */
/* Limits of integral types. */
#ifndef INT8_MIN
#define INT8_MIN (-128)
#endif
#ifndef INT16_MIN
#define INT16_MIN (-32767-1)
#endif
#ifndef INT32_MIN
#define INT32_MIN (-2147483647-1)
#endif
#ifndef INT8_MAX
#define INT8_MAX (127)
#endif
#ifndef INT16_MAX
#define INT16_MAX (32767)
#endif
#ifndef INT32_MAX
#define INT32_MAX (2147483647)
#endif
#ifndef UINT8_MAX
#define UINT8_MAX (255U)
#endif
#ifndef UINT16_MAX
#define UINT16_MAX (65535U)
#endif
#ifndef UINT32_MAX
#define UINT32_MAX (4294967295U)
#endif
#endif /* ! FLEXINT_H */
#ifdef __cplusplus
/* The "const" storage-class-modifier is valid. */
#define YY_USE_CONST
#else /* ! __cplusplus */
/* C99 requires __STDC__ to be defined as 1. */
#if defined (__STDC__)
#define YY_USE_CONST
#endif /* defined (__STDC__) */
#endif /* ! __cplusplus */
#ifdef YY_USE_CONST
#define yyconst const
#else
#define yyconst
#endif
/* Returned upon end-of-file. */
#define YY_NULL 0
/* Promotes a possibly negative, possibly signed char to an unsigned
* integer for use as an array index. If the signed char is negative,
* we want to instead treat it as an 8-bit unsigned char, hence the
* double cast.
*/
#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)
/* Enter a start condition. This macro really ought to take a parameter,
* but we do it the disgusting crufty way forced on us by the ()-less
* definition of BEGIN.
*/
#define BEGIN (yy_start) = 1 + 2 *
/* Translate the current start state into a value that can be later handed
* to BEGIN to return to the state. The YYSTATE alias is for lex
* compatibility.
*/
#define YY_START (((yy_start) - 1) / 2)
#define YYSTATE YY_START
/* Action number for EOF rule of a given start state. */
#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
/* Special action meaning "start processing a new file". */
#define YY_NEW_FILE yyrestart(yyin )
#define YY_END_OF_BUFFER_CHAR 0
/* Size of default input buffer. */
#ifndef YY_BUF_SIZE
#define YY_BUF_SIZE 16384
#endif
/* The state buf must be large enough to hold one state per character in the main buffer.
*/
#define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type))
#ifndef YY_TYPEDEF_YY_BUFFER_STATE
#define YY_TYPEDEF_YY_BUFFER_STATE
typedef struct yy_buffer_state *YY_BUFFER_STATE;
#endif
extern int yyleng;
extern FILE *yyin, *yyout;
#define EOB_ACT_CONTINUE_SCAN 0
#define EOB_ACT_END_OF_FILE 1
#define EOB_ACT_LAST_MATCH 2
#define YY_LESS_LINENO(n)
/* Return all but the first "n" matched characters back to the input stream. */
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
*yy_cp = (yy_hold_char); \
YY_RESTORE_YY_MORE_OFFSET \
(yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
YY_DO_BEFORE_ACTION; /* set up yytext again */ \
} \
while ( 0 )
#define unput(c) yyunput( c, (yytext_ptr) )
#ifndef YY_TYPEDEF_YY_SIZE_T
#define YY_TYPEDEF_YY_SIZE_T
typedef size_t yy_size_t;
#endif
#ifndef YY_STRUCT_YY_BUFFER_STATE
#define YY_STRUCT_YY_BUFFER_STATE
struct yy_buffer_state
{
FILE *yy_input_file;
char *yy_ch_buf; /* input buffer */
char *yy_buf_pos; /* current position in input buffer */
/* Size of input buffer in bytes, not including room for EOB
* characters.
*/
yy_size_t yy_buf_size;
/* Number of characters read into yy_ch_buf, not including EOB
* characters.
*/
int yy_n_chars;
/* Whether we "own" the buffer - i.e., we know we created it,
* and can realloc() it to grow it, and should free() it to
* delete it.
*/
int yy_is_our_buffer;
/* Whether this is an "interactive" input source; if so, and
* if we're using stdio for input, then we want to use getc()
* instead of fread(), to make sure we stop fetching input after
* each newline.
*/
int yy_is_interactive;
/* Whether we're considered to be at the beginning of a line.
* If so, '^' rules will be active on the next match, otherwise
* not.
*/
int yy_at_bol;
int yy_bs_lineno; /**< The line count. */
int yy_bs_column; /**< The column count. */
/* Whether to try to fill the input buffer when we reach the
* end of it.
*/
int yy_fill_buffer;
int yy_buffer_status;
#define YY_BUFFER_NEW 0
#define YY_BUFFER_NORMAL 1
/* When an EOF's been seen but there's still some text to process
* then we mark the buffer as YY_EOF_PENDING, to indicate that we
* shouldn't try reading from the input source any more. We might
* still have a bunch of tokens to match, though, because of
* possible backing-up.
*
* When we actually see the EOF, we change the status to "new"
* (via yyrestart()), so that the user can continue scanning by
* just pointing yyin at a new input file.
*/
#define YY_BUFFER_EOF_PENDING 2
};
#endif /* !YY_STRUCT_YY_BUFFER_STATE */
/* Stack of input buffers. */
static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */
static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */
static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */
/* We provide macros for accessing buffer states in case in the
* future we want to put the buffer states in a more general
* "scanner state".
*
* Returns the top of the stack, or NULL.
*/
#define YY_CURRENT_BUFFER ( (yy_buffer_stack) \
? (yy_buffer_stack)[(yy_buffer_stack_top)] \
: NULL)
/* Same as previous macro, but useful when we know that the buffer stack is not
* NULL or when we need an lvalue. For internal use only.
*/
#define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)]
/* yy_hold_char holds the character lost when yytext is formed. */
static char yy_hold_char;
static int yy_n_chars; /* number of characters read into yy_ch_buf */
int yyleng;
/* Points to current character in buffer. */
static char *yy_c_buf_p = (char *) 0;
static int yy_init = 0; /* whether we need to initialize */
static int yy_start = 0; /* start state number */
/* Flag which is used to allow yywrap()'s to do buffer switches
* instead of setting up a fresh yyin. A bit of a hack ...
*/
static int yy_did_buffer_switch_on_eof;
void yyrestart (FILE *input_file );
void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer );
YY_BUFFER_STATE yy_create_buffer (FILE *file,int size );
void yy_delete_buffer (YY_BUFFER_STATE b );
void yy_flush_buffer (YY_BUFFER_STATE b );
void yypush_buffer_state (YY_BUFFER_STATE new_buffer );
void yypop_buffer_state (void );
static void yyensure_buffer_stack (void );
static void yy_load_buffer_state (void );
static void yy_init_buffer (YY_BUFFER_STATE b,FILE *file );
#define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER )
YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size );
YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str );
YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,int len );
void *yyalloc (yy_size_t );
void *yyrealloc (void *,yy_size_t );
void yyfree (void * );
#define yy_new_buffer yy_create_buffer
#define yy_set_interactive(is_interactive) \
{ \
if ( ! YY_CURRENT_BUFFER ){ \
yyensure_buffer_stack (); \
YY_CURRENT_BUFFER_LVALUE = \
yy_create_buffer(yyin,YY_BUF_SIZE ); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
}
#define yy_set_bol(at_bol) \
{ \
if ( ! YY_CURRENT_BUFFER ){\
yyensure_buffer_stack (); \
YY_CURRENT_BUFFER_LVALUE = \
yy_create_buffer(yyin,YY_BUF_SIZE ); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
}
#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
/* Begin user sect3 */
typedef unsigned char YY_CHAR;
FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0;
typedef int yy_state_type;
extern int yylineno;
int yylineno = 1;
extern char *yytext;
#define yytext_ptr yytext
static yy_state_type yy_get_previous_state (void );
static yy_state_type yy_try_NUL_trans (yy_state_type current_state );
static int yy_get_next_buffer (void );
static void yy_fatal_error (yyconst char msg[] );
/* Done after the current pattern has been matched and before the
* corresponding action - sets up yytext.
*/
#define YY_DO_BEFORE_ACTION \
(yytext_ptr) = yy_bp; \
yyleng = (size_t) (yy_cp - yy_bp); \
(yy_hold_char) = *yy_cp; \
*yy_cp = '\0'; \
(yy_c_buf_p) = yy_cp;
#define YY_NUM_RULES 76
#define YY_END_OF_BUFFER 77
/* This struct is not used in this scanner,
but its presence is necessary. */
struct yy_trans_info
{
flex_int32_t yy_verify;
flex_int32_t yy_nxt;
};
static yyconst flex_int16_t yy_accept[426] =
{ 0,
0, 0, 0, 0, 77, 75, 74, 74, 63, 75,
69, 62, 75, 56, 57, 67, 66, 54, 65, 61,
68, 34, 34, 60, 51, 70, 55, 70, 73, 31,
31, 58, 59, 71, 31, 31, 31, 31, 31, 31,
31, 31, 31, 31, 31, 31, 31, 31, 31, 31,
52, 72, 53, 64, 3, 76, 50, 0, 39, 0,
41, 53, 47, 0, 0, 44, 45, 46, 0, 37,
1, 2, 38, 33, 0, 34, 0, 34, 59, 52,
58, 43, 49, 42, 31, 31, 0, 0, 31, 31,
31, 31, 31, 31, 31, 31, 31, 8, 31, 31,
31, 31, 31, 31, 14, 31, 31, 31, 31, 31,
31, 31, 31, 31, 31, 31, 48, 35, 40, 0,
37, 37, 0, 38, 33, 0, 36, 32, 29, 31,
31, 31, 31, 31, 31, 31, 31, 31, 31, 31,
31, 31, 29, 31, 31, 31, 31, 24, 31, 31,
31, 31, 31, 31, 31, 31, 31, 31, 31, 31,
12, 31, 31, 21, 31, 31, 31, 31, 31, 31,
31, 31, 31, 31, 31, 31, 31, 31, 31, 31,
0, 37, 0, 37, 0, 38, 36, 32, 31, 31,
31, 31, 31, 31, 31, 31, 31, 31, 31, 31,
31, 31, 31, 31, 31, 31, 31, 31, 31, 31,
31, 31, 31, 11, 31, 5, 31, 31, 31, 31,
9, 10, 31, 31, 13, 31, 31, 31, 31, 31,
31, 31, 31, 31, 31, 31, 31, 31, 31, 31,
0, 37, 31, 31, 31, 24, 31, 31, 31, 31,
31, 31, 31, 31, 31, 31, 31, 31, 31, 31,
31, 31, 31, 31, 31, 31, 31, 31, 31, 31,
4, 22, 31, 31, 31, 31, 31, 31, 31, 31,
31, 31, 31, 31, 31, 31, 31, 20, 31, 31,
23, 31, 31, 31, 31, 31, 31, 31, 31, 31,
31, 31, 30, 31, 31, 30, 31, 31, 31, 31,
31, 31, 31, 31, 31, 31, 31, 31, 31, 31,
31, 31, 31, 15, 16, 17, 18, 19, 31, 25,
31, 31, 31, 31, 31, 24, 31, 22, 31, 31,
31, 31, 31, 31, 31, 31, 31, 31, 31, 31,
31, 31, 31, 31, 31, 31, 31, 7, 31, 31,
31, 31, 31, 31, 31, 31, 31, 31, 31, 31,
31, 31, 31, 31, 11, 31, 31, 31, 31, 25,
31, 6, 31, 26, 31, 31, 22, 31, 31, 31,
31, 31, 31, 31, 31, 30, 31, 31, 31, 31,
31, 11, 22, 25, 22, 26, 31, 27, 31, 31,
31, 31, 31, 31, 31, 31, 27, 31, 28, 31,
31, 31, 31, 31, 0
} ;
static yyconst flex_int32_t yy_ec[256] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 2, 3,
2, 1, 2, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 2, 4, 5, 6, 1, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 19,
19, 19, 19, 19, 19, 19, 19, 20, 21, 22,
23, 24, 25, 1, 26, 26, 26, 26, 27, 28,
29, 29, 30, 29, 29, 31, 29, 32, 29, 29,
29, 29, 29, 29, 33, 29, 29, 34, 29, 29,
35, 36, 37, 38, 39, 1, 40, 41, 42, 43,
44, 45, 46, 47, 48, 29, 49, 50, 51, 52,
53, 54, 29, 55, 56, 57, 58, 59, 60, 61,
62, 63, 64, 65, 66, 67, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1
} ;
static yyconst flex_int32_t yy_meta[68] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 2, 1,
1, 1, 1, 1, 1, 1, 1, 3, 3, 1,
1, 1, 1, 1, 1, 3, 3, 3, 4, 4,
4, 4, 4, 4, 1, 1, 1, 1, 4, 3,
3, 3, 3, 3, 3, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 1, 1, 1, 1
} ;
static yyconst flex_int16_t yy_base[431] =
{ 0,
0, 947, 0, 0, 952, 954, 954, 954, 928, 63,
46, 63, 914, 954, 954, 926, 59, 954, 60, 58,
68, 84, 77, 924, 954, 100, 924, 55, 954, 907,
85, 954, 954, 922, 905, 58, 34, 66, 86, 94,
59, 87, 98, 99, 92, 109, 102, 49, 108, 112,
954, 106, 954, 954, 954, 954, 954, 127, 954, 940,
954, 954, 954, 140, 151, 954, 954, 954, 926, 154,
954, 954, 156, 161, 178, 176, 0, 194, 954, 954,
954, 918, 954, 917, 900, 129, 153, 902, 235, 114,
151, 163, 123, 139, 175, 178, 179, 164, 181, 184,
189, 190, 192, 193, 898, 201, 196, 260, 202, 210,
263, 197, 218, 265, 261, 262, 954, 954, 954, 307,
954, 296, 315, 954, 298, 241, 319, 312, 897, 273,
303, 312, 300, 293, 296, 319, 313, 322, 324, 268,
334, 335, 337, 340, 341, 342, 343, 896, 344, 42,
231, 346, 348, 349, 361, 354, 363, 359, 365, 372,
895, 369, 375, 894, 374, 376, 377, 297, 378, 379,
382, 380, 386, 388, 391, 389, 390, 393, 400, 402,
428, 430, 438, 954, 436, 441, 954, 431, 432, 426,
428, 427, 411, 431, 434, 440, 445, 443, 456, 446,
448, 466, 449, 462, 451, 470, 457, 472, 474, 475,
477, 481, 476, 893, 479, 892, 483, 485, 484, 486,
891, 890, 490, 492, 889, 495, 496, 498, 499, 500,
502, 505, 511, 509, 521, 522, 504, 516, 525, 527,
549, 555, 539, 531, 537, 888, 533, 541, 545, 546,
548, 542, 551, 552, 559, 563, 564, 565, 568, 567,
570, 571, 575, 576, 582, 573, 584, 585, 588, 592,
887, 886, 593, 594, 596, 597, 599, 595, 602, 603,
614, 194, 609, 607, 615, 617, 620, 885, 619, 621,
884, 631, 627, 629, 628, 634, 635, 636, 637, 639,
638, 641, 879, 642, 647, 645, 648, 651, 657, 656,
664, 665, 666, 667, 672, 670, 675, 668, 676, 678,
681, 683, 687, 868, 867, 866, 865, 864, 679, 863,
689, 691, 704, 693, 695, 696, 701, 862, 706, 708,
709, 710, 711, 705, 723, 713, 716, 725, 726, 727,
728, 729, 730, 731, 732, 734, 738, 861, 739, 740,
747, 748, 859, 750, 752, 749, 757, 759, 760, 761,
763, 764, 765, 766, 858, 769, 767, 771, 770, 857,
772, 831, 776, 698, 779, 787, 788, 789, 790, 791,
793, 796, 795, 797, 803, 800, 801, 802, 812, 816,
810, 814, 574, 820, 438, 822, 824, 404, 825, 350,
826, 827, 828, 830, 834, 837, 835, 839, 836, 842,
850, 843, 269, 851, 954, 908, 912, 916, 918, 167
} ;
static yyconst flex_int16_t yy_def[431] =
{ 0,
425, 1, 426, 426, 425, 425, 425, 425, 425, 427,
425, 425, 428, 425, 425, 425, 425, 425, 425, 425,
425, 425, 425, 425, 425, 425, 425, 425, 425, 429,
429, 425, 425, 425, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
425, 425, 425, 425, 425, 425, 425, 427, 425, 427,
425, 425, 425, 428, 428, 425, 425, 425, 425, 425,
425, 425, 425, 425, 425, 425, 430, 425, 425, 425,
425, 425, 425, 425, 429, 429, 427, 428, 425, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 425, 425, 425, 425,
425, 425, 425, 425, 425, 425, 425, 430, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
425, 425, 425, 425, 425, 425, 425, 425, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
425, 425, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 429, 429, 429, 429, 429, 429,
429, 429, 429, 429, 0, 425, 425, 425, 425, 425
} ;
static yyconst flex_int16_t yy_nxt[1022] =
{ 0,
6, 7, 8, 9, 10, 6, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 30, 30, 30, 30,
31, 30, 30, 30, 32, 6, 33, 34, 35, 36,
37, 38, 39, 40, 41, 42, 30, 43, 30, 44,
30, 30, 30, 30, 45, 46, 47, 48, 49, 50,
30, 30, 30, 51, 52, 53, 54, 59, 61, 62,
63, 66, 86, 69, 67, 70, 70, 83, 84, 71,
86, 61, 61, 68, 72, 61, 92, 86, 93, 87,
61, 164, 73, 88, 78, 78, 86, 86, 60, 73,
114, 74, 74, 75, 86, 94, 80, 76, 102, 76,
75, 103, 95, 90, 76, 91, 76, 77, 96, 81,
75, 82, 83, 86, 86, 86, 76, 75, 61, 97,
86, 59, 86, 76, 76, 108, 86, 86, 98, 104,
86, 76, 105, 99, 77, 100, 86, 86, 118, 106,
86, 107, 86, 425, 101, 109, 110, 59, 116, 64,
115, 86, 60, 113, 148, 111, 151, 86, 112, 128,
117, 70, 70, 122, 122, 65, 73, 86, 74, 74,
120, 121, 123, 124, 121, 129, 124, 75, 60, 86,
126, 125, 126, 125, 152, 127, 127, 120, 121, 123,
124, 86, 86, 121, 75, 124, 76, 149, 76, 73,
125, 78, 78, 86, 153, 150, 86, 86, 125, 86,
75, 156, 86, 155, 76, 76, 76, 86, 86, 154,
86, 86, 86, 76, 86, 86, 157, 75, 325, 86,
86, 158, 160, 76, 174, 159, 161, 165, 86, 162,
163, 76, 85, 85, 169, 170, 86, 164, 127, 127,
85, 85, 85, 85, 130, 85, 85, 85, 85, 86,
215, 175, 171, 86, 131, 85, 132, 133, 134, 135,
85, 85, 136, 137, 138, 139, 85, 85, 140, 141,
142, 143, 144, 145, 146, 147, 85, 85, 86, 86,
86, 86, 172, 86, 189, 166, 86, 424, 178, 180,
179, 86, 176, 122, 122, 167, 168, 173, 204, 181,
177, 181, 183, 184, 182, 182, 184, 185, 125, 185,
125, 86, 186, 186, 86, 86, 127, 127, 86, 183,
184, 86, 188, 196, 188, 184, 187, 125, 198, 187,
86, 86, 190, 197, 229, 125, 191, 86, 192, 193,
86, 188, 86, 187, 194, 195, 201, 203, 187, 188,
199, 200, 86, 86, 202, 86, 206, 205, 86, 86,
86, 86, 86, 207, 86, 212, 86, 86, 415, 216,
213, 209, 86, 211, 220, 210, 214, 86, 208, 86,
219, 86, 164, 86, 217, 218, 221, 86, 223, 222,
86, 224, 86, 86, 86, 86, 86, 86, 86, 164,
86, 225, 226, 227, 86, 232, 86, 86, 86, 86,
231, 86, 230, 228, 236, 164, 233, 238, 86, 239,
86, 237, 414, 234, 235, 182, 182, 182, 182, 86,
241, 240, 241, 186, 186, 242, 242, 121, 186, 186,
121, 188, 243, 188, 86, 86, 86, 247, 124, 86,
86, 124, 86, 244, 121, 245, 412, 246, 86, 121,
188, 86, 248, 86, 86, 124, 86, 86, 188, 86,
124, 249, 252, 250, 86, 86, 257, 254, 251, 260,
86, 253, 258, 255, 86, 256, 262, 259, 86, 261,
86, 264, 86, 86, 86, 86, 263, 86, 267, 86,
269, 86, 86, 86, 86, 265, 268, 271, 86, 270,
86, 266, 273, 86, 86, 275, 86, 86, 86, 272,
86, 274, 86, 86, 276, 281, 277, 86, 164, 86,
284, 278, 279, 280, 86, 288, 164, 282, 283, 86,
86, 289, 285, 86, 286, 86, 242, 242, 292, 86,
291, 86, 242, 242, 287, 86, 293, 86, 294, 86,
86, 290, 184, 86, 86, 184, 86, 296, 298, 86,
86, 301, 299, 305, 304, 302, 297, 86, 303, 184,
300, 86, 86, 86, 184, 86, 86, 308, 86, 86,
307, 86, 411, 86, 86, 306, 310, 309, 314, 315,
86, 312, 86, 86, 318, 316, 86, 313, 317, 311,
86, 86, 86, 86, 86, 86, 303, 86, 303, 164,
86, 86, 214, 321, 320, 86, 319, 86, 214, 323,
326, 322, 86, 86, 324, 86, 164, 86, 86, 86,
329, 328, 333, 327, 330, 86, 336, 86, 332, 86,
331, 335, 86, 86, 86, 86, 86, 86, 334, 86,
86, 337, 341, 86, 129, 86, 86, 345, 340, 86,
303, 338, 343, 344, 86, 86, 339, 347, 342, 346,
348, 303, 86, 86, 86, 86, 86, 349, 86, 303,
86, 352, 350, 86, 86, 356, 86, 86, 354, 86,
351, 86, 353, 214, 355, 86, 359, 86, 360, 86,
363, 86, 361, 86, 86, 357, 397, 358, 365, 86,
362, 366, 86, 86, 86, 364, 86, 86, 86, 86,
370, 86, 129, 368, 86, 369, 375, 371, 372, 376,
373, 86, 374, 86, 86, 86, 86, 86, 86, 86,
86, 214, 86, 303, 380, 379, 86, 86, 86, 381,
378, 382, 377, 303, 303, 86, 86, 86, 86, 164,
86, 272, 385, 214, 384, 387, 272, 86, 86, 86,
388, 86, 86, 86, 86, 86, 386, 86, 86, 86,
86, 393, 389, 129, 396, 303, 303, 86, 392, 303,
303, 395, 390, 303, 303, 86, 86, 86, 86, 86,
303, 402, 129, 86, 86, 404, 398, 303, 86, 406,
86, 86, 401, 399, 129, 400, 405, 407, 86, 129,
86, 403, 86, 129, 86, 408, 129, 129, 86, 409,
86, 410, 86, 86, 387, 387, 86, 303, 417, 86,
129, 413, 419, 86, 86, 86, 129, 86, 129, 416,
86, 86, 129, 129, 420, 423, 129, 418, 86, 396,
129, 129, 129, 422, 421, 394, 391, 383, 303, 86,
367, 86, 86, 86, 86, 86, 86, 129, 56, 56,
56, 56, 58, 58, 58, 58, 64, 86, 64, 64,
85, 85, 86, 86, 86, 86, 295, 86, 86, 86,
86, 86, 86, 86, 86, 86, 86, 65, 86, 61,
61, 119, 425, 89, 61, 86, 57, 79, 61, 65,
57, 425, 55, 5, 425, 425, 425, 425, 425, 425,
425, 425, 425, 425, 425, 425, 425, 425, 425, 425,
425, 425, 425, 425, 425, 425, 425, 425, 425, 425,
425, 425, 425, 425, 425, 425, 425, 425, 425, 425,
425, 425, 425, 425, 425, 425, 425, 425, 425, 425,
425, 425, 425, 425, 425, 425, 425, 425, 425, 425,
425, 425, 425, 425, 425, 425, 425, 425, 425, 425,
425
} ;
static yyconst flex_int16_t yy_chk[1022] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 10, 11, 11,
12, 17, 37, 20, 19, 20, 20, 28, 28, 21,
150, 17, 19, 19, 21, 12, 37, 48, 37, 31,
21, 150, 23, 31, 23, 23, 36, 41, 10, 22,
48, 22, 22, 23, 38, 38, 26, 23, 41, 23,
22, 41, 38, 36, 22, 36, 22, 22, 38, 26,
23, 26, 26, 31, 39, 42, 23, 22, 52, 39,
45, 58, 40, 22, 23, 45, 43, 44, 39, 42,
47, 22, 43, 40, 22, 40, 49, 46, 64, 43,
50, 44, 90, 65, 40, 46, 46, 87, 50, 65,
49, 93, 58, 47, 90, 46, 93, 86, 46, 430,
52, 70, 70, 73, 73, 64, 74, 94, 74, 74,
70, 70, 73, 73, 70, 86, 73, 74, 87, 91,
75, 74, 75, 74, 94, 75, 75, 70, 70, 73,
73, 92, 98, 70, 74, 73, 76, 91, 76, 78,
74, 78, 78, 95, 95, 92, 96, 97, 74, 99,
78, 98, 100, 97, 78, 76, 78, 101, 102, 96,
103, 104, 282, 76, 107, 112, 99, 78, 282, 106,
109, 100, 102, 78, 112, 101, 103, 107, 110, 104,
106, 78, 89, 89, 109, 110, 113, 106, 126, 126,
89, 89, 89, 89, 89, 89, 89, 89, 89, 151,
151, 113, 110, 89, 89, 89, 89, 89, 89, 89,
89, 89, 89, 89, 89, 89, 89, 89, 89, 89,
89, 89, 89, 89, 89, 89, 89, 89, 108, 115,
116, 111, 111, 114, 130, 108, 140, 423, 115, 116,
115, 130, 114, 122, 122, 108, 108, 111, 140, 120,
114, 120, 122, 122, 120, 120, 122, 123, 125, 123,
125, 134, 123, 123, 135, 168, 127, 127, 133, 122,
122, 131, 128, 133, 128, 122, 127, 125, 135, 127,
132, 137, 131, 134, 168, 125, 131, 136, 131, 131,
138, 128, 139, 127, 132, 132, 137, 139, 127, 128,
136, 136, 141, 142, 138, 143, 142, 141, 144, 145,
146, 147, 149, 143, 152, 146, 153, 154, 410, 152,
147, 144, 156, 145, 156, 144, 149, 158, 143, 155,
155, 157, 153, 159, 154, 154, 157, 162, 159, 158,
160, 160, 165, 163, 166, 167, 169, 170, 172, 165,
171, 162, 163, 166, 173, 171, 174, 176, 177, 175,
170, 178, 169, 167, 175, 178, 172, 177, 179, 179,
180, 176, 408, 173, 174, 181, 181, 182, 182, 193,
183, 180, 183, 185, 185, 183, 183, 182, 186, 186,
182, 188, 189, 188, 190, 192, 191, 193, 186, 194,
189, 186, 195, 190, 182, 191, 405, 192, 196, 182,
188, 198, 194, 197, 200, 186, 201, 203, 188, 205,
186, 195, 197, 196, 199, 207, 200, 198, 196, 203,
204, 197, 201, 199, 202, 199, 205, 202, 206, 204,
208, 207, 209, 210, 213, 211, 206, 215, 210, 212,
212, 217, 219, 218, 220, 208, 211, 215, 223, 213,
224, 209, 218, 226, 227, 220, 228, 229, 230, 217,
231, 219, 237, 232, 223, 231, 226, 234, 224, 233,
234, 227, 228, 229, 238, 237, 230, 232, 233, 235,
236, 238, 235, 239, 236, 240, 241, 241, 243, 244,
240, 247, 242, 242, 236, 245, 244, 243, 245, 248,
252, 239, 242, 249, 250, 242, 251, 247, 249, 253,
254, 251, 249, 254, 253, 251, 248, 255, 252, 242,
250, 256, 257, 258, 242, 260, 259, 257, 261, 262,
256, 266, 403, 263, 264, 255, 259, 258, 263, 264,
265, 261, 267, 268, 268, 265, 269, 262, 266, 260,
270, 273, 274, 278, 275, 276, 269, 277, 267, 275,
279, 280, 277, 274, 273, 284, 270, 283, 276, 279,
283, 278, 281, 285, 280, 286, 281, 289, 287, 290,
286, 285, 292, 284, 287, 293, 295, 294, 290, 292,
289, 294, 296, 297, 298, 299, 301, 300, 293, 302,
304, 296, 300, 306, 295, 305, 307, 306, 299, 308,
305, 297, 302, 304, 310, 309, 298, 309, 301, 307,
310, 308, 311, 312, 313, 314, 318, 311, 316, 314,
315, 315, 312, 317, 319, 319, 320, 329, 317, 321,
313, 322, 316, 329, 318, 323, 322, 331, 323, 332,
333, 334, 331, 335, 336, 320, 384, 321, 335, 337,
332, 337, 333, 344, 339, 334, 340, 341, 342, 343,
341, 346, 336, 339, 347, 340, 346, 342, 343, 347,
344, 345, 345, 348, 349, 350, 351, 352, 353, 354,
355, 352, 356, 354, 353, 351, 357, 359, 360, 355,
349, 357, 348, 350, 356, 361, 362, 366, 364, 361,
365, 362, 365, 359, 364, 367, 360, 368, 369, 370,
370, 371, 372, 373, 374, 377, 366, 376, 379, 378,
381, 379, 373, 367, 383, 368, 369, 385, 377, 371,
372, 381, 374, 378, 376, 386, 387, 388, 389, 390,
390, 391, 383, 393, 392, 394, 385, 392, 396, 397,
398, 395, 389, 386, 387, 388, 395, 398, 401, 391,
399, 393, 402, 394, 400, 399, 396, 397, 404, 400,
406, 401, 407, 409, 411, 412, 413, 409, 414, 382,
402, 407, 415, 417, 419, 416, 404, 418, 406, 413,
420, 422, 411, 412, 416, 422, 414, 414, 421, 424,
415, 417, 419, 421, 418, 380, 375, 363, 420, 358,
338, 330, 328, 327, 326, 325, 324, 424, 426, 426,
426, 426, 427, 427, 427, 427, 428, 303, 428, 428,
429, 429, 291, 288, 272, 271, 246, 225, 222, 221,
216, 214, 164, 161, 148, 129, 105, 88, 85, 84,
82, 69, 60, 35, 34, 30, 27, 24, 16, 13,
9, 5, 2, 425, 425, 425, 425, 425, 425, 425,
425, 425, 425, 425, 425, 425, 425, 425, 425, 425,
425, 425, 425, 425, 425, 425, 425, 425, 425, 425,
425, 425, 425, 425, 425, 425, 425, 425, 425, 425,
425, 425, 425, 425, 425, 425, 425, 425, 425, 425,
425, 425, 425, 425, 425, 425, 425, 425, 425, 425,
425, 425, 425, 425, 425, 425, 425, 425, 425, 425,
425
} ;
static yy_state_type yy_last_accepting_state;
static char *yy_last_accepting_cpos;
extern int yy_flex_debug;
int yy_flex_debug = 0;
/* The intent behind this definition is that it'll catch
* any uses of REJECT which flex missed.
*/
#define REJECT reject_used_but_not_detected
#define yymore() yymore_used_but_not_detected
#define YY_MORE_ADJ 0
#define YY_RESTORE_YY_MORE_OFFSET
char *yytext;
#line 1 "c.l"
#line 9 "c.l"
#include <stdio.h>
#include <ptree.h>
#include "pt_c.tab.hh"
#include <map>
#include <string>
using namespace std;
extern map<string,int> name2id;
void count();
void comment();
void cpp_comment();
void macro();
// The global variables are not good for reentrance.
// But for now, the wrong line number doesn't hurt our bug finding because
// we rely on terminal IDs instead of line numbers.
int column = 0;
int line = 1;
#define YY_DECL int yylex(YYSTYPE *yylvalp)
#line 841 "lex.yy.cc"
#define INITIAL 0
#define COMMENT 1
#ifndef YY_NO_UNISTD_H
/* Special case for "unistd.h", since it is non-ANSI. We include it way
* down here because we want the user's section 1 to have been scanned first.
* The user has a chance to override it with an option.
*/
#include <unistd.h>
#endif
#ifndef YY_EXTRA_TYPE
#define YY_EXTRA_TYPE void *
#endif
static int yy_init_globals (void );
/* Accessor methods to globals.
These are made visible to non-reentrant scanners for convenience. */
int yylex_destroy (void );
int yyget_debug (void );
void yyset_debug (int debug_flag );
YY_EXTRA_TYPE yyget_extra (void );
void yyset_extra (YY_EXTRA_TYPE user_defined );
FILE *yyget_in (void );
void yyset_in (FILE * in_str );
FILE *yyget_out (void );
void yyset_out (FILE * out_str );
int yyget_leng (void );
char *yyget_text (void );
int yyget_lineno (void );
void yyset_lineno (int line_number );
/* Macros after this point can all be overridden by user definitions in
* section 1.
*/
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
extern "C" int yywrap (void );
#else
extern int yywrap (void );
#endif
#endif
static void yyunput (int c,char *buf_ptr );
#ifndef yytext_ptr
static void yy_flex_strncpy (char *,yyconst char *,int );
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * );
#endif
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (void );
#else
static int input (void );
#endif
#endif
/* Amount of stuff to slurp up with each read. */
#ifndef YY_READ_BUF_SIZE
#define YY_READ_BUF_SIZE 8192
#endif
/* Copy whatever the last rule matched to the standard output. */
#ifndef ECHO
/* This used to be an fputs(), but since the string might contain NUL's,
* we now use fwrite().
*/
#define ECHO fwrite( yytext, yyleng, 1, yyout )
#endif
/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL,
* is returned in "result".
*/
#ifndef YY_INPUT
#define YY_INPUT(buf,result,max_size) \
if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
{ \
int c = '*'; \
yy_size_t n; \
for ( n = 0; n < max_size && \
(c = getc( yyin )) != EOF && c != '\n'; ++n ) \
buf[n] = (char) c; \
if ( c == '\n' ) \
buf[n++] = (char) c; \
if ( c == EOF && ferror( yyin ) ) \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
result = n; \
} \
else \
{ \
errno=0; \
while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
{ \
if( errno != EINTR) \
{ \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
break; \
} \
errno=0; \
clearerr(yyin); \
} \
}\
\
#endif
/* No semi-colon after return; correct usage is to write "yyterminate();" -
* we don't want an extra ';' after the "return" because that will cause
* some compilers to complain about unreachable statements.
*/
#ifndef yyterminate
#define yyterminate() return YY_NULL
#endif
/* Number of entries by which start-condition stack grows. */
#ifndef YY_START_STACK_INCR
#define YY_START_STACK_INCR 25
#endif
/* Report a fatal error. */
#ifndef YY_FATAL_ERROR
#define YY_FATAL_ERROR(msg) yy_fatal_error( msg )
#endif
/* end tables serialization structures and prototypes */
/* Default declaration of generated scanner - a define so the user can
* easily add parameters.
*/
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
extern int yylex (void);
#define YY_DECL int yylex (void)
#endif /* !YY_DECL */
/* Code executed at the beginning of each rule, after yytext and yyleng
* have been set up.
*/
#ifndef YY_USER_ACTION
#define YY_USER_ACTION
#endif
/* Code executed at the end of each rule. */
#ifndef YY_BREAK
#define YY_BREAK break;
#endif
#define YY_RULE_SETUP \
if ( yyleng > 0 ) \
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = \
(yytext[yyleng - 1] == '\n'); \
YY_USER_ACTION
/** The main scanner function which does all the work.
*/
YY_DECL
{
register yy_state_type yy_current_state;
register char *yy_cp, *yy_bp;
register int yy_act;
#line 34 "c.l"
#line 1030 "lex.yy.cc"
if ( !(yy_init) )
{
(yy_init) = 1;
#ifdef YY_USER_INIT
YY_USER_INIT;
#endif
if ( ! (yy_start) )
(yy_start) = 1; /* first start state */
if ( ! yyin )
yyin = stdin;
if ( ! yyout )
yyout = stdout;
if ( ! YY_CURRENT_BUFFER ) {
yyensure_buffer_stack ();
YY_CURRENT_BUFFER_LVALUE =
yy_create_buffer(yyin,YY_BUF_SIZE );
}
yy_load_buffer_state( );
}
while ( 1 ) /* loops until end-of-file is reached */
{
yy_cp = (yy_c_buf_p);
/* Support of yytext. */
*yy_cp = (yy_hold_char);
/* yy_bp points to the position in yy_ch_buf of the start of
* the current run.
*/
yy_bp = yy_cp;
yy_current_state = (yy_start);
yy_current_state += YY_AT_BOL();
yy_match:
do
{
register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)];
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 426 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
++yy_cp;
}
while ( yy_base[yy_current_state] != 954 );
yy_find_action:
yy_act = yy_accept[yy_current_state];
if ( yy_act == 0 )
{ /* have to back up */
yy_cp = (yy_last_accepting_cpos);
yy_current_state = (yy_last_accepting_state);
yy_act = yy_accept[yy_current_state];
}
YY_DO_BEFORE_ACTION;
do_action: /* This label is used only to access EOF actions. */
switch ( yy_act )
{ /* beginning of action switch */
case 0: /* must back up */
/* undo the effects of YY_DO_BEFORE_ACTION */
*yy_cp = (yy_hold_char);
yy_cp = (yy_last_accepting_cpos);
yy_current_state = (yy_last_accepting_state);
goto yy_find_action;
case 1:
YY_RULE_SETUP
#line 36 "c.l"
{ count(); comment();}
YY_BREAK
case 2:
YY_RULE_SETUP
#line 37 "c.l"
{ count(); cpp_comment(); }
YY_BREAK
case 3:
YY_RULE_SETUP
#line 38 "c.l"
{count(); macro();}
YY_BREAK
case 4:
YY_RULE_SETUP
#line 40 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["BREAK"],yytext,line);
return(BREAK); }
YY_BREAK
case 5:
YY_RULE_SETUP
#line 44 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["CASE"],yytext,line);
return(CASE); }
YY_BREAK
case 6:
YY_RULE_SETUP
#line 48 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["CONTINUE"],yytext,line);
return(CONTINUE); }
YY_BREAK
case 7:
YY_RULE_SETUP
#line 52 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["DEFAULT"],yytext,line);
return(DEFAULT); }
YY_BREAK
case 8:
YY_RULE_SETUP
#line 56 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["DO"],yytext,line);
return(DO); }
YY_BREAK
case 9:
YY_RULE_SETUP
#line 60 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["ELSE"],yytext,line);
return(ELSE); }
YY_BREAK
case 10:
YY_RULE_SETUP
#line 64 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["ENUM"],yytext,line);
return(ENUM); }
YY_BREAK
case 11:
YY_RULE_SETUP
#line 68 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["SCSPEC"],yytext,line);
return(SCSPEC); }
YY_BREAK
case 12:
YY_RULE_SETUP
#line 72 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["FOR"],yytext,line);
return(FOR); }
YY_BREAK
case 13:
YY_RULE_SETUP
#line 76 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["GOTO"],yytext,line);
return(GOTO); }
YY_BREAK
case 14:
YY_RULE_SETUP
#line 80 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["IF"],yytext,line);
return(IF); }
YY_BREAK
case 15:
YY_RULE_SETUP
#line 84 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["RETURN"],yytext,line);
return(RETURN); }
YY_BREAK
case 16:
YY_RULE_SETUP
#line 88 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["SIZEOF"],yytext,line);
return(SIZEOF); }
YY_BREAK
case 17:
YY_RULE_SETUP
#line 92 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["STATIC"],yytext,line);
return(STATIC); }
YY_BREAK
case 18:
YY_RULE_SETUP
#line 96 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["STRUCT"],yytext,line);
return(STRUCT); }
YY_BREAK
case 19:
YY_RULE_SETUP
#line 100 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["SWITCH"],yytext,line);
return(SWITCH); }
YY_BREAK
case 20:
YY_RULE_SETUP
#line 104 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["UNION"],yytext,line);
return(UNION); }
YY_BREAK
case 21:
YY_RULE_SETUP
#line 108 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["TYPESPEC"],yytext,line);
return(TYPESPEC);
}
YY_BREAK
case 22:
YY_RULE_SETUP
#line 113 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["TYPE_QUAL"],yytext,line);
return(TYPE_QUAL); }
YY_BREAK
case 23:
YY_RULE_SETUP
#line 117 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["WHILE"],yytext,line);
return(WHILE); }
YY_BREAK
case 24:
YY_RULE_SETUP
#line 121 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["ASM_KEYWORD"],yytext,line);
return(ASM_KEYWORD); }
YY_BREAK
case 25:
YY_RULE_SETUP
#line 125 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["TYPEOF"],yytext,line);
return(TYPEOF); }
YY_BREAK
case 26:
YY_RULE_SETUP
#line 130 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["ALIGNOF"],yytext,line);
return(ALIGNOF); }
YY_BREAK
case 27:
YY_RULE_SETUP
#line 135 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["ATTRIBUTE"],yytext,line);
return(ATTRIBUTE); }
YY_BREAK
case 28:
YY_RULE_SETUP
#line 140 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["EXTENSION"],yytext,line);
return(EXTENSION); }
YY_BREAK
case 29:
YY_RULE_SETUP
#line 144 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["TYPENAME"],yytext,line);
return(TYPENAME); }
YY_BREAK
case 30:
YY_RULE_SETUP
#line 148 "c.l"
{count();}
YY_BREAK
case 31:
YY_RULE_SETUP
#line 150 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["IDENTIFIER"],yytext,line);
return(IDENTIFIER); }
YY_BREAK
case 32:
YY_RULE_SETUP
#line 154 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["CONSTANT"],yytext,line);
return(CONSTANT); }
YY_BREAK
case 33:
YY_RULE_SETUP
#line 158 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["CONSTANT"],yytext,line);
return(CONSTANT); }
YY_BREAK
case 34:
YY_RULE_SETUP
#line 162 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["CONSTANT"],yytext,line);
return(CONSTANT); }
YY_BREAK
case 35:
/* rule 35 can match eol */
YY_RULE_SETUP
#line 166 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["CONSTANT"],yytext,line);
return(CONSTANT); }
YY_BREAK
case 36:
YY_RULE_SETUP
#line 171 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["CONSTANT"],yytext,line);
return(CONSTANT); }
YY_BREAK
case 37:
YY_RULE_SETUP
#line 175 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["CONSTANT"],yytext,line);
return(CONSTANT); }
YY_BREAK
case 38:
YY_RULE_SETUP
#line 179 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["CONSTANT"],yytext,line);
return(CONSTANT); }
YY_BREAK
case 39:
/* rule 39 can match eol */
YY_RULE_SETUP
#line 184 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["STRING"],yytext,line);
return(STRING); }
YY_BREAK
case 40:
YY_RULE_SETUP
#line 188 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["ELLIPSIS"],yytext,line);
return(ELLIPSIS); }
YY_BREAK
case 41:
YY_RULE_SETUP
#line 192 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["ASSIGN"],yytext,line);
return(ASSIGN); }
YY_BREAK
case 42:
YY_RULE_SETUP
#line 196 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["RSHIFT"],yytext,line);
return(RSHIFT); }
YY_BREAK
case 43:
YY_RULE_SETUP
#line 200 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["LSHIFT"],yytext,line);
return(LSHIFT); }
YY_BREAK
case 44:
YY_RULE_SETUP
#line 204 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["PLUSPLUS"],yytext,line);
return(PLUSPLUS); }
YY_BREAK
case 45:
YY_RULE_SETUP
#line 208 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["MINUSMINUS"],yytext,line);
return(MINUSMINUS); }
YY_BREAK
case 46:
YY_RULE_SETUP
#line 212 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["POINTSAT"],yytext,line);
return(POINTSAT); }
YY_BREAK
case 47:
YY_RULE_SETUP
#line 216 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["ANDAND"],yytext,line);
return(ANDAND); }
YY_BREAK
case 48:
YY_RULE_SETUP
#line 220 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["OROR"],yytext,line);
return(OROR); }
YY_BREAK
case 49:
YY_RULE_SETUP
#line 224 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["ARITHCOMPARE"],yytext,line);
return(ARITHCOMPARE); }
YY_BREAK
case 50:
YY_RULE_SETUP
#line 228 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["EOCOMPARE"],yytext,line);
return(EQCOMPARE); }
YY_BREAK
case 51:
YY_RULE_SETUP
#line 232 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["';'"],yytext,line);
return(';'); }
YY_BREAK
case 52:
YY_RULE_SETUP
#line 236 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["'{'"],yytext,line);
return('{'); }
YY_BREAK
case 53:
YY_RULE_SETUP
#line 240 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["'}'"],yytext,line);
return('}'); }
YY_BREAK
case 54:
YY_RULE_SETUP
#line 244 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["','"],yytext,line);
return(','); }
YY_BREAK
case 55:
YY_RULE_SETUP
#line 248 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["'='"],yytext,line);
return('='); }
YY_BREAK
case 56:
YY_RULE_SETUP
#line 252 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["'('"],yytext,line);
return('('); }
YY_BREAK
case 57:
YY_RULE_SETUP
#line 256 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["')'"],yytext,line);
return(')'); }
YY_BREAK
case 58:
YY_RULE_SETUP
#line 260 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["'['"],yytext,line);
return('['); }
YY_BREAK
case 59:
YY_RULE_SETUP
#line 264 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["']'"],yytext,line);
return(']'); }
YY_BREAK
case 60:
YY_RULE_SETUP
#line 268 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["':'"],yytext,line);
return(':'); }
YY_BREAK
case 61:
YY_RULE_SETUP
#line 272 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["'.'"],yytext,line);
return('.'); }
YY_BREAK
case 62:
YY_RULE_SETUP
#line 276 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["'&'"],yytext,line);
return('&'); }
YY_BREAK
case 63:
YY_RULE_SETUP
#line 280 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["'!'"],yytext,line);
return('!'); }
YY_BREAK
case 64:
YY_RULE_SETUP
#line 284 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["'~'"],yytext,line);
return('~'); }
YY_BREAK
case 65:
YY_RULE_SETUP
#line 288 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["'-'"],yytext,line);
return('-'); }
YY_BREAK
case 66:
YY_RULE_SETUP
#line 292 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["'+'"],yytext,line);
return('+'); }
YY_BREAK
case 67:
YY_RULE_SETUP
#line 296 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["'*'"],yytext,line);
return('*'); }
YY_BREAK
case 68:
YY_RULE_SETUP
#line 300 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["'/'"],yytext,line);
return('/'); }
YY_BREAK
case 69:
YY_RULE_SETUP
#line 304 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["'%'"],yytext,line);
return('%'); }
YY_BREAK
case 70:
YY_RULE_SETUP
#line 308 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["ARITHCOMPARE"],yytext,line);
return(ARITHCOMPARE); }
YY_BREAK
case 71:
YY_RULE_SETUP
#line 312 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["'^'"],yytext,line);
return('^'); }
YY_BREAK
case 72:
YY_RULE_SETUP
#line 316 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["'|'"],yytext,line);
return('|'); }
YY_BREAK
case 73:
YY_RULE_SETUP
#line 320 "c.l"
{
count();
yylvalp->t = new Terminal(name2id["'?'"],yytext,line);
return('?'); }
YY_BREAK
case 74:
/* rule 74 can match eol */
YY_RULE_SETUP
#line 325 "c.l"
{
count();
}
YY_BREAK
case 75:
YY_RULE_SETUP
#line 328 "c.l"
{count();}
YY_BREAK
case 76:
YY_RULE_SETUP
#line 330 "c.l"
ECHO;
YY_BREAK
#line 1707 "lex.yy.cc"
case YY_STATE_EOF(INITIAL):
case YY_STATE_EOF(COMMENT):
yyterminate();
case YY_END_OF_BUFFER:
{
/* Amount of text matched not including the EOB char. */
int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1;
/* Undo the effects of YY_DO_BEFORE_ACTION. */
*yy_cp = (yy_hold_char);
YY_RESTORE_YY_MORE_OFFSET
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
{
/* We're scanning a new file or input source. It's
* possible that this happened because the user
* just pointed yyin at a new source and called
* yylex(). If so, then we have to assure
* consistency between YY_CURRENT_BUFFER and our
* globals. Here is the right place to do so, because
* this is the first action (other than possibly a
* back-up) that will match for the new input source.
*/
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
}
/* Note that here we test for yy_c_buf_p "<=" to the position
* of the first EOB in the buffer, since yy_c_buf_p will
* already have been incremented past the NUL character
* (since all states make transitions on EOB to the
* end-of-buffer state). Contrast this with the test
* in input().
*/
if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
{ /* This was really a NUL. */
yy_state_type yy_next_state;
(yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( );
/* Okay, we're now positioned to make the NUL
* transition. We couldn't have
* yy_get_previous_state() go ahead and do it
* for us because it doesn't know how to deal
* with the possibility of jamming (and we don't
* want to build jamming into it because then it
* will run more slowly).
*/
yy_next_state = yy_try_NUL_trans( yy_current_state );
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
if ( yy_next_state )
{
/* Consume the NUL. */
yy_cp = ++(yy_c_buf_p);
yy_current_state = yy_next_state;
goto yy_match;
}
else
{
yy_cp = (yy_c_buf_p);
goto yy_find_action;
}
}
else switch ( yy_get_next_buffer( ) )
{
case EOB_ACT_END_OF_FILE:
{
(yy_did_buffer_switch_on_eof) = 0;
if ( yywrap( ) )
{
/* Note: because we've taken care in
* yy_get_next_buffer() to have set up
* yytext, we can now set up
* yy_c_buf_p so that if some total
* hoser (like flex itself) wants to
* call the scanner after we return the
* YY_NULL, it'll still work - another
* YY_NULL will get returned.
*/
(yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ;
yy_act = YY_STATE_EOF(YY_START);
goto do_action;
}
else
{
if ( ! (yy_did_buffer_switch_on_eof) )
YY_NEW_FILE;
}
break;
}
case EOB_ACT_CONTINUE_SCAN:
(yy_c_buf_p) =
(yytext_ptr) + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( );
yy_cp = (yy_c_buf_p);
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
goto yy_match;
case EOB_ACT_LAST_MATCH:
(yy_c_buf_p) =
&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)];
yy_current_state = yy_get_previous_state( );
yy_cp = (yy_c_buf_p);
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
goto yy_find_action;
}
break;
}
default:
YY_FATAL_ERROR(
"fatal flex scanner internal error--no action found" );
} /* end of action switch */
} /* end of scanning one token */
} /* end of yylex */
/* yy_get_next_buffer - try to read in a new buffer
*
* Returns a code representing an action:
* EOB_ACT_LAST_MATCH -
* EOB_ACT_CONTINUE_SCAN - continue scanning from current position
* EOB_ACT_END_OF_FILE - end of file
*/
static int yy_get_next_buffer (void)
{
register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
register char *source = (yytext_ptr);
register int number_to_move, i;
int ret_val;
if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] )
YY_FATAL_ERROR(
"fatal flex scanner internal error--end of buffer missed" );
if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
{ /* Don't try to fill the buffer, so this is an EOF. */
if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 )
{
/* We matched a single character, the EOB, so
* treat this as a final EOF.
*/
return EOB_ACT_END_OF_FILE;
}
else
{
/* We matched some text prior to the EOB, first
* process it.
*/
return EOB_ACT_LAST_MATCH;
}
}
/* Try to read more data. */
/* First move last chars to start of buffer. */
number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr)) - 1;
for ( i = 0; i < number_to_move; ++i )
*(dest++) = *(source++);
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
/* don't do the read, it's not guaranteed to return an EOF,
* just force an EOF
*/
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0;
else
{
int num_to_read =
YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
while ( num_to_read <= 0 )
{ /* Not enough room in the buffer - grow it. */
/* just a shorter name for the current buffer */
YY_BUFFER_STATE b = YY_CURRENT_BUFFER;
int yy_c_buf_p_offset =
(int) ((yy_c_buf_p) - b->yy_ch_buf);
if ( b->yy_is_our_buffer )
{
int new_size = b->yy_buf_size * 2;
if ( new_size <= 0 )
b->yy_buf_size += b->yy_buf_size / 8;
else
b->yy_buf_size *= 2;
b->yy_ch_buf = (char *)
/* Include room in for 2 EOB chars. */
yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 );
}
else
/* Can't grow it, we don't own it. */
b->yy_ch_buf = 0;
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR(
"fatal error - scanner input buffer overflow" );
(yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset];
num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
number_to_move - 1;
}
if ( num_to_read > YY_READ_BUF_SIZE )
num_to_read = YY_READ_BUF_SIZE;
/* Read in more data. */
YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
(yy_n_chars), (size_t) num_to_read );
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
if ( (yy_n_chars) == 0 )
{
if ( number_to_move == YY_MORE_ADJ )
{
ret_val = EOB_ACT_END_OF_FILE;
yyrestart(yyin );
}
else
{
ret_val = EOB_ACT_LAST_MATCH;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
YY_BUFFER_EOF_PENDING;
}
}
else
ret_val = EOB_ACT_CONTINUE_SCAN;
if ((yy_size_t) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
/* Extend the array by 50%, plus the number we really need. */
yy_size_t new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1);
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size );
if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
}
(yy_n_chars) += number_to_move;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR;
(yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
return ret_val;
}
/* yy_get_previous_state - get the state just before the EOB char was reached */
static yy_state_type yy_get_previous_state (void)
{
register yy_state_type yy_current_state;
register char *yy_cp;
yy_current_state = (yy_start);
yy_current_state += YY_AT_BOL();
for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp )
{
register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 426 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
}
return yy_current_state;
}
/* yy_try_NUL_trans - try to make a transition on the NUL character
*
* synopsis
* next_state = yy_try_NUL_trans( current_state );
*/
static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state )
{
register int yy_is_jam;
register char *yy_cp = (yy_c_buf_p);
register YY_CHAR yy_c = 1;
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 426 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
yy_is_jam = (yy_current_state == 425);
return yy_is_jam ? 0 : yy_current_state;
}
static void yyunput (int c, register char * yy_bp )
{
register char *yy_cp;
yy_cp = (yy_c_buf_p);
/* undo effects of setting up yytext */
*yy_cp = (yy_hold_char);
if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
{ /* need to shift things up to make room */
/* +2 for EOB chars. */
register int number_to_move = (yy_n_chars) + 2;
register char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[
YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2];
register char *source =
&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move];
while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
*--dest = *--source;
yy_cp += (int) (dest - source);
yy_bp += (int) (dest - source);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars =
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_buf_size;
if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
YY_FATAL_ERROR( "flex scanner push-back overflow" );
}
*--yy_cp = (char) c;
(yytext_ptr) = yy_bp;
(yy_hold_char) = *yy_cp;
(yy_c_buf_p) = yy_cp;
}
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (void)
#else
static int input (void)
#endif
{
int c;
*(yy_c_buf_p) = (yy_hold_char);
if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR )
{
/* yy_c_buf_p now points to the character we want to return.
* If this occurs *before* the EOB characters, then it's a
* valid NUL; if not, then we've hit the end of the buffer.
*/
if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
/* This was really a NUL. */
*(yy_c_buf_p) = '\0';
else
{ /* need more input */
int offset = (yy_c_buf_p) - (yytext_ptr);
++(yy_c_buf_p);
switch ( yy_get_next_buffer( ) )
{
case EOB_ACT_LAST_MATCH:
/* This happens because yy_g_n_b()
* sees that we've accumulated a
* token and flags that we need to
* try matching the token before
* proceeding. But for input(),
* there's no matching to consider.
* So convert the EOB_ACT_LAST_MATCH
* to EOB_ACT_END_OF_FILE.
*/
/* Reset buffer status. */
yyrestart(yyin );
/*FALLTHROUGH*/
case EOB_ACT_END_OF_FILE:
{
if ( yywrap( ) )
return EOF;
if ( ! (yy_did_buffer_switch_on_eof) )
YY_NEW_FILE;
#ifdef __cplusplus
return yyinput();
#else
return input();
#endif
}
case EOB_ACT_CONTINUE_SCAN:
(yy_c_buf_p) = (yytext_ptr) + offset;
break;
}
}
}
c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */
*(yy_c_buf_p) = '\0'; /* preserve yytext */
(yy_hold_char) = *++(yy_c_buf_p);
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = (c == '\n');
return c;
}
#endif /* ifndef YY_NO_INPUT */
/** Immediately switch to a different input stream.
* @param input_file A readable stream.
*
* @note This function does not reset the start condition to @c INITIAL .
*/
void yyrestart (FILE * input_file )
{
if ( ! YY_CURRENT_BUFFER ){
yyensure_buffer_stack ();
YY_CURRENT_BUFFER_LVALUE =
yy_create_buffer(yyin,YY_BUF_SIZE );
}
yy_init_buffer(YY_CURRENT_BUFFER,input_file );
yy_load_buffer_state( );
}
/** Switch to a different input buffer.
* @param new_buffer The new input buffer.
*
*/
void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer )
{
/* TODO. We should be able to replace this entire function body
* with
* yypop_buffer_state();
* yypush_buffer_state(new_buffer);
*/
yyensure_buffer_stack ();
if ( YY_CURRENT_BUFFER == new_buffer )
return;
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*(yy_c_buf_p) = (yy_hold_char);
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
YY_CURRENT_BUFFER_LVALUE = new_buffer;
yy_load_buffer_state( );
/* We don't actually know whether we did this switch during
* EOF (yywrap()) processing, but the only time this flag
* is looked at is after yywrap() is called, so it's safe
* to go ahead and always set it.
*/
(yy_did_buffer_switch_on_eof) = 1;
}
static void yy_load_buffer_state (void)
{
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
(yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
(yy_hold_char) = *(yy_c_buf_p);
}
/** Allocate and initialize an input buffer state.
* @param file A readable stream.
* @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE.
*
* @return the allocated buffer state.
*/
YY_BUFFER_STATE yy_create_buffer (FILE * file, int size )
{
YY_BUFFER_STATE b;
b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_buf_size = size;
/* yy_ch_buf has to be 2 characters longer than the size given because
* we need to put in 2 end-of-buffer characters.
*/
b->yy_ch_buf = (char *) yyalloc(b->yy_buf_size + 2 );
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_is_our_buffer = 1;
yy_init_buffer(b,file );
return b;
}
/** Destroy the buffer.
* @param b a buffer created with yy_create_buffer()
*
*/
void yy_delete_buffer (YY_BUFFER_STATE b )
{
if ( ! b )
return;
if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
if ( b->yy_is_our_buffer )
yyfree((void *) b->yy_ch_buf );
yyfree((void *) b );
}
#ifndef __cplusplus
extern int isatty (int );
#endif /* __cplusplus */
/* Initializes or reinitializes a buffer.
* This function is sometimes called more than once on the same buffer,
* such as during a yyrestart() or at EOF.
*/
static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file )
{
int oerrno = errno;
yy_flush_buffer(b );
b->yy_input_file = file;
b->yy_fill_buffer = 1;
/* If b is the current buffer, then yy_init_buffer was _probably_
* called from yyrestart() or through yy_get_next_buffer.
* In that case, we don't want to reset the lineno or column.
*/
if (b != YY_CURRENT_BUFFER){
b->yy_bs_lineno = 1;
b->yy_bs_column = 0;
}
b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0;
errno = oerrno;
}
/** Discard all buffered characters. On the next scan, YY_INPUT will be called.
* @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
*
*/
void yy_flush_buffer (YY_BUFFER_STATE b )
{
if ( ! b )
return;
b->yy_n_chars = 0;
/* We always need two end-of-buffer characters. The first causes
* a transition to the end-of-buffer state. The second causes
* a jam in that state.
*/
b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
b->yy_buf_pos = &b->yy_ch_buf[0];
b->yy_at_bol = 1;
b->yy_buffer_status = YY_BUFFER_NEW;
if ( b == YY_CURRENT_BUFFER )
yy_load_buffer_state( );
}
/** Pushes the new state onto the stack. The new state becomes
* the current state. This function will allocate the stack
* if necessary.
* @param new_buffer The new state.
*
*/
void yypush_buffer_state (YY_BUFFER_STATE new_buffer )
{
if (new_buffer == NULL)
return;
yyensure_buffer_stack();
/* This block is copied from yy_switch_to_buffer. */
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*(yy_c_buf_p) = (yy_hold_char);
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
/* Only push if top exists. Otherwise, replace top. */
if (YY_CURRENT_BUFFER)
(yy_buffer_stack_top)++;
YY_CURRENT_BUFFER_LVALUE = new_buffer;
/* copied from yy_switch_to_buffer. */
yy_load_buffer_state( );
(yy_did_buffer_switch_on_eof) = 1;
}
/** Removes and deletes the top of the stack, if present.
* The next element becomes the new top.
*
*/
void yypop_buffer_state (void)
{
if (!YY_CURRENT_BUFFER)
return;
yy_delete_buffer(YY_CURRENT_BUFFER );
YY_CURRENT_BUFFER_LVALUE = NULL;
if ((yy_buffer_stack_top) > 0)
--(yy_buffer_stack_top);
if (YY_CURRENT_BUFFER) {
yy_load_buffer_state( );
(yy_did_buffer_switch_on_eof) = 1;
}
}
/* Allocates the stack if it does not exist.
* Guarantees space for at least one push.
*/
static void yyensure_buffer_stack (void)
{
int num_to_alloc;
if (!(yy_buffer_stack)) {
/* First allocation is just for 2 elements, since we don't know if this
* scanner will even need a stack. We use 2 instead of 1 to avoid an
* immediate realloc on the next call.
*/
num_to_alloc = 1;
(yy_buffer_stack) = (struct yy_buffer_state**)yyalloc
(num_to_alloc * sizeof(struct yy_buffer_state*)
);
if ( ! (yy_buffer_stack) )
YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*));
(yy_buffer_stack_max) = num_to_alloc;
(yy_buffer_stack_top) = 0;
return;
}
if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){
/* Increase the buffer to prepare for a possible push. */
int grow_size = 8 /* arbitrary grow size */;
num_to_alloc = (yy_buffer_stack_max) + grow_size;
(yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc
((yy_buffer_stack),
num_to_alloc * sizeof(struct yy_buffer_state*)
);
if ( ! (yy_buffer_stack) )
YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
/* zero only the new slots.*/
memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*));
(yy_buffer_stack_max) = num_to_alloc;
}
}
/** Setup the input buffer state to scan directly from a user-specified character buffer.
* @param base the character buffer
* @param size the size in bytes of the character buffer
*
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size )
{
YY_BUFFER_STATE b;
if ( size < 2 ||
base[size-2] != YY_END_OF_BUFFER_CHAR ||
base[size-1] != YY_END_OF_BUFFER_CHAR )
/* They forgot to leave room for the EOB's. */
return 0;
b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" );
b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */
b->yy_buf_pos = b->yy_ch_buf = base;
b->yy_is_our_buffer = 0;
b->yy_input_file = 0;
b->yy_n_chars = b->yy_buf_size;
b->yy_is_interactive = 0;
b->yy_at_bol = 1;
b->yy_fill_buffer = 0;
b->yy_buffer_status = YY_BUFFER_NEW;
yy_switch_to_buffer(b );
return b;
}
/** Setup the input buffer state to scan a string. The next call to yylex() will
* scan from a @e copy of @a str.
* @param yystr a NUL-terminated string to scan
*
* @return the newly allocated buffer state object.
* @note If you want to scan bytes that may contain NUL values, then use
* yy_scan_bytes() instead.
*/
YY_BUFFER_STATE yy_scan_string (yyconst char * yystr )
{
return yy_scan_bytes(yystr,strlen(yystr) );
}
/** Setup the input buffer state to scan the given bytes. The next call to yylex() will
* scan from a @e copy of @a bytes.
* @param bytes the byte buffer to scan
* @param len the number of bytes in the buffer pointed to by @a bytes.
*
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE yy_scan_bytes (yyconst char * yybytes, int _yybytes_len )
{
YY_BUFFER_STATE b;
char *buf;
yy_size_t n;
int i;
/* Get memory for full buffer, including space for trailing EOB's. */
n = _yybytes_len + 2;
buf = (char *) yyalloc(n );
if ( ! buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" );
for ( i = 0; i < _yybytes_len; ++i )
buf[i] = yybytes[i];
buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
b = yy_scan_buffer(buf,n );
if ( ! b )
YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" );
/* It's okay to grow etc. this buffer, and we should throw it
* away when we're done.
*/
b->yy_is_our_buffer = 1;
return b;
}
#ifndef YY_EXIT_FAILURE
#define YY_EXIT_FAILURE 2
#endif
static void yy_fatal_error (yyconst char* msg )
{
(void) fprintf( stderr, "%s\n", msg );
exit( YY_EXIT_FAILURE );
}
/* Redefine yyless() so it works in section 3 code. */
#undef yyless
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
yytext[yyleng] = (yy_hold_char); \
(yy_c_buf_p) = yytext + yyless_macro_arg; \
(yy_hold_char) = *(yy_c_buf_p); \
*(yy_c_buf_p) = '\0'; \
yyleng = yyless_macro_arg; \
} \
while ( 0 )
/* Accessor methods (get/set functions) to struct members. */
/** Get the current line number.
*
*/
int yyget_lineno (void)
{
return yylineno;
}
/** Get the input stream.
*
*/
FILE *yyget_in (void)
{
return yyin;
}
/** Get the output stream.
*
*/
FILE *yyget_out (void)
{
return yyout;
}
/** Get the length of the current token.
*
*/
int yyget_leng (void)
{
return yyleng;
}
/** Get the current token.
*
*/
char *yyget_text (void)
{
return yytext;
}
/** Set the current line number.
* @param line_number
*
*/
void yyset_lineno (int line_number )
{
yylineno = line_number;
}
/** Set the input stream. This does not discard the current
* input buffer.
* @param in_str A readable stream.
*
* @see yy_switch_to_buffer
*/
void yyset_in (FILE * in_str )
{
yyin = in_str ;
}
void yyset_out (FILE * out_str )
{
yyout = out_str ;
}
int yyget_debug (void)
{
return yy_flex_debug;
}
void yyset_debug (int bdebug )
{
yy_flex_debug = bdebug ;
}
static int yy_init_globals (void)
{
/* Initialization is the same as for the non-reentrant scanner.
* This function is called from yylex_destroy(), so don't allocate here.
*/
(yy_buffer_stack) = 0;
(yy_buffer_stack_top) = 0;
(yy_buffer_stack_max) = 0;
(yy_c_buf_p) = (char *) 0;
(yy_init) = 0;
(yy_start) = 0;
/* Defined in main.c */
#ifdef YY_STDINIT
yyin = stdin;
yyout = stdout;
#else
yyin = (FILE *) 0;
yyout = (FILE *) 0;
#endif
/* For future reference: Set errno on error, since we are called by
* yylex_init()
*/
return 0;
}
/* yylex_destroy is for both reentrant and non-reentrant scanners. */
int yylex_destroy (void)
{
/* Pop the buffer stack, destroying each element. */
while(YY_CURRENT_BUFFER){
yy_delete_buffer(YY_CURRENT_BUFFER );
YY_CURRENT_BUFFER_LVALUE = NULL;
yypop_buffer_state();
}
/* Destroy the stack itself. */
yyfree((yy_buffer_stack) );
(yy_buffer_stack) = NULL;
/* Reset the globals. This is important in a non-reentrant scanner so the next time
* yylex() is called, initialization will occur. */
yy_init_globals( );
return 0;
}
/*
* Internal utility routines.
*/
#ifndef yytext_ptr
static void yy_flex_strncpy (char* s1, yyconst char * s2, int n )
{
register int i;
for ( i = 0; i < n; ++i )
s1[i] = s2[i];
}
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * s )
{
register int n;
for ( n = 0; s[n]; ++n )
;
return n;
}
#endif
void *yyalloc (yy_size_t size )
{
return (void *) malloc( size );
}
void *yyrealloc (void * ptr, yy_size_t size )
{
/* The cast to (char *) in the following accommodates both
* implementations that use char* generic pointers, and those
* that use void* generic pointers. It works with the latter
* because both ANSI C and C++ allow castless assignment from
* any pointer type to void*, and deal with argument conversions
* as though doing an assignment.
*/
return (void *) realloc( (char *) ptr, size );
}
void yyfree (void * ptr )
{
free( (char *) ptr ); /* see yyrealloc() for (char *) cast */
}
#define YYTABLES_NAME "yytables"
#line 330 "c.l"
int yywrap()
{
return(1);
}
void comment()
{
int c;
for (;;) {
while ( (c = yyinput()) != '*' && c != EOF ) {
if (c=='\n') {
line++;column=0;
} else {
column++;
}
}
if ( c == '*' ) {
while ( (c = yyinput()) == '*' )
column++;
column++;
if (c =='\n') {line++;column=0;}
if ( c == '/' )
break;
}
if ( c == EOF ) {
break;
}
}
}
void cpp_comment()
{
int c;
while ((c = yyinput()) != '\n' && c != 0 && c!=EOF)
column++;
line++;
column= 0;
}
void macro()
{
int c,last=0;
again:
last= 0;
while ((c = yyinput()) != '\n' && c != 0 && c!=EOF) {
last= c;
}
if (c == '\n' && last == '\\') {
line++;
goto again;
}
line++;
column= 0;
}
void count()
{
int i;
for (i = 0; yytext[i] != '\0'; i++)
if (yytext[i] == '\n') {
column = 0;
line++;
} else if (yytext[i] == '\t')
column += 4;
else
column++;
//ECHO;
}
| 27.712903 | 116 | 0.582341 | [
"object"
] |
6f5cfffc3c573152d577986cea0e1a7c7ab0b245 | 4,338 | cpp | C++ | src/Conversion/ONNXToKrnl/Sequence/SequenceErase.cpp | philass/onnx-mlir | 09965003137f82d8891676c986ec6403faa9c3cb | [
"Apache-2.0"
] | 1 | 2022-03-23T06:41:14.000Z | 2022-03-23T06:41:14.000Z | src/Conversion/ONNXToKrnl/Sequence/SequenceErase.cpp | philass/onnx-mlir | 09965003137f82d8891676c986ec6403faa9c3cb | [
"Apache-2.0"
] | 1 | 2022-03-31T23:58:31.000Z | 2022-03-31T23:58:31.000Z | src/Conversion/ONNXToKrnl/Sequence/SequenceErase.cpp | philass/onnx-mlir | 09965003137f82d8891676c986ec6403faa9c3cb | [
"Apache-2.0"
] | null | null | null | /*
* SPDX-License-Identifier: Apache-2.0
*/
//===-------SequenceErase.cpp - Lowering SequenceErase Op-----------------=== //
//
// Copyright 2022 The IBM Research Authors.
//
// =============================================================================
//
// This file lowers the ONNX SequenceErase Operator to Krnl dialect.
//
//===----------------------------------------------------------------------===//
#include "src/Conversion/ONNXToKrnl/ONNXToKrnlCommon.hpp"
#include "src/Dialect/Krnl/KrnlHelper.hpp"
#include "src/Dialect/ONNX/ShapeInference/ONNXShapeHelper.hpp"
using namespace mlir;
namespace onnx_mlir {
struct ONNXSequenceEraseOpLowering : public ConversionPattern {
ONNXSequenceEraseOpLowering(TypeConverter &typeConverter, MLIRContext *ctx)
: ConversionPattern(typeConverter,
mlir::ONNXSequenceEraseOp::getOperationName(), 1, ctx) {}
LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const final {
Location loc = op->getLoc();
ONNXSequenceEraseOpAdaptor operandAdaptor(operands);
ONNXSequenceInsertOp thisOp = dyn_cast<ONNXSequenceInsertOp>(op);
MultiDialectBuilder<MathBuilder, MemRefBuilder> create(rewriter, loc);
IndexExprScope IEScope(&rewriter, loc);
auto input_sequence = operandAdaptor.input_sequence();
auto dimSize = create.mem.dim(input_sequence, 0);
SymbolIndexExpr boundIE(dimSize);
auto seqElementType =
input_sequence.getType().cast<MemRefType>().getElementType();
SmallVector<int64_t, 1> dims;
// Number of element in seq may be statically known from shape inference
dims.emplace_back(thisOp.getResult().getType().cast<SeqType>().getLength());
llvm::ArrayRef<int64_t> shape(dims.data(), dims.size());
MemRefType outputMemRefType = MemRefType::get(shape, seqElementType);
auto outputBound = boundIE - 1;
SmallVector<IndexExpr, 1> ubsIE;
ubsIE.emplace_back(outputBound);
Value alloc =
insertAllocAndDeallocSimple(rewriter, op, outputMemRefType, loc, ubsIE);
// Fill the output sequence
IndexExpr positionIE;
if (isFromNone(operandAdaptor.position())) {
// Insert at the end of the sequence
// Could be optimized as: Copy the input sequence and attach input tensor
// at the end But the size for KrnlMemcpy is integer, not Value
// memref::copy requires that source and destination have the same shape
positionIE = boundIE - 1;
} else {
positionIE = SymbolIndexExpr(operandAdaptor.position());
// Handle the negative position
auto correctionIE = positionIE + boundIE;
positionIE = IndexExpr::select(positionIE < 0, correctionIE, positionIE);
}
// Copy before the insert
KrnlBuilder createKrnl(rewriter, loc);
SmallVector<IndexExpr, 1> lbs;
lbs.emplace_back(LiteralIndexExpr(0));
SmallVector<IndexExpr, 1> ubs;
ubs.emplace_back(positionIE);
ValueRange firstLoopDef = createKrnl.defineLoops(1);
createKrnl.iterateIE(firstLoopDef, firstLoopDef, lbs, ubs,
[&](KrnlBuilder createKrnl, ValueRange indicesLoopInd) {
auto element = createKrnl.load(
operandAdaptor.input_sequence(), indicesLoopInd[0]);
createKrnl.store(element, alloc, indicesLoopInd[0]);
});
// ToDo (chentong)Free the erased element
// Copy after the insert
SmallVector<IndexExpr, 1> lbs1;
lbs1.emplace_back(positionIE + 1);
SmallVector<IndexExpr, 1> ubs1;
ubs1.emplace_back(boundIE);
ValueRange secondLoopDef = createKrnl.defineLoops(1);
createKrnl.iterateIE(secondLoopDef, secondLoopDef, lbs1, ubs1,
[&](KrnlBuilder createKrnl, ValueRange indicesLoopInd) {
auto element = createKrnl.load(
operandAdaptor.input_sequence(), indicesLoopInd[0]);
auto oneIndex = create.math.constantIndex(1);
auto outputIndex = create.math.sub(indicesLoopInd[0], oneIndex);
createKrnl.store(element, alloc, outputIndex);
});
rewriter.replaceOp(op, alloc);
return success();
}
};
void populateLoweringONNXSequenceEraseOpPattern(RewritePatternSet &patterns,
TypeConverter &typeConverter, MLIRContext *ctx) {
patterns.insert<ONNXSequenceEraseOpLowering>(typeConverter, ctx);
}
} // namespace onnx_mlir
| 39.081081 | 80 | 0.684878 | [
"shape"
] |
6f62d3ac824e79f869deb60aa84c42dc3626a5c8 | 41,649 | cpp | C++ | bng/semantic_analyzer.cpp | mcellteam/libbng | 1d9fe00a2cc9a8d223078aec2700e7b86b10426a | [
"MIT"
] | null | null | null | bng/semantic_analyzer.cpp | mcellteam/libbng | 1d9fe00a2cc9a8d223078aec2700e7b86b10426a | [
"MIT"
] | null | null | null | bng/semantic_analyzer.cpp | mcellteam/libbng | 1d9fe00a2cc9a8d223078aec2700e7b86b10426a | [
"MIT"
] | 1 | 2021-05-11T21:13:20.000Z | 2021-05-11T21:13:20.000Z | /******************************************************************************
* Copyright (C) 2020-2021 by
* The Salk Institute for Biological Studies
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
******************************************************************************/
#include <sstream>
#include <cmath>
#include "bng/semantic_analyzer.h"
#include "bng/bng_data.h"
#include "bng/elem_mol_type.h"
#include "bng/parser_utils.h"
#include "bng/bngl_names.h"
// each semantic check has in comment the name of a test for it
using namespace std;
namespace BNG {
const char* const DIR_FORWARD = "forward";
const char* const DIR_REVERSE = "reverse";
// function names - name and number of arguments, list used by data model to pymcell4 converter
// is in generator_utils.h: mdl_functions_to_py_bngl_map
struct BnglFunctionInfo {
uint num_arguments;
double (*eval_1_arg_func_call)(double);
double (*eval_2_args_func_call)(double, double);
};
static double bngl_max(const double a, const double b) {
return (a<b)?b:a;
}
static double bngl_min(const double a, const double b) {
return !(b<a)?a:b;
}
// TODO: check allowed argument ranges e.g. for asin
// TODO: only the intersection of MDL and BNGL functions is supported now, some BNGL functios are missing
static const std::map<std::string, BnglFunctionInfo> bngl_function_infos {
{ "sqrt", {1, sqrt, nullptr} },
{ "exp", {1, exp, nullptr} },
{ "ln", {1, log, nullptr} },
{ "log10", {1, log10, nullptr} },
{ "sin", {1, sin, nullptr} },
{ "cos", {1, cos, nullptr} },
{ "tan", {1, tan, nullptr} },
{ "asin", {1, asin, nullptr} },
{ "acos", {1, acos, nullptr} },
{ "atan", {1, atan, nullptr} },
{ "abs", {1, fabs, nullptr} },
{ "ceil", {1, ceil, nullptr} },
{ "floor", {1, floor, nullptr} },
{ "max", {2, nullptr, bngl_max} },
{ "min", {2, nullptr, bngl_min} }
};
static bool is_thrash_or_zero(const string& name) {
// same check as in nfsim
return name == COMPLEX_ZERO || name == COMPLEX_Trash || name == COMPLEX_TRASH || name == COMPLEX_trash;
}
double SemanticAnalyzer::evaluate_function_call(ASTExprNode* call_node, const std::vector<double>& arg_values) {
assert(call_node != nullptr);
const string& name = call_node->get_function_name();
const auto& func_info_it = bngl_function_infos.find(name);
if (func_info_it != bngl_function_infos.end()) {
if (arg_values.size() == func_info_it->second.num_arguments) {
const BnglFunctionInfo& info = func_info_it->second;
if (info.num_arguments == 1) {
return info.eval_1_arg_func_call(arg_values[0]);
}
else if (info.num_arguments == 2) {
return info.eval_2_args_func_call(arg_values[0], arg_values[1]);
}
else {
assert(false);
return 0;
}
}
else {
errs_loc(call_node) <<
"Invalid number of arguments for function '" << name << "', got " << arg_values.size() <<
" expected " << func_info_it->second.num_arguments << ".\n"; // test TODO
ctx->inc_error_count();
return 0;
}
}
else {
errs_loc(call_node) <<
"Unknown function '" << name << "' encountered.\n"; // test TODO
ctx->inc_error_count();
return 0;
}
}
// returns new node, owned by ctx if any new nodes were created
// called recursively, the set used_ids is copied intentionally every call
ASTExprNode* SemanticAnalyzer::evaluate_to_dbl(ASTExprNode* root, set<string> used_ids) {
if (root->is_dbl()) {
// already computed
return root;
}
else if (root->is_llong()) {
return ctx->new_dbl_node(root->get_llong(), root);
}
else if (root->is_id()) {
const string& id = root->get_id();
if (used_ids.count(id) != 0) {
errs_loc(root) <<
"Cyclic dependence while evaluating an expression, id '" << id << "' was already used.\n"; // test N0012
ctx->inc_error_count();
return ctx->new_dbl_node(0, root);
}
// find the value in the symbol table
ASTBaseNode* val = ctx->symtab.get(root->get_id(), root, ctx);
if (val == nullptr) {
// error msg was printed by the symbol table
return ctx->new_dbl_node(0, root);
}
if (!val->is_expr()) {
errs_loc(root) <<
"Referenced id '" << id << "' cannot be used in an expression.\n";
ctx->inc_error_count();
return ctx->new_dbl_node(0, root);
}
used_ids.insert(id);
return evaluate_to_dbl(to_expr_node(val), used_ids);
}
else if (root->is_unary_expr()) {
assert(root->get_left() != nullptr);
assert(root->get_right() == nullptr);
double res = evaluate_to_dbl(root->get_left(), used_ids)->get_dbl();
return ctx->new_dbl_node( (root->get_op() == ExprType::UnaryMinus) ? -res : res, root);
}
else if (root->is_binary_expr()) {
assert(root->get_left() != nullptr);
assert(root->get_right() != nullptr);
double res_left = evaluate_to_dbl(root->get_left(), used_ids)->get_dbl();
double res_right = evaluate_to_dbl(root->get_right(), used_ids)->get_dbl();
double res = 0;
switch (root->get_op()) {
case ExprType::Add:
res = res_left + res_right;
break;
case ExprType::Sub:
res = res_left - res_right;
break;
case ExprType::Mul:
res = res_left * res_right;
break;
case ExprType::Div:
if (res_right == 0) {
errs_loc(root) << "Division by zero, left operand evaluated to " << res_left << " and right to 0.\n";
ctx->inc_error_count();
}
else {
res = res_left / res_right;
}
break;
case ExprType::Pow:
res = pow(res_left, res_right);
break;
default:
release_assert(false && "Invalid operator");
}
return ctx->new_dbl_node(res, root);
}
else if (root->is_function_call()) {
assert(root->get_args() != nullptr);
// evaluate all arguments
vector<double> arg_values;
for (ASTBaseNode* base_arg_node: root->get_args()->items) {
ASTExprNode* arg_node = to_expr_node(base_arg_node);
arg_values.push_back(evaluate_to_dbl(arg_node, used_ids)->get_dbl());
}
double res = evaluate_function_call(root, arg_values);
return ctx->new_dbl_node(res, root);
}
assert(false && "unreachable");
return nullptr;
}
// compute all reaction rates and replace them with a floating point value (BNGL uses integers only for bond indices)
void SemanticAnalyzer::resolve_rxn_rates() {
// the only place where expressions are currently used are rates
// (parameters are evaluated along the way)
// we are also checking that
// for each rxn rule
for (ASTBaseNode* n: ctx->rxn_rules.items) {
ASTRxnRuleNode* rule = to_rxn_rule_node(n);
// do we have the right number of rates?
if (rule->reversible && rule->rates->size() != 2) {
errs_loc(rule) <<
"A reversible rule must have exactly 2 rates, "<<
rule->rates->size() << " rate(s) provided.\n"; // test N0015
ctx->inc_error_count();
}
if (!rule->reversible && rule->rates->size() != 1) {
errs_loc(rule) <<
"A unidirectional rule must have exactly 1 rate, " <<
rule->rates->size() << " rate(s) provided.\n"; // test N0014
ctx->inc_error_count();
}
// replace each of its rates with a float constant
for (size_t i = 0; i < rule->rates->items.size(); i++) {
ASTExprNode* orig_expr = to_expr_node(rule->rates->items[i]);
ASTExprNode* new_expr = evaluate_to_dbl(orig_expr);
// all nodes are owned by context and deleted after parsing has finished
rule->rates->items[i] = new_expr;
}
}
}
// the following conversions do not use the bng_data.parameters map
// if a parameter is in the map parameter_overrides, the supplied value is used instead
void SemanticAnalyzer::convert_and_evaluate_parameters(
const std::map<std::string, double>& parameter_overrides) {
// first go trough all parameter overrides and either change definition or add
// this parameter to the symbol table
ASTSymbolTable::IdToNodeMap& symtab_map = ctx->symtab.get_as_map();
for (auto it_override: parameter_overrides) {
// is defined?
auto it_found_sym = symtab_map.find(it_override.first);
if (it_found_sym != symtab_map.end()) {
// and it is a symbol
if (it_found_sym->second->is_expr()) {
// override its value
it_found_sym->second = ctx->new_dbl_node(it_override.second);
}
else {
errs() <<
"Cannot override symbol " << it_override.first << " that is not a parameter.\n";
ctx->inc_error_count();
}
}
else {
// define as a new symbol
ctx->symtab.insert(
it_override.first,
ctx->new_dbl_node(it_override.second),
ctx
);
}
}
// every symbol that maps directly into a value is a parameter
// evaluate them and store
for (auto it_sym: ctx->symtab.get_as_map()) {
if (it_sym.second->is_expr()) {
ASTExprNode* orig_expr = to_expr_node(it_sym.second);
ASTExprNode* new_expr = evaluate_to_dbl(orig_expr);
bng_data->add_parameter(it_sym.first, new_expr->get_dbl());
}
}
}
state_id_t SemanticAnalyzer::convert_state_name(const ASTStrNode* s) {
assert(s != nullptr);
return bng_data->find_or_add_state_name(s->str);
}
ComponentType SemanticAnalyzer::convert_component_type(
const std::string& elem_mol_type_name,
const ASTComponentNode* c,
const bool allow_components_to_have_bonds
) {
ComponentType ct;
ct.name = c->name;
ct.elem_mol_type_name = elem_mol_type_name;
// states
for (const ASTBaseNode* state: c->states->items) {
state_id_t state_id = convert_state_name(to_str_node(state));
ct.allowed_state_ids.insert(state_id);
}
// bond - ignored, only error is printed
if (!allow_components_to_have_bonds && c->bond->str != "") {
errs_loc(c) <<
"Definition of a component in the molecule types section must not have a bond, "
"error for '!" << c->bond->str << "'.\n"; // checked by parser, original test N0100
ctx->inc_error_count();
}
return ct;
}
ElemMolType SemanticAnalyzer::convert_molecule_type(
const ASTMolNode* n,
// when parsing single cplx we don't have the full information from the molecule types section
// so we allow merging component types and also bonds
const bool parsing_single_cplx
) {
ElemMolType mt;
mt.name = n->name;
for (const ASTBaseNode* c: n->components->items) {
const ASTComponentNode* comp = to_component_node(c);
// did we already define a component for this molecule with this name?
component_type_id_t ct_id = bng_data->find_component_type_id(mt, comp->name);
if (ct_id == COMPONENT_TYPE_ID_INVALID) {
// new component type
ComponentType ct = convert_component_type(mt.name, to_component_node(c), parsing_single_cplx);
component_type_id_t new_ct_id = bng_data->find_or_add_component_type(ct, parsing_single_cplx);
mt.component_type_ids.push_back(new_ct_id);
}
else {
// check or add states used in the new component against
// what we defined before
ComponentType& existing_ct = bng_data->get_component_type(ct_id);
ComponentType new_ct = convert_component_type(mt.name, comp, parsing_single_cplx);
assert(existing_ct.name == new_ct.name);
if (!parsing_single_cplx) {
if (existing_ct.allowed_state_ids != new_ct.allowed_state_ids) {
errs_loc(n) <<
"Molecule type has 2 components with name '" << existing_ct.name <<
"' but with different states, this is not allowed.\n"; // test N0101
ctx->inc_error_count();
}
}
else {
// while parsing a single cplx, we didn't get the molecule types definitions
// so we do not know how the component definitions look like, let's merge the allowed states
existing_ct.allowed_state_ids.insert(new_ct.allowed_state_ids.begin(), new_ct.allowed_state_ids.end());
}
// append it to the molecule type's components
mt.component_type_ids.push_back(ct_id);
}
}
return mt;
}
void SemanticAnalyzer::convert_and_store_molecule_types() {
// for each molecule (type) from the symbol table
const ASTSymbolTable::IdToNodeMap& table = ctx->symtab.get_as_map();
for (const auto& it: table) {
assert(it.second != nullptr);
if (it.second->is_mol()) {
const ASTMolNode* n = to_molecule_node(it.second);
if (n->has_compartment()) {
errs_loc(n) <<
"Compartments cannot be used in 'molecule types' section, error for molecule '" << n->name << "'.\n"; // test N0302
ctx->inc_error_count();
continue;
}
ElemMolType mt = convert_molecule_type(n);
bng_data->find_or_add_elem_mol_type(mt);
}
}
}
void SemanticAnalyzer::convert_and_store_compartments() {
// first define all compartments without their parents and children
for (size_t i = 0; i < ctx->compartments.items.size(); i++) {
const ASTCompartmentNode* n = to_compartment_node(ctx->compartments.items[i]);
Compartment c;
// name
if (bng_data->find_compartment_id(n->name) != COMPARTMENT_ID_INVALID) {
errs_loc(n) <<
"Compartment '" << n->name << "' was already defined.\n"; // test N0302
ctx->inc_error_count();
continue;
}
if (n->name == DEFAULT_COMPARTMENT_NAME) {
errs_loc(n) <<
"Compartment name '" << n->name << "' is reserved, the specification will be ignored.\n"; // test TODO
continue;
}
c.name = n->name;
// dimensions
if (n->dimensions != 2 && n->dimensions != 3) {
errs_loc(n) <<
"Compartment '" << n->name << "' has invalid dimension of value " << n->dimensions <<
", the only values allowed are 2 or 3.\n"; // test N0300
ctx->inc_error_count();
continue;
}
c.is_3d = n->dimensions == 3;
// volume
ASTExprNode* evaluated_volume = evaluate_to_dbl(n->volume);
double volume = evaluated_volume->get_dbl();
if (volume < 0) {
errs_loc(n) <<
"Compartment '" << n->name << "' has negative volume " << volume << ".\n"; // test N0301
ctx->inc_error_count();
continue;
}
if (c.is_3d) {
c.set_volume(volume);
}
else {
c.set_area(volume / SURFACE_COMPARTMENT_THICKNESS);
}
bng_data->add_compartment(c);
}
if (ctx->get_error_count()) {
return;
}
// now define their parents and children
for (size_t i = 0; i < ctx->compartments.items.size(); i++) {
const ASTCompartmentNode* n = to_compartment_node(ctx->compartments.items[i]);
Compartment* c = bng_data->find_compartment(n->name);
if (c == nullptr) {
// ignoring default_compartment
assert(n->name == DEFAULT_COMPARTMENT_NAME);
continue;
}
if (n->parent_name != "") {
compartment_id_t parent_compartment_id = bng_data->find_compartment_id(n->parent_name);
if (parent_compartment_id == COMPARTMENT_ID_INVALID) {
errs_loc(n) <<
"Compartment's '" << n->name << "' parent '" << n->parent_name << "' was not defined.\n"; // test N0303
ctx->inc_error_count();
continue;
}
// set parent
c->parent_compartment_id = parent_compartment_id;
Compartment& parent = bng_data->get_compartment(parent_compartment_id);
// check
if (c->is_3d == parent.is_3d) {
errs_loc(n) <<
"Parent compartment " + parent.name +
" must be of different dimensionality than its child '" + c->name + "'."; // test TODO
ctx->inc_error_count();
continue;
}
// set 'c' as a child of its parent
parent.children_compartments.insert(c->id);
}
}
if (ctx->get_error_count()) {
return;
}
for (size_t i = 0; i < ctx->compartments.items.size(); i++) {
const ASTCompartmentNode* n = to_compartment_node(ctx->compartments.items[i]);
// check that the lowest level children is 3d
const Compartment* c = bng_data->find_compartment(n->name);
if (c == nullptr) {
// ignoring default_compartment
assert(n->name == DEFAULT_COMPARTMENT_NAME);
continue;
}
if (!c->has_children() && !c->is_3d) {
errs() <<
"Compartment without sub-compartments '" + c->name + "' must be a 3D compartment.\n"; // test TODO
ctx->inc_error_count();
}
}
}
void SemanticAnalyzer::collect_molecule_types_molecule_list(
const ASTListNode* cplx_list,
vector<const ASTMolNode*>& molecule_nodes
) {
for (size_t i = 0; i < cplx_list->items.size(); i++) {
const ASTCplxNode* cplx = to_cplx_node(cplx_list->items[i]);
molecule_nodes.insert(molecule_nodes.end(), cplx->mols.begin(), cplx->mols.end());
}
}
void SemanticAnalyzer::collect_and_store_implicit_molecule_types() {
// go through reaction rules and seed species to define molecule types
// first collect all molecule nodes
// for each rxn rule
vector<const ASTMolNode*> found_mol_nodes;
for (const ASTBaseNode* n: ctx->rxn_rules.items) {
const ASTRxnRuleNode* r = to_rxn_rule_node(n);
collect_molecule_types_molecule_list(r->reactants, found_mol_nodes);
collect_molecule_types_molecule_list(r->products, found_mol_nodes);
}
for (const ASTBaseNode* n: ctx->seed_species.items) {
const ASTSeedSpeciesNode* ss = to_seed_species_node(n);
found_mol_nodes.insert(found_mol_nodes.end(),
ss->cplx->mols.begin(), ss->cplx->mols.end());
}
// sort by name and skip those that are already known
map<string, vector<const ASTMolNode*>> mol_uses_with_same_name;
for (const ASTMolNode* n: found_mol_nodes) {
elem_mol_type_id_t mt_id = bng_data->find_elem_mol_type_id(n->name);
if (mt_id == ELEM_MOL_TYPE_ID_INVALID) {
mol_uses_with_same_name[n->name].push_back(n);
}
}
// and merge into a single definition
// for each different name
for (auto same_name_it: mol_uses_with_same_name) {
// create a map of used states per each component
map<string, set<string>> component_state_names;
// also count the maximum number of components
map<string, uint> max_component_count_per_all_mts;
for (const ASTMolNode* mn: same_name_it.second) {
map<string, uint> max_component_count_per_single_mt;
for (const ASTBaseNode* cnb: mn->components->items) {
const ASTComponentNode* cn = to_component_node(cnb);
// count occurrence
if (max_component_count_per_single_mt.count(cn->name) == 0) {
max_component_count_per_single_mt[cn->name] = 1;
}
else {
max_component_count_per_single_mt[cn->name]++;
}
// collect state names
for (const ASTBaseNode* snb: cn->states->items) {
const ASTStrNode* sn = to_str_node(snb);
component_state_names[cn->name].insert(sn->str);
}
}
// update max count of these components
for (auto single_max: max_component_count_per_single_mt) {
const string& comp_name = single_max.first;
if (max_component_count_per_all_mts.count(comp_name) == 0) {
// count for this component was not set
max_component_count_per_all_mts[comp_name] = single_max.second;
}
else {
// overwrite smaller
if (max_component_count_per_all_mts[comp_name] < single_max.second) {
max_component_count_per_all_mts[comp_name] = single_max.second;
}
}
}
}
// we finally know how the components will look like, lets create it
// component_state_names - component name and allowed states
// max_component_count_per_all_mts - how many components per molecule type are there
ElemMolType new_mt;
new_mt.name = same_name_it.first;
if (is_thrash_or_zero(new_mt.name)) {
continue;
}
for (auto comp_info_it: max_component_count_per_all_mts) {
ComponentType new_ct;
new_ct.name = comp_info_it.first;
new_ct.elem_mol_type_name = new_mt.name;
for (const string& s: component_state_names[new_ct.name]) {
state_id_t s_id = bng_data->find_or_add_state_name(s);
new_ct.allowed_state_ids.insert(s_id);
}
component_type_id_t ct_id = bng_data->find_or_add_component_type(new_ct);
for (uint i = 0; i < comp_info_it.second; i++) {
new_mt.component_type_ids.push_back(ct_id);
}
}
bng_data->find_or_add_elem_mol_type(new_mt);
}
}
ElemMol SemanticAnalyzer::convert_molecule_pattern(const ASTMolNode* m) {
ElemMol mi;
// there is no support for surface molecules in BNGL yet, so everything must be volume molecule
mi.set_is_vol();
// process and remember ID
elem_mol_type_id_t molecule_type_id = bng_data->find_elem_mol_type_id(m->name);
if (molecule_type_id == ELEM_MOL_TYPE_ID_INVALID) {
errs_loc(m) << "Molecule type with name '" + m->name + "' was not defined.\n"; // test N0200
ctx->inc_error_count();
return mi;
}
const ElemMolType& mt = bng_data->get_elem_mol_type(molecule_type_id);
mi.elem_mol_type_id = molecule_type_id;
// process compartment
compartment_id_t cid = COMPARTMENT_ID_NONE;
if (m->compartment != nullptr) {
string compartment_name = m->compartment->str;
if (compartment_name != "") {
cid = bng_data->find_compartment_id(compartment_name);
if (cid == COMPARTMENT_ID_INVALID) {
errs_loc(m) <<
"Compartment '" << compartment_name << "' was not defined.\n"; // test XXX
ctx->inc_error_count();
return mi;
}
}
}
mi.compartment_id = cid;
// make a multiset of components type ids so that we can check that
// out molecule instance does not use wrong or too many components
multiset<component_type_id_t> remaining_component_ids;
for (component_type_id_t component_type_id: mt.component_type_ids) {
remaining_component_ids.insert(component_type_id);
}
uint current_component_index = 0;
// process component instances for this molecule type pattern/instance
for (size_t i = 0; i < m->components->items.size(); i++) {
// component_instances
const ASTComponentNode* component = to_component_node(m->components->items[i]);
// search in
component_type_id_t component_type_id =
bng_data->find_component_type_id(mt, component->name);
if (component_type_id == COMPONENT_TYPE_ID_INVALID) {
errs_loc(m) <<
"Molecule type '" << mt.name << "' does not declare component '" << component->name << "'.\n"; // test N0201
ctx->inc_error_count();
return mi;
}
// didn't we use the component too many times?
if (remaining_component_ids.count(component_type_id) == 0) {
errs_loc(m) <<
"Molecule type's '" << mt.name << "' component '" << component->name << "' is used too many times.\n"; // test N0102
ctx->inc_error_count();
return mi;
}
remaining_component_ids.erase(remaining_component_ids.find(component_type_id));
// add this component to our instance
mi.components.push_back(Component(component_type_id));
// state
if (component->states->items.size() > 1) {
// checked by parser, original test N0202
errs_loc(component) <<
"A component might have max. 1 state specified, error for component " << component->name << ".\n";
ctx->inc_error_count();
return mi;
}
// check and set if state is specified
if (component->states->items.size() == 1) {
const string& state_name = to_str_node(component->states->items[0])->str;
// does this state exist at all?
state_id_t state_id = bng_data->find_state_id(state_name);
if (state_id == STATE_ID_INVALID) {
errs_loc(component) <<
"Unknown state name '" << state_name << "' for component '" << component->name <<
"' (this state name was not found for any declared component).\n"; // test N0203
ctx->inc_error_count();
return mi;
}
// is this state allowed for this component?
const ComponentType& ct = bng_data->get_component_type(component_type_id);
if (ct.allowed_state_ids.count(state_id) == 0) {
errs_loc(component) <<
"State name '" << state_name << "' was not declared as allowed for component '" << component->name << "'.\n"; // test N0204
ctx->inc_error_count();
return mi;
}
// finally set the component's state
mi.components[current_component_index].state_id = state_id;
}
// bond
const string& bond = component->bond->str;
bond_value_t b = str_to_bond_value(bond);
if (b == BOND_VALUE_INVALID) {
// this is already checked by parser, so the a test checks parser message but let's keep this
// parser test: N0205
ctx->internal_error(component->bond, "Invalid bond index");
}
mi.components.back().bond_value = b;
// need to move component index because we processed this component
current_component_index++;
}
return mi;
}
void insert_compartment_id_to_set_based_on_type(
const BNGData* bng_data,
const compartment_id_t cid,
bool& all_are_none_or_inout,
bool& has_compartment_none,
uint_set<compartment_id_t>& vol_compartments,
uint_set<compartment_id_t>& surf_compartments) {
if (cid == COMPARTMENT_ID_NONE) {
has_compartment_none = true;
}
else if (cid == COMPARTMENT_ID_IN ||
cid == COMPARTMENT_ID_OUT) {
// continue
}
else if (bng_data->get_compartment(cid).is_3d) {
vol_compartments.insert(cid);
all_are_none_or_inout = false;
}
else {
surf_compartments.insert(cid);
all_are_none_or_inout = false;
}
}
// for a pattern it is ok to not to list all components
void SemanticAnalyzer::convert_cplx(
const ASTCplxNode* cplx_node,
Cplx& bng_cplx,
const bool in_rule_or_observable,
const bool check_compartments
) {
for (const ASTMolNode* m: cplx_node->mols) {
// molecule ids are based on their name
bng_cplx.elem_mols.push_back( convert_molecule_pattern(m) );
if (ctx->get_error_count() != 0) {
return;
}
}
// semantic checks on bonds validity
map<bond_value_t, vector<uint> > bond_value_to_molecule_index;
for (uint i = 0; i < bng_cplx.elem_mols.size(); i++) {
const ElemMol& mi = bng_cplx.elem_mols[i];
for (const Component& compi: mi.components) {
if (compi.bond_has_numeric_value()) {
// remember molecule index in this complex for a given bond
bond_value_to_molecule_index[compi.bond_value].push_back(i);
}
}
}
for (const auto& it: bond_value_to_molecule_index) {
// each bond is used exactly twice
if (it.second.size() != 2) {
assert(cplx_node->size() > 0);
errs_loc(cplx_node->mols[0]) <<
"Bond with numerical value '" << it.first << "' must be used exactly twice in a complex pattern of a rule.\n"; // test N0206
ctx->inc_error_count();
return;
}
}
// global compartment
compartment_id_t global_compartment_id = COMPARTMENT_ID_NONE;
if (cplx_node->compartment != nullptr) {
string compartment_name = cplx_node->compartment->str;
if (compartment_name != "") {
global_compartment_id = bng_data->find_compartment_id(compartment_name);
if (global_compartment_id == COMPARTMENT_ID_INVALID) {
errs_loc(cplx_node) <<
"Compartment '" << compartment_name << "' was not defined.\n"; // tests N0305, N0306
ctx->inc_error_count();
return;
}
}
}
// apply global compartment to elem mols that were not specified
if (global_compartment_id != COMPARTMENT_ID_NONE) {
for (auto& em: bng_cplx.elem_mols) {
if (em.compartment_id == COMPARTMENT_ID_NONE) {
em.compartment_id = global_compartment_id;
}
}
}
if (check_compartments) {
// check that compartments are used consistently
// we do not know yet whether elementary molecules are surface or not, but
// compartments were already defined in case we are parsing whole BNGL file
uint_set<compartment_id_t> vol_compartments;
uint_set<compartment_id_t> surf_compartments;
bool all_are_none_or_inout = true;
bool has_compartment_none = false;
for (const auto& em: bng_cplx.elem_mols) {
insert_compartment_id_to_set_based_on_type(
bng_data, em.compartment_id,
all_are_none_or_inout, has_compartment_none, vol_compartments, surf_compartments);
}
uint_set<compartment_id_t> all_vol_surf_compartment_ids;
all_vol_surf_compartment_ids.insert(vol_compartments.begin(), vol_compartments.end());
all_vol_surf_compartment_ids.insert(surf_compartments.begin(), surf_compartments.end());
if (!all_are_none_or_inout && surf_compartments.empty() && vol_compartments.size() > 1) {
errs_loc(cplx_node->mols[0]) <<
"The maximum number of compartments that a volume complex may use is 1, error for '" << bng_cplx.to_str() << "'.\n"; // test N307
ctx->inc_error_count();
return;
}
if (!all_are_none_or_inout && surf_compartments.size() > 1) {
errs_loc(cplx_node->mols[0]) <<
"The maximum number of surface compartments that a surface complex may use is 1, error for '" << bng_cplx.to_str() << "'.\n"; // test XXX
ctx->inc_error_count();
return;
}
if (!all_are_none_or_inout && surf_compartments.size() == 1 && vol_compartments.size() > 2) {
errs_loc(cplx_node->mols[0]) <<
"The maximum number of volume compartments that a surface complex may use is 2, error for '" << bng_cplx.to_str() << "'.\n"; // test XXX
ctx->inc_error_count();
return;
}
bng_cplx.finalize_cplx();
if (!bng_cplx.is_connected() && !in_rule_or_observable) {
errs_loc(cplx_node->mols[0]) <<
"All complexes that are not patterns must be currently fully connected, error for '" << bng_cplx.to_str() << "'.\n"; // test XXX
ctx->inc_error_count();
return;
}
}
}
// take one side of a reaction rule and create pattern for rule matching
void SemanticAnalyzer::convert_rxn_rule_side(
const ASTListNode* rule_side,
const bool reactants_side,
CplxVector& patterns) {
// we need to check each molecule type from each complex
std::vector<const ASTMolNode*> current_complex_nodes;
for (size_t i = 0; i < rule_side->items.size(); i++) {
const ASTCplxNode* cplx = to_cplx_node(rule_side->items[i]);
if (cplx->size() == 1) {
const ASTMolNode* m = to_molecule_node(cplx->mols[0]);
if (is_thrash_or_zero(m->name)) {
if (reactants_side) {
errs_loc(m) <<
"Null/Trash product cannot be used on the reactants side of a reeaction rule.\n"; // test N0620
ctx->inc_error_count();
return;
}
else {
// ok, ignore
continue;
}
}
}
Cplx pattern(bng_data);
convert_cplx(cplx, pattern, true);
if (ctx->get_error_count() > 0) {
return;
}
pattern.finalize_cplx();
patterns.push_back(pattern);
}
}
void SemanticAnalyzer::finalize_and_store_rxn_rule(
const ASTRxnRuleNode* n, RxnRule& r, const bool forward_direction) {
// check in/out
if (r.reactants.size() == 2) {
if (r.reactants[0].has_compartment_class_in_out() && r.reactants[1].has_compartment_class_in_out()) {
errs_loc(n) << "Maximum one reactant may use @" << COMPARTMENT_NAME_IN << " or @" << COMPARTMENT_NAME_OUT <<
" compartment class. Reported for reaction in the " <<
(forward_direction ? DIR_FORWARD : DIR_REVERSE) << " direction.\n"; // TEST 600
ctx->inc_error_count();
return;
}
}
r.finalize();
// determine mapping from molecule instances on one side to another
stringstream out;
bool ok = r.check_reactants_products_mapping(out);
if (!ok) {
// tests N0220, N0230, N0231, N0232
errs_loc(n) << out.str() <<
" Reported for reaction in the " << (forward_direction ? DIR_FORWARD : DIR_REVERSE) << " direction.\n";
ctx->inc_error_count();
return;
}
bng_data->find_or_add_rxn_rule(r);
}
void SemanticAnalyzer::convert_and_store_rxn_rules() {
// for each reaction rule
for (const ASTBaseNode* n: ctx->rxn_rules.items) {
const ASTRxnRuleNode* r = to_rxn_rule_node(n);
CplxVector reactants;
convert_rxn_rule_side(r->reactants, true, reactants);
CplxVector products;
convert_rxn_rule_side(r->products, false, products);
if (ctx->get_error_count() > 0) {
return;
}
RxnRule fwd_rule(bng_data);
fwd_rule.type = RxnType::Standard;
fwd_rule.name = r->name;
assert(r->rates->items.size() >= 1);
fwd_rule.base_rate_constant = to_expr_node(r->rates->items[0])->get_dbl();
fwd_rule.reactants = reactants;
fwd_rule.products = products;
finalize_and_store_rxn_rule(r, fwd_rule, true);
if (r->reversible) {
RxnRule rev_rule(bng_data);
rev_rule.type = RxnType::Standard;
rev_rule.name = r->name;
if (products.empty()) {
errs_loc(r) <<
"A reversible rule must have at least one complex pattern " <<
"on the right side of the reaction rule.\n"; // caught by parser, test N0211
ctx->inc_error_count();
}
assert(r->rates->items.size() == 2);
rev_rule.base_rate_constant = to_expr_node(r->rates->items[1])->get_dbl();
rev_rule.reactants = products;
rev_rule.products = reactants;
finalize_and_store_rxn_rule(r, rev_rule, false);
}
}
}
void SemanticAnalyzer::convert_seed_species() {
for (const ASTBaseNode* n: ctx->seed_species.items) {
const ASTSeedSpeciesNode* ss_node = to_seed_species_node(n);
SeedSpecies ss(bng_data);
convert_cplx(ss_node->cplx, ss.cplx, false);
if (ctx->get_error_count() != 0) {
return;
}
if (ss.cplx.has_compartment_class_in_out()) {
errs_loc(ss_node->cplx) <<
"It is not allowed to use compartment @" << compartment_id_to_str(ss.cplx.get_primary_compartment_id()) <<
" in the seed species section.\n"; // test N0601
ctx->inc_error_count();
return;
}
uint_set<compartment_id_t> used_compartments;
ss.cplx.get_used_compartments(used_compartments);
if (used_compartments.count(COMPARTMENT_ID_NONE) && used_compartments.size() > 1) {
errs_loc(n) <<
"In the seed species section either all elementary molecules must have their compartment specified or none, error for '" <<
ss.cplx.to_str() << "'.\n"; // test N0621
ctx->inc_error_count();
return;
}
ASTExprNode* orig_expr = to_expr_node(ss_node->count);
ASTExprNode* new_expr = evaluate_to_dbl(orig_expr);
ss.count = new_expr->get_dbl();
bng_data->add_seed_species(ss);
}
}
void SemanticAnalyzer::convert_observables() {
for (const ASTBaseNode* n: ctx->observables.items) {
const ASTObservableNode* o_node = to_observable_node(n);
Observable o;
if (o_node->type == OBSERVABLE_MOLECULES) {
o.type = ObservableType::Molecules;
}
else if (o_node->type == OBSERVABLE_SPECIES) {
o.type = ObservableType::Species;
}
else {
errs_loc(o_node) <<
"Invalid observable type '" << o_node->type << "', the allowed values are" <<
OBSERVABLE_MOLECULES << " or " << OBSERVABLE_SPECIES << ".\n"; // TODO test
ctx->inc_error_count();
continue;
}
o.name = o_node->name;
for (const ASTBaseNode* base_pat: o_node->cplx_patterns->items) {
const ASTCplxNode* cplx_pat = to_cplx_node(base_pat);
Cplx cplx(bng_data);
convert_cplx(cplx_pat, cplx, true);
if (ctx->get_error_count() != 0) {
return;
}
if (cplx.has_compartment_class_in_out()) {
errs_loc(cplx_pat) <<
"It is not allowed to use compartment @" << compartment_id_to_str(cplx.get_primary_compartment_id()) <<
" in the observables section.\n"; // test N0602
ctx->inc_error_count();
return;
}
o.patterns.push_back(cplx);
}
bng_data->add_observable(o);
}
}
// returns true if conversion and semantic checks passed
bool SemanticAnalyzer::check_and_convert_parsed_file(
ParserContext* ctx_,
BNGData* res_bng,
const std::map<std::string, double>& parameter_overrides) {
assert(ctx_ != nullptr);
assert(res_bng != nullptr);
ctx = ctx_;
bng_data = res_bng;
// the following conversions do not use the bng_data.parameters map
convert_and_evaluate_parameters(parameter_overrides);
if (ctx->get_error_count() != 0) {
return false;
}
// first compute all reaction rates
resolve_rxn_rates();
if (ctx->get_error_count() != 0) {
return false;
}
// convert molecule types
// the single purpose of molecule types is to be able to check
// that reaction rules and also new releases adhere to the molecule type template
convert_and_store_molecule_types();
if (ctx->get_error_count() != 0) {
return false;
}
convert_and_store_compartments();
if (ctx->get_error_count() != 0) {
return false;
}
// molecule types do not have to be defined,
// in this case we will define them based on what we found in the
// seed species, reactions (and observables - not supported yet)
collect_and_store_implicit_molecule_types();
if (ctx->get_error_count() != 0) {
return false;
}
// convert rxn rules
convert_and_store_rxn_rules();
if (ctx->get_error_count() != 0) {
return false;
}
convert_seed_species();
if (ctx->get_error_count() != 0) {
return false;
}
convert_observables();
if (ctx->get_error_count() != 0) {
return false;
}
return true;
}
// analyze AST for a single complex and extend molecule type definitions by what it contains
void SemanticAnalyzer::extend_molecule_type_definitions(const ASTCplxNode* cplx_node) {
for (const ASTMolNode* mol: cplx_node->mols) {
// was this molecule type already defined?
elem_mol_type_id_t mt_id = bng_data->find_elem_mol_type_id(mol->name);
if (mt_id == ELEM_MOL_TYPE_ID_INVALID) {
// no, simply add as a new one
ElemMolType mt = convert_molecule_type(mol, true);
bng_data->find_or_add_elem_mol_type(mt);
}
else {
// yes - extend existing components definitions
ElemMolType& mt = bng_data->get_elem_mol_type(mt_id);
// for each component of the new cplx
for (const ASTBaseNode* c: mol->components->items) {
const ASTComponentNode* comp_node = to_component_node(c);
// find whether a component with the same name is already present
// and extend its allowed states
ComponentType* ct = nullptr;
for (component_type_id_t existing_ct_id: mt.component_type_ids) {
// we must limit ourselves to the components already defined for this molecule
ComponentType* ct_existing = &bng_data->get_component_type(existing_ct_id);
if (comp_node->name == ct_existing->name) {
ct = ct_existing;
break;
}
}
if (ct != nullptr) {
// found existing component, extend its allowed states
for (const ASTBaseNode* state: comp_node->states->items) {
state_id_t state_id = convert_state_name(to_str_node(state));
ct->allowed_state_ids.insert(state_id);
}
}
else {
// there is no such component, this may happen in cases such as:
// CaMKII(l!1,Y286~0,cam!2).CaM(C~0,N~0,camkii!2).CaMKII(r!1,Y286~P)
// we must add the component to the molecule type
ComponentType ct = convert_component_type(mt.name, to_component_node(c), true);
component_type_id_t new_ct_id = bng_data->find_or_add_component_type(ct);
mt.component_type_ids.push_back(new_ct_id);
}
}
}
}
}
void SemanticAnalyzer::define_compartments_used_by_cplx_as_3d_compartments(
ASTCplxNode* cplx_node) {
// to be used only for single cplx mode
set<string> compartment_names;
if (cplx_node->compartment != nullptr && cplx_node->compartment->str != "") {
compartment_names.insert(cplx_node->compartment->str);
}
for (ASTMolNode* mol: cplx_node->mols) {
if (mol->compartment != nullptr && mol->compartment->str != "") {
compartment_names.insert(mol->compartment->str);
}
}
for (const string& n: compartment_names) {
compartment_id_t in_out_id = get_in_or_out_compartment_id(n);
if (in_out_id == COMPARTMENT_ID_INVALID) {
// is a standard compartment, add it
Compartment c;
c.name = n;
c.is_3d = true;
bng_data->add_compartment(c);
}
}
}
// returns true if conversion and semantic checks passed,
// resulting complex is stored into res
// called only from parse_single_cplx_string
bool SemanticAnalyzer::check_and_convert_single_cplx(
ParserContext* ctx_, BNGData* res_bng, Cplx& res) {
assert(ctx_ != nullptr);
assert(res_bng != nullptr);
ctx = ctx_;
bng_data = res_bng;
// define molecule types first
extend_molecule_type_definitions(ctx->single_cplx);
if (ctx->get_error_count() != 0) {
return false;
}
define_compartments_used_by_cplx_as_3d_compartments(ctx->single_cplx);
convert_cplx(ctx->single_cplx, res, true, false);
if (ctx->get_error_count() != 0) {
return false;
}
return true;
}
} /* namespace BNG */
| 33.107313 | 147 | 0.652981 | [
"vector",
"model",
"3d"
] |
6f6c7de0acf1f4003056f9f0b0a988079a3d002d | 7,204 | cpp | C++ | games/xworld3d/x3item.cpp | ziyuli/XWorld | 97db71daf1b82a179a5c3a85b58c46c9debbc247 | [
"Apache-2.0"
] | 83 | 2017-08-22T20:13:58.000Z | 2022-02-14T01:39:00.000Z | games/xworld3d/x3item.cpp | ziyuli/XWorld | 97db71daf1b82a179a5c3a85b58c46c9debbc247 | [
"Apache-2.0"
] | 15 | 2017-08-24T00:07:29.000Z | 2019-04-25T15:24:53.000Z | games/xworld3d/x3item.cpp | ziyuli/XWorld | 97db71daf1b82a179a5c3a85b58c46c9debbc247 | [
"Apache-2.0"
] | 30 | 2017-08-23T23:19:12.000Z | 2022-02-14T01:43:07.000Z | // Copyright (c) 2017 Baidu Inc. All Rights Reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "x3item.h"
namespace simulator {
namespace xworld3d {
using simulator::util::path_join;
const x3real X3Item::UNIT = FLAGS_x3_unit;
const x3real X3Item::UNIT_INV = 1.0 / FLAGS_x3_unit;
const x3real REACH_HEIGHT_THRESHOLD = X3Item::UNIT;
const x3real CAMERA_BIRD_VIEW_HEIGHT = 10.0 * X3Item::UNIT;
X3ItemPtr X3Item::create_item(const Entity& e, World& world) {
if (e.type == "agent") {
return std::make_shared<X3Agent>(e, 0.5, world);
} else {
return std::make_shared<X3Item>(e, 1, world);
}
}
X3Item::X3Item(const Entity& e, x3real scale, World& world) : e_(e) {
Pose pose(e_.loc.x * UNIT, e_.loc.y * UNIT, e_.loc.z * UNIT);
pose.rotate_z(e_.yaw);
object_ = world.load_urdf(e.asset_path, pose, scale, false, false);
object_.query_position();
b3handle_ = object_.bullet_handle();
}
Vec3 X3Item::location() const {
const Pose& pose = object_.pose();
return Vec3(pose.x(), pose.y(), pose.z());
}
void X3Item::set_speed(x3real vx, x3real vy, x3real vz) {
object_.set_speed(vx, vy, vz);
}
void X3Item::set_pose(const Pose& pose) {
object_.set_pose(pose);
}
void X3Item::set_pose_and_speed(const Pose& pose,
x3real vx, x3real vy, x3real vz) {
object_.set_pose_and_speed(pose, vx, vy, vz);
}
void X3Item::sync_entity_info() {
Pose pose = object_.pose();
std::tie(e_.loc.x, e_.loc.y, e_.loc.z) = pose.xyz();
e_.loc.scale(UNIT_INV);
e_.yaw = std::get<2>(pose.rpy());
}
void X3Item::move_underground() {
Pose pose(object_.pose());
pose.set_xyz(pose.x(), pose.y(), -2);
object_.set_pose_and_speed(pose, 0.0f, 0.0f, 0.0f);
}
void X3Item::set_entity(const Entity& e) {
e_ = e;
Pose pose(e_.loc.x * UNIT, e_.loc.y * UNIT, e_.loc.z * UNIT);
pose.rotate_z(e_.yaw);
object_.set_pose_and_speed(pose, 0.0f, 0.0f, 0.0f);
}
X3Agent::X3Agent(const Entity& e, x3real scale, World& world) :
X3Item(e, scale, world),
move_speed_norm_(FLAGS_x3_move_speed * UNIT),
jump_speed_norm_(FLAGS_x3_jump_speed * UNIT),
reaching_dist_(FLAGS_x3_collect_distance * UNIT) {}
void X3Agent::move_forward() {
Pose pose(object_.pose());
x3real yaw = std::get<2>(pose.rpy());
pose.set_xyz(pose.x(), pose.y(), 0.0f);
x3real vx = move_speed_norm_ * cos(yaw);
x3real vy = move_speed_norm_ * sin(yaw);
// x3real vz = object_.speed_z();
object_.set_pose_and_speed(pose, vx, vy, 0.0f);
}
void X3Agent::move_backward() {
Pose pose(object_.pose());
x3real yaw = std::get<2>(pose.rpy());
pose.set_xyz(pose.x(), pose.y(), 0.0f);
x3real vx = -move_speed_norm_ * cos(yaw);
x3real vy = -move_speed_norm_ * sin(yaw);
// x3real vz = object_.speed_z();
object_.set_pose_and_speed(pose, vx, vy, 0.0f);
}
void X3Agent::move_left() {
Pose pose(object_.pose());
x3real yaw = std::get<2>(pose.rpy());
pose.set_xyz(pose.x(), pose.y(), 0.0f);
x3real vx = -move_speed_norm_ * sin(yaw);
x3real vy = move_speed_norm_ * cos(yaw);
// x3real vz = object_.speed_z();
object_.set_pose_and_speed(pose, vx, vy, 0.0f);
}
void X3Agent::move_right() {
Pose pose(object_.pose());
x3real yaw = std::get<2>(pose.rpy());
pose.set_xyz(pose.x(), pose.y(), 0.0f);
x3real vx = move_speed_norm_ * sin(yaw);
x3real vy = -move_speed_norm_ * cos(yaw);
// x3real vz = object_.speed_z();
object_.set_pose_and_speed(pose, vx, vy, 0.0f);
}
void X3Agent::turn_left() {
Pose pose(object_.pose());
pose.set_xyz(pose.x(), pose.y(), 0.0f);
pose.rotate_z(FLAGS_x3_turning_rad);
// x3real vz = object_.speed_z();
object_.set_pose_and_speed(pose, 0.0f, 0.0f, 0.0f);
}
void X3Agent::turn_right() {
Pose pose(object_.pose());
pose.set_xyz(pose.x(), pose.y(), 0.0f);
pose.rotate_z(-FLAGS_x3_turning_rad);
// x3real vz = object_.speed_z();
object_.set_pose_and_speed(pose, 0.0f, 0.0f, 0.0f);
}
void X3Agent::jump() {
if (fabs(pose().z()) < EPSILON) {
object_.set_speed(0.0f, 0.0f, jump_speed_norm_);
}
}
void X3Agent::clear_move() {
Pose pose(object_.pose());
object_.set_pose_and_speed(pose, 0.0f, 0.0f, 0.0f);
}
X3ItemPtr X3Agent::collect_item(const std::map<std::string, X3ItemPtr>& items,
const std::string& type) {
X3ItemPtr item = nullptr;
object_.set_speed(0.0f, 0.0f, 0.0f);
// the angle between the agent's facing direction and
// the direction from the agent to the item should be less than 45 degrees
x3real best_score = 0.707; // 45 degrees is the minimum
x3real score;
for (auto& kv : items) {
if (kv.second->type() == type) {
score = reach_test(kv.second->pose());
if (score > best_score) {
item = kv.second;
best_score = score;
}
}
}
return item;
}
x3real X3Agent::reach_test(const Pose& pose) {
const Pose self = object_.pose();
x3real yaw = std::get<2>(pose.rpy());
x3real dir_x = cos(yaw);
x3real dir_y = sin(yaw);
x3real dx = pose.x() - self.x();
x3real dy = pose.y() - self.y();
x3real dz = pose.z() - self.z();
x3real d = sqrt(dx * dx + dy * dy);
x3real reaching_score = -1; // lower end of cos range
if (d < reaching_dist_ && dz < REACH_HEIGHT_THRESHOLD) {
dx /= d;
dy /= d;
reaching_score = dx * dir_x + dy * dir_y;
}
return reaching_score;
}
/********************************** X3Camera **********************************/
X3Camera::X3Camera(World& world, int img_height, int img_width) :
camera_(world.new_camera_free_float(img_width, img_height, "camera")),
item_(NULL) {}
void X3Camera::attach_item(X3Item* item) {
if (item && item_ != item) {
item_ = item;
}
}
void X3Camera::update(bool bird_view) {
// TODO: to support rendering using detached camera
CHECK(item_) << "camera is detached";
Pose p = item_->pose();
if (!bird_view) {
x3real dir_x, dir_y;
item_->get_direction(dir_x, dir_y);
camera_.move_and_look_at(p.x(), p.y(), p.z() + 1.5 * X3Item::UNIT,
p.x() + dir_x, p.y() + dir_y, p.z() + 1.0 * X3Item::UNIT);
} else {
// bird view
camera_.move_and_look_at(p.x(), p.y(), CAMERA_BIRD_VIEW_HEIGHT, p.x(), p.y(), p.z());
}
}
roboschool::RenderResult X3Camera::render(X3Item* item, bool bird_view) {
attach_item(item);
update(bird_view);
return camera_.render(false, false, false);
}
}} // simulator::xworld3d
| 31.876106 | 93 | 0.621044 | [
"render"
] |
6f7166db0d99fd80f0b711b540f45a6499ef52d5 | 20,589 | cpp | C++ | source/lowlevel/bralgorithm.cpp | Olde-Skuul/burgerlib | 80848a4dfa17c5c05095ecea14a9bd87f86dfb9d | [
"Zlib"
] | 115 | 2015-01-18T17:29:30.000Z | 2022-01-30T04:31:48.000Z | source/lowlevel/bralgorithm.cpp | Olde-Skuul/burgerlib | 80848a4dfa17c5c05095ecea14a9bd87f86dfb9d | [
"Zlib"
] | 9 | 2015-01-22T04:53:38.000Z | 2015-01-31T13:52:40.000Z | source/lowlevel/bralgorithm.cpp | Olde-Skuul/burgerlib | 80848a4dfa17c5c05095ecea14a9bd87f86dfb9d | [
"Zlib"
] | 9 | 2015-01-23T20:06:46.000Z | 2020-05-20T16:06:00.000Z | /***************************************
Templates to support "algorithm"
Copyright (c) 1995-2018 by Rebecca Ann Heineman <becky@burgerbecky.com>
It is released under an MIT Open Source license. Please see LICENSE for
license details. Yes, you can use it in a commercial title without paying
anything, just give me a credit.
Please? It's not like I'm asking you for money!
***************************************/
#include "bralgorithm.h"
/*! ************************************
\namespace Burger::type_traits
\brief Semi-private template classes for type checking.
For templates that requite checking of types, many helper structures are in
this namespace to prevent pollution of the Burger namespace.
***************************************/
/*! ************************************
\typedef Burger::type_traits::yes_type
\brief Type used for templates to return 1.
This type resolves to sizeof(char) to force sizeof( \ref
type_traits::yes_type) != sizeof( \ref type_traits::no_type)
\sa type_traits::no_type
***************************************/
/*! ************************************
\struct Burger::type_traits::no_type
\brief Type used for templates to return 0.
This type resolves to (sizeof(char) * 8) to force sizeof( \ref
type_traits::yes_type) != sizeof( \ref type_traits::no_type)
\sa type_traits::yes_type
***************************************/
/*! ************************************
\struct Burger::type_traits::size_type
\brief Type used for templates the require a specific size.
This type resolves to an empty struct that could be used to force a template
to only instantiate with a specific data size. The struct itself is not
meant to be used.
***************************************/
/*! ************************************
\struct Burger::conditional
\brief Select a type based if the conditional is true or false.
The first parameter is a conditional boolean. This will be evaluated as true or
false. The second parameter is the type used if the condition is true and the
third parameter is the type used if the condition is false.
\note This is functionally the same as std::conditional<>
\tparam B Condition to test for ``true``.
\tparam T Type of the result if condition is ``true``.
\tparam F Type of the result if condition is ``false``.
\sa enable_if
***************************************/
/*! ************************************
\struct Burger::enable_if
\brief Create typedef type if condition is true.
The first parameter is a conditional boolean. This will be evaluated as true
or false. The second parameter is the type of the resulting typedef.
If the test is successful, typedef type exists. If not, the typedef does
not exist, causing template instantiation failure.
This is a duplicate of std::enable_if.
\note: Not supported on Open WATCOM
\tparam B Condition to test for ``true``.
\tparam T Type of the result, void is the default.
\sa disable_if
***************************************/
/*! ************************************
\struct Burger::disable_if
\brief Create typedef type if condition is false.
The first parameter conditional boolean. This will be evaluated as true or
false. The second parameter is the type of the resulting typedef.
If the test failed, typedef type exists. If it succeeded, the typedef does
not exist, causing template instantiation failure.
\note: Not supported on Open WATCOM
\tparam B Condition to test for ``false``.
\tparam T Type of the result, void is the default.
\sa enable_if
***************************************/
/*! ************************************
\struct Burger::integral_constant
\brief Wrap a static constant of specified type.
A template to wrap a static constant of a specified type so templates can
resolve the value at compile time. It's the base class for type traits.
\tparam T Type of wrapped value
\tparam _Value value to wrap.
\sa bool_constant
***************************************/
/*! ************************************
\fn Burger::integral_constant::operator T() const
\brief Function to return the encapsulated value.
\return The encapsulated value.
***************************************/
/*! ************************************
\fn Burger::integral_constant::operator ()() const
\brief Function to return the encapsulated value.
\return The encapsulated value.
***************************************/
/*! ************************************
\struct Burger::bool_constant
\brief Wrap a static bool constant.
A template to wrap a static bool constant so templates can resolve the value
at compile time.
This is an implementation from C++17.
\tparam _Value value to wrap.
\sa integral_constant
***************************************/
/*! ************************************
\typedef Burger::true_type
\brief Static bool constant of true.
A bool_constant set to true.
\sa bool_constant or false_type
***************************************/
/*! ************************************
\typedef Burger::false_type
\brief Static bool constant of false.
A bool_constant set to false.
\sa bool_constant or true_type
***************************************/
/*! ************************************
\struct Burger::alignment_of
\brief Determine the alignment of an object.
A template to obtain the alignment value of an object.
\tparam T Type of object to test
Example of use:
\code
printf("Alignment of int is %u", Burger::alignment_of<int>::value);
\endcode
\sa integral_constant
***************************************/
/*! ************************************
\struct Burger::ice_and
\brief Test for all values being true.
A helper template that sets its output to true or false based on all inputs
being true. It's implemented as a compile time constant for use in other
templates.
Example of use:
\code
// iResult is false
int iResult = Burger::ice_and<false, false>::value;
// iResult is true
iResult = Burger::ice_and<true, true>::value;
// iResult is true
iResult = Burger::ice_and<true, true, true>::value;
// iResult is false
iResult = Burger::ice_and<true, false, true>::value;
\endcode
***************************************/
/*! ************************************
\struct Burger::ice_and<true, true, true, true, true, true, true>
Helper for \ref Burger::ice_and
\sa Burger::ice_and
***************************************/
/*! ************************************
\struct Burger::ice_or
\brief Test for any value being true.
A helper template that sets its output to true or false based on any input
being true. It's implemented as a compile time constant for use in other
templates.
Example of use:
\code
// iResult is false
int iResult = Burger::ice_or<false, false>::value;
// iResult is true
iResult = Burger::ice_or<true, true>::value;
// iResult is true
iResult = Burger::ice_or<true, true, true>::value;
// iResult is true
iResult = Burger::ice_or<true, false, true>::value;
\endcode
***************************************/
/*! ************************************
\struct Burger::ice_or<false, false, false, false, false, false, false>
Helper for \ref Burger::ice_or
\sa Burger::ice_or
***************************************/
/*! ************************************
\struct Burger::ice_eq
\brief Test for equality
A helper template that sets its output to true if both inputs are the same
integer value. It's implemented as a compile time constant for use in other
templates.
Example of use:
\code
// iResult is true
int iResult = Burger::ice_eq<false, false>::value;
// iResult is false
iResult = Burger::ice_eq<true, false>::value;
\endcode
***************************************/
/*! ************************************
\struct Burger::ice_ne
\brief Test for inequality
A helper template that sets its output to true if both inputs are different
integer values. It's implemented as a compile time constant for use in other
templates.
Example of use:
\code
// iResult is false
int iResult = Burger::ice_ne<false, false>::value;
// iResult is true
iResult = Burger::ice_ne<true, false>::value;
\endcode
***************************************/
/*! ************************************
\struct Burger::ice_not
\brief Reverse boolean input
A helper template that sets its output to true if the input is false and
vice versa. It's implemented as a compile time constant for use in other
templates.
Example of use:
\code
// iResult is true
int iResult = Burger::ice_not<false>::value;
// iResult is false
iResult = Burger::ice_not<true>::value;
\endcode
***************************************/
/*! ************************************
\struct Burger::is_same
\brief Determine if two objects are the same type.
A template that sets its value to true if both classes are the same type.
\tparam T Type of first object to test
\tparam U Type of second object to test
Example of use:
\code
printf("int and float are not the same %u", Burger::is_same<int,
float>::value);
printf("int and int are the same %u", Burger::is_same<int, int>::value);
\endcode
\sa is_same<T,T>
***************************************/
/*! ************************************
\struct Burger::is_same<T,T>
\brief Determine if two objects are the same type.
A template that sets its value to true if both classes are the same type.
\tparam T Type that matched
Example of use:
\code
printf("int and float are not the same %u", Burger::is_same<int,
float>::value);
printf("int and int are the same %u", Burger::is_same<int,int>::value);
\endcode
\sa is_same
***************************************/
/*! ************************************
\struct Burger::remove_const
\brief Remove the const qualifier from a type.
A template that sets its type to be the declared type without the const
keyword.
\tparam T Type to remove the const keyword.
\sa remove_const<const T>
***************************************/
/*! ************************************
\struct Burger::remove_const<const T>
\brief Remove the const qualifier from a type.
A template that sets its type to be the declared type without the const
keyword.
\tparam T Type to remove the const keyword.
\sa remove_const, remove_volatile or remove_cv
***************************************/
/*! ************************************
\struct Burger::remove_volatile
\brief Remove the volatile qualifier from a type.
A template that sets its type to be the declared type without the volatile
keyword.
\tparam T Type to remove the volatile keyword.
\sa remove_volatile<const T>
***************************************/
/*! ************************************
\struct Burger::remove_volatile<volatile T>
\brief Remove the volatile qualifier from a type.
A template that sets its type to be the declared type without the volatile
keyword.
\tparam T Type to remove the volatile keyword.
\sa remove_volatile, remove_const or remove_cv
***************************************/
/*! ************************************
\struct Burger::remove_cv
\brief Remove the volatile and const qualifier from a type.
A template that sets its type to be the declared type without the volatile
or const keywords.
\tparam T Type to remove the volatile or const keywords.
\sa remove_volatile or remove_const
***************************************/
/*! ************************************
\struct Burger::add_const
\brief Add the const qualifier to a type.
A template that sets its type to be the declared type with the const
keyword.
\tparam T Type to add the const keyword.
\sa add_volatile or add_cv
***************************************/
/*! ************************************
\struct Burger::add_volatile
\brief Add the volatile qualifier to a type.
A template that sets its type to be the declared type with the volatile
keyword.
\tparam T Type to add the volatile keyword.
\sa add_const or add_cv
***************************************/
/*! ************************************
\struct Burger::add_cv
\brief Add the const and volatile qualifier to a type.
A template that sets its type to be the declared type with the const and
volatile keywords.
\tparam T Type to add the const and volatile keywords.
\sa add_const or add_volatile
***************************************/
/*! ************************************
\struct Burger::remove_reference
\brief Remove the reference qualifier to a type.
A template that sets its type to be the declared type without references.
\tparam T Type to remove reference.
\sa remove_reference<T&> or remove_reference<T&&>
***************************************/
/*! ************************************
\struct Burger::remove_reference<T&>
\brief Remove the reference qualifier to a type.
A template that sets its type to be the declared type without references.
\tparam T Type to remove reference.
\sa remove_reference or remove_reference<T&&>
***************************************/
/*! ************************************
\struct Burger::remove_reference<T&&>
\brief Remove the reference qualifier to a type.
A template that sets its type to be the declared type without references.
\tparam T Type to remove reference.
\sa remove_reference or remove_reference<T&>
***************************************/
/*! ************************************
\struct Burger::is_const
\brief Test if a type is const.
A template that checks a type if it has the keyword const.
This instantiation derives from \ref false_type
\tparam T Type to check.
\sa is_const<const T> or false_type
***************************************/
/*! ************************************
\struct Burger::is_const<const T>
\brief Test if a type is const.
A template that checks a type if it has the keyword const.
This instantiation derives from \ref true_type
\tparam T Type to check.
\sa is_const or true_type
***************************************/
/*! ************************************
\struct Burger::is_volatile
\brief Test if a type is volatile.
A template that checks a type if it has the keyword volatile.
This instantiation derives from \ref false_type
\tparam T Type to check.
\sa is_volatile<volatile T> or false_type
***************************************/
/*! ************************************
\struct Burger::is_volatile<volatile T>
\brief Test if a type is volatile.
A template that checks a type if it has the keyword volatile.
This instantiation derives from \ref true_type
\tparam T Type to check.
\sa is_volatile or true_type
***************************************/
/*! ************************************
\struct Burger::is_floating_point
\brief Test if a type is a float.
A template that checks a type if it is a floating point integral.
\tparam T Type to check.
\sa false_type or true_type
***************************************/
/*! ************************************
\struct Burger::is_function
\brief Test if a type is a function pointer.
A template that checks a type if it is a function pointer.
\tparam T Type to check.
\sa false_type or true_type
***************************************/
/*! ************************************
\fn Burger::round_up_pointer(T*,uintptr_t uSize)
\brief Align a pointer.
A template to force the alignment value of a pointer. The template will use
a specified alignment or auto detect the alignment of the data referenced by
the pointer.
\tparam T Pointer of object to align.
\param pInput Pointer to force alignment
\param uSize Power of 2 alignment to use.
\return Newly aligned pointer.
Example of use:
\code
// Pointer is already aligned
char *pWork;
pWork = reinterpret_cast<char *>(0);
pWork = Burger::round_up_pointer(pWork,8);
pWork == reinterpret_cast<char *>(0);
// Force 8 byte alignment
pWork = reinterpret_cast<char *>(1);
pWork = Burger::round_up_pointer(pWork,8);
pWork == reinterpret_cast<char *>(8);
// Force alignment of data automatically by using the alignment of the data
//of the pointer.
pWork = reinterpret_cast<uint32_t *>(1);
pWork = Burger::round_up_pointer(pWork);
pWork == reinterpret_cast<char *>(4);
\endcode
\sa alignment_of
***************************************/
/*! ************************************
\struct Burger::default_delete
\brief Delete an object using delete
A template to pass to \ref unique_ptr to delete the object with std::delete.
\tparam T Type of object to delete
\sa unique_ptr
***************************************/
/*! ************************************
\struct Burger::default_delete_array
\brief Delete an object using delete[]
A template to pass to \ref unique_ptr to delete the object with
std::delete[].
\note This is explicitly used to maintain compatibility with compilers that
don't support SFINAE.
\tparam T Type of object to delete with std::delete[]
\sa unique_ptr
***************************************/
/*! ************************************
\struct Burger::Base_delete
\brief Delete an object using Burger::Delete()
A template to pass to \ref unique_ptr to delete the object with
Burger::Delete.
Most classes in Burgerlib use the New allocator to use the Burgerlib memory
manager, as such they need to be released using the Burger::Delete
function.
\tparam T Type of object to delete with Burger::Delete()
\sa unique_ptr or Burger::Delete()
***************************************/
/*! ************************************
\struct Burger::Free_delete
\brief Delete an object using Burger::Free()
A template to pass to \ref unique_ptr to delete the object with
Burger::Free().
When memory is allocated with Burger::Alloc(), it should be released with
Burger::Free(), this deleter handles the case.
\tparam T Type of object to delete with Burger::Free()
\sa unique_ptr or Burger::Free()
***************************************/
/*! ************************************
\struct Burger::unique_ptr
\brief Simplified implementation of std::unique_ptr
Burger::unique_ptr is a smart pointer that owns and manages a pointer to an
object and disposes of the object when this class goes out of scope.
This class is based on
[std::unique_ptr](https://en.cppreference.com/w/cpp/memory/unique_ptr)
\note This class can be moved, but not copied.
\tparam T Type of object to maintain a pointer to.
\tparam Deleter Type of object to delete the object.
\sa default_delete, Free_delete or Base_delete
***************************************/
/*! ************************************
\fn T Burger::Min(T A,T B)
\brief Return the lesser of two objects
A template to compare the two input values and return the lesser of the two.
\tparam T Type of the two values
\param A First value to test
\param B Second value to test
\return The lesser of the two inputs
\sa Max(T,T)
***************************************/
/*! ************************************
\fn T Burger::Max(T A,T B)
\brief Return the greater of two objects
A template to compare the two input values and return the greater of the
two.
\tparam T Type of the two values
\param A First value to test
\param B Second value to test
\return The greater of the two inputs
\sa Min(T,T)
***************************************/
| 26.128173 | 83 | 0.558648 | [
"object"
] |
4cf9a5099823db6c368544e330afdff19929cfd4 | 761 | cpp | C++ | AtCoder/abc155/c/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | null | null | null | AtCoder/abc155/c/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | 1 | 2021-10-19T08:47:23.000Z | 2022-03-07T05:23:56.000Z | AtCoder/abc155/c/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
int N; cin >> N;
vector<string> S(N, "");
int MX = 0;
for (int i = 0; i < N; ++i) {
cin >> S[i];
}
sort(S.begin(), S.end());
string str = ""; int cnt = 0;
vector<pair<string, int>> ans;
for (int i = 0; i < N; ++i) {
if (str != S[i]) {
if (str != "") ans.push_back(make_pair(str, cnt));
MX = max(MX, cnt);
str = S[i];
cnt = 1;
}
else cnt++;
}
ans.push_back(make_pair(str, cnt));
MX = max(MX, cnt);
for (int k = 0; k < ans.size(); ++k) {
if (ans[k].second == MX)
cout << ans[k].first << endl;
}
} | 23.78125 | 62 | 0.442838 | [
"vector"
] |
9801d5bbe782c41471f56668c0d267621096b9a7 | 3,491 | cpp | C++ | src/life/Life3d.cpp | zibas/futz | 83fc0e1a7489940bb55e2db6ccc8ca7d1ac0719f | [
"MIT"
] | 4 | 2019-01-30T00:14:29.000Z | 2020-05-15T01:14:28.000Z | src/life/Life3d.cpp | zibas/futz | 83fc0e1a7489940bb55e2db6ccc8ca7d1ac0719f | [
"MIT"
] | null | null | null | src/life/Life3d.cpp | zibas/futz | 83fc0e1a7489940bb55e2db6ccc8ca7d1ac0719f | [
"MIT"
] | null | null | null | #include "Life3d.h"
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include "Futz.h"
#include "input/InputEventQueue.h"
#include "core/components/DrawAxis.h"
Life3d::Life3d() {
width = 100;
height = 100;
depth = 1;
cellClock = 0;
cellPeriod = 0.3;
speed = 0.5;
turnSpeed = 20;
srand(time(NULL));
Futz* futz = Futz::Instance();
char* file = (char*)"assets/cell.obj";
model = futz->LoadModel(file);
model->Load();
grid = life_init(width, height, depth);
for (int i = 0; i < width*height*depth; i++) {
cellNodes[i] = new Node();
cellNodes[i]->AddModel(model);
cellNodes[i]->transform.SetScale(0.5);
cellNodes[i]->useLighting = false;
//cellNodes[i]->enabled = false;
futz->scene.AddNode(cellNodes[i]);
}
/*
Node* center = new Node();
DrawAxis* drawAxis = new DrawAxis();
center->AddComponent((Component*)drawAxis);
Futz::Instance()->scene.AddNode(center);
*/
Randomize();
ArrangeCells();
}
void Life3d::Init(int argc, char** argv) {
//life_read_lif(grid, argv[1]);
}
void Life3d::UpdateLoop() {
this->HandleInput();
cellClock += Futz::Instance()->time.delta;
if (cellClock >= cellPeriod) {
life_next_gen(grid);
ArrangeCells();
cellClock = 0;
}
}
void Life3d::ArrangeCells() {
int i, x, y, z;
i = 0;
for (y = 0; y < grid->y; y++) {
for (x = 0; x < grid->x; x++)
for (z = 0; z < grid->z; z++)
{
if (life_is_alive(grid, x, y, z)) {
cellNodes[i]->transform.SetPosition((x - grid->x / 2), (y - grid->y / 2), (z - grid->z / 2));
cellNodes[i]->enabled = true;
}
else {
cellNodes[i]->enabled = false;
}
i++;
}
}
}
void Life3d::Randomize() {
int i, x, y, z;
for (y = 0; y < grid->y; y++) {
for (x = 0; x < grid->x; x++) {
for (z = 0; z < grid->z; z++)
{
if (rand() % 2 == 1) {
life_set_alive(grid, x, y, z);
}
else {
life_set_dead(grid, x, y, z);
}
}
}
}
}
void Life3d::RenderLoop()
{
Futz::Instance()->renderer->DefaultLighting();
}
void Life3d::HandleInput() {
Futz* futz = Futz::Instance();
futzInputEvent* event = futz->inputEventQueue.Pop();
double deltaX = 0;
double deltaY = 0;
Vector3 rotateDelta;
rotateDelta.x = 1;
rotateDelta.y = 0;
rotateDelta.z = 0;
if (futz->input.OnMouseMove()) {
deltaX = futz->input.mouseState.pixelX - futz->input.lastMouseState.pixelX;
deltaY = futz->input.mouseState.pixelY - futz->input.lastMouseState.pixelY;
rotateDelta.x = -deltaY * futz->time.delta * turnSpeed;
rotateDelta.y = -deltaX * futz->time.delta * turnSpeed;
futz->camera.Rotate(rotateDelta);
}
if (futz->input.IsDown(FUTZ_LEFT)) {
futz->camera.MoveRight(-speed);
}
if (futz->input.IsDown(FUTZ_RIGHT)) {
futz->camera.MoveRight(speed);
}
if (futz->input.IsDown(FUTZ_UP)) {
futz->camera.MoveForward(speed);
}
if (futz->input.IsDown(FUTZ_DOWN)) {
futz->camera.MoveForward(-speed);
}
if (futz->input.IsDown('q')) {
futz->camera.MoveUp(speed);
}
if (futz->input.IsDown('e')) {
futz->camera.MoveUp(-speed);
}
if (futz->input.OnDown('f')) {
futz->platform->ToggleFullscreen();
}
if (futz->input.OnDown('p')) {
life_print(grid);
}
if (futz->input.OnDown('r')) {
Randomize();
ArrangeCells();
}
if (futz->input.OnDown('n')) {
life_next_gen(grid);
ArrangeCells();
}
if (futz->input.OnDown(FUTZ_ASCEND)) {
cellPeriod += 0.1;
}
if (futz->input.OnDown(FUTZ_DESCEND)) {
cellPeriod -= 0.1;
}
if (futz->input.OnDown(FUTZ_BACK)) {
exit(0);
}
}
Life3d::~Life3d() {}
| 19.61236 | 98 | 0.610713 | [
"model",
"transform"
] |
980bf92a0698531deef25a3c0ed88c97c1cd04a0 | 2,598 | cpp | C++ | 2018/1027_tenka1-2018/E.cpp | kazunetakahashi/atcoder | 16ce65829ccc180260b19316e276c2fcf6606c53 | [
"MIT"
] | 7 | 2019-03-24T14:06:29.000Z | 2020-09-17T21:16:36.000Z | 2018/1027_tenka1-2018/E.cpp | kazunetakahashi/atcoder | 16ce65829ccc180260b19316e276c2fcf6606c53 | [
"MIT"
] | null | null | null | 2018/1027_tenka1-2018/E.cpp | kazunetakahashi/atcoder | 16ce65829ccc180260b19316e276c2fcf6606c53 | [
"MIT"
] | 1 | 2020-07-22T17:27:09.000Z | 2020-07-22T17:27:09.000Z | /**
* File : E.cpp
* Author : Kazune Takahashi
* Created : 2018-10-27 22:01:40
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
const int C = 610;
// const ll M = 1000000007;
int H, W;
string S[310];
bool X[C][C];
int value(int x, int y)
{
return (0 <= x && x < C && 0 <= y && y < C && X[x][y]);
}
int main()
{
cin >> H >> W;
for (auto i = 0; i < H; i++)
{
cin >> S[i];
}
fill(&X[0][0], &X[0][0] + C * C, false);
for (auto i = 0; i < H; i++)
{
for (auto j = 0; j < W; j++)
{
if (S[i][j] == '#')
{
X[i + j][i - j + C / 2] = true;
}
}
}
ll ans = 0;
for (auto i = 0; i < C; i++)
{
for (auto j = 0; j < C; j++)
{
for (auto l = 1; l < C; l++)
{
int cnt_x = 0;
cnt_x += value(i - l, j);
cnt_x += value(i + l, j);
int cnt_y = 0;
cnt_y += value(i, j - l);
cnt_y += value(i, j + l);
ans += cnt_x * cnt_y;
if (H < 10 && cnt_x > 0 && cnt_y > 0)
{
cerr << "now: (" << i << ", " << j - C / 2 << ")" << endl;
if (value(i - l, j) > 0)
{
cerr << "(" << i - l << ", " << j - C / 2 << ")" << endl;
}
if (value(i + l, j) > 0)
{
cerr << "(" << i + l << ", " << j - C / 2 << ")" << endl;
}
if (value(i, j - l) > 0)
{
cerr << "(" << i << ", " << j - l - C / 2 << ")" << endl;
}
if (value(i, j + l) > 0)
{
cerr << "(" << i << ", " << j + l - C / 2 << ")" << endl;
}
}
}
}
}
cout << ans << endl;
} | 24.509434 | 103 | 0.445343 | [
"vector"
] |
98144b7be4905d7bef586572c6faa73e1e80d2ea | 1,364 | cc | C++ | core/http.cc | theanarkh/No.js | 0a1a72ada412a46de8994691b9b490092e515157 | [
"MIT"
] | 42 | 2021-06-09T02:25:35.000Z | 2022-02-16T06:12:44.000Z | core/http.cc | tangkepeng/No.js | 5569dec2d416118cc33b1209c9d4569e51094921 | [
"MIT"
] | null | null | null | core/http.cc | tangkepeng/No.js | 5569dec2d416118cc33b1209c9d4569e51094921 | [
"MIT"
] | 2 | 2021-09-19T02:24:21.000Z | 2021-10-07T13:28:42.000Z | #include "http.h"
void No::HTTP::Parser::New(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetEnvByContext(args.GetIsolate()->GetCurrentContext());
new Parser(env, args.This());
}
void No::HTTP::Parser::Parse(const char * data, size_t len) {
// string str;
// str.append(data, len);
// cout<<str;
httpparser->parse(data, len);
// httpparser->print();
}
void No::HTTP::Parser::Parse(const FunctionCallbackInfo<Value>& args) {
Parser * parser = (Parser *)unwrap(args.This());
Local<Uint8Array> uint8Array = args[0].As<Uint8Array>();
Local<ArrayBuffer> arrayBuffer = uint8Array->Buffer();
std::shared_ptr<BackingStore> backing = arrayBuffer->GetBackingStore();
const char * data = (const char * )backing->Data();
parser->Parse(data, strlen(data));
}
void No::HTTP::Init(Isolate* isolate, Local<Object> target) {
Local<FunctionTemplate> parser = FunctionTemplate::New(isolate, No::HTTP::Parser::New);
parser->InstanceTemplate()->SetInternalFieldCount(1);
parser->SetClassName(newStringToLcal(isolate, "HTTPParser"));
parser->PrototypeTemplate()->Set(newStringToLcal(isolate, "parse"), FunctionTemplate::New(isolate, No::HTTP::Parser::Parse));
setObjectValue(isolate, target, "HTTPParser", parser->GetFunction(isolate->GetCurrentContext()).ToLocalChecked());
}
| 38.971429 | 129 | 0.697214 | [
"object"
] |
981da0ccb8fd6ec3ec3a349f4309c6b6a62d7a01 | 2,880 | hpp | C++ | include/raycaster/twist.hpp | yycho0108/PCLRayCaster | b80fda4c5357a7777e4e9ea31f36fc09b6502312 | [
"MIT"
] | null | null | null | include/raycaster/twist.hpp | yycho0108/PCLRayCaster | b80fda4c5357a7777e4e9ea31f36fc09b6502312 | [
"MIT"
] | null | null | null | include/raycaster/twist.hpp | yycho0108/PCLRayCaster | b80fda4c5357a7777e4e9ea31f36fc09b6502312 | [
"MIT"
] | null | null | null | #pragma once
#include <Eigen/Core>
#include <Eigen/Geometry>
template <class Scalar>
class Twist {
using Vector3x = Eigen::Matrix<Scalar, 3, 1>;
public:
Twist() {}
Twist(const Vector3x& rotation, const Vector3x& translation)
: rotation_(rotation), translation_(translation) {}
Twist(const Twist& twist)
: rotation_(twist.rotation_), translation_(twist.translation_) {}
const Vector3x& Translation() const { return translation_; }
Vector3x& Translation() { return translation_; }
const Vector3x& Rotation() const { return rotation_; }
Vector3x& Rotation() { return rotation_; }
private:
Vector3x rotation_;
Vector3x translation_;
};
template <class Scalar>
Twist<Scalar> operator*(const Twist<Scalar>& twist, const float scale) {
return Twist<Scalar>{twist.Rotation() * scale, twist.Translation() * scale};
}
template <class Scalar>
Twist<Scalar> operator*(const float scale, const Twist<Scalar>& twist) {
return Twist<Scalar>{twist.Rotation() * scale, twist.Translation() * scale};
}
/**
* se3 -> SE3
*/
template <class Scalar>
Eigen::Transform<Scalar, 3, Eigen::Isometry> Exp(const Twist<Scalar>& T) {
const auto& w = T.Rotation();
const auto& v = T.Translation();
const float t2 = w.dot(w);
const float t = std::sqrt(t2);
const bool is_small_angle = (t <= std::numeric_limits<float>::epsilon());
const Eigen::AngleAxis<Scalar> rotation(t, is_small_angle ? w : w / t);
if (is_small_angle) {
const Eigen::Matrix<Scalar, 3, 1> position = v + 0.5 * w.cross(v);
return Eigen::Translation<Scalar, 3>{position} * rotation;
}
const float ct = std::cos(t);
const float st = std::sin(t);
const float awxv = (1.0 - ct) / t2;
const float av = (st / t);
const float aw = (1.0 - av) / t2;
const Eigen::Matrix<Scalar, 3, 1> position =
av * v + aw * w.dot(v) * w + awxv * w.cross(v);
return Eigen::Translation<Scalar, 3>{position} * rotation;
}
/**
* SE3 -> se3
*/
template <class Scalar>
Twist<Scalar> Log(const Eigen::Transform<Scalar, 3, Eigen::Isometry>& T) {
Twist<Scalar> out;
// Extract components.
const Eigen::AngleAxis<Scalar> axa{T.linear()};
const Eigen::Matrix<Scalar, 3, 1>& w = axa.axis() * axa.angle();
const Eigen::Matrix<Scalar, 3, 1>& p = T.translation();
// Set intermediate values.
const float t = axa.angle();
const float t2 = t * t;
const bool is_small_angle = (t <= std::numeric_limits<float>::epsilon());
if (is_small_angle) {
const Eigen::Matrix<Scalar, 3, 1>& v = p + 0.5 * p.cross(w);
return Twist<Scalar>{w, v};
}
const float st = std::sin(t);
const float ct = std::cos(t);
const float alpha = (t * st / (2.0 * (1.0 - ct)));
const float beta = (1.0 / t2 - st / (2.0 * t * (1.0 - ct)));
const Eigen::Matrix<Scalar, 3, 1>& v =
(alpha * p - 0.5 * w.cross(p) + beta * w.dot(p) * w);
return Twist<Scalar>{w, v};
}
| 28.514851 | 78 | 0.642708 | [
"geometry",
"transform"
] |
98232ad4817133e8a168451e2ee22da4b17a1136 | 2,362 | cpp | C++ | source/segmentation/Segmentation.cpp | intive/StudyBox_CV | 5ea9b643177667ebdc9809f28db6705b308409f4 | [
"Apache-2.0"
] | 3 | 2016-03-07T09:40:49.000Z | 2018-05-29T16:13:10.000Z | source/segmentation/Segmentation.cpp | intive/StudyBox_CV | 5ea9b643177667ebdc9809f28db6705b308409f4 | [
"Apache-2.0"
] | 38 | 2016-03-06T20:44:46.000Z | 2016-05-18T19:16:40.000Z | source/segmentation/Segmentation.cpp | blstream/StudyBox_CV | 5ea9b643177667ebdc9809f28db6705b308409f4 | [
"Apache-2.0"
] | 10 | 2016-03-10T21:30:18.000Z | 2016-04-20T07:01:12.000Z | #include "Segmentation.hpp"
Segmentation::Segmentation()
: usedScale(1)
, morphEllipseSize(1, 1)
, morphRectSize(1, 1)
{
}
void Segmentation::SetImage(const cv::Mat& image)
{
if (image.type() != CV_8UC1)
cv::cvtColor(image, grayImage, CV_BGR2GRAY);
else
grayImage = image;
}
void Segmentation::ScaleImage(size_t scale)
{
if (scale < 1)
return;
usedScale = scale;
for (size_t i = 1; i < scale; i++)
cv::pyrDown(grayImage, grayImage);
}
void Segmentation::SetMorphEllipseSize(const cv::Size& mes)
{
morphEllipseSize = mes;
}
void Segmentation::SetMorphRectSize(const cv::Size& mrs)
{
morphRectSize = mrs;
}
std::vector<Rectangle> Segmentation::CreateRectangles()
{
Algorithm();
size_t s = usedScale > 1 ? 1 << (usedScale - 1) : 1;
std::vector<Rectangle> rectnagles;
if (contours.empty())
return rectnagles;
for (int idx = 0; idx >= 0; idx = hierarchy[idx][0])
{
Rectangle rect = Rectangle(minAreaRect(contours[idx]));
rectnagles.push_back(rect * s);
}
return rectnagles;
}
std::vector<RotatedRectangle> Segmentation::CreateRotatedRectangles()
{
Algorithm();
size_t s = usedScale > 1 ? 1 << (usedScale - 1) : 1;
std::vector<RotatedRectangle> rotatedRectangles;
if (contours.empty())
return rotatedRectangles;
for (int idx = 0; idx >= 0; idx = hierarchy[idx][0])
{
cv::RotatedRect rr = minAreaRect(contours[idx]);
cv::Point2f p[4];
rr.points(p);
std::cout << rr.size << std::endl;
rotatedRectangles.push_back(RotatedRectangle(p[0], p[1], p[2], p[3]) * s);
}
return rotatedRectangles;
}
void Segmentation::Algorithm()
{
contours.clear(); hierarchy.clear();
cv::Mat morphKernel = cv::getStructuringElement(cv::MORPH_ELLIPSE, morphEllipseSize);
cv::Mat morphGradient;
morphologyEx(grayImage, morphGradient, cv::MORPH_GRADIENT, morphKernel);
cv::Mat binarize;
cv::threshold(morphGradient, binarize, 0.0, 255.0, cv::THRESH_BINARY | cv::THRESH_OTSU);
morphKernel = cv::getStructuringElement(cv::MORPH_RECT, morphRectSize);
cv::Mat chor;
cv::morphologyEx(binarize, chor, cv::MORPH_CLOSE, morphKernel);
findContours(chor, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0));
}
| 23.858586 | 100 | 0.647756 | [
"vector"
] |
9831040c3470587ef9a8a4ec3dc89f5d9a809a00 | 11,983 | cpp | C++ | artifact/storm/src/storm/builder/BuilderOptions.cpp | glatteis/tacas21-artifact | 30b4f522bd3bdb4bebccbfae93f19851084a3db5 | [
"MIT"
] | null | null | null | artifact/storm/src/storm/builder/BuilderOptions.cpp | glatteis/tacas21-artifact | 30b4f522bd3bdb4bebccbfae93f19851084a3db5 | [
"MIT"
] | null | null | null | artifact/storm/src/storm/builder/BuilderOptions.cpp | glatteis/tacas21-artifact | 30b4f522bd3bdb4bebccbfae93f19851084a3db5 | [
"MIT"
] | 1 | 2022-02-05T12:39:53.000Z | 2022-02-05T12:39:53.000Z | #include "storm/builder/BuilderOptions.h"
#include "storm/builder/TerminalStatesGetter.h"
#include "storm/logic/Formulas.h"
#include "storm/logic/LiftableTransitionRewardsVisitor.h"
#include "storm/settings/SettingsManager.h"
#include "storm/settings/modules/GeneralSettings.h"
#include "storm/utility/macros.h"
#include "storm/exceptions/InvalidSettingsException.h"
namespace storm {
namespace builder {
LabelOrExpression::LabelOrExpression(storm::expressions::Expression const& expression) : labelOrExpression(expression) {
// Intentionally left empty.
}
LabelOrExpression::LabelOrExpression(std::string const& label) : labelOrExpression(label) {
// Intentionally left empty.
}
bool LabelOrExpression::isLabel() const {
return labelOrExpression.which() == 0;
}
std::string const& LabelOrExpression::getLabel() const {
return boost::get<std::string>(labelOrExpression);
}
bool LabelOrExpression::isExpression() const {
return labelOrExpression.which() == 1;
}
storm::expressions::Expression const& LabelOrExpression::getExpression() const {
return boost::get<storm::expressions::Expression>(labelOrExpression);
}
BuilderOptions::BuilderOptions(bool buildAllRewardModels, bool buildAllLabels) : buildAllRewardModels(buildAllRewardModels), buildAllLabels(buildAllLabels), applyMaximalProgressAssumption(false), buildChoiceLabels(false), buildStateValuations(false), buildChoiceOrigins(false), scaleAndLiftTransitionRewards(true), explorationChecks(false), inferObservationsFromActions(false), addOverlappingGuardsLabel(false), addOutOfBoundsState(false), reservedBitsForUnboundedVariables(32), showProgress(false), showProgressDelay(0) {
// Intentionally left empty.
}
BuilderOptions::BuilderOptions(storm::logic::Formula const& formula, storm::storage::SymbolicModelDescription const& modelDescription) : BuilderOptions({formula.asSharedPointer()}, modelDescription) {
// Intentionally left empty.
}
BuilderOptions::BuilderOptions(std::vector<std::shared_ptr<storm::logic::Formula const>> const& formulas, storm::storage::SymbolicModelDescription const& modelDescription) : BuilderOptions() {
if (!formulas.empty()) {
for (auto const& formula : formulas) {
this->preserveFormula(*formula, modelDescription);
}
if (formulas.size() == 1) {
this->setTerminalStatesFromFormula(*formulas.front());
}
}
auto const& generalSettings = storm::settings::getModule<storm::settings::modules::GeneralSettings>();
if (modelDescription.hasModel()) {
this->setApplyMaximalProgressAssumption(modelDescription.getModelType() == storm::storage::SymbolicModelDescription::ModelType::MA);
this->setBuildChoiceOrigins(modelDescription.getModelType() == storm::storage::SymbolicModelDescription::ModelType::POMDP);
this->setBuildChoiceLabels(modelDescription.getModelType() == storm::storage::SymbolicModelDescription::ModelType::POMDP);
}
showProgress = generalSettings.isVerboseSet();
showProgressDelay = generalSettings.getShowProgressDelay();
}
void BuilderOptions::preserveFormula(storm::logic::Formula const& formula, storm::storage::SymbolicModelDescription const& modelDescription) {
// If we already had terminal states, we need to erase them.
if (hasTerminalStates()) {
clearTerminalStates();
}
// Determine the reward models we need to build.
std::set<std::string> referencedRewardModels = formula.getReferencedRewardModels();
for (auto const& rewardModelName : referencedRewardModels) {
rewardModelNames.emplace(rewardModelName);
}
// Extract all the labels used in the formula.
std::vector<std::shared_ptr<storm::logic::AtomicLabelFormula const>> atomicLabelFormulas = formula.getAtomicLabelFormulas();
for (auto const& formula : atomicLabelFormulas) {
addLabel(formula->getLabel());
}
// Extract all the expressions used in the formula.
std::vector<std::shared_ptr<storm::logic::AtomicExpressionFormula const>> atomicExpressionFormulas = formula.getAtomicExpressionFormulas();
for (auto const& formula : atomicExpressionFormulas) {
addLabel(formula->getExpression());
}
scaleAndLiftTransitionRewards = scaleAndLiftTransitionRewards && storm::logic::LiftableTransitionRewardsVisitor(modelDescription).areTransitionRewardsLiftable(formula);
}
void BuilderOptions::setTerminalStatesFromFormula(storm::logic::Formula const& formula) {
getTerminalStatesFromFormula(formula, [this](storm::expressions::Expression const& expr, bool inverted){ this->addTerminalExpression(expr, inverted);}
, [this](std::string const& label, bool inverted){ this->addTerminalLabel(label, inverted);});
}
std::set<std::string> const& BuilderOptions::getRewardModelNames() const {
return rewardModelNames;
}
std::set<std::string> const& BuilderOptions::getLabelNames() const {
return labelNames;
}
std::vector<std::pair<std::string, storm::expressions::Expression>> const& BuilderOptions::getExpressionLabels() const {
return expressionLabels;
}
std::vector<std::pair<LabelOrExpression, bool>> const& BuilderOptions::getTerminalStates() const {
return terminalStates;
}
bool BuilderOptions::hasTerminalStates() const {
return !terminalStates.empty();
}
void BuilderOptions::clearTerminalStates() {
terminalStates.clear();
}
bool BuilderOptions::isApplyMaximalProgressAssumptionSet() const {
return applyMaximalProgressAssumption;
}
bool BuilderOptions::isBuildChoiceLabelsSet() const {
return buildChoiceLabels;
}
bool BuilderOptions::isBuildStateValuationsSet() const {
return buildStateValuations;
}
bool BuilderOptions::isBuildChoiceOriginsSet() const {
return buildChoiceOrigins;
}
bool BuilderOptions::isBuildAllRewardModelsSet() const {
return buildAllRewardModels;
}
bool BuilderOptions::isBuildAllLabelsSet() const {
return buildAllLabels;
}
bool BuilderOptions::isInferObservationsFromActionsSet() const {
return inferObservationsFromActions;
}
bool BuilderOptions::isScaleAndLiftTransitionRewardsSet() const {
return scaleAndLiftTransitionRewards;
}
bool BuilderOptions::isAddOutOfBoundsStateSet() const {
return addOutOfBoundsState;
}
uint64_t BuilderOptions::getReservedBitsForUnboundedVariables() const {
return reservedBitsForUnboundedVariables;
}
bool BuilderOptions::isAddOverlappingGuardLabelSet() const {
return addOverlappingGuardsLabel;
}
BuilderOptions& BuilderOptions::setBuildAllRewardModels(bool newValue) {
buildAllRewardModels = newValue;
return *this;
}
bool BuilderOptions::isExplorationChecksSet() const {
return explorationChecks;
}
bool BuilderOptions::isShowProgressSet() const {
return showProgress;
}
uint64_t BuilderOptions::getShowProgressDelay() const {
return showProgressDelay;
}
BuilderOptions& BuilderOptions::setExplorationChecks(bool newValue) {
explorationChecks = newValue;
return *this;
}
BuilderOptions& BuilderOptions::addRewardModel(std::string const& rewardModelName) {
STORM_LOG_THROW(!buildAllRewardModels, storm::exceptions::InvalidSettingsException, "Cannot add reward model, because all reward models are built anyway.");
rewardModelNames.emplace(rewardModelName);
return *this;
}
BuilderOptions& BuilderOptions::setBuildAllLabels(bool newValue) {
buildAllLabels = newValue;
return *this;
}
BuilderOptions& BuilderOptions::addLabel(storm::expressions::Expression const& expression) {
std::stringstream stream;
stream << expression;
expressionLabels.emplace_back(stream.str(), expression);
return *this;
}
BuilderOptions& BuilderOptions::addLabel(std::string const& labelName) {
STORM_LOG_THROW(!buildAllLabels, storm::exceptions::InvalidSettingsException, "Cannot add label, because all labels are built anyway.");
labelNames.insert(labelName);
return *this;
}
BuilderOptions& BuilderOptions::addTerminalExpression(storm::expressions::Expression const& expression, bool value) {
terminalStates.push_back(std::make_pair(LabelOrExpression(expression), value));
return *this;
}
BuilderOptions& BuilderOptions::addTerminalLabel(std::string const& label, bool value) {
terminalStates.push_back(std::make_pair(LabelOrExpression(label), value));
return *this;
}
BuilderOptions& BuilderOptions::setApplyMaximalProgressAssumption(bool newValue) {
applyMaximalProgressAssumption = newValue;
return *this;
}
BuilderOptions& BuilderOptions::setBuildChoiceLabels(bool newValue) {
buildChoiceLabels = newValue;
return *this;
}
BuilderOptions& BuilderOptions::setBuildStateValuations(bool newValue) {
buildStateValuations = newValue;
return *this;
}
BuilderOptions& BuilderOptions::setBuildChoiceOrigins(bool newValue) {
buildChoiceOrigins = newValue;
return *this;
}
BuilderOptions& BuilderOptions::setScaleAndLiftTransitionRewards(bool newValue) {
scaleAndLiftTransitionRewards = newValue;
return *this;
}
BuilderOptions& BuilderOptions::setAddOutOfBoundsState(bool newValue) {
addOutOfBoundsState = newValue;
return *this;
}
BuilderOptions& BuilderOptions::setReservedBitsForUnboundedVariables(uint64_t newValue) {
reservedBitsForUnboundedVariables = newValue;
return *this;
}
BuilderOptions& BuilderOptions::setAddOverlappingGuardsLabel(bool newValue) {
addOverlappingGuardsLabel = newValue;
return *this;
}
BuilderOptions& BuilderOptions::substituteExpressions(std::function<storm::expressions::Expression(storm::expressions::Expression const&)> const& substitutionFunction) {
for (auto& e : expressionLabels) {
e.second = substitutionFunction(e.second);
}
for (auto& t : terminalStates) {
if (t.first.isExpression()) {
t.first = LabelOrExpression(substitutionFunction(t.first.getExpression()));
}
}
return *this;
}
}
}
| 42.492908 | 530 | 0.63323 | [
"vector",
"model"
] |
983358d0953e9d32158b5c700381aa9786cbd24c | 5,083 | cpp | C++ | executor/operator/arm64/prelu_float.cpp | wangshankun/Tengine_Atlas | b5485039e72b4a624c795ff95d73eb6d719c7706 | [
"Apache-2.0"
] | 25 | 2018-12-09T09:31:56.000Z | 2021-08-12T10:32:19.000Z | executor/operator/arm64/prelu_float.cpp | wangshankun/Tengine_Atlas | b5485039e72b4a624c795ff95d73eb6d719c7706 | [
"Apache-2.0"
] | 1 | 2022-03-31T03:33:42.000Z | 2022-03-31T03:33:42.000Z | executor/operator/arm64/prelu_float.cpp | wangshankun/Tengine_Atlas | b5485039e72b4a624c795ff95d73eb6d719c7706 | [
"Apache-2.0"
] | 6 | 2018-12-16T01:18:42.000Z | 2019-09-18T07:29:56.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* License); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (c) 2018, Open AI Lab
* Author: chunyinglv@openailab.com
*/
#include <functional>
#include <cstring>
#include "logger.hpp"
#include "node_ops.hpp"
#include "tensor_mem.hpp"
#include "graph.hpp"
#include <arm_neon.h>
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
namespace TEngine {
namespace PReluFP32Impl64 {
const int default_prio = 300;
struct PreluOps : public NodeOps
{
PreluOps()
{
name_ = "arm_prelu_fp32";
}
bool OnBind(Node* node);
bool Run(Node* node);
bool Direct_Prelu(float *input,float *output,float* slope,int channel, int height ,int width);
};
bool PreluOps::OnBind(Node* node)
{
// set the inplace feature
inplace_t io_map;
io_map[0] = 0;
node->SetAttr(ATTR_INPLACE, io_map);
return true;
}
void prelu_kernel(int i, int id, void* data, const float *input,float *output,float* slope,int channel_size)
{
int step = ((int*)data)[0];
float32x4_t _zero = vdupq_n_f32(0.f);
for(int c = 0; c < step; c++)
{
int cur_c = id * step + c;
const float* cur_input = input + cur_c * channel_size;
float* cur_output = output + cur_c * channel_size;
float32x4_t _slope = vdupq_n_f32(slope[cur_c]);
for(int l=0; l< (channel_size & -4); l += 4)
{
float32x4_t _p = vld1q_f32(cur_input);
// ri = ai <= bi ? 1...1:0...0
uint32x4_t _lemask = vcleq_f32(_p, _zero);
float32x4_t _ps = vmulq_f32(_p, _slope);
// bitwise select
_p = vbslq_f32(_lemask, _ps, _p);
vst1q_f32(cur_output, _p);
cur_input += 4;
cur_output += 4;
}
for(int l = channel_size & ~3; l < channel_size; l++)
{
*cur_output = MAX(cur_input[0], 0.f) + slope[cur_c] * MIN(cur_input[0], 0.f);
cur_input ++;
}
}
}
bool PreluOps::Run(Node* node)
{
// inplace implement
Tensor* input_tensor = node->GetInputTensor(0);
Tensor* output_tensor = node->GetOutputTensor(0);
const TShape& shape = input_tensor->GetShape();
const std::vector<int> dims = shape.GetDim();
int channel_size = dims[2] * dims[3];
int channel_num = dims[1];
int img_size = channel_size * channel_num;
const float* input = ( float* )get_tensor_mem(input_tensor);
float* output = ( float* )get_tensor_mem(output_tensor);
const Tensor* slope_tensor = node->GetInputTensor(1);
float* slope = ( float* )get_tensor_mem(slope_tensor);
int cpu_number = cpu_info->GetCPUNumber();
int block = channel_num ;
block = block > 0 ? block : 1;
int num_task = cpu_number < block ? cpu_number : block;
int step = channel_num / num_task;
for(int n = 0; n < dims[0]; n++)
{
const float *input_data = input + n * img_size;
float *out_data = output + n * img_size;
if(num_task == 1)
prelu_kernel( 0, 0, &step, input_data, out_data, slope, channel_size);
else
{
MULTI_THREAD_START(num_task, step, p_id, p_param)
prelu_kernel(0, p_id, p_param, input_data, out_data, slope, channel_size);
MULTI_THREAD_END();
}
if(num_task * step != channel_num)
{
int offset = num_task * step;
int remain_num = channel_num - offset;
input_data += offset * channel_size;
out_data += offset * channel_size;
prelu_kernel(0, 0, &remain_num, input_data, out_data, slope + offset, channel_size);
}
}
return true;
}
NodeOps* SelectFunc(const CPUInfo* cpu_info, Node* node)
{
Tensor* input = node->GetInputTensor(0);
const int data_type = input->GetDataType();
const ExecAttr* exec_attr = any_cast<const ExecAttr*>(node->GetAttr(ATTR_EXEC_ATTR));
if(data_type != TENGINE_DT_FP32 || exec_attr->graph_layout != TENGINE_LAYOUT_NCHW)
return nullptr;
PreluOps* ops = new PreluOps();
return ops;
}
} // namespace PreluImpl
using namespace PReluFP32Impl64;
void RegisterPReluFP32(void)
{
NodeOpsRegistryManager::RegisterOPImplementor("arm64", "PReLU", PReluFP32Impl64::SelectFunc, PReluFP32Impl64::default_prio);
}
} // namespace TEngine
| 31.376543 | 128 | 0.634271 | [
"shape",
"vector"
] |
98378cae74782e931fa24326a43485175ac1ab90 | 3,114 | cc | C++ | VerStarting/main_local.cc | gynvael/MythTracer | a33b0c9a6cce8bb66ae2c59d68d20adaf35ce906 | [
"MIT"
] | 17 | 2017-06-30T19:57:59.000Z | 2020-11-17T20:54:18.000Z | VerStarting/main_local.cc | gynvael/MythTracer | a33b0c9a6cce8bb66ae2c59d68d20adaf35ce906 | [
"MIT"
] | 2 | 2017-07-11T07:54:40.000Z | 2017-07-11T22:00:16.000Z | VerStarting/main_local.cc | gynvael/MythTracer | a33b0c9a6cce8bb66ae2c59d68d20adaf35ce906 | [
"MIT"
] | 6 | 2017-07-10T22:12:33.000Z | 2020-11-16T19:08:48.000Z | #include <stdio.h>
#include <stdint.h>
#include <vector>
#ifdef __unix__
# include <sys/stat.h>
# include <sys/types.h>
#else
# include <direct.h>
#endif
#include "mythtracer.h"
#include "camera.h"
#include "octtree.h"
using math3d::V3D;
using raytracer::MythTracer;
using raytracer::AABB;
using raytracer::PerPixelDebugInfo;
using raytracer::Camera;
using raytracer::Light;
const int W = 1920/4; // 960 480
const int H = 1080/4; // 540 270
int main(void) {
puts("Creating anim/ directory");
#ifdef __unix__
mkdir("anim", 0700);
#else
_mkdir("anim");
#endif
printf("Resolution: %u %u\n", W, H);
MythTracer mt;
if (!mt.LoadObj("../Models/Living Room USSU Design.obj")) {
return 1;
}
AABB aabb = mt.GetScene()->tree.GetAABB();
printf("%f %f %f x %f %f %f\n",
aabb.min.v[0],
aabb.min.v[1],
aabb.min.v[2],
aabb.max.v[0],
aabb.max.v[1],
aabb.max.v[2]);
std::vector<PerPixelDebugInfo> debug(W * H);
std::vector<uint8_t> bitmap(W * H * 3);
int frame = 0;
for (double angle = 0.0; angle <= 360.0; angle += 2.0, frame++) {
// Skip some frames
if (frame <= 73) {
continue;
}
// Really good camera setting.
/*Camera cam{
{ 300.0, 57.0, 160.0 },
0.0, 180.0, 0.0,
110.0
};*/
// Camera set a lamp.
/*Camera cam{
{ 250.0, 50.0, -20.0 },
-90.0, 180.0, 0.0,
110.0
};*/
Camera cam{
{ 300.0, 107.0, 40.0 },
30.0, angle + 90, 0.0,
110.0
};
// XXX: light at camera
mt.GetScene()->lights.clear();
mt.GetScene()->lights.push_back(
Light{
{ 231.82174, 81.69966, -27.78259 },
{ 0.3, 0.3, 0.3 },
{ 1.0, 1.0, 1.0 },
{ 1.0, 1.0, 1.0 }
});
mt.GetScene()->lights.push_back(
Light{
{ 200, 80.0, 0 },
{ 0.0, 0.0, 0.0 },
{ 0.3, 0.3, 0.3 },
{ 0.3, 0.3, 0.3 }
});
mt.GetScene()->lights.push_back(
Light{
{ 200, 80.0, 80 },
{ 0.0, 0.0, 0.0 },
{ 0.3, 0.3, 0.3 },
{ 0.3, 0.3, 0.3 }
});
mt.GetScene()->lights.push_back(
Light{
{ 200, 80.0, 160 },
{ 0.0, 0.0, 0.0 },
{ 0.3, 0.3, 0.3 },
{ 0.3, 0.3, 0.3 }
});
/*raytracer::WorkChunk chunk{
W, H,
100, 100, 100, 100,
&cam,
&bitmap,
nullptr
};*/
//mt.RayTrace(&chunk);
mt.RayTrace(W, H, &cam, &bitmap);
puts("Writing");
char fname[256];
sprintf(fname, "anim/dump_%.5i.raw", frame);
FILE *f = fopen(fname, "wb");
fwrite(&bitmap[0], bitmap.size(), 1, f);
fclose(f);
/*sprintf(fname, "anim/dump_%.5i.txt", frame);
f = fopen(fname, "w");
int idx = 0;
for (int j = 0; j < H; j++) {
for (int i = 0; i < W; i++, idx++) {
fprintf(f, "%i, %i: line %i point %s\n",
i, j,
debug[idx].line_no,
V3DStr(debug[idx].point));
}
}
fclose(f);
*/
//break;
}
puts("Done");
return 0;
}
| 19.834395 | 68 | 0.47431 | [
"vector"
] |
9839abef73adcaf622998e9d88928805f5b293af | 17,195 | cpp | C++ | net/tapi/skywalker/apps/avdialer/avtapi/confdetail.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | net/tapi/skywalker/apps/avdialer/avtapi/confdetail.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | net/tapi/skywalker/apps/avdialer/avtapi/confdetail.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | ////////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 1997 Active Voice Corporation. All Rights Reserved.
//
// Active Agent(r) and Unified Communications(tm) are trademarks of Active Voice Corporation.
//
// Other brand and product names used herein are trademarks of their respective owners.
//
// The entire program and user interface including the structure, sequence, selection,
// and arrangement of the dialog, the exclusively "yes" and "no" choices represented
// by "1" and "2," and each dialog message are protected by copyrights registered in
// the United States and by international treaties.
//
// Protected by one or more of the following United States patents: 5,070,526, 5,488,650,
// 5,434,906, 5,581,604, 5,533,102, 5,568,540, 5,625,676, 5,651,054.
//
// Active Voice Corporation
// Seattle, Washington
// USA
//
/////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
// ConfDetails.cpp
#include "stdafx.h"
#include "TapiDialer.h"
#include "CEDetailsVw.h"
#include "ConfDetails.h"
#define MAX_STR 255
#define MAX_FORMAT 500
int CompareDate( DATE d1, DATE d2 )
{
if ( d1 > d2 )
return -1;
else if ( d1 == d2 )
return 0;
return 1;
}
//////////////////////////////////////////////////////////
// class CConfSDP
//
CConfSDP::CConfSDP()
{
m_nConfMediaType = MEDIA_AUDIO_VIDEO;
}
CConfSDP::~CConfSDP()
{
}
void CConfSDP::UpdateData( ITSdp *pSdp )
{
m_nConfMediaType = MEDIA_NONE;
// Let's see what kind of media this conf supports
ITMediaCollection *pMediaCollection;
if ( SUCCEEDED(pSdp->get_MediaCollection(&pMediaCollection)) )
{
IEnumMedia *pEnum;
if ( SUCCEEDED(pMediaCollection->get_EnumerationIf(&pEnum)) )
{
ITMedia *pMedia;
while ( pEnum->Next(1, &pMedia, NULL) == S_OK )
{
BSTR bstrMedia = NULL;
pMedia->get_MediaName( &bstrMedia );
if ( bstrMedia )
{
if ( !_wcsicmp(bstrMedia, L"audio") )
m_nConfMediaType = (ConfMediaType) (m_nConfMediaType + MEDIA_AUDIO);
else if ( !_wcsicmp(bstrMedia, L"video") )
m_nConfMediaType = (ConfMediaType) (m_nConfMediaType + MEDIA_VIDEO);
}
pMedia->Release();
SysFreeString( bstrMedia );
}
pEnum->Release();
}
pMediaCollection->Release();
}
}
CConfSDP& CConfSDP::operator=(const CConfSDP &src)
{
m_nConfMediaType = src.m_nConfMediaType;
return *this;
}
////////////////////////////////////////////////////////////
// class CConfDetails
//
CPersonDetails::CPersonDetails()
{
m_bstrName = NULL;
m_bstrAddress = NULL;
m_bstrComputer = NULL;
}
CPersonDetails::~CPersonDetails()
{
SysFreeString( m_bstrName );
SysFreeString( m_bstrAddress );
SysFreeString( m_bstrComputer );
}
void CPersonDetails::Empty()
{
SysFreeString( m_bstrName );
m_bstrName = NULL;
SysFreeString( m_bstrAddress );
m_bstrAddress = NULL;
SysFreeString( m_bstrComputer );
m_bstrComputer = NULL;
}
CPersonDetails& CPersonDetails::operator =( const CPersonDetails& src )
{
SysReAllocString( &m_bstrName, src.m_bstrName );
SysReAllocString( &m_bstrAddress, src.m_bstrAddress );
SysReAllocString( &m_bstrComputer, src.m_bstrComputer );
return *this;
}
int CPersonDetails::Compare( const CPersonDetails& src )
{
int nRet = wcscmp( m_bstrName, src.m_bstrName );
if ( nRet != 0 ) return nRet;
nRet = wcscmp( m_bstrAddress, src.m_bstrAddress );
return nRet;
}
void CPersonDetails::Populate( BSTR bstrServer, ITDirectoryObject *pITDirObject )
{
// Extract information from ITDirectoryObject
Empty();
pITDirObject->get_Name( &m_bstrName );
// Get a computer name
IEnumDialableAddrs *pEnum = NULL;
if ( SUCCEEDED(pITDirObject->EnumerateDialableAddrs(LINEADDRESSTYPE_DOMAINNAME, &pEnum)) && pEnum )
{
SysFreeString( m_bstrComputer );
m_bstrComputer = NULL;
pEnum->Next(1, &m_bstrComputer, NULL );
pEnum->Release();
}
// Get an IP Address
pEnum = NULL;
if ( SUCCEEDED(pITDirObject->EnumerateDialableAddrs(LINEADDRESSTYPE_IPADDRESS, &pEnum)) && pEnum )
{
SysFreeString( m_bstrAddress );
m_bstrAddress = NULL;
pEnum->Next(1, &m_bstrAddress, NULL );
pEnum->Release();
}
}
////////////////////////////////////////////////////////////
// class CConfDetails
//
CConfDetails::CConfDetails()
{
m_bstrServer = m_bstrName = m_bstrDescription = m_bstrOriginator = m_bstrAddress = NULL;
m_dateStart = m_dateEnd = 0;
m_bIsEncrypted = FALSE;
}
CConfDetails::~CConfDetails()
{
SysFreeString( m_bstrServer );
SysFreeString( m_bstrName );
SysFreeString( m_bstrDescription );
SysFreeString( m_bstrOriginator );
SysFreeString( m_bstrAddress );
}
int CConfDetails::Compare( CConfDetails *p2, bool bAscending, int nSortCol1, int nSortCol2 ) const
{
USES_CONVERSION;
if ( !p2 ) return -1;
//
// PREFIX 49769 - VLADE
// We initialize local variables
//
BSTR bstr1 = NULL, bstr2 = NULL;
int nRet;
for ( int nSearch = 0; nSearch < 2; nSearch++ )
{
bool bStrCmp = true;
// Secondary sort is always ascending
nRet = (bAscending || nSearch) ? 1 : -1;
switch( (nSearch) ? nSortCol2 : nSortCol1 )
{
case CConfExplorerDetailsView::COL_STARTS: nRet *= CompareDate( m_dateStart, p2->m_dateStart ); bStrCmp = false; break;
case CConfExplorerDetailsView::COL_ENDS: nRet *= CompareDate( m_dateEnd, p2->m_dateEnd ); bStrCmp = false; break;
case CConfExplorerDetailsView::COL_NAME: bstr1 = m_bstrName; bstr2 = p2->m_bstrName; break;
case CConfExplorerDetailsView::COL_PURPOSE: bstr1 = m_bstrDescription; bstr2 = p2->m_bstrDescription; break;
case CConfExplorerDetailsView::COL_ORIGINATOR: bstr1 = m_bstrOriginator, bstr2 = p2->m_bstrOriginator; break;
case CConfExplorerDetailsView::COL_SERVER: bstr1 = m_bstrServer, bstr2 = p2->m_bstrServer; break;
default: _ASSERT( false );
}
// Perform string comparison and guard against NULLs
if ( bStrCmp )
{
if ( bstr1 && bstr2 )
nRet *= _wcsicoll( bstr1, bstr2 );
else if ( bstr2 )
nRet *= -1;
else if ( !bstr1 && !bstr2 )
nRet = 0;
}
// If we have a definite search order, then break
if ( nRet ) break;
}
return nRet;
}
CConfDetails& CConfDetails::operator=( const CConfDetails& src )
{
SysReAllocString( &m_bstrServer, src.m_bstrServer );
SysReAllocString( &m_bstrName, src.m_bstrName );
SysReAllocString( &m_bstrDescription, src.m_bstrDescription );
SysReAllocString( &m_bstrOriginator, src.m_bstrOriginator );
SysReAllocString( &m_bstrAddress, src.m_bstrAddress );
m_dateStart = src.m_dateStart;
m_dateEnd = src.m_dateEnd;
m_bIsEncrypted = src.m_bIsEncrypted;
m_sdp = src.m_sdp;
return *this;
}
HRESULT CConfDetails::get_bstrDisplayableServer( BSTR *pbstrServer )
{
*pbstrServer = NULL;
if ( m_bstrServer )
return SysReAllocString( pbstrServer, m_bstrServer );
USES_CONVERSION;
TCHAR szText[255];
LoadString( _Module.GetResourceInstance(), IDS_DEFAULT_SERVER, szText, ARRAYSIZE(szText) );
return SysReAllocString( pbstrServer, T2COLE(szText) );
}
void CConfDetails::MakeDetailsCaption( BSTR& bstrCaption )
{
USES_CONVERSION;
TCHAR szText[MAX_STR], szMessage[MAX_FORMAT], szMedia[MAX_STR];
BSTR bstrStart = NULL, bstrEnd = NULL;
// Convert start and stop time to strings
VarBstrFromDate( m_dateStart, LOCALE_USER_DEFAULT, NULL, &bstrStart );
VarBstrFromDate( m_dateEnd, LOCALE_USER_DEFAULT, NULL, &bstrEnd );
// What type of media do we support?
//
// We should initialize nIDS
//
UINT nIDS = IDS_CONFROOM_MEDIA_AUDIO;
switch ( m_sdp.m_nConfMediaType )
{
case CConfSDP::MEDIA_AUDIO: nIDS = IDS_CONFROOM_MEDIA_AUDIO; break;
case CConfSDP::MEDIA_VIDEO: nIDS = IDS_CONFROOM_MEDIA_VIDEO; break;
case CConfSDP::MEDIA_AUDIO_VIDEO: nIDS = IDS_CONFROOM_MEDIA_AUDIO_VIDEO; break;
}
LoadString( _Module.GetResourceInstance(), nIDS, szMedia, ARRAYSIZE(szMedia) );
LoadString( _Module.GetResourceInstance(), IDS_CONFROOM_DETAILS, szText, ARRAYSIZE(szText) );
_sntprintf( szMessage, MAX_FORMAT, szText, OLE2CT(m_bstrName),
szMedia,
OLE2CT(bstrStart),
OLE2CT(bstrEnd),
OLE2CT(m_bstrOriginator) );
szMessage[MAX_FORMAT-1] = _T('\0');
// Store return value
bstrCaption = SysAllocString( T2COLE(szMessage) );
SysFreeString( bstrStart );
SysFreeString( bstrEnd );
}
bool CConfDetails::IsSimilar( BSTR bstrText )
{
if ( bstrText )
{
if ( !wcsicmp(m_bstrName, bstrText) ) return true;
if ( !wcsicmp(m_bstrOriginator, bstrText) ) return true;
// Case independent search of the description
if ( m_bstrDescription )
{
CComBSTR bstrTempText( bstrText );
CComBSTR bstrTempDescription( m_bstrDescription );
wcsupr( bstrTempText );
wcsupr( bstrTempDescription );
if ( wcsstr(bstrTempDescription, bstrTempText) ) return true;
}
}
return false;
}
void CConfDetails::Populate( BSTR bstrServer, ITDirectoryObject *pITDirObject )
{
// Set CConfDetails object information
m_bstrServer = SysAllocString( bstrServer );
pITDirObject->get_Name( &m_bstrName );
ITDirectoryObjectConference *pConf;
if ( SUCCEEDED(pITDirObject->QueryInterface(IID_ITDirectoryObjectConference, (void **) &pConf)) )
{
pConf->get_Description( &m_bstrDescription );
pConf->get_Originator( &m_bstrOriginator );
pConf->get_StartTime( &m_dateStart );
pConf->get_StopTime( &m_dateEnd );
pConf->get_IsEncrypted( &m_bIsEncrypted );
IEnumDialableAddrs *pEnum;
if ( SUCCEEDED(pITDirObject->EnumerateDialableAddrs( LINEADDRESSTYPE_SDP, &pEnum)) )
{
pEnum->Next( 1, &m_bstrAddress, NULL );
pEnum->Release();
}
// Download the SDP information for the conference
ITSdp *pSdp;
if ( SUCCEEDED(pConf->QueryInterface(IID_ITSdp, (void **) &pSdp)) )
{
m_sdp.UpdateData( pSdp );
pSdp->Release();
}
pConf->Release();
}
}
///////////////////////////////////////////////////////////////////////
// class CConfServerDetails()
//
CConfServerDetails::CConfServerDetails()
{
m_bstrServer = NULL;
m_nState = SERVER_UNKNOWN;
m_bArchived = true;
m_dwTickCount = 0;
}
CConfServerDetails::~CConfServerDetails()
{
SysFreeString( m_bstrServer );
DELETE_CRITLIST( m_lstConfs, m_critLstConfs );
DELETE_CRITLIST( m_lstPersons, m_critLstPersons );
}
bool CConfServerDetails::IsSameAs( const OLECHAR *lpoleServer ) const
{
// Compare server names (case independent); protect against NULL strings
if ( ((lpoleServer && m_bstrServer) && !wcsicmp(lpoleServer, m_bstrServer)) || (!lpoleServer && !m_bstrServer) )
return true;
return false;
}
void CConfServerDetails::CopyLocalProperties( const CConfServerDetails& src )
{
SysReAllocString( &m_bstrServer, src.m_bstrServer );
m_nState = src.m_nState;
m_bArchived = src.m_bArchived;
m_dwTickCount = src.m_dwTickCount;
}
CConfServerDetails& CConfServerDetails::operator=( const CConfServerDetails& src )
{
CopyLocalProperties( src );
// Copy the conference list
m_critLstConfs.Lock();
{
DELETE_LIST( m_lstConfs );
CONFDETAILSLIST::iterator i, iEnd = src.m_lstConfs.end();
for ( i = src.m_lstConfs.begin(); i != iEnd; i++ )
{
CConfDetails *pDetails = new CConfDetails;
if ( pDetails )
{
*pDetails = *(*i);
m_lstConfs.push_back( pDetails );
}
}
}
m_critLstConfs.Unlock();
// Copy the people lists
m_critLstPersons.Lock();
{
DELETE_LIST( m_lstPersons );
PERSONDETAILSLIST::iterator i, iEnd = src.m_lstPersons.end();
for ( i = src.m_lstPersons.begin(); i != iEnd; i++ )
{
CPersonDetails *pDetails = new CPersonDetails;
if ( pDetails )
{
*pDetails = *(*i);
m_lstPersons.push_back( pDetails );
}
}
}
m_critLstPersons.Unlock();
return *this;
}
void CConfServerDetails::BuildJoinConfList( CONFDETAILSLIST *pList, BSTR bstrMatchText )
{
m_critLstConfs.Lock();
CONFDETAILSLIST::iterator i, iEnd = m_lstConfs.end();
for ( i = m_lstConfs.begin(); i != iEnd; i++ )
{
// Add if the conference either about to start, or started?
// drop Start time back 15 minutes
if ( (*i)->IsSimilar(bstrMatchText) )
{
CConfDetails *pDetails = new CConfDetails;
if ( pDetails )
{
*pDetails = *(*i);
pList->push_back( pDetails );
}
}
}
m_critLstConfs.Unlock();
}
void CConfServerDetails::BuildJoinConfList( CONFDETAILSLIST *pList, VARIANT_BOOL bAllConfs )
{
DATE dateNow;
SYSTEMTIME st;
GetLocalTime( &st );
SystemTimeToVariantTime( &st, &dateNow );
m_critLstConfs.Lock();
CONFDETAILSLIST::iterator i, iEnd = m_lstConfs.end();
for ( i = m_lstConfs.begin(); i != iEnd; i++ )
{
// Add if the conference either about to start, or started?
// drop Start time back 15 minutes
if ( bAllConfs || ((((*i)->m_dateStart - (DATE) (.125 / 12)) <= dateNow) && ((*i)->m_dateEnd >= dateNow)) )
{
CConfDetails *pDetails = new CConfDetails;
if ( pDetails )
{
*pDetails = *(*i);
pList->push_back( pDetails );
}
}
}
m_critLstConfs.Unlock();
}
HRESULT CConfServerDetails::RemoveConference( BSTR bstrName )
{
HRESULT hr = E_FAIL;
m_critLstConfs.Lock();
CONFDETAILSLIST::iterator i, iEnd = m_lstConfs.end();
for ( i = m_lstConfs.begin(); i != iEnd; i++ )
{
// Remove if we have a name match
if ( !wcscmp((*i)->m_bstrName, bstrName) )
{
delete *i;
m_lstConfs.erase( i );
hr = S_OK;
break;
}
}
m_critLstConfs.Unlock();
return hr;
}
HRESULT CConfServerDetails::AddConference( BSTR bstrServer, ITDirectoryObject *pDirObj )
{
HRESULT hr = E_FAIL;
CConfDetails *pNew = new CConfDetails;
if ( pNew )
{
pNew->Populate( bstrServer, pDirObj );
// First, make sure it doesn't exist
RemoveConference( pNew->m_bstrName );
// Add it to the list
m_critLstConfs.Lock();
m_lstConfs.push_back( pNew );
m_critLstConfs.Unlock();
hr = S_OK;
}
return hr;
}
HRESULT CConfServerDetails::AddPerson( BSTR bstrServer, ITDirectoryObject *pDirObj )
{
// Create a CPersonDetails object containing the information stored in the
// ITDirectoryObject
CPersonDetails *pPerson = new CPersonDetails;
if ( !pPerson ) return E_OUTOFMEMORY;
pPerson->Populate(bstrServer, pDirObj );
bool bMatch = false;
m_critLstPersons.Lock();
{
PERSONDETAILSLIST::iterator i, iEnd = m_lstPersons.end();
for ( i = m_lstPersons.begin(); i != iEnd; i++ )
{
if ( pPerson->Compare(**i) == 0 )
{
bMatch = true;
break;
}
}
}
// Add or delete the item depending on whether or not it already exists in the list
if ( !bMatch )
m_lstPersons.push_back( pPerson );
else
delete pPerson;
m_critLstPersons.Unlock();
return S_OK;
}
| 30.166667 | 145 | 0.57604 | [
"object"
] |
98436637ccd8edf3c9a451af28e79b7ab9d9e6fa | 20,644 | cpp | C++ | Core/Code/Testing/mitkPointSetTest.cpp | rfloca/MITK | b7dcb830dc36a5d3011b9828c3d71e496d3936ad | [
"BSD-3-Clause"
] | null | null | null | Core/Code/Testing/mitkPointSetTest.cpp | rfloca/MITK | b7dcb830dc36a5d3011b9828c3d71e496d3936ad | [
"BSD-3-Clause"
] | null | null | null | Core/Code/Testing/mitkPointSetTest.cpp | rfloca/MITK | b7dcb830dc36a5d3011b9828c3d71e496d3936ad | [
"BSD-3-Clause"
] | null | null | null | /*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkTestingMacros.h"
#include <mitkPointSet.h>
#include <mitkVector.h>
#include <mitkPointOperation.h>
#include <mitkInteractionConst.h>
#include <fstream>
class mitkPointSetTestClass { public:
static void TestGetITKPointSet(mitk::PointSet *pointSet)
{
//try to get the itkPointSet
mitk::PointSet::DataType::Pointer itkdata = NULL;
itkdata = pointSet->GetPointSet();
MITK_TEST_CONDITION( itkdata.IsNotNull(), "try to get the itkPointSet from a newly created PointSet" )
}
static void TestGetSizeIsZero(mitk::PointSet *pointSet)
{
//fresh PointSet has to be empty!
MITK_TEST_CONDITION( pointSet->GetSize() == 0, "check if the PointSet size is 0 " )
}
static void TestIsEmpty(mitk::PointSet *pointSet)
{
MITK_TEST_CONDITION(pointSet->IsEmptyTimeStep(0), "check if the PointSet is empty" )
}
static void TestCreateOperationAndAddPoint(mitk::PointSet *pointSet)
{
int id = 0;
mitk::Point3D point;
point.Fill(1);
mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpINSERT, point, id);
pointSet->ExecuteOperation(doOp);
MITK_TEST_CONDITION( pointSet->GetSize()==1 && pointSet->IndexExists(id), "check if added points exists" )
delete doOp;
mitk::Point3D tempPoint;
tempPoint.Fill(0);
tempPoint = pointSet->GetPoint(id);
MITK_TEST_CONDITION( point == tempPoint, "check if added point contains real value" )
}
static void TestAddSecondPoint(mitk::PointSet *pointSet)
{
//add a point directly
int id=0;
mitk::Point3D point;
mitk::FillVector3D(point, 1.0, 2.0, 3.0);
++id;
pointSet->GetPointSet()->GetPoints()->InsertElement(id, point);
MITK_TEST_CONDITION( pointSet->GetSize()==2 ||pointSet->IndexExists(id), "check if added points exists" )
mitk::Point3D tempPoint;
tempPoint.Fill(0);
tempPoint = pointSet->GetPoint(id);
MITK_TEST_CONDITION( point == tempPoint, "check if added point contains real value" )
}
static void TestIsNotEmpty(mitk::PointSet *pointSet)
{
//PointSet can not be empty!
MITK_TEST_CONDITION( !pointSet->IsEmptyTimeStep(0), "check if the PointSet is not empty " )
/*
std::cout << "check if the PointSet is not empty ";
if (pointSet->IsEmpty(0))
{
std::cout<<"[FAILED]"<<std::endl;
return EXIT_FAILURE;
}
std::cout<<"[PASSED]"<<std::endl;
*/
}
static void TestSwapPointPositionUpwards(mitk::PointSet *pointSet)
{
//Check SwapPointPosition upwards
mitk::Point3D point;
mitk::Point3D tempPoint;
point = pointSet->GetPoint(1);
pointSet->SwapPointPosition(1, true);
tempPoint = pointSet->GetPoint(0);
MITK_TEST_CONDITION( point == tempPoint, "check SwapPointPosition upwards" )
/*
if(point != tempPoint)
{
std::cout<<"[FAILED]"<<std::endl;
return EXIT_FAILURE;
}
std::cout<<"[PASSED]"<<std::endl;
*/
}
static void TestSwapPointPositionUpwardsNotPossible(mitk::PointSet *pointSet)
{
//Check SwapPointPosition upwards not possible
MITK_TEST_CONDITION( pointSet->SwapPointPosition(0, true)==false, "check SwapPointPosition upwards not possible" )
/*
if(pointSet->SwapPointPosition(0, true))
{
std::cout<<"[FAILED]"<<std::endl;
return EXIT_FAILURE;
}
std::cout<<"[PASSED]"<<std::endl;
*/
}
static void TestSwapPointPositionDownwards(mitk::PointSet *pointSet)
{
//Check SwapPointPosition downwards
mitk::Point3D point;
mitk::Point3D tempPoint;
point = pointSet->GetPoint(0);
pointSet->SwapPointPosition(0, false);
tempPoint = pointSet->GetPoint(1);
MITK_TEST_CONDITION( point == tempPoint, "check SwapPointPosition down" )
/*
if(point != tempPoint)
{
std::cout<<"[FAILED]"<<std::endl;
return EXIT_FAILURE;
}
std::cout<<"[PASSED]"<<std::endl;
*/
}
static void TestSwapPointPositionDownwardsNotPossible(mitk::PointSet * /*pointSet*/)
{
mitk::PointSet::Pointer pointSet2 = mitk::PointSet::New();
int id = 0;
mitk::Point3D point;
point.Fill(1);
pointSet2->SetPoint(id, point);
//Check SwapPointPosition downwards not possible
MITK_TEST_CONDITION(!pointSet2->SwapPointPosition(id, false), "check SwapPointPosition downwards not possible" )
/*
if(pointSet->SwapPointPosition(1, false))
{
std::cout<<"[FAILED]"<<std::endl;
return EXIT_FAILURE;
}
std::cout<<"[PASSED]"<<std::endl;
*/
}
static void TestPointOperationOpMove(mitk::PointSet *pointSet)
{
//check opMOVE ExecuteOperation
int id=1;
mitk::Point3D point1;
mitk::Point3D tempPoint;
point1.Fill(2);
mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpMOVE, point1, id);
pointSet->ExecuteOperation(doOp);
tempPoint = pointSet->GetPoint(id);
MITK_TEST_CONDITION(tempPoint == point1 , "check PointOperation OpMove " )
delete doOp;
/*
if (tempPoint != point1)
{
std::cout<<"[FAILED]"<<std::endl;
return EXIT_FAILURE;
}
delete doOp;
std::cout<<"[PASSED]"<<std::endl;
*/
}
static void TestPointOperationOpRemove(mitk::PointSet *pointSet)
{
//check OpREMOVE ExecuteOperation
int id=0;
mitk::Point3D point;
mitk::Point3D tempPoint;
point = pointSet->GetPoint(id);
mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpREMOVE, point, id);
pointSet->ExecuteOperation(doOp);
tempPoint = pointSet->GetPoint(id);
MITK_TEST_CONDITION(!pointSet->IndexExists(id) , "check PointOperation OpREMOVE " )
delete doOp;
/*
if(pointSet->IndexExists(id))
{
std::cout<<"[FAILED]"<<std::endl;
return EXIT_FAILURE;
}
delete doOp;
std::cout<<"[PASSED]"<<std::endl;
*/
}
static void TestPointOperationOpSelectPoint(mitk::PointSet *pointSet)
{
mitk::Point3D point4;
//check OpSELECTPOINT ExecuteOperation
mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpSELECTPOINT, point4,4);
pointSet->ExecuteOperation(doOp);
MITK_TEST_CONDITION(pointSet->GetSelectInfo(4) , "check PointOperation OpSELECTPOINT " )
delete doOp;
/*
if (!pointSet->GetSelectInfo(4))
{
std::cout<<"[FAILED]"<<std::endl;
return EXIT_FAILURE;
}
delete doOp;
std::cout<<"[PASSED]"<<std::endl;
*/
}
static void TestGetNumberOfSelected(mitk::PointSet *pointSet)
{
// check GetNumeberOfSelected
MITK_TEST_CONDITION(pointSet->GetNumberOfSelected() == 1 , "check GetNumeberOfSelected " )
/*
if(pointSet->GetNumberOfSelected() != 1)
{
std::cout<<"[FAILED]"<<std::endl;
return EXIT_FAILURE;
}
std::cout<<"[PASSED]"<<std::endl;
*/
}
static void TestSearchSelectedPoint(mitk::PointSet *pointSet)
{
// check SearchSelectedPoint
MITK_TEST_CONDITION(pointSet->SearchSelectedPoint() == 4 , "check SearchSelectedPoint " )
/*
if( pointSet->SearchSelectedPoint() != 4)
{
std::cout<<"[FAILED]"<<std::endl;
return EXIT_FAILURE;
}
std::cout<<"[PASSED]"<<std::endl;
*/
}
static void TestOpDeselectPoint(mitk::PointSet *pointSet)
{
//check OpDESELECTPOINT ExecuteOperation
mitk::Point3D point4;
mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpDESELECTPOINT, point4,4);
pointSet->ExecuteOperation(doOp);
MITK_TEST_CONDITION(!pointSet->GetSelectInfo(4) , "check PointOperation OpDESELECTPOINT " )
MITK_TEST_CONDITION(pointSet->GetNumberOfSelected() == 0 , "check GetNumeberOfSelected " )
delete doOp;
/*
if (pointSet->GetSelectInfo(4))
{
std::cout<<"[FAILED]"<<std::endl;
return EXIT_FAILURE;
}
delete doOp;
std::cout<<"[PASSED]"<<std::endl;
if(pointSet->GetNumberOfSelected() != 0)
{
std::cout<<"[FAILED]"<<std::endl;
return EXIT_FAILURE;
}
std::cout<<"[PASSED]"<<std::endl;
*/
}
static void TestOpMovePointUp(mitk::PointSet *pointSet)
{
//check OpMOVEPOINTUP ExecuteOperation
int id = 4;
mitk::Point3D point4;
mitk::Point3D point;
mitk::Point3D tempPoint;
point = pointSet->GetPoint(id);
mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpMOVEPOINTUP, point4, id);
pointSet->ExecuteOperation(doOp);
tempPoint = pointSet->GetPoint(id-1);
MITK_TEST_CONDITION(tempPoint == point , "check PointOperation OpMOVEPOINTUP " )
delete doOp;
/*
if (tempPoint != point)
{
std::cout<<"[FAILED]"<<std::endl;
return EXIT_FAILURE;
}
delete doOp;
std::cout<<"[PASSED]"<<std::endl;
*/
}
static void TestOpMovePointDown(mitk::PointSet *pointSet)
{
//check OpMOVEPOINTDown ExecuteOperation
int id = 2;
mitk::Point3D point;
mitk::Point3D point2;
mitk::Point3D tempPoint;
point = pointSet->GetPoint(id);
mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpMOVEPOINTDOWN, point2, id);
pointSet->ExecuteOperation(doOp);
tempPoint = pointSet->GetPoint(id+1);
MITK_TEST_CONDITION(tempPoint == point , "check PointOperation OpMOVEPOINTDOWN " )
delete doOp;
/*
if (tempPoint != point)
{
std::cout<<"[FAILED]"<<std::endl;
return EXIT_FAILURE;
}
std::cout<<"[PASSED]"<<std::endl;
*/
}
static void TestSetSelectInfo(mitk::PointSet *pointSet)
{
//check SetSelectInfo
pointSet->SetSelectInfo(2, true);
MITK_TEST_CONDITION(pointSet->GetSelectInfo(2) , "check SetSelectInfo" )
/*
if (!pointSet->GetSelectInfo(2))
{
std::cout<<"[FAILED]"<<std::endl;
return EXIT_FAILURE;
}
delete doOp;
std::cout<<"[PASSED]"<<std::endl;
*/
}
static void TestInsertPointWithPointSpecification(mitk::PointSet *pointSet)
{
//check InsertPoint with PointSpecification
mitk::Point3D point5;
mitk::Point3D tempPoint;
point5.Fill(7);
pointSet->SetPoint(5, point5, mitk::PTEDGE );
tempPoint = pointSet->GetPoint(5);
MITK_TEST_CONDITION(tempPoint == point5, "check InsertPoint with PointSpecification" )
/*
if (tempPoint != point5)
{
std::cout<<"[FAILED]"<<std::endl;
return EXIT_FAILURE;
}
std::cout<<"[PASSED]"<<std::endl;
*/
}
static void TestGetPointIfExists(mitk::PointSet *pointSet)
{
//check GetPointIfExists
mitk::Point3D point5;
mitk::Point3D tempPoint;
point5.Fill(7);
mitk::PointSet::PointType tmpPoint;
pointSet->GetPointIfExists(5, &tmpPoint);
MITK_TEST_CONDITION(tmpPoint == point5, "check GetPointIfExists: " )
/*
if (tmpPoint != point5)
{
std::cout<<"[FAILED]"<<std::endl;
return EXIT_FAILURE;
}
std::cout<<"[PASSED]"<<std::endl;
*/
}
static void TestCreateHoleInThePointIDs(mitk::PointSet *pointSet)
{
// create a hole in the point IDs
mitk::Point3D point;
mitk::PointSet::PointType p10, p11, p12;
p10.Fill(10.0);
p11.Fill(11.0);
p12.Fill(12.0);
pointSet->InsertPoint(10, p10);
pointSet->InsertPoint(11, p11);
pointSet->InsertPoint(12, p12);
MITK_TEST_CONDITION((pointSet->IndexExists(10) == true) || (pointSet->IndexExists(11) == true) || (pointSet->IndexExists(12) == true), "add points with id 10, 11, 12: " )
//check OpREMOVE ExecuteOperation
int id = 11;
mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpREMOVE, point, id);
pointSet->ExecuteOperation(doOp);
MITK_TEST_CONDITION(!pointSet->IndexExists(id), "remove point id 11: ")
/*
if(pointSet->IndexExists(id))
{
std::cout<<"[FAILED]"<<std::endl;
return EXIT_FAILURE;
}
delete doOp;
std::cout<<"[PASSED]"<<std::endl;
*/
//mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpMOVEPOINTUP, p12, 12);
//pointSet->ExecuteOperation(doOp);
delete doOp;
//check OpMOVEPOINTUP ExecuteOperation
doOp = new mitk::PointOperation(mitk::OpMOVEPOINTUP, p12, 12);
pointSet->ExecuteOperation(doOp);
delete doOp;
mitk::PointSet::PointType newP10 = pointSet->GetPoint(10);
mitk::PointSet::PointType newP12 = pointSet->GetPoint(12);
MITK_TEST_CONDITION(((newP10 == p12) && (newP12 == p10)) == true, "check PointOperation OpMOVEPOINTUP for point id 12:" )
//check OpMOVEPOINTDOWN ExecuteOperation
doOp = new mitk::PointOperation(mitk::OpMOVEPOINTDOWN, p10, 10);
pointSet->ExecuteOperation(doOp);
delete doOp;
newP10 = pointSet->GetPoint(10);
newP12 = pointSet->GetPoint(12);
MITK_TEST_CONDITION(((newP10 == p10) && (newP12 == p12)) == true, "check PointOperation OpMOVEPOINTDOWN for point id 10: ")
}
static void TestOpMovePointUpOnFirstPoint(mitk::PointSet *pointSet)
{
//check OpMOVEPOINTUP on first point ExecuteOperation
mitk::PointSet::PointType p1 = pointSet->GetPoint(1);
mitk::PointSet::PointType p2 = pointSet->GetPoint(2);
mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpMOVEPOINTUP, p1, 1);
pointSet->ExecuteOperation(doOp);
delete doOp;
mitk::PointSet::PointType newP1 = pointSet->GetPoint(1);
mitk::PointSet::PointType newP2 = pointSet->GetPoint(2);
MITK_TEST_CONDITION(((newP1 == p1) && (newP2 == p2)) == true, "check PointOperation OpMOVEPOINTUP for point id 1: ")
/*
if (((newP1 == p1) && (newP2 == p2)) == false)
{
std::cout<<"[FAILED]"<<std::endl;
return EXIT_FAILURE;
}
std::cout<<"[PASSED]"<<std::endl;
*/
}
static void TestPointContainerPointDataContainer(mitk::PointSet* ps)
{
mitk::PointSet::PointsContainer* pc = ps->GetPointSet()->GetPoints();
mitk::PointSet::PointDataContainer* pd = ps->GetPointSet()->GetPointData();
MITK_TEST_CONDITION_REQUIRED(pc->Size() == pd->Size(), "PointContainer and PointDataContainer have same size");
mitk::PointSet::PointsContainer::ConstIterator pIt = pc->Begin();
mitk::PointSet::PointDataContainer::ConstIterator dIt = pd->Begin();
bool failed = false;
for (; pIt != pc->End(); ++pIt, ++dIt)
if (pIt->Index() != dIt->Index())
{
failed = true;
break;
}
MITK_TEST_CONDITION(failed == false, "Indices in PointContainer and PointDataContainer are equal");
}
};
int mitkPointSetTest(int /*argc*/, char* /*argv*/[])
{
MITK_TEST_BEGIN("PointSet")
//Create PointSet
mitk::PointSet::Pointer pointSet = mitk::PointSet::New();
MITK_TEST_CONDITION_REQUIRED(pointSet.IsNotNull(),"Testing instantiation")
mitkPointSetTestClass::TestGetITKPointSet(pointSet);
mitkPointSetTestClass::TestGetSizeIsZero(pointSet);
mitkPointSetTestClass::TestIsEmpty(pointSet);
mitkPointSetTestClass::TestCreateOperationAndAddPoint(pointSet);
mitk::Point3D point2, point3, point4;
point2.Fill(3);
point3.Fill(4);
point4.Fill(5);
pointSet->InsertPoint(2,point2);
pointSet->InsertPoint(3,point3);
pointSet->InsertPoint(4,point4);
mitkPointSetTestClass::TestAddSecondPoint(pointSet);
mitkPointSetTestClass::TestIsNotEmpty(pointSet);
mitkPointSetTestClass::TestSwapPointPositionUpwards(pointSet);
mitkPointSetTestClass::TestSwapPointPositionUpwardsNotPossible(pointSet);
mitkPointSetTestClass::TestSwapPointPositionDownwards(pointSet);
mitkPointSetTestClass::TestSwapPointPositionDownwardsNotPossible(pointSet);
mitkPointSetTestClass::TestPointOperationOpMove(pointSet);
mitkPointSetTestClass::TestPointOperationOpRemove(pointSet);
mitkPointSetTestClass::TestPointOperationOpSelectPoint(pointSet);
mitkPointSetTestClass::TestGetNumberOfSelected(pointSet);
mitkPointSetTestClass::TestSearchSelectedPoint(pointSet);
mitkPointSetTestClass::TestOpDeselectPoint(pointSet);
mitkPointSetTestClass::TestOpMovePointUp(pointSet);
mitkPointSetTestClass::TestOpMovePointDown(pointSet);
mitkPointSetTestClass::TestSetSelectInfo(pointSet);
mitkPointSetTestClass::TestInsertPointWithPointSpecification(pointSet);
mitkPointSetTestClass::TestGetPointIfExists(pointSet);
mitkPointSetTestClass::TestCreateHoleInThePointIDs(pointSet);
mitkPointSetTestClass::TestOpMovePointUpOnFirstPoint(pointSet);
MITK_TEST_OUTPUT(<< "Test InsertPoint(), SetPoint() and SwapPointPosition()");
mitk::PointSet::PointType point;
mitk::FillVector3D(point, 2.2, 3.3, -4.4);
/* call everything that might modify PointContainer and PointDataContainer */
pointSet->InsertPoint(17, point);
pointSet->SetPoint(4, point);
pointSet->SetPoint(7, point);
pointSet->SetPoint(2, point);
pointSet->SwapPointPosition(7, true);
pointSet->SwapPointPosition(3, true);
pointSet->SwapPointPosition(2, false);
mitkPointSetTestClass::TestPointContainerPointDataContainer(pointSet);
MITK_TEST_OUTPUT(<< "Test OpREMOVE");
mitk::PointOperation op1(mitk::OpREMOVE, mitk::Point3D(), 2); // existing index
pointSet->ExecuteOperation(&op1);
mitk::PointOperation op1b(mitk::OpREMOVE, mitk::Point3D(), 112); // non existing index
pointSet->ExecuteOperation(&op1b);
mitkPointSetTestClass::TestPointContainerPointDataContainer(pointSet);
MITK_TEST_OUTPUT(<< "Test OpMove");
mitk::PointOperation op2(mitk::OpMOVE, mitk::Point3D(), 4); // existing index
pointSet->ExecuteOperation(&op2);
mitk::PointOperation op3(mitk::OpMOVE, mitk::Point3D(), 34); // non existing index
pointSet->ExecuteOperation(&op3);
mitkPointSetTestClass::TestPointContainerPointDataContainer(pointSet);
MITK_TEST_OUTPUT(<< "Test OpINSERT");
mitk::PointOperation op4(mitk::OpINSERT, mitk::Point3D(), 38); // non existing index
pointSet->ExecuteOperation(&op4);
mitk::PointOperation op5(mitk::OpINSERT, mitk::Point3D(), 17); // existing index
pointSet->ExecuteOperation(&op5);
mitkPointSetTestClass::TestPointContainerPointDataContainer(pointSet);
pointSet = mitk::PointSet::New();
pointSet->Expand(3);
mitk::Point3D new0, new1, new2;
new0.Fill(0);
new1.Fill(1);
new2.Fill(2);
pointSet->InsertPoint(5,new0, mitk::PTCORNER,0);
pointSet->InsertPoint(112,new1,0);
pointSet->InsertPoint(2,new2,0);
pointSet->InsertPoint(2,new0,1);
pointSet->InsertPoint(1,new1,1);
pointSet->InsertPoint(0,new2,1);
pointSet->InsertPoint(0,new0,2);
pointSet->InsertPoint(2,new1,2);
pointSet->InsertPoint(1,new2,2);
MITK_TEST_OUTPUT( << "... pointset ts: " << pointSet->GetTimeSteps() )
mitk::PointSet::Pointer clonePS = pointSet->Clone();
MITK_TEST_OUTPUT( << "... clone pointset ts: " << clonePS->GetTimeSteps() )
for (unsigned int t=0; t< pointSet->GetTimeSteps(); t++)
{
MITK_TEST_OUTPUT( << "testing timestep: " << t )
MITK_TEST_CONDITION_REQUIRED(pointSet->GetSize(t) == clonePS->GetSize(t), "Clone has same size")
// test for equal point coordinates
for (mitk::PointSet::PointsConstIterator i = pointSet->Begin(), j = clonePS->Begin();
i != pointSet->End() && j != clonePS->End(); ++i, ++j)
{
MITK_TEST_CONDITION_REQUIRED(i.Index() == j.Index() && mitk::Equal(i.Value(),j.Value()), "Cloned PS and PS have same points")
}
// test for equal point data
mitk::PointSet::PointDataContainer* pointDataCont = pointSet->GetPointSet(t)->GetPointData();
mitk::PointSet::PointDataContainer* clonePointDataCont = clonePS->GetPointSet(t)->GetPointData();
MITK_TEST_CONDITION_REQUIRED(pointDataCont && clonePointDataCont, "Valid point data container")
MITK_TEST_CONDITION_REQUIRED(pointDataCont->Size() == clonePointDataCont->Size(), "Cloned point data container has same size")
for (mitk::PointSet::PointDataConstIterator i = pointDataCont->Begin(), j = clonePointDataCont->Begin();
i != pointDataCont->End() && j != clonePointDataCont->End(); ++i, ++j)
{
MITK_TEST_CONDITION_REQUIRED(i.Index() == j.Index() && i.Value() == j.Value(), "Cloned PS and PS have same point data")
}
}
mitkPointSetTestClass::TestIsNotEmpty(clonePS);
MITK_TEST_CONDITION_REQUIRED(clonePS->GetPointSetSeriesSize() == pointSet->GetPointSetSeriesSize(), "Testing cloned point set's size!");
MITK_TEST_CONDITION_REQUIRED(clonePS.GetPointer() != pointSet.GetPointer(), "Testing that the clone is not the source PS!");
MITK_TEST_CONDITION_REQUIRED(clonePS->GetGeometry()->GetCenter() == pointSet->GetGeometry()->GetCenter() , "Testing if the geometry is cloned correctly!");
MITK_TEST_CONDITION_REQUIRED(clonePS->GetPropertyList()->GetMap()->size() == pointSet->GetPropertyList()->GetMap()->size() , "Testing if the property list is cloned correctly!");
// Also testing, that clone is independent from original
mitk::Point3D p, p2;
p.Fill(42);
p2.Fill(84);
clonePS->InsertPoint(0,p);
pointSet->InsertPoint(0,p2);
p = clonePS->GetPoint(0);
p2 = pointSet->GetPoint(0);
MITK_TEST_CONDITION_REQUIRED(p != p2, "Testing that the clone is independent from source!");
MITK_TEST_END();
}
| 30.950525 | 180 | 0.70311 | [
"geometry"
] |
984a90b877c6c762d81729c5fe780edd3ca015fd | 6,153 | cpp | C++ | Kuma Engine/Component_Camera.cpp | GerardClotet/Kuma-Engine | 16759a8c5e18b69eb6ce50b6feeaf50d5312e957 | [
"MIT"
] | 2 | 2019-10-07T07:11:16.000Z | 2019-10-31T16:45:56.000Z | Kuma Engine/Component_Camera.cpp | GerardClotet/Kuma-Engine | 16759a8c5e18b69eb6ce50b6feeaf50d5312e957 | [
"MIT"
] | null | null | null | Kuma Engine/Component_Camera.cpp | GerardClotet/Kuma-Engine | 16759a8c5e18b69eb6ce50b6feeaf50d5312e957 | [
"MIT"
] | null | null | null | #include "Component_Camera.h"
#include "Application.h"
#include "GameObject.h"
#include "ModuleWindow.h"
#include "ModuleSceneIntro.h"
#include "Component_Transform.h"
#include "ImGui/imgui.h"
Component_Camera::Component_Camera(GameObject* game_object)
{
this->gameObject_Item = game_object;
name = "camera";
comp_type = GO_COMPONENT::CAMERA;
SetAspectRatio(16, 9);
culling = false;
float a = frustum.horizontalFov;
LOG("%f", a);
frustum.type = FrustumType::PerspectiveFrustum;
frustum.pos = float3::zero;
frustum.front = float3::unitZ;
frustum.up = float3::unitY;
frustum.nearPlaneDistance = 1.0f;
frustum.farPlaneDistance = 100.0f;
frustum.verticalFov = 60.0f * DEGTORAD;
frustum.horizontalFov = 2.0f * atanf(tanf(frustum.verticalFov / 2.0f) * 1.3f);
far_plane = frustum.farPlaneDistance;
near_plane = frustum.nearPlaneDistance;
vertical_fov = frustum.verticalFov;
horizontal_fov = frustum.horizontalFov;
color_camera_bg = Color(0.5f, 0.5f, 0.5f, 1.0f);
color_frustum = Color( 1.0f, 0.54f, 0.0f, 1.0f );
ReloadFrustrum();
}
Component_Camera::Component_Camera()
{
comp_type = GO_COMPONENT::CAMERA;
}
Component_Camera::~Component_Camera()
{
for (std::vector<Components*>::iterator item = App->scene_intro->camera_list.begin(); item != App->scene_intro->camera_list.end(); ++item)
{
if (this == (*item))
{
App->scene_intro->camera_list.erase(item);
break;
}
}
}
void Component_Camera::ReloadFrustrum()
{
frustum.GetCornerPoints(points);
}
void Component_Camera::DrawFrustum()
{
ReloadFrustrum();
glLineWidth(3.0);
glColor3f(color_frustum.r, color_frustum.g, color_frustum.b);
glBegin(GL_LINES);
glVertex3f(points[0].x, points[0].y, points[0].z);
glVertex3f(points[1].x, points[1].y, points[1].z);
glVertex3f(points[0].x, points[0].y, points[0].z);
glVertex3f(points[4].x, points[4].y, points[4].z);
glVertex3f(points[4].x, points[4].y, points[4].z);
glVertex3f(points[5].x, points[5].y, points[5].z);
glVertex3f(points[0].x, points[0].y, points[0].z);
glVertex3f(points[2].x, points[2].y, points[2].z);
glVertex3f(points[2].x, points[2].y, points[2].z);
glVertex3f(points[3].x, points[3].y, points[3].z);
glVertex3f(points[1].x, points[1].y, points[1].z);
glVertex3f(points[3].x, points[3].y, points[3].z);
glVertex3f(points[1].x, points[1].y, points[1].z);
glVertex3f(points[5].x, points[5].y, points[5].z);
glVertex3f(points[4].x, points[4].y, points[4].z);
glVertex3f(points[6].x, points[6].y, points[6].z);
glVertex3f(points[2].x, points[2].y, points[2].z);
glVertex3f(points[6].x, points[6].y, points[6].z);
glVertex3f(points[6].x, points[6].y, points[6].z);
glVertex3f(points[7].x, points[7].y, points[7].z);
glVertex3f(points[5].x, points[5].y, points[5].z);
glVertex3f(points[7].x, points[7].y, points[7].z);
glVertex3f(points[3].x, points[3].y, points[3].z);
glVertex3f(points[7].x, points[7].y, points[7].z);
glEnd();
glLineWidth(1.0);
}
void Component_Camera::UpdateTransformFrustum()
{
gameObject_Item->transform->GetGlobalMatrix();
frustum.pos = gameObject_Item->transform->GetGlobalPosition();
frustum.front = gameObject_Item->transform->GetGlobalRotation() * float3::unitZ;
frustum.up = gameObject_Item->transform->GetGlobalRotation() * float3::unitY;;
}
void Component_Camera::DisplayInspector()
{
if (ImGui::DragFloat("Near Plane", &near_plane, 1, 0.1f, far_plane - 0.1f, "%.1f"))
{
frustum.nearPlaneDistance = near_plane;
}
ImGui::Spacing();
if (ImGui::DragFloat("Far Plane", &far_plane, 1, near_plane + 0.1f, 500, "%.1f"))
{
frustum.farPlaneDistance = far_plane;
}
ImGui::Spacing();
ImGui::Spacing();
if (ImGui::DragFloat("FOV Horizontal", &horizontal_fov, 1, 1, 163, "%.1f"))
{
frustum.horizontalFov = horizontal_fov * DEGTORAD;
SetAspectRatio(16, 9, true);
vertical_fov = frustum.verticalFov * RADTODEG;
}
if (ImGui::DragFloat("FOV Vertical", &vertical_fov, 1, 1, 150, "%.1f"))
{
frustum.verticalFov = vertical_fov * DEGTORAD;
SetAspectRatio(16, 9);
horizontal_fov = frustum.horizontalFov * RADTODEG;
}
ImGui::Spacing();
ImGui::Checkbox("Frustum Culling", &culling);
ImGui::Spacing();
ImGui::ColorEdit4("Frustum Color", (float*)& color_frustum);
}
void Component_Camera::Look(const float3 & position)
{
float3 direction = position - frustum.pos;
float3x3 matrix = float3x3::LookAt(frustum.front, direction.Normalized(), frustum.up, float3::unitY);
frustum.front = matrix.MulDir(frustum.front).Normalized();
frustum.up = matrix.MulDir(frustum.up).Normalized();
}
float3 Component_Camera::GetCameraPosition() const
{
return frustum.pos;
}
float * Component_Camera::GetViewMatrix()
{
return (float*)static_cast<float4x4>(frustum.ViewMatrix()).Transposed().v;
}
float * Component_Camera::GetProjectionMatrix() const
{
return (float*)frustum.ProjectionMatrix().Transposed().v;
}
void Component_Camera::SetAspectRatio(int width_ratio, int height_ratio, bool type)
{
if (!type)
{
frustum.horizontalFov = (2.f * atanf(tanf(frustum.verticalFov * 0.5f) * ((float)width_ratio / (float)height_ratio)));
}
else
{
frustum.verticalFov = (2.f * atanf(tanf(frustum.horizontalFov * 0.5f) * ((float)height_ratio) / (float)width_ratio));
}
}
bool Component_Camera::Update()
{
UpdateTransformFrustum();
if (!this->gameObject_Item->show)
DrawFrustum();
return true;
}
void Component_Camera::SaveScene(R_JSON_Value* val) const
{
R_JSON_Value* camera = val->NewValue(rapidjson::kObjectType);
camera->SetString("Component", "Camera");
camera->SetUint("FrustumType", frustum.type);
camera->SetFloat("Horizontal Fov", frustum.horizontalFov);
camera->SetFloat("Vertical Fov", frustum.verticalFov);
camera->SetFloat("AspectRatio", aspect_ratio);
camera->SetFloat("Far Plane", frustum.farPlaneDistance);
camera->SetFloat("Near Plane", frustum.nearPlaneDistance);
camera->Set3DVec("Position", GetCameraPosition());
camera->Set3DVec("front", frustum.front);
camera->Set3DVec("Up", frustum.up);
camera->SetColor("Frustum Color", color_frustum);
camera->SetColor("Camera Background Color", color_camera_bg);
val->AddValue("Camera", *camera);
} | 25.6375 | 139 | 0.707785 | [
"vector",
"transform"
] |
984b26f1a910f375fe6516a7e9430e744ebd2ef3 | 4,780 | cpp | C++ | cegui/src/ScriptModules/Python/bindings/output/CEGUI/NamedArea.pypp.cpp | OpenTechEngine-Libraries/CEGUI | 6f00952d31f318f9482766d1ad2206cb540a78b9 | [
"MIT"
] | 257 | 2020-01-03T10:13:29.000Z | 2022-03-26T14:55:12.000Z | cegui/src/ScriptModules/Python/bindings/output/CEGUI/NamedArea.pypp.cpp | OpenTechEngine-Libraries/CEGUI | 6f00952d31f318f9482766d1ad2206cb540a78b9 | [
"MIT"
] | 116 | 2020-01-09T18:13:13.000Z | 2022-03-15T18:32:02.000Z | cegui/src/ScriptModules/Python/bindings/output/CEGUI/NamedArea.pypp.cpp | OpenTechEngine-Libraries/CEGUI | 6f00952d31f318f9482766d1ad2206cb540a78b9 | [
"MIT"
] | 58 | 2020-01-09T03:07:02.000Z | 2022-03-22T17:21:36.000Z | // This file has been generated by Py++.
#include "boost/python.hpp"
#include "generators/include/python_CEGUI.h"
#include "NamedArea.pypp.hpp"
namespace bp = boost::python;
void register_NamedArea_class(){
{ //::CEGUI::NamedArea
typedef bp::class_< CEGUI::NamedArea > NamedArea_exposer_t;
NamedArea_exposer_t NamedArea_exposer = NamedArea_exposer_t( "NamedArea", bp::init< >() );
bp::scope NamedArea_scope( NamedArea_exposer );
NamedArea_exposer.def( bp::init< CEGUI::String const & >(( bp::arg("name") )) );
bp::implicitly_convertible< CEGUI::String const &, CEGUI::NamedArea >();
{ //::CEGUI::NamedArea::getArea
typedef ::CEGUI::ComponentArea const & ( ::CEGUI::NamedArea::*getArea_function_type )( ) const;
NamedArea_exposer.def(
"getArea"
, getArea_function_type( &::CEGUI::NamedArea::getArea )
, bp::return_value_policy< bp::copy_const_reference >()
, "*!\n\
\n\
Return the ComponentArea of this NamedArea\n\
\n\
@return\n\
ComponentArea object describing the NamedArea's current target area.\n\
*\n" );
}
{ //::CEGUI::NamedArea::getName
typedef ::CEGUI::String const & ( ::CEGUI::NamedArea::*getName_function_type )( ) const;
NamedArea_exposer.def(
"getName"
, getName_function_type( &::CEGUI::NamedArea::getName )
, bp::return_value_policy< bp::copy_const_reference >()
, "*!\n\
\n\
Return the name of this NamedArea.\n\
\n\
@return\n\
String object holding the name of this NamedArea.\n\
*\n" );
}
{ //::CEGUI::NamedArea::handleFontRenderSizeChange
typedef bool ( ::CEGUI::NamedArea::*handleFontRenderSizeChange_function_type )( ::CEGUI::Window &,::CEGUI::Font const * ) const;
NamedArea_exposer.def(
"handleFontRenderSizeChange"
, handleFontRenderSizeChange_function_type( &::CEGUI::NamedArea::handleFontRenderSizeChange )
, ( bp::arg("window"), bp::arg("font") )
, "! perform any processing required due to the given font having changed.\n" );
}
{ //::CEGUI::NamedArea::setArea
typedef void ( ::CEGUI::NamedArea::*setArea_function_type )( ::CEGUI::ComponentArea const & ) ;
NamedArea_exposer.def(
"setArea"
, setArea_function_type( &::CEGUI::NamedArea::setArea )
, ( bp::arg("area") )
, "*!\n\
\n\
Set the Area for this NamedArea.\n\
\n\
@param area\n\
ComponentArea object describing a new target area for the NamedArea..\n\
\n\
@return\n\
Nothing.\n\
*\n" );
}
{ //::CEGUI::NamedArea::setName
typedef void ( ::CEGUI::NamedArea::*setName_function_type )( ::CEGUI::String const & ) ;
NamedArea_exposer.def(
"setName"
, setName_function_type( &::CEGUI::NamedArea::setName )
, ( bp::arg("name") )
, "*!\n\
\n\
set the name for this NamedArea.\n\
\n\
@param area\n\
String object holding the name of this NamedArea.\n\
\n\
@return\n\
Nothing.\n\
*\n" );
}
{ //::CEGUI::NamedArea::writeXMLToStream
typedef void ( ::CEGUI::NamedArea::*writeXMLToStream_function_type )( ::CEGUI::XMLSerializer & ) const;
NamedArea_exposer.def(
"writeXMLToStream"
, writeXMLToStream_function_type( &::CEGUI::NamedArea::writeXMLToStream )
, ( bp::arg("xml_stream") )
, "*!\n\
\n\
Writes an xml representation of this NamedArea to out_stream.\n\
\n\
@param out_stream\n\
Stream where xml data should be output.\n\
\n\
@return\n\
Nothing.\n\
*\n" );
}
}
}
| 38.24 | 140 | 0.470711 | [
"object"
] |
985a5b5236c1c4baf226d08d5fabd7310cb5a9b8 | 3,689 | cpp | C++ | Homeworks/0_CppPratices/project/src/executables/4_list_Polynomial/PolynomialList.cpp | Chaphlagical/USTC_CG | 9f8b0321e09e5a05afb1c93303e3c736f78503fa | [
"MIT"
] | 13 | 2020-05-21T03:12:48.000Z | 2022-01-20T01:25:02.000Z | Homeworks/0_CppPratices/project/src/executables/4_list_Polynomial/PolynomialList.cpp | lyf7115/USTC_CG | 9f8b0321e09e5a05afb1c93303e3c736f78503fa | [
"MIT"
] | null | null | null | Homeworks/0_CppPratices/project/src/executables/4_list_Polynomial/PolynomialList.cpp | lyf7115/USTC_CG | 9f8b0321e09e5a05afb1c93303e3c736f78503fa | [
"MIT"
] | 4 | 2020-06-13T13:14:14.000Z | 2021-12-15T07:36:05.000Z | #include "PolynomialList.h"
bool Node_cmp(const Node &node1, const Node &node2)
{
return node1.deg < node2.deg ? true : false;
}
void PolynomialList::Compress()
{
std::list<Node>::iterator it1, it2, it3;
it1 = m_Polynomial.begin();
for (; it1 != m_Polynomial.end(); it1++)
{
for (it2=it1; ++it2 != m_Polynomial.end();)
{
if (it1->deg == it2->deg)
{
it1->cof += it2->cof;
it2 = --m_Polynomial.erase(it2);
}
}
}
it1 = m_Polynomial.begin();
for (; it1 != m_Polynomial.end(); it1++)
{
if (it1->cof == 0)
it1 = --m_Polynomial.erase(it1);
}
}
void PolynomialList::ReadFromFile(std::string file)
{
std::ifstream infile;
char buf;
int n;
infile.open(file.c_str(), std::ios::in);
infile >> buf;
infile >> n;
for (int i = 0; i < n; i++)
{
Node node;
infile >> node.deg;
infile >> node.cof;
m_Polynomial.push_back(node);
}
}
void PolynomialList::AddOneTerm(Node term)
{
m_Polynomial.push_back(term);
}
PolynomialList::PolynomialList()
{
}
PolynomialList::PolynomialList(std::string file)
{
ReadFromFile(file);
m_Polynomial.sort(Node_cmp);
Compress();
}
PolynomialList::PolynomialList(double *cof, double *deg, int n)
{
for (int i = 0; i < n; i++)
{
Node node;
node.cof = cof[i];
node.deg = deg[i];
AddOneTerm(node);
}
m_Polynomial.sort(Node_cmp);
Compress();
}
PolynomialList::PolynomialList(std::vector<double>cof, std::vector<int>deg)
{
if (cof.size() != deg.size())
{
std::cout << "(cof.size() != deg.size()" << std::endl;
}
size_t size = cof.size() < deg.size() ? cof.size() : deg.size();
for (int i = 0; i < size; i++)
{
Node node = { cof[i],deg[i] };
AddOneTerm(node);
}
m_Polynomial.sort(Node_cmp);
Compress();
}
PolynomialList::~PolynomialList()
{
}
void PolynomialList::Print()
{
std::list<Node>::iterator it = m_Polynomial.begin();
if (it == m_Polynomial.end())
{
std::cout << "Polynomial empty!" << std::endl;
return;
}
if (it->deg == 0)
{
std::cout << it->cof;
}
else
{
std::cout << it->cof << "*x^" << it->deg;
}
it++;
for (; it != m_Polynomial.end(); it++)
{
if (it->cof >= 0)
std::cout << "+" << it->cof << "*x^" << it->deg;
else
std::cout << it->cof << "*x^" << it->deg;
}
std::cout << std::endl;
}
PolynomialList &PolynomialList::operator=(const PolynomialList &right)
{
m_Polynomial.clear();
std::list<Node>::const_iterator it = right.m_Polynomial.begin();
for (; it != right.m_Polynomial.end(); it++)
{
AddOneTerm(*it);
}
return *this;
}
PolynomialList PolynomialList::operator+(const PolynomialList &right)
{
PolynomialList ploy(right);
std::list<Node>::const_iterator it = m_Polynomial.begin();
for (; it != m_Polynomial.end(); it++)
{
ploy.AddOneTerm(*it);
}
ploy.m_Polynomial.sort(Node_cmp);
ploy.Compress();
return ploy;
}
PolynomialList PolynomialList::operator-(const PolynomialList &right)
{
PolynomialList ploy(*this);
std::list<Node>::const_iterator it = right.m_Polynomial.begin();
for (; it != right.m_Polynomial.end(); it++)
{
Node node = { -it->cof ,it->deg };
ploy.AddOneTerm(node);
}
ploy.m_Polynomial.sort(Node_cmp);
ploy.Compress();
return ploy;
}
PolynomialList PolynomialList::operator*(const PolynomialList &right)
{
PolynomialList ploy;
int count = 0;
for (std::list<Node>::const_iterator it_right = right.m_Polynomial.begin(); it_right != right.m_Polynomial.end(); it_right++)
{
for (std::list<Node>::const_iterator it_left = m_Polynomial.begin(); it_left != m_Polynomial.end(); it_left++)
{
Node node = { it_right->cof*it_left->cof, it_right->deg + it_left->deg };
ploy.AddOneTerm(node);
}
}
ploy.m_Polynomial.sort(Node_cmp);
ploy.Compress();
return ploy;
} | 19.11399 | 126 | 0.635945 | [
"vector"
] |
985d0ab477a6552b709007467e547b4d4d8d6d74 | 7,854 | cpp | C++ | src/gfx-pbr/Light.cpp | alecnunn/mud | 9e204e2dc65f4a8ab52da3d11e6a261ff279d353 | [
"Zlib"
] | 1 | 2019-03-28T20:45:32.000Z | 2019-03-28T20:45:32.000Z | src/gfx-pbr/Light.cpp | alecnunn/mud | 9e204e2dc65f4a8ab52da3d11e6a261ff279d353 | [
"Zlib"
] | null | null | null | src/gfx-pbr/Light.cpp | alecnunn/mud | 9e204e2dc65f4a8ab52da3d11e6a261ff279d353 | [
"Zlib"
] | null | null | null | // Copyright (c) 2019 Hugo Amiard hugo.amiard@laposte.net
// This software is provided 'as-is' under the zlib License, see the LICENSE.txt file.
// This notice and the license may not be removed or altered from any source distribution.
#include <gfx/Cpp20.h>
#include <bgfx/bgfx.h>
#ifdef MUD_MODULES
module mud.gfx.pbr;
#else
#include <infra/Vector.h>
#include <infra/StringConvert.h>
#include <math/VecOps.h>
#include <gfx/Shot.h>
#include <gfx/Item.h>
#include <gfx/Viewport.h>
#include <gfx/Scene.h>
#include <gfx/Camera.h>
#include <gfx/Froxel.h>
#include <gfx-pbr/Types.h>
#include <gfx-pbr/Light.h>
#include <gfx-pbr/Shadow.h>
#endif
namespace mud
{
constexpr size_t BlockLight::ShotUniform::max_lights;
constexpr size_t BlockLight::ShotUniform::max_shadows;
constexpr size_t BlockLight::ShotUniform::max_forward_lights;
constexpr size_t BlockLight::ShotUniform::max_direct_lights;
BlockLight::BlockLight(GfxSystem& gfx_system, BlockShadow& block_shadow)
: DrawBlock(gfx_system, type<BlockLight>())
, m_block_shadow(block_shadow)
{
static cstring options[2] = { "FOG", "DIRECT_LIGHT" };
m_shader_block->m_options = { options, 2 };
static string max_lights = to_string(ShotUniform::max_lights);
static string max_shadows = to_string(ShotUniform::max_shadows);
static string max_dir_lights = to_string(ShotUniform::max_direct_lights);
static ShaderDefine defines[3] = {
{ "MAX_LIGHTS", max_lights.c_str() },
{ "MAX_SHADOWS", max_shadows.c_str() },
{ "MAX_DIRECT_LIGHTS", max_dir_lights.c_str() }
};
m_shader_block->m_defines = { defines, 3 };
}
void BlockLight::init_block()
{
u_shot.createUniforms();
u_scene.createUniforms();
u_fog.createUniforms();
}
void BlockLight::begin_render(Render& render)
{
UNUSED(render);
m_direct_lights.clear();
for(Light* light : render.m_shot->m_lights)
{
if(light->m_type == LightType::Direct && m_direct_lights.size() < ShotUniform::max_direct_lights)
m_direct_lights.push_back(light);
}
m_direct_light = m_direct_lights.empty() ? nullptr : m_direct_lights[m_direct_light_index];
m_block_shadow.m_direct_light = m_direct_light;
}
void BlockLight::begin_pass(Render& render)
{
UNUSED(render);
}
void BlockLight::begin_draw_pass(Render& render)
{
this->update_lights(render, render.m_camera.m_transform, to_array(render.m_shot->m_lights), to_array(m_block_shadow.m_shadows));
m_direct_light_index = 0;
m_direct_light = m_direct_lights.empty() ? nullptr : m_direct_lights[m_direct_light_index];
m_block_shadow.m_direct_light = m_direct_light;
#ifdef MULTIPLE_DIRECT_LIGHTS
if(!m_direct_lights.empty())
m_direct_light = m_direct_lights[m_direct_light_index++];
if(m_direct_light_index > 0)
render_pass.m_bgfx_state |= BGFX_STATE_BLEND_ADD;
request.num_passes = m_direct_lights.empty() ? 1 : m_direct_lights.size();
#endif
}
void BlockLight::options(Render& render, ShaderVersion& shader_version) const
{
if(render.m_camera.m_clustered)
shader_version.set_option(0, CLUSTERED, true);
if(render.m_environment && render.m_environment->m_fog.m_enabled)
shader_version.set_option(m_index, FOG, true);
bool cull = !m_direct_light || false; // !(element.m_item->m_layer_mask & m_direct_light->m_layers);
if(!cull)
shader_version.set_option(m_index, DIRECT_LIGHT, true);
}
void BlockLight::submit(Render& render, const Pass& render_pass) const
{
bgfx::Encoder& encoder = *render_pass.m_encoder;
if(render.m_camera.m_clustered)
render.m_camera.m_clusters->submit(encoder);
this->upload_environment(render, render_pass, render.m_environment);
this->upload_fog(render, render_pass, render.m_scene.m_environment.m_fog);
this->upload_lights(render_pass);
// set to not render if not first direct pass, depending on cull
}
void BlockLight::upload_environment(Render& render, const Pass& render_pass, Environment* environment) const
{
bgfx::Encoder& encoder = *render_pass.m_encoder;
Colour clear_color = render.m_viewport.m_clear_colour;
vec4 radiance_color_energy = { to_vec3(clear_color), 1.f };
vec4 ambient_params = { 0.f, 0.f, 0.f, 0.f };
if(environment)
{
radiance_color_energy = { to_vec3(environment->m_radiance.m_colour), environment->m_radiance.m_energy };
ambient_params = { environment->m_radiance.m_ambient, 0.f, 0.f, 0.f };
}
encoder.setUniform(u_scene.u_radiance_color_energy, &radiance_color_energy);
encoder.setUniform(u_scene.u_ambient_params, &ambient_params);
}
void BlockLight::upload_fog(Render& render, const Pass& render_pass, Fog& fog) const
{
UNUSED(render);
if(!fog.m_enabled)
return;
bgfx::Encoder& encoder = *render_pass.m_encoder;
vec4 fog_params_0 = { fog.m_density, to_vec3(fog.m_colour) };
vec4 fog_params_1 = { float(fog.m_depth), fog.m_depth_begin, fog.m_depth_curve, 0.f };
vec4 fog_params_2 = { float(fog.m_height), fog.m_height_max, fog.m_height_max, fog.m_height_curve };
vec4 fog_params_3 = { float(fog.m_transmit), fog.m_transmit_curve, 0.f, 0.f };
encoder.setUniform(u_fog.u_fog_params_0, &fog_params_0);
encoder.setUniform(u_fog.u_fog_params_1, &fog_params_1);
encoder.setUniform(u_fog.u_fog_params_2, &fog_params_2);
encoder.setUniform(u_fog.u_fog_params_3, &fog_params_3);
}
void BlockLight::update_lights(Render& render, const mat4& view, array<Light*> all_lights, array<LightShadow> shadows)
{
UNUSED(render);
mat4 inverse_view = inverse(view);
array<Light*> lights = { all_lights.m_pointer, min(all_lights.m_count, size_t(ShotUniform::max_lights)) };
uint16_t light_count = 0;
m_lights_data.light_counts = Zero4;
for(Light* light : lights)
{
Colour energy = to_linear(light->m_colour) * light->m_energy;
vec3 position = vec3(view * vec4(light->m_node.position(), 1.f));
vec3 direction = vec3(view * vec4(light->m_node.direction(), 0.f));
Colour shadow_color = to_linear(light->m_shadow_colour);
m_lights_data.shadow_color_enabled[light_count] = { to_vec3(shadow_color), light->m_shadows ? 1.f : 0.f };
m_lights_data.position_range[light_count] = { position, light->m_range };
m_lights_data.energy_specular[light_count] = { to_vec3(energy), light->m_specular };
m_lights_data.direction_attenuation[light_count] = { direction, light->m_attenuation };
m_lights_data.spot_params[light_count] = { light->m_spot_attenuation, cos(to_radians(light->m_spot_angle)), 0.f, 0.f };
float& light_type_count = m_lights_data.light_counts[size_t(light->m_type)];
m_lights_data.light_indices[size_t(light_type_count)][size_t(light->m_type)] = light_count;
light_type_count++;
if(light->m_shadows) //&& shadows[light_count])
{
if(light->m_type == LightType::Direct)
{
for(uint32_t i = 0; i < shadows[light_count].m_frustum_slices.size(); ++i)
{
m_lights_data.csm_splits[light_count][i] = shadows[light_count].m_frustum_slices[i].m_frustum.m_far;
m_lights_data.csm_matrix[light_count][i] = shadows[light_count].m_slices[i].m_shadow_matrix * inverse_view;
}
}
else if(light->m_type == LightType::Point)
{
m_lights_data.shadow_matrix[light_count] = inverse(view * light->m_node.m_transform);
}
else if(light->m_type == LightType::Spot)
{
m_lights_data.shadow_matrix[light_count] = shadows[light_count].m_slices[0].m_shadow_matrix * inverse_view;
}
}
light_count++;
}
m_light_count = light_count;
}
void BlockLight::upload_lights(const Pass& render_pass) const
{
bgfx::Encoder& encoder = *render_pass.m_encoder;
if(m_light_count > 0)
u_shot.u_light_array.setUniforms(encoder, m_lights_data, uint16_t(m_direct_lights.size()), m_light_count);
encoder.setUniform(u_shot.u_light_counts, &m_lights_data.light_counts);
encoder.setUniform(u_shot.u_light_indices, m_lights_data.light_indices, m_light_count);
}
}
| 34.147826 | 130 | 0.742552 | [
"render",
"vector"
] |
98611421b2e25350792198a7aba63315f70d99aa | 7,883 | cpp | C++ | main/main.cpp | chemicstry/eacs-esp32-old | 8d8b9d580a8963e851ed24a87a693066b276e20a | [
"MIT"
] | 1 | 2021-02-01T05:02:51.000Z | 2021-02-01T05:02:51.000Z | main/main.cpp | chemicstry/eacs-esp32-old | 8d8b9d580a8963e851ed24a87a693066b276e20a | [
"MIT"
] | null | null | null | main/main.cpp | chemicstry/eacs-esp32-old | 8d8b9d580a8963e851ed24a87a693066b276e20a | [
"MIT"
] | null | null | null | #include "WebSocketsClient.h"
#include "PN532Instance.h"
#include "JSONRPC/JSONRPC.h"
#include "Service.h"
#include "Utils.h"
#include "esp_log.h"
#include <thread>
#include "Arduino.h"
#include "network.h"
#include "driver/uart.h"
#if CONFIG_USE_MDNS
#include <ESPmDNS.h>
#endif
static const char* TAG = "main";
using namespace std::placeholders;
using json = nlohmann::json;
Service server("eacs-server");
#define RELAY_PIN CONFIG_RELAY_PIN
#define BUZZER_PIN CONFIG_BUZZER_PIN
void tone(int pin, int freq, int duration)
{
int channel = 0;
int resolution = 8;
ledcSetup(channel, 2000, resolution);
ledcAttachPin(pin, channel);
ledcWriteTone(channel, freq);
ledcWrite(channel, 255);
delay(duration);
ledcWrite(channel, 0);
}
#define BUZZ_SHORT 200
#define BUZZ_LONG 800
void buzz(int duration)
{
#if CONFIG_BUZZER_PWM
tone(CONFIG_BUZZER_PIN, 2000, duration);
#else
digitalWrite(CONFIG_BUZZER_PIN, HIGH);
delay(duration);
digitalWrite(CONFIG_BUZZER_PIN, LOW);
#endif
}
// Opens doors
void open()
{
ESP_LOGI(TAG, "Opening doors");
digitalWrite(RELAY_PIN, HIGH);
buzz(BUZZ_SHORT);
delay(CONFIG_DOOR_OPEN_DURATION);
digitalWrite(RELAY_PIN, LOW);
}
void setupNFC()
{
// Start PN532
PN532Serial.begin(PN532_HSU_SPEED, SERIAL_8N1, CONFIG_READER_RX_PIN, CONFIG_READER_TX_PIN);
NFC.begin();
// Get PN532 firmware version
GetFirmwareVersionResponse version;
if (!NFC.GetFirmwareVersion(version)) {
ESP_LOGE(TAG, "Unable to fetch PN532 firmware version");
ESP.restart();
}
// configure board to read RFID tags and prevent going to sleep
if (!NFC.SAMConfig()) {
ESP_LOGE(TAG, "NFC SAMConfig failed");
ESP.restart();
}
// Print chip data
ESP_LOGI(TAG, "Found chip PN5%02X", version.IC);
ESP_LOGI(TAG, "Firmware version: %#04X", version.Ver);
ESP_LOGI(TAG, "Firmware revision: %#04X", version.Rev);
ESP_LOGI(TAG, "Features: ISO18092: %d, ISO14443A: %d, ISO14443B: %d",
(bool)version.Support.ISO18092,
(bool)version.Support.ISO14443_TYPEA,
(bool)version.Support.ISO14443_TYPEB);
// Set the max number of retry attempts to read from a card
// This prevents us from waiting forever for a card, which is
// the default behaviour of the PN532.
if (!NFC.SetPassiveActivationRetries(0x00)) {
ESP_LOGE(TAG, "NFC SetPassiveActivationRetries failed");
ESP.restart();
}
}
// Builds tagInfo JSON object
json BuildTagInfo(const PN532Packets::TargetDataTypeA& tgdata)
{
json taginfo;
taginfo["ATQA"] = tgdata.ATQA;
taginfo["SAK"] = tgdata.SAK;
// Hex encoded strings
taginfo["ATS"] = BinaryDataToHexString(tgdata.ATS);
taginfo["UID"] = BinaryDataToHexString(tgdata.UID);
return taginfo;
}
// Waits for RFID tag and then authenticates
std::thread RFIDThread;
void RFIDThreadFunc()
{
// Configures PN532
setupNFC();
// Door relay
pinMode(RELAY_PIN, OUTPUT);
// Holds index of the current active tag
// Used in matching transceive RPC call to tag
static int currentTg = 0;
// Transceive RPC method
server.RPC->bind("transceive", [](std::string data) {
// Parse hex string to binary array
BinaryData buf = HexStringToBinaryData(data);
// Create interface with tag
TagInterface tif = NFC.CreateTagInterface(currentTg);
// Send
if (tif.Write(buf))
throw JSONRPC::RPCMethodException(1, "Write failed");
// Receive
if (tif.Read(buf) < 0)
throw JSONRPC::RPCMethodException(2, "Read failed");
// Convert back to hex encoded string
return BinaryDataToHexString(buf);
});
while(1)
{
// Finds nearby ISO14443 Type A tags
InListPassiveTargetResponse resp;
if (!NFC.InListPassiveTarget(resp, 1, BRTY_106KBPS_TYPE_A))
{
ESP_LOGE(TAG, "NFC InListPassiveTarget failed");
ESP.restart();
}
// Only read one tag at a time
if (resp.NbTg != 1)
{
// Yield to kernel
delay(10);
continue;
}
ESP_LOGI(TAG, "Detected RFID tag");
// For parsing response data
ByteBuffer buf(resp.TgData);
// Parse as ISO14443 Type A target
PN532Packets::TargetDataTypeA tgdata;
buf >> tgdata;
// Set current active tag
currentTg = tgdata.Tg;
// Convert UID to hex encoded string
std::string UID = BinaryDataToHexString(tgdata.UID);
ESP_LOGI(TAG, "Tag UID: %s", UID.c_str());
// Initiate authentication
try {
ESP_LOGI(TAG, "Performing RPC authentication...");
if (!tagAuth.RPC->call("rfid:auth", BuildTagInfo(tgdata)))
{
ESP_LOGE(TAG, "Tag auth failed!");
buzz(BUZZ_LONG);
continue;
}
} catch (const JSONRPC::RPCMethodException& e) {
ESP_LOGE(TAG, "RPC call failed: %s", e.message.c_str());
buzz(BUZZ_LONG);
continue;
} catch (const JSONRPC::TimeoutException& e) {
ESP_LOGE(TAG, "RPC call timed out");
buzz(BUZZ_LONG);
continue;
}
ESP_LOGI(TAG, "Auth successful!");
// Open doors
open();
}
}
#define READER_BUTTON_PIN CONFIG_READER_BUTTON_PIN
#define READER_BUTTON_TIMEOUT 1000
#define EXIT_BUTTON_PIN CONFIG_EXIT_BUTTON_PIN
#define EXIT_BUTTON_TIMEOUT 1000
std::thread GPIOThread;
void GPIOThreadFunc()
{
static uint64_t readerButtonTimeout = 0;
static uint64_t exitButtonTimeout = 0;
ESP_LOGI(TAG, "GPIO thread started");
while(1)
{
/*if (!digitalRead(READER_BUTTON_PIN) && readerButtonTimeout+READER_BUTTON_TIMEOUT < millis())
{
readerButtonTimeout = millis();
ESP_LOGI(TAG, "Reader button pressed");
messageBus.RPC->notify("publish", "button");
}*/
if (!digitalRead(EXIT_BUTTON_PIN) && exitButtonTimeout+EXIT_BUTTON_TIMEOUT < millis())
{
exitButtonTimeout = millis();
ESP_LOGI(TAG, "Exit button pressed");
open();
}
delay(10);
}
}
std::thread NetworkThread;
void NetworkThreadFunc() {
while(1)
{
if (network_loop())
{
server.transport.update();
}
// Yield to kernel to prevent triggering watchdog
delay(10);
}
}
extern "C" void app_main() {
initArduino();
// Start mDNS
#if CONFIG_USE_MDNS
if (!MDNS.begin("eacs_esp32")) {
ESP_LOGE(TAG, "mDNS responder setup failed.");
ESP.restart();
}
#endif
Serial.begin(115200);
Serial.setDebugOutput(true);
// Configures WiFi and/or Ethernet
network_setup();
// Configures task state reporting if enabled in menuconfig
EnableTaskStats();
// Setup buttons
pinMode(READER_BUTTON_PIN, INPUT);
pinMode(EXIT_BUTTON_PIN, INPUT);
// Setup buzzer
pinMode(BUZZER_PIN, OUTPUT);
digitalWrite(BUZZER_PIN, LOW);
#if CONFIG_SERVER_USE_MDNS
server.MDNSQuery();
#else
server.host = CONFIG_SERVER_HOST;
server.port = CONFIG_SERVER_PORT;
#endif
server.token = CONFIG_SERVER_TOKEN;
#if CONFIG_SERVER_SSL
server.fingerprint = CONFIG_SERVER_SSL_FINGERPRINT;
server.BeginTransportSSL();
#else
server.BeginTransport();
#endif
// Starts network thread
NetworkThread = std::thread(NetworkThreadFunc);
// Starts main RFID thread
RFIDThread = std::thread(RFIDThreadFunc);
// Starts GPIO thread (button checking)
GPIOThread = std::thread(GPIOThreadFunc);
}
| 25.594156 | 102 | 0.624382 | [
"object"
] |
9863b1464152bd7c1601e854c98120f8d25ff205 | 5,461 | cpp | C++ | third_party/WebKit/Source/core/css/threaded/FontObjectThreadedTest.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/core/css/threaded/FontObjectThreadedTest.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/core/css/threaded/FontObjectThreadedTest.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // 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 "core/css/resolver/FilterOperationResolver.h"
#include "core/css/parser/CSSParser.h"
#include "core/css/parser/CSSParserContext.h"
#include "core/css/resolver/FontStyleResolver.h"
#include "core/css/threaded/MultiThreadedTestUtil.h"
#include "platform/Language.h"
#include "platform/fonts/Font.h"
#include "platform/fonts/FontCustomPlatformData.h"
#include "platform/fonts/FontDescription.h"
#include "platform/fonts/FontSelector.h"
#include "platform/fonts/shaping/CachingWordShapeIterator.h"
#include "platform/fonts/shaping/HarfBuzzShaper.h"
#include "platform/testing/FontTestHelpers.h"
#include "platform/testing/UnitTestHelpers.h"
#include "testing/gtest/include/gtest/gtest.h"
using blink::testing::CreateTestFont;
namespace blink {
TSAN_TEST(FontObjectThreadedTest, Language) {
RunOnThreads([]() { EXPECT_EQ(DefaultLanguage(), "en-US"); });
}
TSAN_TEST(FontObjectThreadedTest, GetFontDefinition) {
RunOnThreads([]() {
MutableStylePropertySet* style =
MutableStylePropertySet::Create(kHTMLStandardMode);
CSSParser::ParseValue(style, CSSPropertyFont, "15px Ahem", true);
FontDescription desc = FontStyleResolver::ComputeFont(*style);
EXPECT_EQ(desc.SpecifiedSize(), 15);
EXPECT_EQ(desc.ComputedSize(), 15);
EXPECT_EQ(desc.Family().Family(), "Ahem");
});
}
TSAN_TEST(FontObjectThreadedTest, GetDefaultFontData) {
callbacks_per_thread_ = 30;
num_threads_ = 5;
RunOnThreads([]() {
for (FontDescription::GenericFamilyType family_type :
{FontDescription::kStandardFamily, FontDescription::kSerifFamily,
FontDescription::kSansSerifFamily, FontDescription::kMonospaceFamily,
FontDescription::kCursiveFamily, FontDescription::kFantasyFamily,
FontDescription::kPictographFamily}) {
FontDescription font_description;
font_description.SetComputedSize(12.0);
font_description.SetLocale(LayoutLocale::Get("en"));
ASSERT_EQ(USCRIPT_LATIN, font_description.GetScript());
font_description.SetGenericFamily(family_type);
Font font = Font(font_description);
font.Update(nullptr);
ASSERT_TRUE(font.PrimaryFont());
}
});
}
// This test passes by not crashing TSAN.
TSAN_TEST(FontObjectThreadedTest, FontSelector) {
RunOnThreads([]() {
Font font =
CreateTestFont("Ahem", testing::CoreTestDataPath("Ahem.ttf"), 16);
});
}
TSAN_TEST(FontObjectThreadedTest, TextIntercepts) {
callbacks_per_thread_ = 10;
RunOnThreads([]() {
Font font =
CreateTestFont("Ahem", testing::CoreTestDataPath("Ahem.ttf"), 16);
// A sequence of LATIN CAPITAL LETTER E WITH ACUTE and LATIN SMALL LETTER P
// characters. E ACUTES are squares above the baseline in Ahem, while p's
// are rectangles below the baseline.
UChar ahem_above_below_baseline_string[] = {0xc9, 0x70, 0xc9, 0x70, 0xc9,
0x70, 0xc9, 0x70, 0xc9};
TextRun ahem_above_below_baseline(ahem_above_below_baseline_string, 9);
TextRunPaintInfo text_run_paint_info(ahem_above_below_baseline);
PaintFlags default_paint;
float device_scale_factor = 1;
std::tuple<float, float> below_baseline_bounds = std::make_tuple(2, 4);
Vector<Font::TextIntercept> text_intercepts;
// 4 intercept ranges for below baseline p glyphs in the test string
font.GetTextIntercepts(text_run_paint_info, device_scale_factor,
default_paint, below_baseline_bounds,
text_intercepts);
EXPECT_EQ(text_intercepts.size(), 4u);
for (auto text_intercept : text_intercepts) {
EXPECT_GT(text_intercept.end_, text_intercept.begin_);
}
std::tuple<float, float> above_baseline_bounds = std::make_tuple(-4, -2);
// 5 intercept ranges for the above baseline E ACUTE glyphs
font.GetTextIntercepts(text_run_paint_info, device_scale_factor,
default_paint, above_baseline_bounds,
text_intercepts);
EXPECT_EQ(text_intercepts.size(), 5u);
for (auto text_intercept : text_intercepts) {
EXPECT_GT(text_intercept.end_, text_intercept.begin_);
}
});
}
TSAN_TEST(FontObjectThreadedTest, WordShaperTest) {
RunOnThreads([]() {
FontDescription font_description;
font_description.SetComputedSize(12.0);
font_description.SetLocale(LayoutLocale::Get("en"));
ASSERT_EQ(USCRIPT_LATIN, font_description.GetScript());
font_description.SetGenericFamily(FontDescription::kStandardFamily);
Font font = Font(font_description);
font.Update(nullptr);
ASSERT_TRUE(font.CanShapeWordByWord());
ShapeCache cache;
TextRun text_run(reinterpret_cast<const LChar*>("ABC DEF."), 8);
RefPtr<const ShapeResult> result;
CachingWordShapeIterator iter(&cache, text_run, &font);
ASSERT_TRUE(iter.Next(&result));
EXPECT_EQ(0u, result->StartIndexForResult());
EXPECT_EQ(3u, result->EndIndexForResult());
ASSERT_TRUE(iter.Next(&result));
EXPECT_EQ(0u, result->StartIndexForResult());
EXPECT_EQ(1u, result->EndIndexForResult());
ASSERT_TRUE(iter.Next(&result));
EXPECT_EQ(0u, result->StartIndexForResult());
EXPECT_EQ(4u, result->EndIndexForResult());
ASSERT_FALSE(iter.Next(&result));
});
}
} // namespace blink
| 36.898649 | 79 | 0.719282 | [
"vector"
] |
986c8ba7c82f91a5b7a5926a337198032a4b8754 | 5,676 | cpp | C++ | frontend/src/untested/function_hint.cpp | tyoma/micro-profiler | 32f6981c643b93997752d414f631fd6684772b28 | [
"MIT"
] | 194 | 2015-07-27T09:54:24.000Z | 2022-03-21T20:50:22.000Z | frontend/src/untested/function_hint.cpp | tyoma/micro-profiler | 32f6981c643b93997752d414f631fd6684772b28 | [
"MIT"
] | 63 | 2015-08-19T16:42:33.000Z | 2022-02-22T20:30:49.000Z | frontend/src/untested/function_hint.cpp | tyoma/micro-profiler | 32f6981c643b93997752d414f631fd6684772b28 | [
"MIT"
] | 33 | 2015-08-21T17:48:03.000Z | 2022-02-23T03:54:17.000Z | // Copyright (c) 2011-2021 by Artem A. Gevorkyan (gevorkyan.org)
//
// 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 <frontend/function_hint.h>
#include <agge/blenders.h>
#include <agge/blenders_simd.h>
#include <agge/figures.h>
#include <agge/filling_rules.h>
#include <agge/stroke_features.h>
#include <agge.text/limit.h>
#include <agge.text/text_engine.h>
#include <wpl/helpers.h>
#include <wpl/stylesheet.h>
using namespace agge;
using namespace std;
using namespace wpl;
namespace micro_profiler
{
function_hint::function_hint(gcontext::text_engine_type &text_services)
: _text_services(text_services), _name(font_style_annotation()), _items(font_style_annotation()),
_item_values(font_style_annotation()), _selected(table_model_base::npos())
{ }
void function_hint::apply_styles(const stylesheet &stylesheet_)
{
const font_style_annotation a = { stylesheet_.get_font("text.hint")->get_key(), };
_name.set_base_annotation(a);
_items.set_base_annotation(a);
_item_values.set_base_annotation(a);
_text_color = stylesheet_.get_color("text.hint");
_back_color = stylesheet_.get_color("background.hint");
_border_color = stylesheet_.get_color("border.hint");
_min_width = 20.0f * static_cast<real_t>(a.basic.height);
_padding = stylesheet_.get_value("padding.hint");
_border_width = stylesheet_.get_value("border.hint");
_items.clear();
_items << "Exclusive (total)\nInclusive (total)\nExclusive (average)\nInclusive (average)";
_stroke.width(_border_width);
_stroke.set_join(joins::bevel());
}
void function_hint::set_model(shared_ptr<richtext_table_model> model)
{
_invalidate = model ? model->invalidate += [this] (...) {
if (_selected != table_model_base::npos())
update_text_and_calculate_locations(_selected);
} : nullptr;
_model = model;
_selected = table_model_base::npos();
invalidate(nullptr);
}
bool function_hint::select(table_model_base::index_type item)
{
if (item == _selected)
return false;
const auto hierarchy_changed = item == table_model_base::npos() || _selected == table_model_base::npos();
_selected = item;
if (_model && item != table_model_base::npos())
update_text_and_calculate_locations(item);
return hierarchy_changed;
}
bool function_hint::is_active() const
{ return _selected != table_model_base::npos(); }
box<int> function_hint::get_box() const
{
return create_box(static_cast<int>(_name_location.x2 + _padding),
static_cast<int>(_items_location.y2 + _padding));
}
void function_hint::draw(gcontext &context, gcontext::rasterizer_ptr &rasterizer_) const
{
typedef blender_solid_color<simd::blender_solid_color, platform_pixel_order> blender;
auto rc = create_rect(0.0f, 0.0f, _name_location.x2 + _padding, _items_location.y2 + _padding);
add_path(*rasterizer_, rectangle(rc.x1, rc.y1, rc.x2, rc.y2));
context(rasterizer_, blender(_back_color), winding<>());
inflate(rc, -0.5f * _border_width, -0.5f * _border_width);
add_path(*rasterizer_, assist(rectangle(rc.x1, rc.y1, rc.x2, rc.y2), _stroke));
context(rasterizer_, blender(_border_color), winding<>());
context.text_engine.render(*rasterizer_, _name, align_center, align_near, _name_location, limit::wrap(width(_name_location)));
context.text_engine.render(*rasterizer_, _items, align_near, align_near, _items_location, limit::none());
context.text_engine.render(*rasterizer_, _item_values, align_far, align_near, _items_location, limit::none());
rasterizer_->sort(true);
context(rasterizer_, blender(_text_color), winding<>());
}
void function_hint::update_text_and_calculate_locations(table_model_base::index_type item)
{
_name.clear();
_item_values.clear();
if (item >= _model->get_count())
return;
_model->get_text(item, 1, _name);
_item_values << style::weight(bold);
_model->get_text(item, 4, _item_values), _item_values << "\n";
_model->get_text(item, 5, _item_values), _item_values << "\n";
_model->get_text(item, 6, _item_values), _item_values << "\n";
_model->get_text(item, 7, _item_values);
const auto box_items = _text_services.measure(_items, limit::none());
const auto box_item_values = _text_services.measure(_item_values, limit::none());
const auto width = agge_max(_min_width, box_items.w + box_item_values.w + _padding);
const auto box_name = _text_services.measure(_name, limit::wrap(width));
auto rc = create_rect(0.0f, 0.0f, width, box_name.h);
offset(rc, _padding, _padding);
_name_location = rc;
rc.y2 += _padding;
_items_location = create_rect(_padding, rc.y2, _padding + width, rc.y2 + agge_max(box_items.h, box_item_values.h));
invalidate(nullptr);
}
}
| 39.971831 | 128 | 0.746476 | [
"render",
"model"
] |
9871703305b7ca24b73532aeeec44edf0e4cd57e | 24,685 | cc | C++ | rimenative/src/main/jni/librime_jni/rime.cc | Erhannis/hackerskeyboard | beb8c6b3b34d1b317662aa4b4050943909cb0855 | [
"Apache-2.0"
] | null | null | null | rimenative/src/main/jni/librime_jni/rime.cc | Erhannis/hackerskeyboard | beb8c6b3b34d1b317662aa4b4050943909cb0855 | [
"Apache-2.0"
] | null | null | null | rimenative/src/main/jni/librime_jni/rime.cc | Erhannis/hackerskeyboard | beb8c6b3b34d1b317662aa4b4050943909cb0855 | [
"Apache-2.0"
] | null | null | null | #include "rime.h"
#include "levers.h"
#include <ctime>
#include <rime_api.h>
static jobject _get_value(JNIEnv *env, RimeConfig* config, const char* key);
static RimeSessionId _session_id = 0;
void on_message(void* context_object,
RimeSessionId session_id,
const char* message_type,
const char* message_value) {
if (_session_id == 0) return;
JNIEnv* env = (JNIEnv*)context_object;
if (env == NULL) return;
jclass clazz = env->FindClass(CLASSNAME);
if (clazz == NULL) return;
jmethodID mid_static_method = env->GetStaticMethodID(clazz, "onMessage","(Ljava/lang/String;Ljava/lang/String;)V");
if (mid_static_method == NULL) {
env->DeleteLocalRef(clazz);
return;
}
jstring str_arg1 = newJstring(env, message_type);
jstring str_arg2 = newJstring(env, message_value);
env->CallStaticVoidMethod(clazz, mid_static_method, str_arg1, str_arg2);
env->DeleteLocalRef(clazz);
env->DeleteLocalRef(str_arg1);
env->DeleteLocalRef(str_arg2);
}
void set_notification_handler(JNIEnv *env, jobject thiz) { //TODO
RimeSetNotificationHandler(&on_message, env);
}
void init_traits(JNIEnv *env, jstring shared_data_dir, jstring user_data_dir, void (*func)(RimeTraits *)) {
RIME_STRUCT(RimeTraits, traits);
const char* p_shared_data_dir = shared_data_dir == NULL ? NULL : env->GetStringUTFChars(shared_data_dir, NULL);
const char* p_user_data_dir = user_data_dir == NULL ? NULL : env->GetStringUTFChars(user_data_dir, NULL);
traits.shared_data_dir = p_shared_data_dir;
traits.user_data_dir = p_user_data_dir;
traits.app_name = APP_NAME;
func(&traits);
env->ReleaseStringUTFChars(shared_data_dir, p_shared_data_dir);
env->ReleaseStringUTFChars(user_data_dir, p_user_data_dir);
}
void setup(JNIEnv *env, jobject /*thiz*/, jstring shared_data_dir, jstring user_data_dir) {
init_traits(env, shared_data_dir, user_data_dir, RimeSetup);
}
// entry and exit
void initialize(JNIEnv *env, jobject thiz, jstring shared_data_dir, jstring user_data_dir) {
init_traits(env, shared_data_dir, user_data_dir, RimeInitialize);
}
void finalize(JNIEnv *env, jobject thiz) {
ALOGI("finalize...");
RimeFinalize();
}
jboolean start_maintenance(JNIEnv *env, jobject thiz, jboolean full_check) {
return RimeStartMaintenance((Bool)full_check);
}
jboolean is_maintenance_mode(JNIEnv *env, jobject thiz) {
return RimeIsMaintenancing();
}
void join_maintenance_thread(JNIEnv *env, jobject thiz) {
RimeJoinMaintenanceThread();
}
// deployment
void deployer_initialize(JNIEnv *env, jobject thiz, jstring shared_data_dir, jstring user_data_dir) {
init_traits(env, shared_data_dir, user_data_dir, RimeDeployerInitialize);
}
jboolean prebuild(JNIEnv *env, jobject thiz) {
return RimePrebuildAllSchemas();
}
jboolean deploy(JNIEnv *env, jobject thiz) {
return RimeDeployWorkspace();
}
jboolean deploy_schema(JNIEnv *env, jobject thiz, jstring schema_file) {
const char* s = schema_file == NULL ? NULL : env->GetStringUTFChars(schema_file, NULL);
bool b = RimeDeploySchema(s);
env->ReleaseStringUTFChars(schema_file, s);
return b;
}
jboolean deploy_config_file(JNIEnv *env, jobject thiz, jstring file_name, jstring version_key) {
const char* s = file_name == NULL ? NULL : env->GetStringUTFChars(file_name, NULL);
const char* s2 = version_key == NULL ? NULL : env->GetStringUTFChars(version_key, NULL);
bool b = RimeDeployConfigFile(s, s2);
env->ReleaseStringUTFChars(file_name, s);
env->ReleaseStringUTFChars(version_key, s2);
return b;
}
jboolean sync_user_data(JNIEnv *env, jobject thiz) {
ALOGI("sync user data...");
return RimeSyncUserData();
}
// session management
jint create_session(JNIEnv *env, jobject thiz) {
_session_id = RimeCreateSession();
return _session_id;
}
jboolean find_session(JNIEnv *env, jobject thiz) {
return RimeFindSession((RimeSessionId)_session_id);
}
jboolean destroy_session(JNIEnv *env, jobject thiz) {
bool ret = RimeDestroySession((RimeSessionId)_session_id);
_session_id = 0;
return ret;
}
void cleanup_stale_sessions(JNIEnv *env, jobject thiz) {
RimeCleanupStaleSessions();
}
void cleanup_all_sessions(JNIEnv *env, jobject thiz) {
RimeCleanupAllSessions();
}
// input
jboolean process_key(JNIEnv *env, jobject thiz, jint keycode, jint mask) {
return RimeProcessKey((RimeSessionId)_session_id, keycode, mask);
}
jboolean commit_composition(JNIEnv *env, jobject thiz) {
return RimeCommitComposition((RimeSessionId)_session_id);
}
void clear_composition(JNIEnv *env, jobject thiz) {
RimeClearComposition((RimeSessionId)_session_id);
}
// output
jboolean get_commit(JNIEnv *env, jobject thiz, jobject jcommit) {
RIME_STRUCT(RimeCommit, commit);
Bool r = RimeGetCommit((RimeSessionId)_session_id, &commit);
if (r) {
jclass jc = env->GetObjectClass(jcommit);
jfieldID fid;
fid = env->GetFieldID(jc, "data_size", "I");
env->SetIntField(jcommit, fid, commit.data_size);
fid = env->GetFieldID(jc, "text", "Ljava/lang/String;");
env->SetObjectField(jcommit, fid, newJstring(env, commit.text));
env->DeleteLocalRef(jc);
RimeFreeCommit(&commit);
}
return r;
}
jboolean get_context(JNIEnv *env, jobject thiz, jobject jcontext) {
RIME_STRUCT(RimeContext, context);
Bool r = RimeGetContext(_session_id, &context);
if (r) {
jclass jc = env->GetObjectClass(jcontext);
jfieldID fid;
fid = env->GetFieldID(jc, "data_size", "I");
env->SetIntField(jcontext, fid, context.data_size);
fid = env->GetFieldID(jc, "commit_text_preview", "Ljava/lang/String;");
env->SetObjectField(jcontext, fid, newJstring(env, context.commit_text_preview));
jclass jc1 = env->FindClass(CLASSNAME "$RimeMenu");
jobject jobj = (jobject) env->AllocObject(jc1);
fid = env->GetFieldID(jc1, "num_candidates", "I");
env->SetIntField(jobj, fid, context.menu.num_candidates);
fid = env->GetFieldID(jc1, "page_size", "I");
env->SetIntField(jobj, fid, context.menu.page_size);
fid = env->GetFieldID(jc1, "page_no", "I");
env->SetIntField(jobj, fid, context.menu.page_no);
fid = env->GetFieldID(jc1, "highlighted_candidate_index", "I");
env->SetIntField(jobj, fid, context.menu.highlighted_candidate_index);
fid = env->GetFieldID(jc1, "is_last_page", "Z");
env->SetBooleanField(jobj, fid, context.menu.is_last_page);
fid = env->GetFieldID(jc1, "select_keys", "Ljava/lang/String;");
env->SetObjectField(jobj, fid, newJstring(env, context.menu.select_keys));
fid = env->GetFieldID(jc, "select_labels", "[Ljava/lang/String;");
Bool has_labels = RIME_STRUCT_HAS_MEMBER(context, context.select_labels) && context.select_labels;
if (has_labels) {
int n = context.menu.page_size;
jclass jcs = env->FindClass("java/lang/String");
jobjectArray jlabels = (jobjectArray) env->NewObjectArray(n, jcs, NULL);
for (int i = 0; i < n; ++i) {
env->SetObjectArrayElement(jlabels, i, newJstring(env, context.select_labels[i]));
}
env->SetObjectField(jcontext, fid, jlabels);
env->DeleteLocalRef(jlabels);
env->DeleteLocalRef(jcs);
} else {
env->SetObjectField(jcontext, fid, NULL);
}
int n = context.menu.num_candidates;
jclass jc2 = env->FindClass(CLASSNAME "$RimeCandidate");
jobjectArray jcandidates = (jobjectArray) env->NewObjectArray(n, jc2, NULL);
for (int i = 0; i < n; ++i) {
jobject jcandidate = (jobject) env->AllocObject(jc2);
fid = env->GetFieldID(jc2, "text", "Ljava/lang/String;");
env->SetObjectField(jcandidate, fid, newJstring(env, context.menu.candidates[i].text));
fid = env->GetFieldID(jc2, "comment", "Ljava/lang/String;");
env->SetObjectField(jcandidate, fid, newJstring(env, context.menu.candidates[i].comment));
env->SetObjectArrayElement(jcandidates, i, jcandidate);
env->DeleteLocalRef(jcandidate);
}
fid = env->GetFieldID(jc1, "candidates", "[L" CLASSNAME "$RimeCandidate;");
env->SetObjectField(jobj, fid, jcandidates);
env->DeleteLocalRef(jcandidates);
fid = env->GetFieldID(jc, "menu", "L" CLASSNAME "$RimeMenu;");
env->SetObjectField(jcontext, fid, jobj);
jc1 = env->FindClass(CLASSNAME "$RimeComposition");
jobj = (jobject) env->AllocObject(jc1);
fid = env->GetFieldID(jc1, "length", "I");
env->SetIntField(jobj, fid, context.composition.length);
fid = env->GetFieldID(jc1, "cursor_pos", "I");
env->SetIntField(jobj, fid, context.composition.cursor_pos);
fid = env->GetFieldID(jc1, "sel_start", "I");
env->SetIntField(jobj, fid, context.composition.sel_start);
fid = env->GetFieldID(jc1, "sel_end", "I");
env->SetIntField(jobj, fid, context.composition.sel_end);
fid = env->GetFieldID(jc1, "preedit", "Ljava/lang/String;");
env->SetObjectField(jobj, fid, newJstring(env, context.composition.preedit));
fid = env->GetFieldID(jc, "composition", "L" CLASSNAME "$RimeComposition;");
env->SetObjectField(jcontext, fid, jobj);
env->DeleteLocalRef(jc);
env->DeleteLocalRef(jc1);
env->DeleteLocalRef(jc2);
RimeFreeContext(&context);
}
return r;
}
jboolean get_status(JNIEnv *env, jobject thiz, jobject jstatus) {
RIME_STRUCT(RimeStatus, status);
Bool r = RimeGetStatus(_session_id, &status);
if (r) {
jclass jc = env->GetObjectClass(jstatus);
jfieldID fid;
fid = env->GetFieldID(jc, "data_size", "I");
env->SetIntField(jstatus, fid, status.data_size);
fid = env->GetFieldID(jc, "schema_id", "Ljava/lang/String;");
env->SetObjectField(jstatus, fid, newJstring(env, status.schema_id));
fid = env->GetFieldID(jc, "schema_name", "Ljava/lang/String;");
env->SetObjectField(jstatus, fid, newJstring(env, status.schema_name));
fid = env->GetFieldID(jc, "is_disabled", "Z");
env->SetBooleanField(jstatus, fid, status.is_disabled);
fid = env->GetFieldID(jc, "is_composing", "Z");
env->SetBooleanField(jstatus, fid, status.is_composing);
fid = env->GetFieldID(jc, "is_ascii_mode", "Z");
env->SetBooleanField(jstatus, fid, status.is_ascii_mode);
fid = env->GetFieldID(jc, "is_full_shape", "Z");
env->SetBooleanField(jstatus, fid, status.is_full_shape);
fid = env->GetFieldID(jc, "is_simplified", "Z");
env->SetBooleanField(jstatus, fid, status.is_simplified);
fid = env->GetFieldID(jc, "is_traditional", "Z");
env->SetBooleanField(jstatus, fid, status.is_traditional);
fid = env->GetFieldID(jc, "is_ascii_punct", "Z");
env->SetBooleanField(jstatus, fid, status.is_ascii_punct);
env->DeleteLocalRef(jc);
RimeFreeStatus(&status);
}
return r;
}
static bool is_save_option(const char* p) {
bool is_save = false;
std::string option_name(p);
if (option_name.empty()) return is_save;
RimeConfig config = {0};
bool b = RimeConfigOpen("default", &config);
if (!b) return is_save;
const char *key = "switcher/save_options";
RimeConfigIterator iter = {0};
RimeConfigBeginList(&iter, &config, key);
while(RimeConfigNext(&iter)) {
std::string item(RimeConfigGetCString(&config, iter.path));
if (option_name == item) {
is_save = true;
break;
}
}
RimeConfigEnd(&iter);
RimeConfigClose(&config);
return is_save;
}
// runtime options
void set_option(JNIEnv *env, jobject thiz, jstring option, jboolean value) {
const char* s = option == NULL ? NULL : env->GetStringUTFChars(option, NULL);
std::string option_name(s);
RimeConfig config = {0};
bool b;
if (is_save_option(s)) {
b = RimeConfigOpen("user", &config);
if (b) {
std::string str("var/option/");
str += option_name;
b = RimeConfigSetBool(&config, str.c_str(), value);
}
RimeConfigClose(&config);
}
RimeSetOption(_session_id, s, value);
env->ReleaseStringUTFChars(option, s);
}
jboolean get_option(JNIEnv *env, jobject thiz, jstring option) {
const char* s = option == NULL ? NULL : env->GetStringUTFChars(option, NULL);
bool value = RimeGetOption(_session_id, s);
env->ReleaseStringUTFChars(option, s);
return value;
}
void set_property(JNIEnv *env, jobject thiz, jstring prop, jstring value) {
const char* s = prop == NULL ? NULL : env->GetStringUTFChars(prop, NULL);
const char* v = value == NULL ? NULL : env->GetStringUTFChars(value, NULL);
RimeSetProperty(_session_id, s, v);
env->ReleaseStringUTFChars(prop, s);
env->ReleaseStringUTFChars(value, v);
}
jstring get_property(JNIEnv *env, jobject thiz, jstring prop) {
const char* s = prop == NULL ? NULL : env->GetStringUTFChars(prop, NULL);
char value[BUFSIZE] = {0};
bool b = RimeGetProperty(_session_id, s, value, BUFSIZE);
env->ReleaseStringUTFChars(prop, s);
return b ? newJstring(env, value) : NULL;
}
jobject get_schema_list(JNIEnv *env, jobject thiz) {
RimeSchemaList list;
jobject jobj = NULL;
if (RimeGetSchemaList(&list)) jobj = _get_schema_list(env, &list);
RimeFreeSchemaList(&list);
return jobj;
}
jstring get_current_schema(JNIEnv *env, jobject thiz) {
char current[BUFSIZE] = {0};
bool b = RimeGetCurrentSchema(_session_id, current, sizeof(current));
if (b) return newJstring(env, current);
return NULL;
}
jboolean select_schema(JNIEnv *env, jobject thiz, jstring schema_id) {
const char* s = schema_id == NULL ? NULL : env->GetStringUTFChars(schema_id, NULL);
RimeConfig config = {0};
Bool b = RimeConfigOpen("user", &config);
if (b) {
b = RimeConfigSetString(&config, "var/previously_selected_schema", s);
std::string str(s);
str = "var/schema_access_time/" + str;
b = RimeConfigSetInt(&config, str.c_str(), time(NULL));
}
RimeConfigClose(&config);
bool value = RimeSelectSchema(_session_id, s);
env->ReleaseStringUTFChars(schema_id, s);
return value;
}
// configuration
jobject config_get_bool(JNIEnv *env, jobject thiz, jstring name, jstring key) {
const char* s = env->GetStringUTFChars(name, NULL);
RimeConfig config = {0};
Bool b = RimeConfigOpen(s, &config);
env->ReleaseStringUTFChars(name, s);
Bool value;
if (b) {
s = env->GetStringUTFChars(key, NULL);
b = RimeConfigGetBool(&config, s, &value);
env->ReleaseStringUTFChars(key, s);
}
RimeConfigClose(&config);
if (!b) return NULL;
jclass jc = env->FindClass("java/lang/Boolean");
jmethodID ctorID = env->GetMethodID(jc, "<init>", "(Z)V");
jobject ret = (jobject)env->NewObject(jc, ctorID, value);
env->DeleteLocalRef(jc);
return ret;
}
jboolean config_set_bool(JNIEnv *env, jobject thiz, jstring name, jstring key, jboolean value) {
const char* s = env->GetStringUTFChars(name, NULL);
RimeConfig config = {0};
Bool b = RimeConfigOpen(s, &config);
env->ReleaseStringUTFChars(name, s);
if (b) {
s = env->GetStringUTFChars(key, NULL);
b = RimeConfigSetBool(&config, s, value);
env->ReleaseStringUTFChars(key, s);
}
RimeConfigClose(&config);
return b;
}
jobject config_get_int(JNIEnv *env, jobject thiz, jstring name, jstring key) {
const char* s = env->GetStringUTFChars(name, NULL);
RimeConfig config = {0};
Bool b = RimeConfigOpen(s, &config);
env->ReleaseStringUTFChars(name, s);
int value;
if (b) {
s = env->GetStringUTFChars(key, NULL);
b = RimeConfigGetInt(&config, s, &value);
env->ReleaseStringUTFChars(key, s);
}
RimeConfigClose(&config);
if (!b) return NULL;
jclass jc = env->FindClass("java/lang/Integer");
jmethodID ctorID = env->GetMethodID(jc, "<init>", "(I)V");
jobject ret = (jobject)env->NewObject(jc, ctorID, value);
env->DeleteLocalRef(jc);
return ret;
}
jboolean config_set_int(JNIEnv *env, jobject thiz, jstring name, jstring key, jint value) {
const char* s = env->GetStringUTFChars(name, NULL);
RimeConfig config = {0};
Bool b = RimeConfigOpen(s, &config);
env->ReleaseStringUTFChars(name, s);
if (b) {
s = env->GetStringUTFChars(key, NULL);
b = RimeConfigSetInt(&config, s, value);
env->ReleaseStringUTFChars(key, s);
}
RimeConfigClose(&config);
return b;
}
jobject config_get_double(JNIEnv *env, jobject thiz, jstring name, jstring key) {
const char* s = env->GetStringUTFChars(name, NULL);
RimeConfig config = {0};
Bool b = RimeConfigOpen(s, &config);
env->ReleaseStringUTFChars(name, s);
double value;
if (b) {
s = env->GetStringUTFChars(key, NULL);
b = RimeConfigGetDouble(&config, s, &value);
env->ReleaseStringUTFChars(key, s);
}
RimeConfigClose(&config);
if (!b) return NULL;
jclass jc = env->FindClass("java/lang/Double");
jmethodID ctorID = env->GetMethodID(jc, "<init>", "(D)V");
jobject ret = (jobject)env->NewObject(jc, ctorID, value);
env->DeleteLocalRef(jc);
return ret;
}
jboolean config_set_double(JNIEnv *env, jobject thiz, jstring name, jstring key, jdouble value) {
const char* s = env->GetStringUTFChars(name, NULL);
RimeConfig config = {0};
Bool b = RimeConfigOpen(s, &config);
env->ReleaseStringUTFChars(name, s);
if (b) {
s = env->GetStringUTFChars(key, NULL);
b = RimeConfigSetDouble(&config, s, value);
env->ReleaseStringUTFChars(key, s);
}
RimeConfigClose(&config);
return b;
}
jstring config_get_string(JNIEnv *env, jobject thiz, jstring name, jstring key) {
const char* s = env->GetStringUTFChars(name, NULL);
RimeConfig config = {0};
Bool b = RimeConfigOpen(s, &config);
env->ReleaseStringUTFChars(name, s);
char value[BUFSIZE] = {0};
if (b) {
s = env->GetStringUTFChars(key, NULL);
b = RimeConfigGetString(&config, s, value, BUFSIZE);
env->ReleaseStringUTFChars(key, s);
}
RimeConfigClose(&config);
return b ? newJstring(env, value) : NULL;
}
jboolean config_set_string(JNIEnv *env, jobject thiz, jstring name, jstring key, jstring value) {
const char* s = env->GetStringUTFChars(name, NULL);
RimeConfig config = {0};
Bool b = RimeConfigOpen(s, &config);
env->ReleaseStringUTFChars(name, s);
if (b) {
s = env->GetStringUTFChars(key, NULL);
const char* v = env->GetStringUTFChars(value, NULL);
b = RimeConfigSetString(&config, s, v);
env->ReleaseStringUTFChars(key, s);
env->ReleaseStringUTFChars(key, v);
}
RimeConfigClose(&config);
return b;
}
jint config_list_size(JNIEnv *env, jobject thiz, jstring name, jstring key) {
const char* s = env->GetStringUTFChars(name, NULL);
RimeConfig config = {0};
Bool b = RimeConfigOpen(s, &config);
env->ReleaseStringUTFChars(name, s);
int value = 0;
if (b) {
s = env->GetStringUTFChars(key, NULL);
value = RimeConfigListSize(&config, s);
env->ReleaseStringUTFChars(key, s);
}
RimeConfigClose(&config);
return value;
}
//testing
jboolean simulate_key_sequence(JNIEnv *env, jobject thiz, jstring key_sequence) {
const char* str = key_sequence == NULL ? NULL : env->GetStringUTFChars(key_sequence, NULL);
if (str == NULL) return false; /* OutOfMemoryError already thrown */
jboolean r = RimeSimulateKeySequence((RimeSessionId)_session_id, str);
env->ReleaseStringUTFChars(key_sequence, str);
return r;
}
jstring get_input(JNIEnv *env, jobject thiz) {
const char* c = rime_get_api()->get_input(_session_id);
return newJstring(env, c);
}
jint get_caret_pos(JNIEnv *env, jobject thiz) {
return rime_get_api()->get_caret_pos(_session_id);
}
void set_caret_pos(JNIEnv *env, jobject thiz, jint caret_pos) {
return rime_get_api()->set_caret_pos(_session_id, caret_pos);
}
jboolean select_candidate(JNIEnv *env, jobject thiz, jint index) {
return rime_get_api()->select_candidate(_session_id, index);
}
jboolean select_candidate_on_current_page(JNIEnv *env, jobject thiz, jint index) {
return rime_get_api()->select_candidate_on_current_page(_session_id, index);
}
jstring get_version(JNIEnv *env, jobject thiz) {
return newJstring(env, rime_get_api()->get_version());
}
jstring get_librime_version(JNIEnv *env, jobject thiz) {
return newJstring(env, LIBRIME_VERSION);
}
jobjectArray get_string_list(JNIEnv *env, RimeConfig* config, const char* key) {
jobjectArray jobj = NULL;
jclass jc = env->FindClass("java/lang/String");
int n = RimeConfigListSize(config, key);
if (n > 0) {
jobj = (jobjectArray) env->NewObjectArray(n, jc, NULL);
RimeConfigIterator iter = {0};
RimeConfigBeginList(&iter, config, key);
int i = 0;
while(RimeConfigNext(&iter)) {
env->SetObjectArrayElement(jobj, i++, newJstring(env, RimeConfigGetCString(config, iter.path)));
}
RimeConfigEnd(&iter);
}
env->DeleteLocalRef(jc);
return jobj;
}
static jobject _get_list(JNIEnv *env, RimeConfig* config, const char* key) {
RimeConfigIterator iter = {0};
bool b = RimeConfigBeginList(&iter, config, key);
if (!b) return NULL;
jclass jc = env->FindClass("java/util/ArrayList");
if(jc == NULL) return NULL;
jmethodID init = env->GetMethodID(jc, "<init>", "()V");
jobject jobj = env->NewObject(jc, init);
jmethodID add = env->GetMethodID(jc, "add", "(Ljava/lang/Object;)Z");
while (RimeConfigNext(&iter)) {
jobject o = _get_value(env, config, iter.path);
env->CallBooleanMethod(jobj, add, o);
env->DeleteLocalRef(o);
}
RimeConfigEnd(&iter);
env->DeleteLocalRef(jc);
return jobj;
}
jobject config_get_list(JNIEnv *env, jobject thiz, jstring name, jstring key) {
const char* s = env->GetStringUTFChars(name, NULL);
RimeConfig config = {0};
Bool b = RimeConfigOpen(s, &config);
env->ReleaseStringUTFChars(name, s);
jobject value = NULL;
if (b) {
s = env->GetStringUTFChars(key, NULL);
value = _get_list(env, &config, s);
env->ReleaseStringUTFChars(key, s);
}
RimeConfigClose(&config);
return value;
}
static jobject _get_map(JNIEnv *env, RimeConfig* config, const char* key) {
RimeConfigIterator iter = {0};
bool b = RimeConfigBeginMap(&iter, config, key);
if (!b) return NULL;
jclass jc = env->FindClass("java/util/HashMap");
if(jc == NULL) return NULL;
jmethodID init = env->GetMethodID(jc, "<init>", "()V");
jobject jobj = env->NewObject(jc, init);
jmethodID put = env->GetMethodID(jc, "put",
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
while (RimeConfigNext(&iter)) {
jstring s = newJstring(env, iter.key);
jobject o = _get_value(env, config, iter.path);
env->CallObjectMethod(jobj, put, s, o);
env->DeleteLocalRef(s);
env->DeleteLocalRef(o);
}
RimeConfigEnd(&iter);
env->DeleteLocalRef(jc);
return jobj;
}
jobject config_get_map(JNIEnv *env, jobject thiz, jstring name, jstring key) {
const char* s = env->GetStringUTFChars(name, NULL);
RimeConfig config = {0};
Bool b = RimeConfigOpen(s, &config);
env->ReleaseStringUTFChars(name, s);
jobject value = NULL;
if (b) {
s = env->GetStringUTFChars(key, NULL);
value = _get_map(env, &config, s);
env->ReleaseStringUTFChars(key, s);
}
RimeConfigClose(&config);
return value;
}
jobject _get_value(JNIEnv *env, RimeConfig* config, const char* key) {
jobject ret;
jclass jc;
jmethodID init;
Bool b_value;
const char *value = RimeConfigGetCString(config, key);
if (value != NULL) return newJstring(env, value);
ret = _get_list(env, config, key);
if (ret) return ret;
ret = _get_map(env, config, key);
return ret;
}
jobject config_get_value(JNIEnv *env, jobject thiz, jstring name, jstring key) {
const char* s = env->GetStringUTFChars(name, NULL);
RimeConfig config = {0};
Bool b = RimeConfigOpen(s, &config);
env->ReleaseStringUTFChars(name, s);
jobject ret = NULL;
if (b) {
s = env->GetStringUTFChars(key, NULL);
ret = _get_value(env, &config, s);
env->ReleaseStringUTFChars(key, s);
RimeConfigClose(&config);
}
return ret;
}
jobject schema_get_value(JNIEnv *env, jobject thiz, jstring name, jstring key) {
const char* s = env->GetStringUTFChars(name, NULL);
RimeConfig config = {0};
Bool b = RimeSchemaOpen(s, &config);
env->ReleaseStringUTFChars(name, s);
jobject ret = NULL;
if (b) {
s = env->GetStringUTFChars(key, NULL);
ret = _get_value(env, &config, s);
env->ReleaseStringUTFChars(key, s);
RimeConfigClose(&config);
}
return ret;
}
jboolean run_task(JNIEnv *env, jobject thiz, jstring task_name) {
const char* s = env->GetStringUTFChars(task_name, NULL);
RimeConfig config = {0};
Bool b = RimeRunTask(s);
env->ReleaseStringUTFChars(task_name, s);
return b;
}
jstring get_shared_data_dir(JNIEnv *env, jobject thiz) {
return newJstring(env, RimeGetSharedDataDir());
}
jstring get_user_data_dir(JNIEnv *env, jobject thiz) {
return newJstring(env, RimeGetUserDataDir());
}
jstring get_sync_dir(JNIEnv *env, jobject thiz) {
return newJstring(env, RimeGetSyncDir());
}
jstring get_user_id(JNIEnv *env, jobject thiz) {
return newJstring(env, RimeGetUserId());
}
| 34.572829 | 117 | 0.698359 | [
"object"
] |
98739aa908deccd22421a53756cfb42dbabc6831 | 1,536 | cpp | C++ | CodeForces/Solutions/346C.cpp | Shefin-CSE16/Competitive-Programming | 7c792081ae1d4b7060893165de34ffe7b9b7caed | [
"MIT"
] | 5 | 2020-10-03T17:15:26.000Z | 2022-03-29T21:39:22.000Z | CodeForces/Solutions/346C.cpp | Shefin-CSE16/Competitive-Programming | 7c792081ae1d4b7060893165de34ffe7b9b7caed | [
"MIT"
] | null | null | null | CodeForces/Solutions/346C.cpp | Shefin-CSE16/Competitive-Programming | 7c792081ae1d4b7060893165de34ffe7b9b7caed | [
"MIT"
] | 1 | 2021-03-01T12:56:50.000Z | 2021-03-01T12:56:50.000Z | // #pragma GCC optimize("Ofast,unroll-loops")
// #pragma GCC target("avx,avx2,fma")
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define dd double
#define ld long double
#define sl(n) scanf("%lld", &n)
#define si(n) scanf("%d", &n)
#define sd(n) scanf("%lf", &n)
#define pll pair <ll, ll>
#define pii pair <int, int>
#define mp make_pair
#define pb push_back
#define all(v) v.begin(), v.end()
#define inf (1LL << 61)
#define loop(i, start, stop, inc) for(ll i = start; i <= stop; i += inc)
#define for1(i, stop) for(ll i = 1; i <= stop; ++i)
#define for0(i, stop) for(ll i = 0; i < stop; ++i)
#define rep1(i, start) for(ll i = start; i >= 1; --i)
#define rep0(i, start) for(ll i = (start-1); i >= 0; --i)
#define ms(n, i) memset(n, i, sizeof(n))
#define casep(n) printf("Case %lld:", ++n)
#define pn printf("\n")
#define pf printf
#define EL '\n'
#define fastio std::ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
const ll sz = 1e5 + 10;
vector <int> v;
int main()
{
ll n; sl(n);
for1(i, n) {
ll num; sl(num);
v.pb(num);
}
sort(all(v));
v.erase(unique(all(v)), v.end());
ll ans = 0, a, b;
cin >> a >> b;
while(a > b) {
while(!v.empty() && a - (a % v.back()) < b) v.pop_back();
ans++;
ll nxt = a-1;
for(const int x : v) {
ll nxt2 = a - (a % x);
if(nxt2 >= b) nxt = min(nxt, nxt2);
}
a = nxt;
}
cout << ans << EL;
return 0;
} | 23.272727 | 82 | 0.546224 | [
"vector"
] |
98772f475d911f32ec9de28f39e56bf2b2189eb4 | 16,620 | cpp | C++ | GameFramework_ThirdParty/FCollada/FCollada/FMath/FMMatrix44.cpp | GavWood/tutorials | d5140129b6acd6d61f6feedcd352c12e4ebabd40 | [
"BSD-2-Clause"
] | 8 | 2017-10-26T14:26:55.000Z | 2022-01-07T07:35:39.000Z | GameFramework_ThirdParty/FCollada/FCollada/FMath/FMMatrix44.cpp | GavWood/tutorials | d5140129b6acd6d61f6feedcd352c12e4ebabd40 | [
"BSD-2-Clause"
] | 1 | 2018-01-27T19:21:07.000Z | 2018-01-31T13:55:09.000Z | GameFramework_ThirdParty/FCollada/FCollada/FMath/FMMatrix44.cpp | GavWood/Game-Framework | d5140129b6acd6d61f6feedcd352c12e4ebabd40 | [
"BSD-2-Clause"
] | 1 | 2021-07-21T17:37:33.000Z | 2021-07-21T17:37:33.000Z | /*
Copyright (C) 2005-2007 Feeling Software Inc.
Portions of the code are:
Copyright (C) 2005-2007 Sony Computer Entertainment America
MIT License: http://www.opensource.org/licenses/mit-license.php
*/
#include "StdAfx.h"
#include "FMMatrix44.h"
#include <limits>
static float __identity[] = { 1, 0, 0, 0, 0, 1, 0 ,0 ,0, 0, 1, 0, 0, 0, 0, 1 };
FMMatrix44 FMMatrix44::Identity(__identity);
FMMatrix44::FMMatrix44(const float* _m)
{
Set(_m);
}
FMMatrix44::FMMatrix44(const double* _m)
{
Set(_m);
}
FMMatrix44& FMMatrix44::operator=(const FMMatrix44& copy)
{
m[0][0] = copy.m[0][0]; m[0][1] = copy.m[0][1]; m[0][2] = copy.m[0][2]; m[0][3] = copy.m[0][3];
m[1][0] = copy.m[1][0]; m[1][1] = copy.m[1][1]; m[1][2] = copy.m[1][2]; m[1][3] = copy.m[1][3];
m[2][0] = copy.m[2][0]; m[2][1] = copy.m[2][1]; m[2][2] = copy.m[2][2]; m[2][3] = copy.m[2][3];
m[3][0] = copy.m[3][0]; m[3][1] = copy.m[3][1]; m[3][2] = copy.m[3][2]; m[3][3] = copy.m[3][3];
return *this;
}
void FMMatrix44::Set(const float* _m)
{
m[0][0] = _m[0]; m[1][0] = _m[1]; m[2][0] = _m[2]; m[3][0] = _m[3];
m[0][1] = _m[4]; m[1][1] = _m[5]; m[2][1] = _m[6]; m[3][1] = _m[7];
m[0][2] = _m[8]; m[1][2] = _m[9]; m[2][2] = _m[10]; m[3][2] = _m[11];
m[0][3] = _m[12]; m[1][3] = _m[13]; m[2][3] = _m[14]; m[3][3] = _m[15];
}
void FMMatrix44::Set(const double* _m)
{
m[0][0] = (float)_m[0]; m[1][0] = (float)_m[1]; m[2][0] = (float)_m[2]; m[3][0] = (float)_m[3];
m[0][1] = (float)_m[4]; m[1][1] = (float)_m[5]; m[2][1] = (float)_m[6]; m[3][1] = (float)_m[7];
m[0][2] = (float)_m[8]; m[1][2] = (float)_m[9]; m[2][2] = (float)_m[10]; m[3][2] = (float)_m[11];
m[0][3] = (float)_m[12]; m[1][3] = (float)_m[13]; m[2][3] = (float)_m[14]; m[3][3] = (float)_m[15];
}
// Returns the transpose of this matrix
FMMatrix44 FMMatrix44::Transposed() const
{
FMMatrix44 mx;
mx.m[0][0] = m[0][0]; mx.m[1][0] = m[0][1]; mx.m[2][0] = m[0][2]; mx.m[3][0] = m[0][3];
mx.m[0][1] = m[1][0]; mx.m[1][1] = m[1][1]; mx.m[2][1] = m[1][2]; mx.m[3][1] = m[1][3];
mx.m[0][2] = m[2][0]; mx.m[1][2] = m[2][1]; mx.m[2][2] = m[2][2]; mx.m[3][2] = m[2][3];
mx.m[0][3] = m[3][0]; mx.m[1][3] = m[3][1]; mx.m[2][3] = m[3][2]; mx.m[3][3] = m[3][3];
return mx;
}
FMVector3 FMMatrix44::TransformCoordinate(const FMVector3& coordinate) const
{
return FMVector3(
m[0][0] * coordinate.x + m[1][0] * coordinate.y + m[2][0] * coordinate.z + m[3][0],
m[0][1] * coordinate.x + m[1][1] * coordinate.y + m[2][1] * coordinate.z + m[3][1],
m[0][2] * coordinate.x + m[1][2] * coordinate.y + m[2][2] * coordinate.z + m[3][2]
);
}
FMVector4 FMMatrix44::TransformCoordinate(const FMVector4& coordinate) const
{
return FMVector4(
m[0][0] * coordinate.x + m[1][0] * coordinate.y + m[2][0] * coordinate.z + m[3][0] * coordinate.w,
m[0][1] * coordinate.x + m[1][1] * coordinate.y + m[2][1] * coordinate.z + m[3][1] * coordinate.w,
m[0][2] * coordinate.x + m[1][2] * coordinate.y + m[2][2] * coordinate.z + m[3][2] * coordinate.w,
m[0][3] * coordinate.x + m[1][3] * coordinate.y + m[2][3] * coordinate.z + m[3][3] * coordinate.w
);
}
FMVector3 FMMatrix44::TransformVector(const FMVector3& v) const
{
return FMVector3(
m[0][0] * v.x + m[1][0] * v.y + m[2][0] * v.z,
m[0][1] * v.x + m[1][1] * v.y + m[2][1] * v.z,
m[0][2] * v.x + m[1][2] * v.y + m[2][2] * v.z
);
}
/*
void FMMatrix44::SetTranslation(const FMVector3& translation)
{
m[3][0] = translation.x;
m[3][1] = translation.y;
m[3][2] = translation.z;
}
*/
static float det3x3(float a1, float a2, float a3, float b1, float b2, float b3, float c1, float c2, float c3);
void FMMatrix44::Decompose(FMVector3& scale, FMVector3& rotation, FMVector3& translation, float& inverted) const
{
// translation * rotation [x*y*z order] * scale = original matrix
// if inverted is true, then negate scale and the above formula will be correct
scale.x = sqrtf(m[0][0] * m[0][0] + m[0][1] * m[0][1] + m[0][2] * m[0][2]);
scale.y = sqrtf(m[1][0] * m[1][0] + m[1][1] * m[1][1] + m[1][2] * m[1][2]);
scale.z = sqrtf(m[2][0] * m[2][0] + m[2][1] * m[2][1] + m[2][2] * m[2][2]);
FMVector3 savedScale(scale);
if (IsEquivalent(scale.x, 0.0f)) { scale.x = FLT_TOLERANCE; }
if (IsEquivalent(scale.y, 0.0f)) { scale.y = FLT_TOLERANCE; }
if (IsEquivalent(scale.z, 0.0f)) { scale.z = FLT_TOLERANCE; }
inverted = FMath::Sign(det3x3(m[0][0], m[0][1], m[0][2], m[1][0], m[1][1], m[1][2], m[2][0], m[2][1], m[2][2]));
if (inverted < 0.0f)
{
// intentionally do not want to do this on the savedScale
scale.x = -scale.x;
scale.y = -scale.y;
scale.z = -scale.z;
}
// Calculate the rotation in Y first, using m[0][2], checking for out-of-bounds values
float c;
if (m[2][0] / scale.z >= 1.0f - FLT_TOLERANCE)
{
rotation.y = ((float) FMath::Pi) / 2.0f;
c = 0.0f;
}
else if (m[2][0] / scale.z <= -1.0f + FLT_TOLERANCE)
{
rotation.y = ((float) FMath::Pi) / -2.0f;
c = 0.0f;
}
else
{
rotation.y = asinf(m[2][0] / scale.z);
c = cosf(rotation.y);
}
// Using the cosine of the Y rotation will give us the rotation in X and Z.
// Check for the infamous Gimbal Lock.
if (fabsf(c) > 0.01f)
{
float rx = m[2][2] / scale.z / c;
float ry = -m[2][1] / scale.z / c;
rotation.x = atan2f(ry, rx);
rx = m[0][0] / scale.x / c;
ry = -m[1][0] / scale.y / c;
rotation.z = atan2f(ry, rx);
}
else
{
rotation.z = 0;
float rx = m[1][1] / scale.y;
float ry = m[1][2] / scale.y;
rotation.x = atan2f(ry, rx);
}
translation = GetTranslation();
scale = savedScale;
}
void FMMatrix44::Recompose(const FMVector3& scale, const FMVector3& rotation, const FMVector3& translation, float inverted)
{
(*this) = FMMatrix44::TranslationMatrix(translation) * FMMatrix44::AxisRotationMatrix(FMVector3::ZAxis, rotation.z)
* FMMatrix44::AxisRotationMatrix(FMVector3::YAxis, rotation.y) * FMMatrix44::AxisRotationMatrix(FMVector3::XAxis, rotation.x)
* FMMatrix44::ScaleMatrix(inverted * scale);
}
// Code taken and adapted from nVidia's nv_algebra: det2x2, det3x3, invert, multiply
// -----
// Calculate the determinant of a 2x2 matrix
static float det2x2(float a1, float a2, float b1, float b2)
{
return a1 * b2 - b1 * a2;
}
// Calculate the determinent of a 3x3 matrix
static float det3x3(float a1, float a2, float a3, float b1, float b2, float b3, float c1, float c2, float c3)
{
return a1 * det2x2(b2, b3, c2, c3) - b1 * det2x2(a2, a3, c2, c3) + c1 * det2x2(a2, a3, b2, b3);
}
// Returns the inverse of this matrix
FMMatrix44 FMMatrix44::Inverted() const
{
FMMatrix44 b;
b.m[0][0] = det3x3(m[1][1], m[1][2], m[1][3], m[2][1], m[2][2], m[2][3], m[3][1], m[3][2], m[3][3]);
b.m[0][1] = -det3x3(m[0][1], m[0][2], m[0][3], m[2][1], m[2][2], m[2][3], m[3][1], m[3][2], m[3][3]);
b.m[0][2] = det3x3(m[0][1], m[0][2], m[0][3], m[1][1], m[1][2], m[1][3], m[3][1], m[3][2], m[3][3]);
b.m[0][3] = -det3x3(m[0][1], m[0][2], m[0][3], m[1][1], m[1][2], m[1][3], m[2][1], m[2][2], m[2][3]);
b.m[1][0] = -det3x3(m[1][0], m[1][2], m[1][3], m[2][0], m[2][2], m[2][3], m[3][0], m[3][2], m[3][3]);
b.m[1][1] = det3x3(m[0][0], m[0][2], m[0][3], m[2][0], m[2][2], m[2][3], m[3][0], m[3][2], m[3][3]);
b.m[1][2] = -det3x3(m[0][0], m[0][2], m[0][3], m[1][0], m[1][2], m[1][3], m[3][0], m[3][2], m[3][3]);
b.m[1][3] = det3x3(m[0][0], m[0][2], m[0][3], m[1][0], m[1][2], m[1][3], m[2][0], m[2][2], m[2][3]);
b.m[2][0] = det3x3(m[1][0], m[1][1], m[1][3], m[2][0], m[2][1], m[2][3], m[3][0], m[3][1], m[3][3]);
b.m[2][1] = -det3x3(m[0][0], m[0][1], m[0][3], m[2][0], m[2][1], m[2][3], m[3][0], m[3][1], m[3][3]);
b.m[2][2] = det3x3(m[0][0], m[0][1], m[0][3], m[1][0], m[1][1], m[1][3], m[3][0], m[3][1], m[3][3]);
b.m[2][3] = -det3x3(m[0][0], m[0][1], m[0][3], m[1][0], m[1][1], m[1][3], m[2][0], m[2][1], m[2][3]);
b.m[3][0] = -det3x3(m[1][0], m[1][1], m[1][2], m[2][0], m[2][1], m[2][2], m[3][0], m[3][1], m[3][2]);
b.m[3][1] = det3x3(m[0][0], m[0][1], m[0][2], m[2][0], m[2][1], m[2][2], m[3][0], m[3][1], m[3][2]);
b.m[3][2] = -det3x3(m[0][0], m[0][1], m[0][2], m[1][0], m[1][1], m[1][2], m[3][0], m[3][1], m[3][2]);
b.m[3][3] = det3x3(m[0][0], m[0][1], m[0][2], m[1][0], m[1][1], m[1][2], m[2][0], m[2][1], m[2][2]);
double det = (m[0][0] * b.m[0][0]) + (m[1][0] * b.m[0][1]) + (m[2][0] * b.m[0][2]) + (m[3][0] * b.m[0][3]);
double epsilon = std::numeric_limits<double>::epsilon();
if (det + epsilon >= 0.0f && det - epsilon <= 0.0f) det = FMath::Sign(det) * 0.0001f;
float oodet = (float) (1.0 / det);
b.m[0][0] *= oodet;
b.m[0][1] *= oodet;
b.m[0][2] *= oodet;
b.m[0][3] *= oodet;
b.m[1][0] *= oodet;
b.m[1][1] *= oodet;
b.m[1][2] *= oodet;
b.m[1][3] *= oodet;
b.m[2][0] *= oodet;
b.m[2][1] *= oodet;
b.m[2][2] *= oodet;
b.m[2][3] *= oodet;
b.m[3][0] *= oodet;
b.m[3][1] *= oodet;
b.m[3][2] *= oodet;
b.m[3][3] *= oodet;
return b;
}
float FMMatrix44::Determinant() const
{
float cofactor0 = det3x3(m[1][1], m[1][2], m[1][3], m[2][1], m[2][2],
m[2][3], m[3][1], m[3][2], m[3][3]);
float cofactor1 = -det3x3(m[0][1], m[0][2], m[0][3], m[2][1], m[2][2],
m[2][3], m[3][1], m[3][2], m[3][3]);
float cofactor2 = det3x3(m[0][1], m[0][2], m[0][3], m[1][1], m[1][2],
m[1][3], m[3][1], m[3][2], m[3][3]);
float cofactor3 = -det3x3(m[0][1], m[0][2], m[0][3], m[1][1], m[1][2],
m[1][3], m[2][1], m[2][2], m[2][3]);
return (m[0][0] * cofactor0) + (m[1][0] * cofactor1) +
(m[2][0] * cofactor2) + (m[3][0] * cofactor3);
}
FMMatrix44 operator*(const FMMatrix44& m1, const FMMatrix44& m2)
{
FMMatrix44 mx;
mx.m[0][0] = m1.m[0][0] * m2.m[0][0] + m1.m[1][0] * m2.m[0][1] + m1.m[2][0] * m2.m[0][2] + m1.m[3][0] * m2.m[0][3];
mx.m[0][1] = m1.m[0][1] * m2.m[0][0] + m1.m[1][1] * m2.m[0][1] + m1.m[2][1] * m2.m[0][2] + m1.m[3][1] * m2.m[0][3];
mx.m[0][2] = m1.m[0][2] * m2.m[0][0] + m1.m[1][2] * m2.m[0][1] + m1.m[2][2] * m2.m[0][2] + m1.m[3][2] * m2.m[0][3];
mx.m[0][3] = m1.m[0][3] * m2.m[0][0] + m1.m[1][3] * m2.m[0][1] + m1.m[2][3] * m2.m[0][2] + m1.m[3][3] * m2.m[0][3];
mx.m[1][0] = m1.m[0][0] * m2.m[1][0] + m1.m[1][0] * m2.m[1][1] + m1.m[2][0] * m2.m[1][2] + m1.m[3][0] * m2.m[1][3];
mx.m[1][1] = m1.m[0][1] * m2.m[1][0] + m1.m[1][1] * m2.m[1][1] + m1.m[2][1] * m2.m[1][2] + m1.m[3][1] * m2.m[1][3];
mx.m[1][2] = m1.m[0][2] * m2.m[1][0] + m1.m[1][2] * m2.m[1][1] + m1.m[2][2] * m2.m[1][2] + m1.m[3][2] * m2.m[1][3];
mx.m[1][3] = m1.m[0][3] * m2.m[1][0] + m1.m[1][3] * m2.m[1][1] + m1.m[2][3] * m2.m[1][2] + m1.m[3][3] * m2.m[1][3];
mx.m[2][0] = m1.m[0][0] * m2.m[2][0] + m1.m[1][0] * m2.m[2][1] + m1.m[2][0] * m2.m[2][2] + m1.m[3][0] * m2.m[2][3];
mx.m[2][1] = m1.m[0][1] * m2.m[2][0] + m1.m[1][1] * m2.m[2][1] + m1.m[2][1] * m2.m[2][2] + m1.m[3][1] * m2.m[2][3];
mx.m[2][2] = m1.m[0][2] * m2.m[2][0] + m1.m[1][2] * m2.m[2][1] + m1.m[2][2] * m2.m[2][2] + m1.m[3][2] * m2.m[2][3];
mx.m[2][3] = m1.m[0][3] * m2.m[2][0] + m1.m[1][3] * m2.m[2][1] + m1.m[2][3] * m2.m[2][2] + m1.m[3][3] * m2.m[2][3];
mx.m[3][0] = m1.m[0][0] * m2.m[3][0] + m1.m[1][0] * m2.m[3][1] + m1.m[2][0] * m2.m[3][2] + m1.m[3][0] * m2.m[3][3];
mx.m[3][1] = m1.m[0][1] * m2.m[3][0] + m1.m[1][1] * m2.m[3][1] + m1.m[2][1] * m2.m[3][2] + m1.m[3][1] * m2.m[3][3];
mx.m[3][2] = m1.m[0][2] * m2.m[3][0] + m1.m[1][2] * m2.m[3][1] + m1.m[2][2] * m2.m[3][2] + m1.m[3][2] * m2.m[3][3];
mx.m[3][3] = m1.m[0][3] * m2.m[3][0] + m1.m[1][3] * m2.m[3][1] + m1.m[2][3] * m2.m[3][2] + m1.m[3][3] * m2.m[3][3];
return mx;
}
FMVector4 operator*(const FMMatrix44& m, const FMVector4& v)
{
float x = m[0][0] * v.x + m[1][0] * v.y + m[2][0] * v.z + m[3][0] * v.w;
float y = m[0][1] * v.x + m[1][1] * v.y + m[2][1] * v.z + m[3][1] * v.w;
float z = m[0][2] * v.x + m[1][2] * v.y + m[2][2] * v.z + m[3][2] * v.w;
float w = m[0][3] * v.x + m[1][3] * v.y + m[2][3] * v.z + m[3][3] * v.w;
return FMVector4(x, y, z, w);
}
FMMatrix44 operator*(float a, const FMMatrix44& m1)
{
FMMatrix44 mx;
mx.m[0][0] = a * m1.m[0][0];
mx.m[0][1] = a * m1.m[0][1];
mx.m[0][2] = a * m1.m[0][2];
mx.m[0][3] = a * m1.m[0][3];
mx.m[1][0] = a * m1.m[1][0];
mx.m[1][1] = a * m1.m[1][1];
mx.m[1][2] = a * m1.m[1][2];
mx.m[1][3] = a * m1.m[1][3];
mx.m[2][0] = a * m1.m[2][0];
mx.m[2][1] = a * m1.m[2][1];
mx.m[2][2] = a * m1.m[2][2];
mx.m[2][3] = a * m1.m[2][3];
mx.m[3][0] = a * m1.m[3][0];
mx.m[3][1] = a * m1.m[3][1];
mx.m[3][2] = a * m1.m[3][2];
mx.m[3][3] = a * m1.m[3][3];
return mx;
}
FMMatrix44 FMMatrix44::TranslationMatrix(const FMVector3& translation)
{
FMMatrix44 matrix;
matrix[0][0] = 1.0f; matrix[0][1] = 0.0f; matrix[0][2] = 0.0f; matrix[0][3] = 0.0f;
matrix[1][0] = 0.0f; matrix[1][1] = 1.0f; matrix[1][2] = 0.0f; matrix[1][3] = 0.0f;
matrix[2][0] = 0.0f; matrix[2][1] = 0.0f; matrix[2][2] = 1.0f; matrix[2][3] = 0.0f;
matrix[3][0] = translation.x; matrix[3][1] = translation.y; matrix[3][2] = translation.z; matrix[3][3] = 1.0f;
return matrix;
}
FMMatrix44 FMMatrix44::AxisRotationMatrix(const FMVector3& axis, float angle)
{
// Formulae inspired from http://www.mines.edu/~gmurray/ArbitraryAxisRotation/ArbitraryAxisRotation.html
FMMatrix44 matrix;
FMVector3 a = (IsEquivalent(axis.LengthSquared(), 1.0f)) ? axis : axis.Normalize();
float xSq = a.x * a.x;
float ySq = a.y * a.y;
float zSq = a.z * a.z;
float cT = cosf(angle);
float sT = sinf(angle);
matrix[0][0] = xSq + (ySq + zSq) * cT;
matrix[0][1] = a.x * a.y * (1.0f - cT) + a.z * sT;
matrix[0][2] = a.x * a.z * (1.0f - cT) - a.y * sT;
matrix[0][3] = 0;
matrix[1][0] = a.x * a.y * (1.0f - cT) - a.z * sT;
matrix[1][1] = ySq + (xSq + zSq) * cT;
matrix[1][2] = a.y * a.z * (1.0f - cT) + a.x * sT;
matrix[1][3] = 0;
matrix[2][0] = a.x * a.z * (1.0f - cT) + a.y * sT;
matrix[2][1] = a.y * a.z * (1.0f - cT) - a.x * sT;
matrix[2][2] = zSq + (xSq + ySq) * cT;
matrix[2][3] = 0;
matrix[3][2] = matrix[3][1] = matrix[3][0] = 0;
matrix[3][3] = 1;
return matrix;
}
FMMatrix44 FMMatrix44::XAxisRotationMatrix(float angle)
{
FMMatrix44 ret = FMMatrix44::Identity;
ret[1][1] = ret[2][2] = cos(angle);
ret[2][1] = -(ret[1][2] = sin(angle));
return ret;
}
FMMatrix44 FMMatrix44::YAxisRotationMatrix(float angle)
{
FMMatrix44 ret = FMMatrix44::Identity;
ret[0][0] = ret[2][2] = cos(angle);
ret[0][2] = -(ret[2][0] = sin(angle));
return ret;
}
FMMatrix44 FMMatrix44::ZAxisRotationMatrix(float angle)
{
FMMatrix44 ret = FMMatrix44::Identity;
ret[0][0] = ret[1][1] = cos(angle);
ret[1][0] = -(ret[0][1] = sin(angle));
return ret;
}
FMMatrix44 FMMatrix44::EulerRotationMatrix(const FMVector3& rotation)
{
FMMatrix44 transform;
if (!IsEquivalent(rotation.x, 0.0f)) transform = XAxisRotationMatrix(rotation.x);
else transform = FMMatrix44::Identity;
if (!IsEquivalent(rotation.y, 0.0f)) transform *= YAxisRotationMatrix(rotation.y);
if (!IsEquivalent(rotation.z, 0.0f)) transform *= ZAxisRotationMatrix(rotation.z);
return transform;
}
FMMatrix44 FMMatrix44::ScaleMatrix(const FMVector3& scale)
{
FMMatrix44 mx(Identity);
mx[0][0] = scale.x; mx[1][1] = scale.y; mx[2][2] = scale.z;
return mx;
}
FMMatrix44 FMMatrix44::LookAtMatrix(const FMVector3& eye, const FMVector3& target, const FMVector3& up)
{
FMMatrix44 mx;
FMVector3 forward = (target - eye).Normalize();
FMVector3 sideways, upward;
if (!IsEquivalent(forward, up) && !IsEquivalent(forward, -up))
{
sideways = (forward ^ up).Normalize();
}
else if (!IsEquivalent(up, FMVector3::XAxis))
{
sideways = FMVector3::XAxis;
}
else
{
sideways = FMVector3::ZAxis;
}
upward = (sideways ^ forward);
mx[0][0] = sideways.x; mx[0][1] = sideways.y; mx[0][2] = sideways.z;
mx[1][0] = upward.x; mx[1][1] = upward.y; mx[1][2] = upward.z;
mx[2][0] = -forward.x; mx[2][1] = -forward.y; mx[2][2] = -forward.z;
mx[3][0] = eye.x; mx[3][1] = eye.y; mx[3][2] = eye.z;
mx[0][3] = mx[1][3] = mx[2][3] = 0.0f;
mx[3][3] = 1.0f;
return mx;
}
bool IsEquivalent(const FMMatrix44& m1, const FMMatrix44& m2)
{
return IsEquivalent(m1.m[0][0], m2.m[0][0]) && IsEquivalent(m1.m[1][0], m2.m[1][0])
&& IsEquivalent(m1.m[2][0], m2.m[2][0]) && IsEquivalent(m1.m[3][0], m2.m[3][0])
&& IsEquivalent(m1.m[0][1], m2.m[0][1]) && IsEquivalent(m1.m[1][1], m2.m[1][1])
&& IsEquivalent(m1.m[2][1], m2.m[2][1]) && IsEquivalent(m1.m[3][1], m2.m[3][1])
&& IsEquivalent(m1.m[0][2], m2.m[0][2]) && IsEquivalent(m1.m[1][2], m2.m[1][2])
&& IsEquivalent(m1.m[2][2], m2.m[2][2]) && IsEquivalent(m1.m[3][2], m2.m[3][2])
&& IsEquivalent(m1.m[0][3], m2.m[0][3]) && IsEquivalent(m1.m[1][3], m2.m[1][3])
&& IsEquivalent(m1.m[2][3], m2.m[2][3]) && IsEquivalent(m1.m[3][3], m2.m[3][3]);
}
| 39.014085 | 127 | 0.522503 | [
"transform"
] |
987b78932adb53ecd1a7f7517cda05f8f56df2fb | 9,191 | cpp | C++ | render_delegate/render_pass.cpp | frenchdog/arnold-usd | 53fbc4f9ae94f906371a4043f0dd32c014cecc15 | [
"Apache-2.0"
] | 2 | 2020-12-01T03:34:51.000Z | 2021-03-06T01:49:44.000Z | render_delegate/render_pass.cpp | BigRoy/arnold-usd | b9d8b237f76348aa45a0e67260336d40901f89d9 | [
"BSD-3-Clause"
] | null | null | null | render_delegate/render_pass.cpp | BigRoy/arnold-usd | b9d8b237f76348aa45a0e67260336d40901f89d9 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 Luma Pictures
//
// 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.
//
// Modifications Copyright 2019 Autodesk, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*
* TODO:
* - Writing to the render buffers directly.
*/
#include "render_pass.h"
#include <pxr/imaging/hd/renderPassState.h>
#include <algorithm>
#include <cstring> // memset
#include "config.h"
#include "constant_strings.h"
#include "nodes/nodes.h"
#include "render_buffer.h"
#include "utils.h"
PXR_NAMESPACE_OPEN_SCOPE
HdArnoldRenderPass::HdArnoldRenderPass(
HdArnoldRenderDelegate* delegate, HdRenderIndex* index, const HdRprimCollection& collection)
: HdRenderPass(index, collection), _delegate(delegate)
{
auto* universe = _delegate->GetUniverse();
_camera = AiNode(universe, str::persp_camera);
AiNodeSetPtr(AiUniverseGetOptions(universe), str::camera, _camera);
AiNodeSetStr(_camera, str::name, _delegate->GetLocalNodeName(str::renderPassCamera));
_beautyFilter = AiNode(universe, str::gaussian_filter);
AiNodeSetStr(_beautyFilter, str::name, _delegate->GetLocalNodeName(str::renderPassFilter));
_closestFilter = AiNode(universe, str::closest_filter);
AiNodeSetStr(_closestFilter, str::name, _delegate->GetLocalNodeName(str::renderPassClosestFilter));
_driver = AiNode(universe, HdArnoldNodeNames::driver);
AiNodeSetStr(_driver, str::name, _delegate->GetLocalNodeName(str::renderPassDriver));
auto* options = _delegate->GetOptions();
auto* outputsArray = AiArrayAllocate(3, 1, AI_TYPE_STRING);
const auto beautyString = TfStringPrintf("RGBA RGBA %s %s", AiNodeGetName(_beautyFilter), AiNodeGetName(_driver));
// We need NDC, and the easiest way is to use the position.
const auto positionString = TfStringPrintf("P VECTOR %s %s", AiNodeGetName(_closestFilter), AiNodeGetName(_driver));
const auto idString = TfStringPrintf("ID UINT %s %s", AiNodeGetName(_closestFilter), AiNodeGetName(_driver));
AiArraySetStr(outputsArray, 0, beautyString.c_str());
AiArraySetStr(outputsArray, 1, positionString.c_str());
AiArraySetStr(outputsArray, 2, idString.c_str());
AiNodeSetArray(options, str::outputs, outputsArray);
const auto& config = HdArnoldConfig::GetInstance();
AiNodeSetFlt(_camera, str::shutter_start, config.shutter_start);
AiNodeSetFlt(_camera, str::shutter_end, config.shutter_end);
}
HdArnoldRenderPass::~HdArnoldRenderPass()
{
AiNodeDestroy(_camera);
AiNodeDestroy(_beautyFilter);
AiNodeDestroy(_closestFilter);
AiNodeDestroy(_driver);
}
void HdArnoldRenderPass::_Execute(const HdRenderPassStateSharedPtr& renderPassState, const TfTokenVector& renderTags)
{
TF_UNUSED(renderTags);
auto* renderParam = reinterpret_cast<HdArnoldRenderParam*>(_delegate->GetRenderParam());
const auto vp = renderPassState->GetViewport();
const auto projMtx = renderPassState->GetProjectionMatrix();
const auto viewMtx = renderPassState->GetWorldToViewMatrix();
auto restarted = false;
if (projMtx != _projMtx || viewMtx != _viewMtx) {
_projMtx = projMtx;
_viewMtx = viewMtx;
renderParam->Restart();
restarted = true;
AiNodeSetMatrix(_camera, str::matrix, HdArnoldConvertMatrix(_viewMtx.GetInverse()));
AiNodeSetMatrix(_driver, HdArnoldDriver::projMtx, HdArnoldConvertMatrix(_projMtx));
AiNodeSetMatrix(_driver, HdArnoldDriver::viewMtx, HdArnoldConvertMatrix(_viewMtx));
const auto fov = static_cast<float>(GfRadiansToDegrees(atan(1.0 / _projMtx[0][0]) * 2.0));
AiNodeSetFlt(_camera, str::fov, fov);
}
const auto width = static_cast<int>(vp[2]);
const auto height = static_cast<int>(vp[3]);
const auto numPixels = static_cast<size_t>(width * height);
if (width != _width || height != _height) {
if (!restarted) {
renderParam->Restart();
}
hdArnoldEmptyBucketQueue([](const HdArnoldBucketData*) {});
const auto oldNumPixels = static_cast<size_t>(_width * _height);
_width = width;
_height = height;
auto* options = _delegate->GetOptions();
AiNodeSetInt(options, str::xres, _width);
AiNodeSetInt(options, str::yres, _height);
if (oldNumPixels < numPixels) {
_colorBuffer.resize(numPixels, AtRGBA8());
_depthBuffer.resize(numPixels, 1.0f);
_primIdBuffer.resize(numPixels, -1);
memset(_colorBuffer.data(), 0, oldNumPixels * sizeof(AtRGBA8));
std::fill(_depthBuffer.begin(), _depthBuffer.begin() + oldNumPixels, 1.0f);
std::fill(_primIdBuffer.begin(), _primIdBuffer.begin() + oldNumPixels, -1);
} else {
if (numPixels != oldNumPixels) {
_colorBuffer.resize(numPixels);
_depthBuffer.resize(numPixels);
_primIdBuffer.resize(numPixels);
}
memset(_colorBuffer.data(), 0, numPixels * sizeof(AtRGBA8));
std::fill(_depthBuffer.begin(), _depthBuffer.end(), 1.0f);
std::fill(_primIdBuffer.begin(), _primIdBuffer.end(), -1);
}
}
_isConverged = renderParam->Render();
bool needsUpdate = false;
hdArnoldEmptyBucketQueue([this, &needsUpdate](const HdArnoldBucketData* data) {
const auto xo = AiClamp(data->xo, 0, _width - 1);
const auto xe = AiClamp(data->xo + data->sizeX, 0, _width - 1);
if (xe == xo) {
return;
}
const auto yo = AiClamp(data->yo, 0, _height - 1);
const auto ye = AiClamp(data->yo + data->sizeY, 0, _height - 1);
if (ye == yo) {
return;
}
needsUpdate = true;
const auto beautyWidth = (xe - xo) * sizeof(AtRGBA8);
const auto depthWidth = (xe - xo) * sizeof(float);
const auto inOffsetG = xo - data->xo - data->sizeX * data->yo;
const auto outOffsetG = _width * (_height - 1);
for (auto y = yo; y < ye; ++y) {
const auto inOffset = data->sizeX * y + inOffsetG;
const auto outOffset = xo + outOffsetG - _width * y;
memcpy(_colorBuffer.data() + outOffset, data->beauty.data() + inOffset, beautyWidth);
memcpy(_depthBuffer.data() + outOffset, data->depth.data() + inOffset, depthWidth);
memcpy(_primIdBuffer.data() + outOffset, data->primId.data() + inOffset, depthWidth);
}
});
HdRenderPassAovBindingVector aovBindings = renderPassState->GetAovBindings();
// If the buffers are empty, needsUpdate will be false.
if (aovBindings.empty()) {
// No AOV bindings means blit current framebuffer contents.
if (needsUpdate) {
#ifdef USD_HAS_UPDATED_COMPOSITOR
_compositor.UpdateColor(_width, _height, HdFormat::HdFormatUNorm8Vec4, _colorBuffer.data());
#else
_compositor.UpdateColor(_width, _height, reinterpret_cast<uint8_t*>(_colorBuffer.data()));
#endif
_compositor.UpdateDepth(_width, _height, reinterpret_cast<uint8_t*>(_depthBuffer.data()));
}
_compositor.Draw();
} else {
// Blit from the framebuffer to the currently selected AOVs.
for (auto& aov : aovBindings) {
if (!TF_VERIFY(aov.renderBuffer != nullptr)) {
continue;
}
auto* rb = static_cast<HdArnoldRenderBuffer*>(aov.renderBuffer);
// Forward convergence state to the render buffers...
rb->SetConverged(_isConverged);
if (needsUpdate) {
if (aov.aovName == HdAovTokens->color) {
rb->Blit(
HdFormatUNorm8Vec4, width, height, 0, width, reinterpret_cast<uint8_t*>(_colorBuffer.data()));
} else if (aov.aovName == HdAovTokens->depth) {
rb->Blit(HdFormatFloat32, width, height, 0, width, reinterpret_cast<uint8_t*>(_depthBuffer.data()));
} else if (aov.aovName == HdAovTokens->primId) {
rb->Blit(HdFormatInt32, width, height, 0, width, reinterpret_cast<uint8_t*>(_primIdBuffer.data()));
}
}
}
}
}
PXR_NAMESPACE_CLOSE_SCOPE
| 44.1875 | 120 | 0.666086 | [
"render",
"vector"
] |
987dc554a696482ac9585cc6f862e739055eacf4 | 4,318 | cpp | C++ | Modules/TArc/Sources/TArc/Controls/Private/ListView.cpp | stinvi/dava.engine | 2b396ca49cdf10cdc98ad8a9ffcf7768a05e285e | [
"BSD-3-Clause"
] | 26 | 2018-09-03T08:48:22.000Z | 2022-02-14T05:14:50.000Z | Modules/TArc/Sources/TArc/Controls/Private/ListView.cpp | ANHELL-blitz/dava.engine | ed83624326f000866e29166c7f4cccfed1bb41d4 | [
"BSD-3-Clause"
] | null | null | null | Modules/TArc/Sources/TArc/Controls/Private/ListView.cpp | ANHELL-blitz/dava.engine | ed83624326f000866e29166c7f4cccfed1bb41d4 | [
"BSD-3-Clause"
] | 45 | 2018-05-11T06:47:17.000Z | 2022-02-03T11:30:55.000Z | #include "TArc/Controls/ListView.h"
#include "TArc/Utils/ScopedValueGuard.h"
#include <QAbstractListModel>
#include <QItemSelectionModel>
#include <QVariant>
namespace DAVA
{
namespace ListViewDetails
{
class ListModel : public QAbstractListModel
{
public:
int rowCount(const QModelIndex& parent) const override
{
return static_cast<int>(values.size());
}
QVariant data(const QModelIndex& index, int role) const override
{
if (role == Qt::DisplayRole)
{
int row = index.row();
DVASSERT(row < static_cast<int>(values.size()));
return values[row].second.Cast<QString>();
}
return QVariant();
}
Qt::ItemFlags flags(const QModelIndex& index) const override
{
return Qt::ItemFlags(Qt::ItemIsSelectable | Qt::ItemNeverHasChildren | Qt::ItemIsEnabled);
}
void BeginReset()
{
beginResetModel();
}
void EndReset()
{
endResetModel();
}
Vector<std::pair<Any, Any>> values;
};
}
ListView::ListView(const Params& params, DataWrappersProcessor* wrappersProcessor, Reflection model, QWidget* parent)
: TBase(params, ControlDescriptor(params.fields), wrappersProcessor, model, parent)
{
SetupControl();
}
ListView::ListView(const Params& params, ContextAccessor* accessor, Reflection model, QWidget* parent)
: TBase(params, ControlDescriptor(params.fields), accessor, model, parent)
{
SetupControl();
}
void ListView::SetupControl()
{
setUniformItemSizes(true);
setSelectionBehavior(QAbstractItemView::SelectItems);
setSelectionMode(QAbstractItemView::SingleSelection);
listModel = new ListViewDetails::ListModel();
setModel(listModel);
QItemSelectionModel* selectModel = new QItemSelectionModel(listModel, this);
connections.AddConnection(selectModel, &QItemSelectionModel::selectionChanged, MakeFunction(this, &ListView::OnSelectionChanged));
setSelectionModel(selectModel);
}
void ListView::UpdateControl(const ControlDescriptor& fields)
{
SCOPED_VALUE_GUARD(bool, updateGuard, true, void());
ListViewDetails::ListModel* m = static_cast<ListViewDetails::ListModel*>(listModel);
if (fields.IsChanged(Fields::ValueList))
{
m->BeginReset();
m->values.clear();
Reflection r = model.GetField(fields.GetName(Fields::ValueList));
DVASSERT(r.IsValid());
Vector<Reflection::Field> fields = r.GetFields();
m->values.reserve(fields.size());
for (const Reflection::Field& f : fields)
{
m->values.emplace_back(f.key, f.ref.GetValue());
}
m->EndReset();
}
if (fields.IsChanged(Fields::CurrentValue) || fields.IsChanged(Fields::ValueList))
{
Any currentValue = GetFieldValue(Fields::CurrentValue, Any());
bool currentValueSet = false;
for (size_t i = 0; i < m->values.size(); ++i)
{
if (m->values[i].first == currentValue)
{
QModelIndex index = m->index(static_cast<int>(i), 0, QModelIndex());
QItemSelectionModel* selectModel = selectionModel();
selectModel->clearCurrentIndex();
selectModel->select(index, QItemSelectionModel::ClearAndSelect);
currentValueSet = true;
break;
}
}
if (currentValueSet == false)
{
wrapper.SetFieldValue(GetFieldName(Fields::CurrentValue), Any());
}
}
setEnabled(!IsValueReadOnly(fields, Fields::CurrentValue, Fields::IsReadOnly));
}
void ListView::OnSelectionChanged(const QItemSelection& newSelection, const QItemSelection& oldSelection)
{
SCOPED_VALUE_GUARD(bool, updateGuard, true, void());
QModelIndexList indexList = newSelection.indexes();
DVASSERT(indexList.size() < 2);
if (indexList.size() == 1)
{
const QModelIndex& index = indexList.front();
ListViewDetails::ListModel* m = static_cast<ListViewDetails::ListModel*>(listModel);
DVASSERT(index.row() < m->values.size());
wrapper.SetFieldValue(GetFieldName(Fields::CurrentValue), m->values[index.row()].first);
}
else
{
wrapper.SetFieldValue(GetFieldName(Fields::CurrentValue), Any());
}
}
} // namespace DAVA
| 29.986111 | 134 | 0.653543 | [
"vector",
"model"
] |
987ffa9d5f73c55edf5131a271497e0836129580 | 2,901 | cpp | C++ | src/app4.cpp | buxtonpaul/raytrace_challenge | 2b19e95f410ee3b0d1b33992bbf4715f6647c6f1 | [
"MIT"
] | 1 | 2021-06-06T03:41:52.000Z | 2021-06-06T03:41:52.000Z | src/app4.cpp | buxtonpaul/raytrace_challenge | 2b19e95f410ee3b0d1b33992bbf4715f6647c6f1 | [
"MIT"
] | null | null | null | src/app4.cpp | buxtonpaul/raytrace_challenge | 2b19e95f410ee3b0d1b33992bbf4715f6647c6f1 | [
"MIT"
] | null | null | null | #include <fstream>
#include <iostream>
#include "camera.h"
#include "canvas.h"
#include "color.h"
#include "light.h"
#include "material.h"
#include "matrix.h"
#include "rays.h"
#include "sphere.h"
#include "tuples.h"
#include "world.h"
#include "pattern.h"
using namespace ray_lib;
int main(int argc, char *argv[])
{
Camera c{640, 480, M_PI / 2};
c.view_transform(view_transform(Point(0, 1.5, -5), Point(0, 1, 0),
Vector(0, 1, 0)));
World w;
std::shared_ptr<Sphere> floor = std::make_shared<Sphere>();
std::shared_ptr<Material> m_floor = std::make_shared<Material>();
SolidPattern mfloor_pat{Color(1.0, 0.9, 0.9)};
m_floor->pattern(mfloor_pat);
floor->Transform(scale(10, 0.01, 10));
m_floor->specular(0);
floor->material(m_floor);
w.WorldShapes().push_back(floor);
std::shared_ptr<Sphere> left_wall = std::make_shared<Sphere>();
left_wall->Transform(scale(10, 0.01, 10)
.rotate_x(M_PI / 2.0)
.rotate_y(-M_PI / 4.0)
.translate(0, 0, 5));
left_wall->material(m_floor);
w.WorldShapes().push_back(left_wall);
std::shared_ptr<Sphere> right_wall = std::make_shared<Sphere>();
right_wall->Transform(scale(10, 0.01, 10)
.rotate_x(M_PI / 2.0)
.rotate_y(M_PI / 4.0)
.translate(0, 0, 5));
right_wall->material(m_floor);
std::shared_ptr<Sphere> middle = std::make_shared<Sphere>();
middle->Transform(translation(-0.5, 1, 0.5));
std::shared_ptr<Material> middle_mat = std::make_shared<Material>(Material());
SolidPattern middle_pat(Color(0.1, 1, 0.5));
middle_mat->pattern(middle_pat);
middle_mat->specular(0.3);
middle_mat->diffuse(0.7);
middle->material(middle_mat);
std::shared_ptr<Sphere> right = std::make_shared<Sphere>();
right->Transform(scale(0.5, 0.5, 0.5).translate(1.5, 0.5, -0.5));
std::shared_ptr<Material> right_mat = std::make_shared<Material>(Material());
SolidPattern right_pat(Color(0.5, 1, 0.1));
right_mat->pattern(right_pat);
right_mat->specular(0.3);
right_mat->diffuse(0.7);
right->material(right_mat);
std::shared_ptr<Sphere> left = std::make_shared<Sphere>();
left->Transform(scale(0.33, 0.33, 0.33).translate(-1.5, 0.33, -0.75));
std::shared_ptr<Material> left_mat;
SolidPattern left_pat(Color(1, 0.8, 0.1));
left_mat->pattern(left_pat);
left_mat->specular(0.3);
left_mat->diffuse(0.7);
left->material(left_mat);
Light l{Color(1.0, 1.0, 1.0), Point(-10, 10, -10)};
w.WorldShapes().push_back(right_wall);
w.WorldShapes().push_back(middle);
w.WorldShapes().push_back(left);
w.WorldShapes().push_back(right);
w.WorldLights().push_back(&l);
Canvas outimage{c.render(&w)};
std::ofstream outfile(genfilestring() + ".ppm");
outfile << outimage.ppm();
outfile.close();
}
| 30.861702 | 80 | 0.636332 | [
"render",
"vector",
"transform"
] |
9884cb31454ecf39c7eda08179d3edf624ce7295 | 16,530 | cpp | C++ | dllmain/FilterXXFixes.cpp | emoose/re4_tweaks | 4d324c7b66f627d4505a5d142146129c0c3daa3b | [
"Zlib"
] | null | null | null | dllmain/FilterXXFixes.cpp | emoose/re4_tweaks | 4d324c7b66f627d4505a5d142146129c0c3daa3b | [
"Zlib"
] | 1 | 2022-03-03T14:43:49.000Z | 2022-03-03T14:43:49.000Z | dllmain/FilterXXFixes.cpp | emoose/re4_tweaks | 4d324c7b66f627d4505a5d142146129c0c3daa3b | [
"Zlib"
] | 1 | 2022-02-18T16:23:58.000Z | 2022-02-18T16:23:58.000Z | #include <iostream>
#include "stdafx.h"
#include "dllmain.h"
#include "Settings.h"
#include "Logging/Logging.h"
struct Filter01Params
{
void* OtHandle; // OT = render pass or something
int Distance;
float AlphaLevel;
uint8_t FocusMode;
uint8_t UnkD; // if set then it uses code-path with constant 4-pass loop, else uses pass with loop based on AlphaLevel
};
float* ptr_InternalWidth;
float* ptr_InternalHeight;
float* ptr_InternalHeightScale;
int* ptr_RenderHeight;
uint32_t* ptr_filter01_buff;
void(__cdecl* GXBegin)(int a1, int a2, short a3);
void(__cdecl* GXPosition3f32)(float a1, float a2, float a3);
void(__cdecl* GXColor4u8)(uint8_t a1, uint8_t a2, uint8_t a3, uint8_t a4);
void(__cdecl* GXTexCoord2f32)(float a1, float a2);
void(__cdecl* GXShaderCall_Maybe)(int a1);
void(__cdecl* GXSetTexCopySrc)(short a1, short a2, short a3, short a4);
void(__cdecl* GXSetTexCopyDst)(short a1, short a2, int a3, char a4);
void(__cdecl* GXCopyTex)(uint32_t a1, char a2, int a3);
void(__cdecl* Filter0aGXDraw_Orig)(
float PositionX, float PositionY, float PositionZ,
float TexOffsetX, float TexOffsetY,
float ColorA,
float ScreenSizeDivisor, int IsMaskTex);
uint32_t* ptr_Filter0aGXDraw_call1;
uint32_t* ptr_Filter0aGXDraw_call2;
uint32_t* ptr_Filter0aGXDraw_call3;
uint8_t* ptr_Filter0aDrawBuffer_GetEFBCall;
int32_t* ptr_filter0a_shader_num;
int filter0a_ecx_value = 0;
// Filter0aGXDraw_Orig makes use of ECX for part of screen-size division code
// So we need a trampoline to set that first before calling it...
void __declspec(naked) Filter0aGXDraw_Orig_Tramp(float PositionX, float PositionY, float PositionZ,
float TexOffsetX, float TexOffsetY,
float ColorA,
float ScreenSizeDivisor, int IsMaskTex)
{
__asm
{
mov ecx, [filter0a_ecx_value]
jmp Filter0aGXDraw_Orig
}
}
void __cdecl Filter0aGXDraw_Hook(
float PositionX, float PositionY, float PositionZ,
float TexOffsetX, float TexOffsetY,
float ColorA,
float ScreenSizeDivisor, int IsMaskTex)
{
// We lost the ECX parameter since VC doesn't have any caller-saved calling conventions that use it, game probably had LTO or something to create a custom one
// Luckily the game only uses a couple different values for it, so we can work out what it was pretty easily
filter0a_ecx_value = (int)ScreenSizeDivisor;
if (ColorA == 255 && ScreenSizeDivisor == 4 && IsMaskTex == 0)
filter0a_ecx_value = 1; // special case for first GXDraw call inside Filter0aDrawBuffer
// Run original Filter0aGXDraw for it to handle the GXInitTexObj etc things
// (needs to be patched to make it skip over the things we reimpl. here first though!)
Filter0aGXDraw_Orig_Tramp(PositionX, PositionY, PositionZ, TexOffsetX, TexOffsetY, ColorA, ScreenSizeDivisor, IsMaskTex);
float GameWidth = *ptr_InternalWidth;
float GameHeight = *ptr_InternalHeight;
// Internally the game is scaled at a seperate aspect ratio, causing some invisible black-bars around the image, which GX drawing code has to skip over
// With this code we first work out the difference between that internal height & the actual render height, which gives us the size of both black bars
// Then work out the proportion of 1 black bar by dividing by "heightInternalScaled + heightInternalScaled" (which is just a more optimized way of dividing by heightInternalScaled and then again dividing result by 2)
// Finally multiply that proportion by the games original GC height to get the size of black-bar in 'GC-space'
float heightInternalScaled = *ptr_InternalHeightScale * 448.0f;
float blackBarSize = 448.0f * (heightInternalScaled - *ptr_RenderHeight) / (heightInternalScaled + heightInternalScaled);
// GameHeight seems to contain both black bars inside it already
// So to scale that properly we first need to remove both black bars, scale it by ScreenSizeDivisor, then add 1 black-bar back to skip over the top black-bar area
float pos_bottom = PositionY + ((GameHeight - (blackBarSize * 2)) / ScreenSizeDivisor) + blackBarSize;
float pos_top = PositionY + blackBarSize;
float pos_left = PositionX;
float pos_right = PositionX + GameWidth / ScreenSizeDivisor;
// Prevent bleed-thru of certain effects into the transparency-drawing area
pos_left += -0.25f;
// Roughly center the blur-mask-effect inside the scope
// TODO: GC version seems to have no blur in the inner-scope at all, any way we can fix this to make it the same here?
if (IsMaskTex)
{
pos_top += -1.0f;
pos_bottom += 4.0f;
pos_left += -4.0f;
pos_right += 4.0f;
}
GXBegin(0x80, 0, 4);
GXPosition3f32(pos_left, pos_top, PositionZ);
GXColor4u8(0xFF, 0xFF, 0xFF, (uint8_t)ColorA);
GXTexCoord2f32(0.0f + TexOffsetX, 0.0f + TexOffsetY);
GXPosition3f32(pos_right, pos_top, PositionZ);
GXColor4u8(0xFF, 0xFF, 0xFF, (uint8_t)ColorA);
GXTexCoord2f32(1.0f + TexOffsetX, 0.0f + TexOffsetY);
GXPosition3f32(pos_right, pos_bottom, PositionZ);
GXColor4u8(0xFF, 0xFF, 0xFF, (uint8_t)ColorA);
GXTexCoord2f32(1.0f + TexOffsetX, 1.0f + TexOffsetY);
GXPosition3f32(pos_left, pos_bottom, PositionZ);
GXColor4u8(0xFF, 0xFF, 0xFF, (uint8_t)ColorA);
GXTexCoord2f32(0.0f + TexOffsetX, 1.0f + TexOffsetY);
int filter0a_shader_num = *ptr_filter0a_shader_num;
GXShaderCall_Maybe(filter0a_shader_num);
}
void __cdecl Filter01Render_Hook1(Filter01Params* params)
{
float blurPositionOffset = params->AlphaLevel * 0.33f;
float GameWidth = *ptr_InternalWidth;
float GameHeight = *ptr_InternalHeight;
// Code that was in original Filter01Render
// Seems to usually be 1/8th of 448, might change depending on ptr_InternalHeightScale / ptr_RenderHeight though
// Offset is used to fix Y coords of the blur effect, otherwise the blur ends up offset from the image for some reason
float heightScaled = *ptr_InternalHeightScale * 448.0f;
float offsetY = 448.0f * (heightScaled - *ptr_RenderHeight) / (heightScaled + heightScaled);
float deltaX = 0;
float deltaY = 0;
float posZ = (float)params->Distance;
for (int loopIdx = 0; loopIdx < 4; loopIdx++)
{
// Main reason for this hook is to add the deltaX/deltaY vars below, needed for the DoF effect to work properly
// GC debug had this, but was removed in X360 port onwards for some reason
// (yet even though this was removed, the X360 devs did add the code for offsetY above to fix the blur...)
if (loopIdx == 0) {
deltaX = 0.0f - blurPositionOffset;
deltaY = 0.0f - blurPositionOffset;
}
else if (loopIdx == 1) {
deltaX = 0.0f + blurPositionOffset;
deltaY = 0.0f + blurPositionOffset;
}
else if (loopIdx == 2) {
deltaX = 0.0f + blurPositionOffset;
deltaY = 0.0f - blurPositionOffset;
}
else if (loopIdx == 3) {
deltaX = 0.0f - blurPositionOffset;
deltaY = 0.0f + blurPositionOffset;
}
posZ = posZ + 100.0f;
if (posZ > 65536)
posZ = 65536;
GXBegin(0x80, 0, 4);
GXPosition3f32(0.0f + deltaX, 0.0f + deltaY + offsetY, posZ);
GXColor4u8(0xFF, 0xFF, 0xFF, (uint8_t)0x80);
GXTexCoord2f32(0.0f, 0.0f);
GXPosition3f32(0.0f + deltaX + GameWidth, 0.0f + deltaY + offsetY, posZ);
GXColor4u8(0xFF, 0xFF, 0xFF, (uint8_t)0x80);
GXTexCoord2f32(1.0f, 0.0f);
GXPosition3f32(0.0f + deltaX + GameWidth, 0.0f + deltaY + GameHeight - offsetY, posZ);
GXColor4u8(0xFF, 0xFF, 0xFF, (uint8_t)0x80);
GXTexCoord2f32(1.0f, 1.0f);
GXPosition3f32(0.0f + deltaX, 0.0f + deltaY + GameHeight - offsetY, posZ);
GXColor4u8(0xFF, 0xFF, 0xFF, (uint8_t)0x80);
GXTexCoord2f32(0.0f, 1.0f);
GXShaderCall_Maybe(0xE);
}
if (params->AlphaLevel > 1)
{
float blurAlpha = ((float)params->AlphaLevel - 1.0f) * 25.0f;
if (blurAlpha > 255.0f)
blurAlpha = 255.0f;
if (blurAlpha > 0.0f)
{
GXSetTexCopySrc(0, 0, (short)GameWidth, (short)GameHeight);
GXSetTexCopyDst(((short)GameWidth) >> 1, ((short)GameHeight) >> 1, 6, 1);
GXCopyTex(*ptr_filter01_buff, 0, 0);
GXBegin(0x80, 0, 4);
GXPosition3f32(0.25f + deltaX, 0.25f + deltaY + offsetY, posZ);
GXColor4u8(0xFF, 0xFF, 0xFF, (uint8_t)blurAlpha);
GXTexCoord2f32(0.0f, 0.0f);
GXPosition3f32(0.25f + deltaX + GameWidth, 0.25f + deltaY + offsetY, posZ);
GXColor4u8(0xFF, 0xFF, 0xFF, (uint8_t)blurAlpha);
GXTexCoord2f32(1.0f, 0.0f);
GXPosition3f32(0.25f + deltaX + GameWidth, 0.25f + deltaY + GameHeight - offsetY, posZ);
GXColor4u8(0xFF, 0xFF, 0xFF, (uint8_t)blurAlpha);
GXTexCoord2f32(1.0f, 1.0f);
GXPosition3f32(0.25f + deltaX, 0.25f + deltaY + GameHeight - offsetY, posZ);
GXColor4u8(0xFF, 0xFF, 0xFF, (uint8_t)blurAlpha);
GXTexCoord2f32(0.0f, 1.0f);
GXShaderCall_Maybe(0xE);
}
}
}
void __cdecl Filter01Render_Hook2(Filter01Params* params)
{
float GameWidth = *ptr_InternalWidth;
float GameHeight = *ptr_InternalHeight;
float AlphaLvlTable[] = { // level_tbl1 in GC debug
0.0f,
0.60f, // 0.60000002
1.5f,
2.60f, // 2.5999999
1.5f,
1.6f,
1.6f,
2.5f,
2.60f, // 2.5999999
4.5f,
6.60f // 6.5999999
};
int AlphaLevel_floor = (int)floorf(params->AlphaLevel); // TODO: should this be ceil instead?
float blurPositionOffset = AlphaLvlTable[AlphaLevel_floor];
int numBlurPasses = 4;
switch (AlphaLevel_floor)
{
case 0:
numBlurPasses = 0;
break;
case 1:
case 2:
case 3:
numBlurPasses = 1;
break;
case 4:
numBlurPasses = 2;
break;
case 5:
numBlurPasses = 3;
break;
}
// Code that was in original Filter01Render
// Seems to usually be 1/8th of 448, might change depending on ptr_InternalHeightScale / ptr_RenderHeight though
// Offset is used to fix Y coords of the blur effect, otherwise the blur ends up offset from the image for some reason
float heightScaled = *ptr_InternalHeightScale * 448.0f;
float offsetY = 448.0f * (heightScaled - *ptr_RenderHeight) / (heightScaled + heightScaled);
float deltaX = 0.0f;
float deltaY = 0.0f;
float posZ = (float)params->Distance;
for (int loopIdx = 0; loopIdx < numBlurPasses; loopIdx++)
{
// Main reason for this hook is to add the deltaX/deltaY vars below, needed for the DoF effect to work properly
// GC debug had this, but was removed in X360 port onwards for some reason
// (yet even though this was removed, the X360 devs did add the code for offsetY above to fix the blur...)
if (loopIdx == 0) {
deltaX = 0.0f - blurPositionOffset;
deltaY = 0.0f - blurPositionOffset;
}
else if (loopIdx == 1) {
deltaX = 0.0f + blurPositionOffset;
deltaY = 0.0f + blurPositionOffset;
}
else if (loopIdx == 2) {
deltaX = 0.0f + blurPositionOffset;
deltaY = 0.0f - blurPositionOffset;
}
else if (loopIdx == 3) {
deltaX = 0.0f - blurPositionOffset;
deltaY = 0.0f + blurPositionOffset;
}
posZ = posZ + 100.f;
if (posZ > 65536.0f)
posZ = 65536.0f;
GXBegin(0xA0, 0, 4); // TODO: 0xA0 (GX_TRIANGLEFAN) in PC, 0x80 (GX_QUADS) in GC - should this be changed?
GXPosition3f32(0.0f + deltaX, 0.0f + deltaY + offsetY, posZ);
GXColor4u8(0xFF, 0xFF, 0xFF, (uint8_t)0x80);
GXTexCoord2f32(0.0f, 0.0f);
GXPosition3f32(0.0f + deltaX + GameWidth, 0.0f + deltaY + offsetY, posZ);
GXColor4u8(0xFF, 0xFF, 0xFF, (uint8_t)0x80);
GXTexCoord2f32(1.0f, 0.0f);
GXPosition3f32(0.0f + deltaX + GameWidth, 0.0f + deltaY + GameHeight - offsetY, posZ);
GXColor4u8(0xFF, 0xFF, 0xFF, (uint8_t)0x80);
GXTexCoord2f32(1.0f, 1.0f);
GXPosition3f32(0.0f + deltaX, 0.0f + deltaY + GameHeight - offsetY, posZ);
GXColor4u8(0xFF, 0xFF, 0xFF, (uint8_t)0x80);
GXTexCoord2f32(0.0f, 1.0f);
GXShaderCall_Maybe(0xE);
}
}
void GetFilterPointers()
{
// GC blur fix
auto pattern = hook::pattern("E8 ? ? ? ? 03 5D ? 6A ? 53 57 E8 ? ? ? ? 0F B6 56");
ReadCall(injector::GetBranchDestination(pattern.get_first()).as_int(), GXBegin);
pattern = hook::pattern("E8 ? ? ? ? D9 45 ? 8B 75 ? 8B 7D ? D9 7D");
ReadCall(injector::GetBranchDestination(pattern.get_first()).as_int(), GXPosition3f32);
pattern = hook::pattern("E8 ? ? ? ? 8B 5D ? 8B 55 ? 83 C4 ? 6A ? 53");
ReadCall(injector::GetBranchDestination(pattern.get_first()).as_int(), GXColor4u8);
pattern = hook::pattern("E8 ? ? ? ? 8B 4D ? 51 E8 ? ? ? ? 8B 4D ? 83 C4 ? 33 CD");
ReadCall(injector::GetBranchDestination(pattern.get_first()).as_int(), GXTexCoord2f32);
pattern = hook::pattern("E8 ? ? ? ? 47 83 C4 ? 83 C6 ? 3B 3D ? ? ? ? 0F 82");
ReadCall(injector::GetBranchDestination(pattern.get_first()).as_int(), GXShaderCall_Maybe);
pattern = hook::pattern("E8 ? ? ? ? 0F B7 4E ? 0F B7 56 ? 6A ? 6A ? 51");
ReadCall(injector::GetBranchDestination(pattern.get_first()).as_int(), GXSetTexCopySrc);
pattern = hook::pattern("E8 ? ? ? ? 6A 01 6A 06 D9");
uint32_t* varPtr = pattern.count(1).get(0).get<uint32_t>(11);
ptr_InternalHeight = (float*)*varPtr;
pattern = hook::pattern("D1 E8 50 D9 AD ? ? ? ? D9 05 ? ? ? ?");
varPtr = pattern.count(1).get(0).get<uint32_t>(11);
ptr_InternalWidth = (float*)*varPtr;
pattern = hook::pattern("E8 ? ? ? ? A1 ? ? ? ? 6A 04 6A 00 50 E8");
ReadCall(injector::GetBranchDestination(pattern.get_first()).as_int(), GXSetTexCopyDst);
pattern = hook::pattern("D1 E9 51 D9 AD ? ? ? ? E8 ? ? ? ? 8B 15");
varPtr = pattern.count(1).get(0).get<uint32_t>(16);
ptr_filter01_buff = (uint32_t*)*varPtr;
pattern = hook::pattern("E8 ? ? ? ? D9 05 ? ? ? ? D9 7D ? 6A ? 0F B7 45");
ReadCall(injector::GetBranchDestination(pattern.get_first()).as_int(), GXCopyTex);
pattern = hook::pattern("83 C4 ? D9 ? ? ? ? ? D9 05 ? ? ? ? 8B ? ? ? ? ? DD");
varPtr = pattern.count(1).get(0).get<uint32_t>(11);
ptr_InternalHeightScale = (float*)*varPtr;
varPtr = pattern.count(1).get(0).get<uint32_t>(17);
ptr_RenderHeight = (int*)*varPtr;
pattern = hook::pattern("E8 ? ? ? ? 33 DB 83 C4 20 39 1D ? ? ? ? 0F 86 ? ? ? ? A1 ? ? ? ? 56");
ptr_Filter0aGXDraw_call1 = pattern.count(1).get(0).get<uint32_t>(0);
pattern = hook::pattern("E8 ? ? ? ? 46 83 C4 20 3B F7 0F 8C ? ? ? ? A1 ? ? ? ? 43 3B 1D ? ? ? ? 0F 82 ? ? ? ? 5F");
ptr_Filter0aGXDraw_call2 = pattern.count(1).get(0).get<uint32_t>(0);
pattern = hook::pattern("E8 ? ? ? ? 6A 01 6A 03 6A 01 E8 ? ? ? ? 6A 01 E8 ? ? ? ? 8B 4D FC 83 C4 30 33 CD 5B E8 ? ? ? ? 8B E5 5D C3 90");
ptr_Filter0aGXDraw_call3 = pattern.count(1).get(0).get<uint32_t>(0);
pattern = hook::pattern("5F 5E 6A 01 6A 01 E8 ? ? ? ? 83 C4 ? E8");
ptr_Filter0aDrawBuffer_GetEFBCall = pattern.count(1).get(0).get<uint8_t>(3);
pattern = hook::pattern("56 6A 00 50 C7 05 ? ? ? ? 1F 00 00 00");
varPtr = pattern.count(1).get(0).get<uint32_t>(6);
ptr_filter0a_shader_num = (int32_t*)*varPtr;
}
void Init_FilterXXFixes()
{
GetFilterPointers();
if (cfg.bEnableGCBlur)
{
// Hook Filter01Render, first block (loop that's ran 4 times + 0.25 pass)
auto pattern = hook::pattern("3C 01 0F 85 ? ? ? ? D9 85");
uint8_t* filter01_end = pattern.count(1).get(0).get<uint8_t>(4);
filter01_end += sizeof(int32_t) + *(int32_t*)filter01_end;
injector::WriteMemory(pattern.get_first(8), uint8_t(0x56), true); // PUSH ESI (esi = Filter01Params*)
injector::MakeCALL(pattern.get_first(9), Filter01Render_Hook1, true);
injector::WriteMemory(pattern.get_first(14), uint8_t(0x58), true); // POP EAX (fixes esp)
injector::MakeJMP(pattern.get_first(15), filter01_end, true); // JMP over code that was reimplemented
// Hook Filter01Render second block (loop ran N times depending on AlphaLevel)
pattern = hook::pattern("D9 46 ? B9 04 00 00 00 D9");
injector::WriteMemory(pattern.get_first(0), uint8_t(0x56), true); // PUSH ESI (esi = Filter01Params*)
injector::MakeCALL(pattern.get_first(1), Filter01Render_Hook2, true);
injector::WriteMemory(pattern.get_first(6), uint8_t(0x58), true); // POP EAX (fixes esp)
injector::MakeJMP(pattern.get_first(7), filter01_end, true); // JMP over code that was reimplemented
Logging::Log() << __FUNCTION__ << " -> EnableGCBlur applied";
}
if (cfg.bEnableGCScopeBlur)
{
// Short-circuit Filter0aGXDraw to skip over the GXPosition etc things that we reimplement ourselves
auto pattern = hook::pattern("D9 45 A4 DC 15 ? ? ? ? DF E0 F6 C4 41 75 ? DC 1D ? ? ? ? DF E0 F6 C4 05 0F 8B ? ? ? ? EB");
injector::WriteMemory(pattern.get_first(27), uint16_t(0xE990), true);
// Change GetEFB(1,1) to GetEFB(4,4)
injector::WriteMemory(ptr_Filter0aDrawBuffer_GetEFBCall, uint8_t(0x4), true);
injector::WriteMemory(ptr_Filter0aDrawBuffer_GetEFBCall + 2, uint8_t(0x4), true);
ReadCall(ptr_Filter0aGXDraw_call1, Filter0aGXDraw_Orig);
InjectHook(ptr_Filter0aGXDraw_call1, Filter0aGXDraw_Hook);
InjectHook(ptr_Filter0aGXDraw_call2, Filter0aGXDraw_Hook);
InjectHook(ptr_Filter0aGXDraw_call3, Filter0aGXDraw_Hook);
Logging::Log() << __FUNCTION__ << " -> EnableGCScopeBlur applied";
}
} | 38.263889 | 217 | 0.708469 | [
"render",
"3d"
] |
988d4c7ef2271eb5e9d28646d7db056aa2c7f535 | 1,681 | hpp | C++ | include/core/Array.hpp | lzubiaur/godot-cpp | 2a4e82b77ea69a3c6dc1ad8117f0019a5adf5cef | [
"MIT"
] | 2 | 2021-11-08T02:44:44.000Z | 2021-11-08T09:41:06.000Z | include/core/Array.hpp | lzubiaur/godot-cpp | 2a4e82b77ea69a3c6dc1ad8117f0019a5adf5cef | [
"MIT"
] | null | null | null | include/core/Array.hpp | lzubiaur/godot-cpp | 2a4e82b77ea69a3c6dc1ad8117f0019a5adf5cef | [
"MIT"
] | null | null | null | #ifndef ARRAY_H
#define ARRAY_H
#include <gdnative/array.h>
#include "Defs.hpp"
#include "String.hpp"
namespace godot {
class Variant;
class PoolByteArray;
class PoolIntArray;
class PoolRealArray;
class PoolStringArray;
class PoolVector2Array;
class PoolVector3Array;
class PoolColorArray;
class Object;
class Array {
godot_array _godot_array;
public:
Array();
Array(const Array &other);
Array &operator=(const Array &other);
Array(const PoolByteArray &a);
Array(const PoolIntArray &a);
Array(const PoolRealArray &a);
Array(const PoolStringArray &a);
Array(const PoolVector2Array &a);
Array(const PoolVector3Array &a);
Array(const PoolColorArray &a);
template <class... Args>
static Array make(Args... args) {
return helpers::append_all(Array(), args...);
}
Variant &operator[](const int idx);
Variant operator[](const int idx) const;
void append(const Variant &v);
void clear();
int count(const Variant &v);
bool empty() const;
void erase(const Variant &v);
Variant front() const;
Variant back() const;
int find(const Variant &what, const int from = 0);
int find_last(const Variant &what);
bool has(const Variant &what) const;
uint32_t hash() const;
void insert(const int pos, const Variant &value);
void invert();
bool is_shared() const;
Variant pop_back();
Variant pop_front();
void push_back(const Variant &v);
void push_front(const Variant &v);
void remove(const int idx);
int size() const;
void resize(const int size);
int rfind(const Variant &what, const int from = -1);
void sort();
void sort_custom(Object *obj, const String &func);
~Array();
};
} // namespace godot
#endif // ARRAY_H
| 15.71028 | 53 | 0.711481 | [
"object"
] |
988dfbf4aaa3139c3dad53f7a8f802946c3727da | 6,380 | cpp | C++ | src/realRosClass.cpp | CVH95/Canyonero_ROS_controller | 8fbe3dcb79086ac9c753b664e75fabc8f53b27a5 | [
"MIT"
] | null | null | null | src/realRosClass.cpp | CVH95/Canyonero_ROS_controller | 8fbe3dcb79086ac9c753b664e75fabc8f53b27a5 | [
"MIT"
] | null | null | null | src/realRosClass.cpp | CVH95/Canyonero_ROS_controller | 8fbe3dcb79086ac9c753b664e75fabc8f53b27a5 | [
"MIT"
] | null | null | null | /* CANYONERO */
// ROS Controller
// MSG generation to communicate with GPIOs
#include "realRosClass.h"
// Costructor
realRosClass::realRosClass()
{
cout << "CANYONERO" << endl << endl;
cout << "Creating a new node..." << endl << endl;
}
// Destructor
realRosClass::~realRosClass()
{
ROS_INFO("ROS node was terminated");
ros::shutdown();
}
void realRosClass::start_control_node()
{
int _argc=0;
char** _argv = NULL;
ros::init(_argc, _argv, controller_name);
if(!ros::master::check())
{
ROS_ERROR("ros::master::check() did not pass!");
}
else
{
const string _host = ros::master::getHost();
const string _uri = ros::master::getURI();
ROS_INFO("ROS Master Hostname: %s.", _host.c_str());
ROS_INFO("ROS Master URI: %s/ \n", _uri.c_str());
}
ros::NodeHandle node("~");
ROS_INFO("ROS node started under the name %s. \n", controller_name.c_str());
// Start publisher:
pub_direction = node.advertise<std_msgs::Int32>("/gpio_driver/joint_direction", 1);
rate = new ros::Rate(17*4);
}
void realRosClass::start_streaming_node()
{
int _argc=0;
char** _argv = NULL;
ros::init(_argc, _argv, stream_name);
if(!ros::master::check())
{
ROS_ERROR("ros::master::check() did not pass!");
}
else
{
const string _host = ros::master::getHost();
const string _uri = ros::master::getURI();
ROS_INFO("ROS Master Hostname: %s.", _host.c_str());
ROS_INFO("ROS Master URI: %s/ \n", _uri.c_str());
}
ros::NodeHandle node("~");
ROS_INFO("ROS node started under the name %s. \n", stream_name.c_str());
//cv::namedWindow("Canyonero Onboard View", CV_WINDOW_AUTOSIZE);
//cv::startWindowThread();
image_transport::ImageTransport it(node);
//Start subscriber:
image_transport::Subscriber img_subscriber = it.subscribe("/camera_driver/image_raw", 1, &realRosClass::streamCallback, this);
state_subscriber = node.subscribe("/gpio_driver/state", 1, &realRosClass::stateCallback, this);
rosSpin();
//cv::destroyWindow("Canyonero Onboard View");
}
// Receive video stream (image transport)
void realRosClass::streamCallback(const sensor_msgs::ImageConstPtr& img)
{
//ROS_INFO("Entered callback");
try
{
cv_bridge::CvImagePtr cv_ptr = cv_bridge::toCvCopy(img, enc::BGR8);
//cv::imshow("Canyonero Onboard View", cv_bridge::toCvShare(img, "bgr8")->image);
cv::Mat fframe = cv_ptr->image;
if(!fframe.empty())
{
//ROS_INFO("Received frame data.");
cv::imshow("Canyonero Onboard View", fframe);
cv::waitKey(1);
}
else
{
ROS_ERROR("Did not receive any frame data.");
}
}
catch(cv_bridge::Exception& e)
{
ROS_ERROR("Could not convert from '%s' to 'bgr8'.", img->encoding.c_str());
}
}
// Receive video stream
void realRosClass::stateCallback(const std_msgs::String::ConstPtr& msg)
{
state = msg->data;
ROS_INFO("%s", state.c_str());
}
// Show video stream
void realRosClass::show_streaming()
{
cv::imshow("Canyonero Onboard View", frame);
cv::waitKey(30);
}
string realRosClass::get_state()
{
string s = state;
return s;
}
// Publish the new direction
void realRosClass::send_command(int direc)
{
std_msgs::Int32 d;
d.data = direc;
pub_direction.publish(d);
}
// ROS Keyboard Teleop
void realRosClass::keyboard_control()
{
//start_ncurses();
//wclear(win);
int cht = 0;
running = true;
//string _st = get_state();
//info_control(_st);
cht = getch();
switch(cht)
{
case 'w':
_Direction = 8;
//state = "FWRD";
running = true;
break;
case 's':
_Direction = 2;
//state = "BACK";
running = true;
break;
case 'd':
_Direction = 6;
//state = "RGHT";
running = true;
break;
case 'a':
_Direction = 4;
//state = "LEFT";
running = true;
break;
case 'b':
_Direction = 0;
//state = "STOP";
running = true;
break;
case 'x':
_Direction = 9;
running = true;
break;
case 'z':
_Direction = 7;
running = true;
break;
case 'm':
_Direction = 11;
break;
case 'i':
_Direction = 21;
running = true;
break;
case 'k':
_Direction = 22;
running = true;
break;
case 'l':
_Direction = 23;
running = true;
break;
case 'j':
_Direction = 24;
running = true;
break;
case 't':
_Direction = 31;
running = true;
break;
case 'y':
_Direction = 32;
running = true;
break;
case 'p':
_Direction = 5;
//state = "STOP";
move(15, 0);
printw("Shutting down Canyonero");
running = false;
break;
}
// Publish command
send_command(_Direction);
// Update state on ncurses window
//refresh();
}
// Handling ros::spin()
void realRosClass::rosSpin()
{
wrefresh(win);
ros::spin();
}
// Handling ros::spinOnce()
void realRosClass::rosSpinOnce()
{
//redrawwin(win);
ros::spinOnce();
bool rateMet = rate->sleep();
//wclear(win);
//string _s = get_state();
//info_control(_s);
if(!rateMet)
{
//ROS_ERROR("Sleep rate not met!");
rate_error++;
}
}
// Handling creation of ncurses object
void realRosClass::start_ncurses()
{
// Start ncurses
initscr();
// No echo (not printing keys pressed)
noecho();
// One key at a time
cbreak();
// Create window
win = newwin(25, 50, 0, 0);
}
// Handling ending of ncurses object
void realRosClass::end_ncurses()
{
endwin();
cout << "Shutting down Canyonero's controller." << endl;
cout << "Sleep rate errors: " << rate_error << endl;
}
// Display message in ncurses window
void realRosClass::info_control(string ss)
{
wclear(win);
move(0,0);
printw("... Runing Keyboard Teleoperation ...");
move(2,0);
printw("MOTION:");
move(4,0);
printw(" >> Forward: w");
move(5,0);
printw(" >> Backward: s");
move(6,0);
printw(" >> Turn right (on spot): d");
move(7,0);
printw(" >> Turn left (on spot): a");
move(8,0);
printw(" >> Stop: b");
move(9,0);
printw(" >> Increase speed: x");
move(10,0);
printw(" >> Reduce speed: z");
move(11,0);
printw(" >> Switch OFF Canyonero: p");
move(13,0);
printw("VISION PLATFORM:");
move(15,0);
printw(" >> Unlock platform: t");
move(16,0);
printw(" >> Lock platform: y");
move(17,0);
printw(" >> Rotate up: i");
move(18,0);
printw(" >> Rotate Down: k");
move(19,0);
printw(" >> Rotate right: l");
move(20,0);
printw(" >> Rotate left:j");
move(21,0);
printw(" >> Lights: m");
} | 18.931751 | 130 | 0.620846 | [
"object"
] |
9892013dc33af1af47e9ae709ba173a08b2b7261 | 17,539 | hpp | C++ | interface/coroutine/channel.hpp | lanza/coroutine | c90caab988f96997f5bc1bd6f1958b80524fa14a | [
"CC-BY-4.0"
] | 368 | 2018-11-22T22:57:04.000Z | 2022-03-31T04:04:54.000Z | interface/coroutine/channel.hpp | lanza/coroutine | c90caab988f96997f5bc1bd6f1958b80524fa14a | [
"CC-BY-4.0"
] | 35 | 2018-11-09T04:38:20.000Z | 2022-01-27T01:10:02.000Z | interface/coroutine/channel.hpp | lanza/coroutine | c90caab988f96997f5bc1bd6f1958b80524fa14a | [
"CC-BY-4.0"
] | 29 | 2018-12-26T14:03:47.000Z | 2022-02-11T17:36:55.000Z | /**
* @file coroutine/channel.hpp
* @author github.com/luncliff (luncliff@gmail.com)
* @copyright CC BY 4.0
*
* @brief C++ Coroutines based channel. It's a simplified form of the channel in The Go Language
*/
#pragma once
#ifndef LUNCLIFF_COROUTINE_CHANNEL_HPP
#define LUNCLIFF_COROUTINE_CHANNEL_HPP
#include <mutex>
#include <tuple>
#if __has_include(<coroutine/frame.h>) && !defined(USE_EXPERIMENTAL_COROUTINE)
#include <coroutine/frame.h>
namespace coro {
using std::coroutine_handle;
using std::suspend_always;
using std::suspend_never;
#elif __has_include(<experimental/coroutine>)
#include <experimental/coroutine>
namespace coro {
using std::experimental::coroutine_handle;
using std::experimental::suspend_always;
using std::experimental::suspend_never;
#else
#error "requires header <experimental/coroutine> or <coroutine/frame.h>"
#endif
/**
* @defgroup channel
* @note
* The implementation of channel heavily rely on `friend` relationship.
* The design may make the template code ugly, but is necessary
* because of 2 behaviors.
*
* - `channel` is a synchronizes 2 awaitable types,
* `channel_reader` and `channel_writer`.
* - Those reader/writer exchanges their information
* before their `resume` of each other.
*
* If user code can become mess because of such relationship,
* it is strongly recommended to hide `channel` internally and open their own interfaces.
*
*/
/**
* @brief Lockable without lock operation
* @note `channel` uses lockable whenever read/write is requested.
* If its object is used without race condition, such lock operation can be skipped.
* Use this **bypass** lockable for such cases.
*/
struct bypass_mutex final {
constexpr bool try_lock() noexcept {
return true;
}
/** @brief Do nothing since this is 'bypass' lock */
constexpr void lock() noexcept {
}
/** @brief Do nothing since it didn't locked something */
constexpr void unlock() noexcept {
}
};
namespace internal {
/**
* @brief Returns a non-null address that leads access violation
* @note Notice that `reinterpret_cast` is not constexpr for some compiler.
* @return void* non-null address
* @ingroup channel
*/
static void* poison() noexcept(false) {
return reinterpret_cast<void*>(0xFADE'038C'BCFA'9E64);
}
/**
* @brief Linked list without allocation
* @tparam T Type of the node. Its member must have `next` pointer
*/
template <typename T>
class list {
T* head{};
T* tail{};
public:
bool is_empty() const noexcept(false) {
return head == nullptr;
}
void push(T* node) noexcept(false) {
if (tail) {
tail->next = node;
tail = node;
} else
head = tail = node;
}
/**
* @return T* The return can be `nullptr`
*/
auto pop() noexcept(false) -> T* {
T* node = head;
if (head == tail) // empty or 1
head = tail = nullptr;
else // 2 or more
head = head->next;
return node;
}
};
} // namespace internal
template <typename T, typename M = bypass_mutex>
class channel; // by default, channel doesn't care about the race condition
template <typename T, typename M>
class channel_reader;
template <typename T, typename M>
class channel_writer;
template <typename T, typename M>
class channel_peeker;
/**
* @brief Awaitable type for `channel`'s read operation.
* It moves the value from writer coroutine's frame to reader coroutine's frame.
*
* @code
* void read_from(channel<int>& ch, int& ref, bool ok = false) {
* tie(ref, ok) = co_await ch.read();
* if(ok == false)
* ; // channel is under destruction !!!
* }
* @endcode
*
* @tparam T type of the element
* @tparam M mutex for the channel
* @see channel_writer
* @ingroup channel
*/
template <typename T, typename M>
class channel_reader {
public:
using value_type = T;
using pointer = T*;
using reference = T&;
using channel_type = channel<T, M>;
private:
using reader_list = typename channel_type::reader_list;
using writer = typename channel_type::writer;
using writer_list = typename channel_type::writer_list;
friend channel_type;
friend writer;
friend reader_list;
protected:
mutable pointer ptr; /// Address of value
mutable void* frame; /// Resumeable Handle
union {
channel_reader* next = nullptr; /// Next reader in channel
channel_type* chan; /// Channel to push this reader
};
protected:
explicit channel_reader(channel_type& ch) noexcept(false)
: ptr{}, frame{nullptr}, chan{std::addressof(ch)} {
}
channel_reader(const channel_reader&) noexcept = delete;
channel_reader& operator=(const channel_reader&) noexcept = delete;
channel_reader(channel_reader&&) noexcept = delete;
channel_reader& operator=(channel_reader&&) noexcept = delete;
public:
~channel_reader() noexcept = default;
public:
/**
* @brief Lock the channel and find available `channel_writer`
*
* @return true Matched with `channel_writer`
* @return false There was no available `channel_writer`.
* The channel will be **lock**ed for this case.
*/
bool await_ready() const noexcept(false) {
chan->mtx.lock();
if (chan->writer_list::is_empty())
// await_suspend will unlock in the case
return false;
writer* w = chan->writer_list::pop();
// exchange address & resumeable_handle
std::swap(this->ptr, w->ptr);
std::swap(this->frame, w->frame);
chan->mtx.unlock();
return true;
}
/**
* @brief Push to the channel and wait for `channel_writer`.
* @note The channel will be **unlock**ed after return.
* @param coro Remember current coroutine's handle to resume later
* @see await_ready
*/
void await_suspend(coroutine_handle<void> coro) noexcept(false) {
// notice that next & chan are sharing memory
channel_type& ch = *(this->chan);
// remember handle before push/unlock
this->frame = coro.address();
this->next = nullptr;
// push to channel
ch.reader_list::push(this);
ch.mtx.unlock();
}
/**
* @brief Returns value from writer coroutine, and `bool` indicator for the associtated channel's destruction
*
* @return tuple<value_type, bool>
*/
auto await_resume() noexcept(false) -> std::tuple<value_type, bool> {
auto t = std::make_tuple(value_type{}, false);
// frame holds poision if the channel is under destruction
if (this->frame == internal::poison())
return t;
// the resume operation can destroy the other coroutine
// store before resume
std::get<0>(t) = std::move(*ptr);
if (auto coro = coroutine_handle<void>::from_address(frame))
coro.resume();
std::get<1>(t) = true;
return t;
}
};
/**
* @brief Awaitable for `channel`'s write operation.
* It exposes a reference to the value for `channel_reader`.
*
* @code
* void write_to(channel<int>& ch, int value) {
* bool ok = co_await ch.write(value);
* if(ok == false)
* ; // channel is under destruction !!!
* }
* @endcode
*
* @tparam T type of the element
* @tparam M mutex for the channel
* @see channel_reader
* @ingroup channel
*/
template <typename T, typename M>
class channel_writer {
public:
using value_type = T;
using pointer = T*;
using reference = T&;
using channel_type = channel<T, M>;
private:
using reader = typename channel_type::reader;
using reader_list = typename channel_type::reader_list;
using writer_list = typename channel_type::writer_list;
using peeker = typename channel_type::peeker;
friend channel_type;
friend reader;
friend writer_list;
friend peeker; // for `peek()` implementation
private:
mutable pointer ptr; /// Address of value
mutable void* frame; /// Resumeable Handle
union {
channel_writer* next = nullptr; /// Next writer in channel
channel_type* chan; /// Channel to push this writer
};
private:
explicit channel_writer(channel_type& ch, pointer pv) noexcept(false)
: ptr{pv}, frame{nullptr}, chan{std::addressof(ch)} {
}
channel_writer(const channel_writer&) noexcept = delete;
channel_writer& operator=(const channel_writer&) noexcept = delete;
channel_writer(channel_writer&&) noexcept = delete;
channel_writer& operator=(channel_writer&&) noexcept = delete;
public:
~channel_writer() noexcept = default;
public:
/**
* @brief Lock the channel and find available `channel_reader`
*
* @return true Matched with `channel_reader`
* @return false There was no available `channel_reader`.
* The channel will be **lock**ed for this case.
*/
bool await_ready() const noexcept(false) {
chan->mtx.lock();
if (chan->reader_list::is_empty())
// await_suspend will unlock in the case
return false;
reader* r = chan->reader_list::pop();
// exchange address & resumeable_handle
std::swap(this->ptr, r->ptr);
std::swap(this->frame, r->frame);
chan->mtx.unlock();
return true;
}
/**
* @brief Push to the channel and wait for `channel_reader`.
* @note The channel will be **unlock**ed after return.
* @param coro Remember current coroutine's handle to resume later
* @see await_ready
*/
void await_suspend(coroutine_handle<void> coro) noexcept(false) {
// notice that next & chan are sharing memory
channel_type& ch = *(this->chan);
this->frame = coro.address(); // remember handle before push/unlock
this->next = nullptr; // clear to prevent confusing
ch.writer_list::push(this); // push to channel
ch.mtx.unlock();
}
/**
* @brief Returns `bool` indicator for the associtated channel's destruction
*
* @return true successfully sent the value to `channel_reader`
* @return false The `channel` is under destruction
*/
bool await_resume() noexcept(false) {
// frame holds poision if the channel is under destruction
if (this->frame == internal::poison())
return false;
if (auto coro = coroutine_handle<void>::from_address(frame))
coro.resume();
return true;
}
};
/**
* @brief C++ Coroutines based channel
* @note It works as synchronizer of `channel_writer`/`channel_reader`.
* The parameter mutex must meet the requirement of the synchronization.
*
* @tparam T type of the element
* @tparam M Type of the mutex(lockable) for its member
* @ingroup channel
*/
template <typename T, typename M>
class channel final : internal::list<channel_reader<T, M>>,
internal::list<channel_writer<T, M>> {
static_assert(std::is_reference<T>::value == false,
"reference type can't be channel's value_type.");
public:
using value_type = T;
using pointer = value_type*;
using reference = value_type&;
using mutex_type = M;
private:
using reader = channel_reader<value_type, mutex_type>;
using reader_list = internal::list<reader>;
using writer = channel_writer<value_type, mutex_type>;
using writer_list = internal::list<writer>;
using peeker = channel_peeker<value_type, mutex_type>;
friend reader;
friend writer;
friend peeker; // for `peek()` implementation
private:
mutex_type mtx{};
private:
channel(const channel&) noexcept(false) = delete;
channel(channel&&) noexcept(false) = delete;
channel& operator=(const channel&) noexcept(false) = delete;
channel& operator=(channel&&) noexcept(false) = delete;
public:
/**
* @brief initialized 2 linked list and given mutex
*/
channel() noexcept(false) : reader_list{}, writer_list{}, mtx{} {
}
/**
* @brief Resume all attached coroutine read/write operations
* @note Channel can't provide exception guarantee
* since the destruction contains coroutines' resume
*
* If the channel is raced hardly, some coroutines can be
* enqueued into list just after this destructor unlocks mutex.
*
* Unfortunately, this can't be detected at once since
* we have 2 list (readers/writers) in the channel.
*
* Current implementation allows checking repeatedly to reduce the
* probability of such interleaving.
* **Modify the repeat count in the code** if the situation occurs.
*/
~channel() noexcept(false) {
void* closing = internal::poison();
writer_list& writers = *this;
reader_list& readers = *this;
// even 5'000+ can be unsafe for hazard usage ...
size_t repeat = 1;
do {
std::unique_lock lck{mtx};
while (writers.is_empty() == false) {
writer* w = writers.pop();
auto coro = coroutine_handle<void>::from_address(w->frame);
w->frame = closing;
coro.resume();
}
while (readers.is_empty() == false) {
reader* r = readers.pop();
auto coro = coroutine_handle<void>::from_address(r->frame);
r->frame = closing;
coro.resume();
}
} while (repeat--);
}
public:
/**
* @brief construct a new writer which references this channel
*
* @param ref `T&` which holds a value to be `move`d to reader.
* @return channel_writer
*/
decltype(auto) write(reference ref) noexcept(false) {
return channel_writer{*this, std::addressof(ref)};
}
/**
* @brief construct a new reader which references this channel
*
* @return channel_reader
*/
decltype(auto) read() noexcept(false) {
return channel_reader{*this};
}
};
/**
* @brief Extension of `channel_reader` for subroutines
*
* @tparam T type of the element
* @tparam M mutex for the channel
* @see channel_reader
* @ingroup channel
*/
template <typename T, typename M>
class channel_peeker final : protected channel_reader<T, M> {
using channel_type = channel<T, M>;
using writer = typename channel_type::writer;
using writer_list = typename channel_type::writer_list;
private:
channel_peeker(const channel_peeker&) noexcept(false) = delete;
channel_peeker(channel_peeker&&) noexcept(false) = delete;
channel_peeker& operator=(const channel_peeker&) noexcept(false) = delete;
channel_peeker& operator=(channel_peeker&&) noexcept(false) = delete;
public:
explicit channel_peeker(channel_type& ch) noexcept(false)
: channel_reader<T, M>{ch} {
}
~channel_peeker() noexcept = default;
public:
/**
* @brief Since there is no suspension for the `peeker`,
* the implementation will use scoped locking
*/
void peek() const noexcept(false) {
std::unique_lock lck{this->chan->mtx};
if (this->chan->writer_list::is_empty() == false) {
writer* w = this->chan->writer_list::pop();
std::swap(this->ptr, w->ptr);
std::swap(this->frame, w->frame);
}
}
/**
* @brief Move a value from matches `writer` to designated storage. After then, resume the `writer` coroutine.
* @note Unless the caller has invoked `peek`, nothing will happen.
*
* @code
* bool peek_channel(channel<string>& ch, string& out){
* peeker p{ch};
* p.peek();
* return p.acquire(out);
* }
* @endcode
*
* @param storage memory object to store the value from `writer`
* @return true Acquired the value
* @return false No `writer` found or `peek` is not invoked
* @see peek
*/
bool acquire(T& storage) noexcept(false) {
// if there was a writer, take its value
if (this->ptr == nullptr)
return false;
storage = std::move(*this->ptr);
// resume writer coroutine
if (auto coro = coroutine_handle<void>::from_address(this->frame))
coro.resume();
return true;
}
};
/**
* @note If the channel is readable, acquire the value and invoke the function
*
* @see channel_peeker
* @ingroup channel
*/
template <typename T, typename M, typename Fn>
void select(channel<T, M>& ch, Fn&& fn) noexcept(false) {
static_assert(sizeof(channel_reader<T, M>) == sizeof(channel_peeker<T, M>));
channel_peeker p{ch}; // peeker will move element
T storage{}; // into the call stack
p.peek(); // the channel has waiting writer?
if (p.acquire(storage)) // acquire + resume writer
fn(storage); // invoke the function
}
/**
* @note For each pair, peeks a channel and invoke the function with the value if the peek was successful.
*
* @ingroup channel
* @see test/channel_select_type.cpp
*/
template <typename... Args, typename Ch, typename Fn>
void select(Ch& ch, Fn&& fn, Args&&... args) noexcept(false) {
using namespace std;
select(ch, forward<Fn&&>(fn)); // evaluate
return select(forward<Args&&>(args)...); // try next pair
}
} // namespace coro
#endif // LUNCLIFF_COROUTINE_CHANNEL_HPP
| 31.773551 | 114 | 0.634244 | [
"object"
] |
98956b2411d075211fdefe58623594efd7cd6f03 | 2,887 | cpp | C++ | src/main.cpp | pc2/ConvFPGA | 7fea531cd4e2f7f820513007a1cdd28d94d37b17 | [
"MIT"
] | null | null | null | src/main.cpp | pc2/ConvFPGA | 7fea531cd4e2f7f820513007a1cdd28d94d37b17 | [
"MIT"
] | null | null | null | src/main.cpp | pc2/ConvFPGA | 7fea531cd4e2f7f820513007a1cdd28d94d37b17 | [
"MIT"
] | 2 | 2022-03-30T20:09:47.000Z | 2022-03-30T20:15:09.000Z | // Arjun Ramaswami
#include <iostream>
#include "helper.hpp"
#include "fft_conv3D.hpp"
extern "C"{
#include "convfpga/convfpga.h"
}
using namespace std;
int main(int argc, char* argv[]){
CONFIG conv_config;
parse_args(argc, argv, conv_config);
print_config(conv_config);
if(conv_config.cpuonly){
#ifdef USE_FFTW
cpu_t cpu_timing = {0.0, 0.0, false};
cpu_timing = fft_conv3D_cpu(conv_config);
if(cpu_timing.valid == false){
cout << "Error in CPU Conv3D Implementation\n";
return EXIT_FAILURE;
}
disp_results(conv_config, cpu_timing);
return EXIT_SUCCESS;
#else
cerr << "FFTW not found" << endl;
return EXIT_FAILURE;
#endif
}
const char* platform;
if(conv_config.emulate){
platform = "Intel(R) FPGA Emulation Platform for OpenCL(TM)";
}
else{
platform = "Intel(R) FPGA SDK for OpenCL(TM)";
}
int isInit = fpga_initialize(platform, conv_config.path.c_str(), conv_config.usesvm);
if(isInit != 0){
cerr << "FPGA initialization error\n";
return EXIT_FAILURE;
}
const unsigned num = conv_config.num;
const unsigned batch = conv_config.batch;
const unsigned numpts = num * num * num;
const size_t filter_inp_sz = sizeof(float2) * numpts;
const size_t sig_sz = sizeof(float2) * numpts * batch;
float2 *filter = (float2*)fpgaf_complex_malloc(filter_inp_sz);
float2 *sig = (float2*)fpgaf_complex_malloc(sig_sz);
float2 *out = (float2*)fpgaf_complex_malloc(sig_sz);
fpga_t runtime[conv_config.iter];
try{
create_data(filter, numpts, 1);
create_data(sig, numpts, batch);
for(unsigned i = 0; i < conv_config.iter; i++){
cout << endl << i << ": Calculating Conv3D" << endl;
if(conv_config.usesvm && conv_config.batch > 1)
runtime[i] = fpgaf_conv3D_svm_batch(conv_config.num, sig, filter, out, batch);
else if(conv_config.usesvm && conv_config.batch == 1)
runtime[i] = fpgaf_conv3D_svm(conv_config.num, sig, filter, out);
else if(!conv_config.usesvm && conv_config.batch > 1)
throw "Non-SVM Batch not implemented for Convolution 3D";
else
runtime[i] = fpgaf_conv3D(conv_config.num, sig, filter, out);
if(runtime[i].valid == false){ throw "FPGA execution found invalid";}
if(!conv_config.noverify){
if(!fft_conv3D_cpu_verify(conv_config, sig, filter, out)){
char excp[80];
snprintf(excp, 80, "Iter %u: FPGA result incorrect in comparison to CPU\n", i);
throw runtime_error(excp);
}
}
}
}
catch(const char* msg){
cerr << msg << endl;
fpga_final();
free(sig);
free(filter);
free(out);
return EXIT_FAILURE;
}
// destroy fpga state
fpga_final();
// Verify convolution with library
disp_results(conv_config, runtime);
free(sig);
free(filter);
free(out);
return EXIT_SUCCESS;
} | 26.981308 | 89 | 0.656044 | [
"3d"
] |
9896e1b2aa19dc12ebb67b095039115da12de96e | 79,724 | cpp | C++ | GCG_Source.build/module.django.core.checks.templates.cpp | Pckool/GCG | cee786d04ea30f3995e910bca82635f442b2a6a8 | [
"MIT"
] | null | null | null | GCG_Source.build/module.django.core.checks.templates.cpp | Pckool/GCG | cee786d04ea30f3995e910bca82635f442b2a6a8 | [
"MIT"
] | null | null | null | GCG_Source.build/module.django.core.checks.templates.cpp | Pckool/GCG | cee786d04ea30f3995e910bca82635f442b2a6a8 | [
"MIT"
] | null | null | null | /* Generated code for Python source for module 'django.core.checks.templates'
* created by Nuitka version 0.5.28.2
*
* This code is in part copyright 2017 Kay Hayen.
*
* 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 "nuitka/prelude.h"
#include "__helpers.h"
/* The _module_django$core$checks$templates is a Python object pointer of module type. */
/* Note: For full compatibility with CPython, every module variable access
* needs to go through it except for cases where the module cannot possibly
* have changed in the mean time.
*/
PyObject *module_django$core$checks$templates;
PyDictObject *moduledict_django$core$checks$templates;
/* The module constants used, if any. */
extern PyObject *const_str_plain_ModuleSpec;
extern PyObject *const_str_plain___spec__;
extern PyObject *const_str_plain___package__;
extern PyObject *const_str_plain_TEMPLATES;
extern PyObject *const_str_plain_unicode_literals;
extern PyObject *const_str_plain_E001;
extern PyObject *const_str_plain___name__;
static PyObject *const_tuple_str_plain_string_if_invalid_str_empty_tuple;
extern PyObject *const_tuple_str_plain_APP_DIRS_tuple;
static PyObject *const_str_plain_check_string_if_invalid_is_string;
extern PyObject *const_str_plain_conf;
extern PyObject *const_int_pos_1;
extern PyObject *const_str_plain_APP_DIRS;
extern PyObject *const_str_plain_Tags;
extern PyObject *const_dict_empty;
static PyObject *const_dict_0766a052c7dd7e7e07d999dad0c36dee;
static PyObject *const_str_digest_949ca64c12f36b488e23e58498115567;
extern PyObject *const_str_plain___file__;
extern PyObject *const_str_plain_copy;
static PyObject *const_str_digest_0c4877586912d53c003980591b4d9eba;
extern PyObject *const_tuple_str_plain_Error_str_plain_Tags_str_plain_register_tuple;
extern PyObject *const_str_plain_OPTIONS;
extern PyObject *const_int_0;
extern PyObject *const_str_plain_string_types;
extern PyObject *const_str_digest_d7803f988ae9afc17e4a4fd2b91f50ce;
extern PyObject *const_str_plain_six;
extern PyObject *const_str_plain_Error;
extern PyObject *const_str_plain_templates;
static PyObject *const_tuple_str_digest_ca69c7a5bc6e5fe2f5e465fece629e50_tuple;
extern PyObject *const_str_digest_e2cff0983efd969a5767cadcc9e9f0e8;
static PyObject *const_str_plain_check_setting_app_dirs_loaders;
extern PyObject *const_str_plain_loaders;
extern PyObject *const_str_plain_msg;
extern PyObject *const_str_plain_string_if_invalid;
extern PyObject *const_tuple_str_plain_settings_tuple;
extern PyObject *const_str_plain_register;
static PyObject *const_str_digest_ca69c7a5bc6e5fe2f5e465fece629e50;
static PyObject *const_tuple_8d321bdc3c0c0aaaa8846c9967b2bf61_tuple;
extern PyObject *const_str_digest_fa133991df808b3571d5fc7f23523a98;
extern PyObject *const_str_plain_id;
static PyObject *const_str_plain_E002;
static PyObject *const_str_digest_1a8295ac4bdf9c9b351c34d87a52895c;
extern PyObject *const_tuple_str_plain_six_tuple;
extern PyObject *const_str_plain_app_configs;
extern PyObject *const_tuple_empty;
extern PyObject *const_str_plain_kwargs;
extern PyObject *const_str_plain_get;
extern PyObject *const_str_digest_467c9722f19d9d40d148689532cdc0b1;
static PyObject *const_tuple_2c7dcbbe0c3a993e658a6fce71318b1e_tuple;
static PyObject *const_dict_75c1c3feca8e358eb7ad1551f99dbb12;
extern PyObject *const_str_plain_append;
extern PyObject *const_str_plain_settings;
extern PyObject *const_str_plain___loader__;
extern PyObject *const_str_plain_format;
extern PyObject *const_str_empty;
extern PyObject *const_str_plain_passed_check;
extern PyObject *const_str_plain_errors;
static PyObject *const_str_digest_1c966c4a3512212044bcc040224adb5a;
static PyObject *const_str_digest_5c4b701071cdd11cef78f50c4806a100;
extern PyObject *const_str_plain___doc__;
extern PyObject *const_str_plain___cached__;
static PyObject *const_tuple_str_digest_949ca64c12f36b488e23e58498115567_tuple;
extern PyObject *const_str_plain_error;
static PyObject *module_filename_obj;
static bool constants_created = false;
static void createModuleConstants( void )
{
const_tuple_str_plain_string_if_invalid_str_empty_tuple = PyTuple_New( 2 );
PyTuple_SET_ITEM( const_tuple_str_plain_string_if_invalid_str_empty_tuple, 0, const_str_plain_string_if_invalid ); Py_INCREF( const_str_plain_string_if_invalid );
PyTuple_SET_ITEM( const_tuple_str_plain_string_if_invalid_str_empty_tuple, 1, const_str_empty ); Py_INCREF( const_str_empty );
const_str_plain_check_string_if_invalid_is_string = UNSTREAM_STRING( &constant_bin[ 771433 ], 33, 1 );
const_dict_0766a052c7dd7e7e07d999dad0c36dee = _PyDict_NewPresized( 1 );
const_str_digest_5c4b701071cdd11cef78f50c4806a100 = UNSTREAM_STRING( &constant_bin[ 771466 ], 14, 0 );
PyDict_SetItem( const_dict_0766a052c7dd7e7e07d999dad0c36dee, const_str_plain_id, const_str_digest_5c4b701071cdd11cef78f50c4806a100 );
assert( PyDict_Size( const_dict_0766a052c7dd7e7e07d999dad0c36dee ) == 1 );
const_str_digest_949ca64c12f36b488e23e58498115567 = UNSTREAM_STRING( &constant_bin[ 771480 ], 75, 0 );
const_str_digest_0c4877586912d53c003980591b4d9eba = UNSTREAM_STRING( &constant_bin[ 771555 ], 14, 0 );
const_tuple_str_digest_ca69c7a5bc6e5fe2f5e465fece629e50_tuple = PyTuple_New( 1 );
const_str_digest_ca69c7a5bc6e5fe2f5e465fece629e50 = UNSTREAM_STRING( &constant_bin[ 771569 ], 137, 0 );
PyTuple_SET_ITEM( const_tuple_str_digest_ca69c7a5bc6e5fe2f5e465fece629e50_tuple, 0, const_str_digest_ca69c7a5bc6e5fe2f5e465fece629e50 ); Py_INCREF( const_str_digest_ca69c7a5bc6e5fe2f5e465fece629e50 );
const_str_plain_check_setting_app_dirs_loaders = UNSTREAM_STRING( &constant_bin[ 771706 ], 30, 1 );
const_tuple_8d321bdc3c0c0aaaa8846c9967b2bf61_tuple = PyTuple_New( 4 );
PyTuple_SET_ITEM( const_tuple_8d321bdc3c0c0aaaa8846c9967b2bf61_tuple, 0, const_str_plain_app_configs ); Py_INCREF( const_str_plain_app_configs );
PyTuple_SET_ITEM( const_tuple_8d321bdc3c0c0aaaa8846c9967b2bf61_tuple, 1, const_str_plain_kwargs ); Py_INCREF( const_str_plain_kwargs );
PyTuple_SET_ITEM( const_tuple_8d321bdc3c0c0aaaa8846c9967b2bf61_tuple, 2, const_str_plain_passed_check ); Py_INCREF( const_str_plain_passed_check );
PyTuple_SET_ITEM( const_tuple_8d321bdc3c0c0aaaa8846c9967b2bf61_tuple, 3, const_str_plain_conf ); Py_INCREF( const_str_plain_conf );
const_str_plain_E002 = UNSTREAM_STRING( &constant_bin[ 771565 ], 4, 1 );
const_str_digest_1a8295ac4bdf9c9b351c34d87a52895c = UNSTREAM_STRING( &constant_bin[ 771736 ], 31, 0 );
const_tuple_2c7dcbbe0c3a993e658a6fce71318b1e_tuple = PyTuple_New( 6 );
PyTuple_SET_ITEM( const_tuple_2c7dcbbe0c3a993e658a6fce71318b1e_tuple, 0, const_str_plain_app_configs ); Py_INCREF( const_str_plain_app_configs );
PyTuple_SET_ITEM( const_tuple_2c7dcbbe0c3a993e658a6fce71318b1e_tuple, 1, const_str_plain_kwargs ); Py_INCREF( const_str_plain_kwargs );
PyTuple_SET_ITEM( const_tuple_2c7dcbbe0c3a993e658a6fce71318b1e_tuple, 2, const_str_plain_errors ); Py_INCREF( const_str_plain_errors );
PyTuple_SET_ITEM( const_tuple_2c7dcbbe0c3a993e658a6fce71318b1e_tuple, 3, const_str_plain_conf ); Py_INCREF( const_str_plain_conf );
PyTuple_SET_ITEM( const_tuple_2c7dcbbe0c3a993e658a6fce71318b1e_tuple, 4, const_str_plain_string_if_invalid ); Py_INCREF( const_str_plain_string_if_invalid );
PyTuple_SET_ITEM( const_tuple_2c7dcbbe0c3a993e658a6fce71318b1e_tuple, 5, const_str_plain_error ); Py_INCREF( const_str_plain_error );
const_dict_75c1c3feca8e358eb7ad1551f99dbb12 = _PyDict_NewPresized( 1 );
PyDict_SetItem( const_dict_75c1c3feca8e358eb7ad1551f99dbb12, const_str_plain_id, const_str_digest_0c4877586912d53c003980591b4d9eba );
assert( PyDict_Size( const_dict_75c1c3feca8e358eb7ad1551f99dbb12 ) == 1 );
const_str_digest_1c966c4a3512212044bcc040224adb5a = UNSTREAM_STRING( &constant_bin[ 771767 ], 37, 0 );
const_tuple_str_digest_949ca64c12f36b488e23e58498115567_tuple = PyTuple_New( 1 );
PyTuple_SET_ITEM( const_tuple_str_digest_949ca64c12f36b488e23e58498115567_tuple, 0, const_str_digest_949ca64c12f36b488e23e58498115567 ); Py_INCREF( const_str_digest_949ca64c12f36b488e23e58498115567 );
constants_created = true;
}
#ifndef __NUITKA_NO_ASSERT__
void checkModuleConstants_django$core$checks$templates( void )
{
// The module may not have been used at all.
if (constants_created == false) return;
}
#endif
// The module code objects.
static PyCodeObject *codeobj_256539fdcf3cf86e945099b24371975a;
static PyCodeObject *codeobj_e0642b55a5ed8b78b6f6fa2eadace110;
static PyCodeObject *codeobj_8fe0fa05597a0817d0a94cd0c454e4b8;
static void createModuleCodeObjects(void)
{
module_filename_obj = MAKE_RELATIVE_PATH( const_str_digest_1a8295ac4bdf9c9b351c34d87a52895c );
codeobj_256539fdcf3cf86e945099b24371975a = MAKE_CODEOBJ( module_filename_obj, const_str_digest_1c966c4a3512212044bcc040224adb5a, 1, const_tuple_empty, 0, 0, CO_NOFREE | CO_FUTURE_UNICODE_LITERALS );
codeobj_e0642b55a5ed8b78b6f6fa2eadace110 = MAKE_CODEOBJ( module_filename_obj, const_str_plain_check_setting_app_dirs_loaders, 22, const_tuple_8d321bdc3c0c0aaaa8846c9967b2bf61_tuple, 1, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_VARKEYWORDS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS );
codeobj_8fe0fa05597a0817d0a94cd0c454e4b8 = MAKE_CODEOBJ( module_filename_obj, const_str_plain_check_string_if_invalid_is_string, 33, const_tuple_2c7dcbbe0c3a993e658a6fce71318b1e_tuple, 1, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_VARKEYWORDS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS );
}
// The module function declarations.
static PyObject *MAKE_FUNCTION_django$core$checks$templates$$$function_1_check_setting_app_dirs_loaders( );
static PyObject *MAKE_FUNCTION_django$core$checks$templates$$$function_2_check_string_if_invalid_is_string( );
// The module function definitions.
static PyObject *impl_django$core$checks$templates$$$function_1_check_setting_app_dirs_loaders( struct Nuitka_FunctionObject const *self, PyObject **python_pars )
{
// Preserve error status for checks
#ifndef __NUITKA_NO_ASSERT__
NUITKA_MAY_BE_UNUSED bool had_error = ERROR_OCCURRED();
#endif
// Local variable declarations.
PyObject *par_app_configs = python_pars[ 0 ];
PyObject *par_kwargs = python_pars[ 1 ];
PyObject *var_passed_check = NULL;
PyObject *var_conf = NULL;
PyObject *tmp_for_loop_1__for_iterator = NULL;
PyObject *tmp_for_loop_1__iter_value = NULL;
PyObject *exception_type = NULL;
PyObject *exception_value = NULL;
PyTracebackObject *exception_tb = NULL;
NUITKA_MAY_BE_UNUSED int exception_lineno = 0;
PyObject *exception_keeper_type_1;
PyObject *exception_keeper_value_1;
PyTracebackObject *exception_keeper_tb_1;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1;
PyObject *exception_keeper_type_2;
PyObject *exception_keeper_value_2;
PyTracebackObject *exception_keeper_tb_2;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_2;
PyObject *tmp_assign_source_1;
PyObject *tmp_assign_source_2;
PyObject *tmp_assign_source_3;
PyObject *tmp_assign_source_4;
PyObject *tmp_assign_source_5;
PyObject *tmp_call_arg_element_1;
PyObject *tmp_call_arg_element_2;
PyObject *tmp_called_instance_1;
PyObject *tmp_called_instance_2;
int tmp_cmp_In_1;
PyObject *tmp_compare_left_1;
PyObject *tmp_compare_right_1;
int tmp_cond_truth_1;
int tmp_cond_truth_2;
PyObject *tmp_cond_value_1;
PyObject *tmp_cond_value_2;
PyObject *tmp_iter_arg_1;
PyObject *tmp_list_element_1;
PyObject *tmp_next_source_1;
PyObject *tmp_return_value;
PyObject *tmp_source_name_1;
static struct Nuitka_FrameObject *cache_frame_e0642b55a5ed8b78b6f6fa2eadace110 = NULL;
struct Nuitka_FrameObject *frame_e0642b55a5ed8b78b6f6fa2eadace110;
NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;
tmp_return_value = NULL;
// Actual function code.
tmp_assign_source_1 = Py_True;
assert( var_passed_check == NULL );
Py_INCREF( tmp_assign_source_1 );
var_passed_check = tmp_assign_source_1;
// Tried code:
MAKE_OR_REUSE_FRAME( cache_frame_e0642b55a5ed8b78b6f6fa2eadace110, codeobj_e0642b55a5ed8b78b6f6fa2eadace110, module_django$core$checks$templates, sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *) );
frame_e0642b55a5ed8b78b6f6fa2eadace110 = cache_frame_e0642b55a5ed8b78b6f6fa2eadace110;
// Push the new frame as the currently active one.
pushFrameStack( frame_e0642b55a5ed8b78b6f6fa2eadace110 );
// Mark the frame object as in use, ref count 1 will be up for reuse.
assert( Py_REFCNT( frame_e0642b55a5ed8b78b6f6fa2eadace110 ) == 2 ); // Frame stack
// Framed code:
tmp_source_name_1 = GET_STRING_DICT_VALUE( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain_settings );
if (unlikely( tmp_source_name_1 == NULL ))
{
tmp_source_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_settings );
}
if ( tmp_source_name_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "settings" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 25;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_iter_arg_1 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_TEMPLATES );
if ( tmp_iter_arg_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 25;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_assign_source_2 = MAKE_ITERATOR( tmp_iter_arg_1 );
Py_DECREF( tmp_iter_arg_1 );
if ( tmp_assign_source_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 25;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
assert( tmp_for_loop_1__for_iterator == NULL );
tmp_for_loop_1__for_iterator = tmp_assign_source_2;
// Tried code:
loop_start_1:;
tmp_next_source_1 = tmp_for_loop_1__for_iterator;
CHECK_OBJECT( tmp_next_source_1 );
tmp_assign_source_3 = ITERATOR_NEXT( tmp_next_source_1 );
if ( tmp_assign_source_3 == NULL )
{
if ( CHECK_AND_CLEAR_STOP_ITERATION_OCCURRED() )
{
goto loop_end_1;
}
else
{
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
type_description_1 = "oooo";
exception_lineno = 25;
goto try_except_handler_2;
}
}
{
PyObject *old = tmp_for_loop_1__iter_value;
tmp_for_loop_1__iter_value = tmp_assign_source_3;
Py_XDECREF( old );
}
tmp_assign_source_4 = tmp_for_loop_1__iter_value;
CHECK_OBJECT( tmp_assign_source_4 );
{
PyObject *old = var_conf;
var_conf = tmp_assign_source_4;
Py_INCREF( var_conf );
Py_XDECREF( old );
}
tmp_called_instance_1 = var_conf;
CHECK_OBJECT( tmp_called_instance_1 );
frame_e0642b55a5ed8b78b6f6fa2eadace110->m_frame.f_lineno = 26;
tmp_cond_value_1 = CALL_METHOD_WITH_ARGS1( tmp_called_instance_1, const_str_plain_get, &PyTuple_GET_ITEM( const_tuple_str_plain_APP_DIRS_tuple, 0 ) );
if ( tmp_cond_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 26;
type_description_1 = "oooo";
goto try_except_handler_2;
}
tmp_cond_truth_1 = CHECK_IF_TRUE( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_cond_value_1 );
exception_lineno = 26;
type_description_1 = "oooo";
goto try_except_handler_2;
}
Py_DECREF( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == 1 )
{
goto branch_no_1;
}
else
{
goto branch_yes_1;
}
branch_yes_1:;
goto loop_start_1;
branch_no_1:;
tmp_compare_left_1 = const_str_plain_loaders;
tmp_called_instance_2 = var_conf;
if ( tmp_called_instance_2 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "conf" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 28;
type_description_1 = "oooo";
goto try_except_handler_2;
}
tmp_call_arg_element_1 = const_str_plain_OPTIONS;
tmp_call_arg_element_2 = PyDict_New();
frame_e0642b55a5ed8b78b6f6fa2eadace110->m_frame.f_lineno = 28;
{
PyObject *call_args[] = { tmp_call_arg_element_1, tmp_call_arg_element_2 };
tmp_compare_right_1 = CALL_METHOD_WITH_ARGS2( tmp_called_instance_2, const_str_plain_get, call_args );
}
Py_DECREF( tmp_call_arg_element_2 );
if ( tmp_compare_right_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 28;
type_description_1 = "oooo";
goto try_except_handler_2;
}
tmp_cmp_In_1 = PySequence_Contains( tmp_compare_right_1, tmp_compare_left_1 );
assert( !(tmp_cmp_In_1 == -1) );
Py_DECREF( tmp_compare_right_1 );
if ( tmp_cmp_In_1 == 1 )
{
goto branch_yes_2;
}
else
{
goto branch_no_2;
}
branch_yes_2:;
tmp_assign_source_5 = Py_False;
{
PyObject *old = var_passed_check;
var_passed_check = tmp_assign_source_5;
Py_INCREF( var_passed_check );
Py_XDECREF( old );
}
branch_no_2:;
if ( CONSIDER_THREADING() == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 25;
type_description_1 = "oooo";
goto try_except_handler_2;
}
goto loop_start_1;
loop_end_1:;
goto try_end_1;
// Exception handler code:
try_except_handler_2:;
exception_keeper_type_1 = exception_type;
exception_keeper_value_1 = exception_value;
exception_keeper_tb_1 = exception_tb;
exception_keeper_lineno_1 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( tmp_for_loop_1__iter_value );
tmp_for_loop_1__iter_value = NULL;
Py_XDECREF( tmp_for_loop_1__for_iterator );
tmp_for_loop_1__for_iterator = NULL;
// Re-raise.
exception_type = exception_keeper_type_1;
exception_value = exception_keeper_value_1;
exception_tb = exception_keeper_tb_1;
exception_lineno = exception_keeper_lineno_1;
goto frame_exception_exit_1;
// End of try:
try_end_1:;
Py_XDECREF( tmp_for_loop_1__iter_value );
tmp_for_loop_1__iter_value = NULL;
Py_XDECREF( tmp_for_loop_1__for_iterator );
tmp_for_loop_1__for_iterator = NULL;
tmp_cond_value_2 = var_passed_check;
if ( tmp_cond_value_2 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "passed_check" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 30;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
tmp_cond_truth_2 = CHECK_IF_TRUE( tmp_cond_value_2 );
if ( tmp_cond_truth_2 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 30;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
if ( tmp_cond_truth_2 == 1 )
{
goto condexpr_true_1;
}
else
{
goto condexpr_false_1;
}
condexpr_true_1:;
tmp_return_value = PyList_New( 0 );
goto condexpr_end_1;
condexpr_false_1:;
tmp_return_value = PyList_New( 1 );
tmp_list_element_1 = GET_STRING_DICT_VALUE( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain_E001 );
if (unlikely( tmp_list_element_1 == NULL ))
{
tmp_list_element_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_E001 );
}
if ( tmp_list_element_1 == NULL )
{
Py_DECREF( tmp_return_value );
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "E001" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 30;
type_description_1 = "oooo";
goto frame_exception_exit_1;
}
Py_INCREF( tmp_list_element_1 );
PyList_SET_ITEM( tmp_return_value, 0, tmp_list_element_1 );
condexpr_end_1:;
goto frame_return_exit_1;
#if 0
RESTORE_FRAME_EXCEPTION( frame_e0642b55a5ed8b78b6f6fa2eadace110 );
#endif
// Put the previous frame back on top.
popFrameStack();
goto frame_no_exception_1;
frame_return_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_e0642b55a5ed8b78b6f6fa2eadace110 );
#endif
// Put the previous frame back on top.
popFrameStack();
goto try_return_handler_1;
frame_exception_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_e0642b55a5ed8b78b6f6fa2eadace110 );
#endif
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( frame_e0642b55a5ed8b78b6f6fa2eadace110, exception_lineno );
}
else if ( exception_tb->tb_frame != &frame_e0642b55a5ed8b78b6f6fa2eadace110->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, frame_e0642b55a5ed8b78b6f6fa2eadace110, exception_lineno );
}
// Attachs locals to frame if any.
Nuitka_Frame_AttachLocals(
(struct Nuitka_FrameObject *)frame_e0642b55a5ed8b78b6f6fa2eadace110,
type_description_1,
par_app_configs,
par_kwargs,
var_passed_check,
var_conf
);
// Release cached frame.
if ( frame_e0642b55a5ed8b78b6f6fa2eadace110 == cache_frame_e0642b55a5ed8b78b6f6fa2eadace110 )
{
Py_DECREF( frame_e0642b55a5ed8b78b6f6fa2eadace110 );
}
cache_frame_e0642b55a5ed8b78b6f6fa2eadace110 = NULL;
assertFrameObject( frame_e0642b55a5ed8b78b6f6fa2eadace110 );
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto try_except_handler_1;
frame_no_exception_1:;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( django$core$checks$templates$$$function_1_check_setting_app_dirs_loaders );
return NULL;
// Return handler code:
try_return_handler_1:;
Py_XDECREF( par_app_configs );
par_app_configs = NULL;
Py_XDECREF( par_kwargs );
par_kwargs = NULL;
Py_XDECREF( var_passed_check );
var_passed_check = NULL;
Py_XDECREF( var_conf );
var_conf = NULL;
goto function_return_exit;
// Exception handler code:
try_except_handler_1:;
exception_keeper_type_2 = exception_type;
exception_keeper_value_2 = exception_value;
exception_keeper_tb_2 = exception_tb;
exception_keeper_lineno_2 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( par_app_configs );
par_app_configs = NULL;
Py_XDECREF( par_kwargs );
par_kwargs = NULL;
Py_XDECREF( var_passed_check );
var_passed_check = NULL;
Py_XDECREF( var_conf );
var_conf = NULL;
// Re-raise.
exception_type = exception_keeper_type_2;
exception_value = exception_keeper_value_2;
exception_tb = exception_keeper_tb_2;
exception_lineno = exception_keeper_lineno_2;
goto function_exception_exit;
// End of try:
// Return statement must have exited already.
NUITKA_CANNOT_GET_HERE( django$core$checks$templates$$$function_1_check_setting_app_dirs_loaders );
return NULL;
function_exception_exit:
assert( exception_type );
RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
return NULL;
function_return_exit:
CHECK_OBJECT( tmp_return_value );
assert( had_error || !ERROR_OCCURRED() );
return tmp_return_value;
}
static PyObject *impl_django$core$checks$templates$$$function_2_check_string_if_invalid_is_string( struct Nuitka_FunctionObject const *self, PyObject **python_pars )
{
// Preserve error status for checks
#ifndef __NUITKA_NO_ASSERT__
NUITKA_MAY_BE_UNUSED bool had_error = ERROR_OCCURRED();
#endif
// Local variable declarations.
PyObject *par_app_configs = python_pars[ 0 ];
PyObject *par_kwargs = python_pars[ 1 ];
PyObject *var_errors = NULL;
PyObject *var_conf = NULL;
PyObject *var_string_if_invalid = NULL;
PyObject *var_error = NULL;
PyObject *tmp_for_loop_1__for_iterator = NULL;
PyObject *tmp_for_loop_1__iter_value = NULL;
PyObject *exception_type = NULL;
PyObject *exception_value = NULL;
PyTracebackObject *exception_tb = NULL;
NUITKA_MAY_BE_UNUSED int exception_lineno = 0;
PyObject *exception_keeper_type_1;
PyObject *exception_keeper_value_1;
PyTracebackObject *exception_keeper_tb_1;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1;
PyObject *exception_keeper_type_2;
PyObject *exception_keeper_value_2;
PyTracebackObject *exception_keeper_tb_2;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_2;
PyObject *tmp_args_element_name_1;
PyObject *tmp_args_element_name_2;
PyObject *tmp_args_element_name_3;
PyObject *tmp_args_element_name_4;
PyObject *tmp_assattr_name_1;
PyObject *tmp_assattr_target_1;
PyObject *tmp_assign_source_1;
PyObject *tmp_assign_source_2;
PyObject *tmp_assign_source_3;
PyObject *tmp_assign_source_4;
PyObject *tmp_assign_source_5;
PyObject *tmp_assign_source_6;
PyObject *tmp_call_arg_element_1;
PyObject *tmp_call_arg_element_2;
PyObject *tmp_called_instance_1;
PyObject *tmp_called_instance_2;
PyObject *tmp_called_name_1;
PyObject *tmp_called_name_2;
PyObject *tmp_called_name_3;
PyObject *tmp_isinstance_cls_1;
PyObject *tmp_isinstance_inst_1;
PyObject *tmp_iter_arg_1;
PyObject *tmp_next_source_1;
int tmp_res;
bool tmp_result;
PyObject *tmp_return_value;
PyObject *tmp_source_name_1;
PyObject *tmp_source_name_2;
PyObject *tmp_source_name_3;
PyObject *tmp_source_name_4;
PyObject *tmp_source_name_5;
PyObject *tmp_source_name_6;
PyObject *tmp_source_name_7;
PyObject *tmp_type_arg_1;
NUITKA_MAY_BE_UNUSED PyObject *tmp_unused;
static struct Nuitka_FrameObject *cache_frame_8fe0fa05597a0817d0a94cd0c454e4b8 = NULL;
struct Nuitka_FrameObject *frame_8fe0fa05597a0817d0a94cd0c454e4b8;
NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;
tmp_return_value = NULL;
// Actual function code.
tmp_assign_source_1 = PyList_New( 0 );
assert( var_errors == NULL );
var_errors = tmp_assign_source_1;
// Tried code:
MAKE_OR_REUSE_FRAME( cache_frame_8fe0fa05597a0817d0a94cd0c454e4b8, codeobj_8fe0fa05597a0817d0a94cd0c454e4b8, module_django$core$checks$templates, sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *) );
frame_8fe0fa05597a0817d0a94cd0c454e4b8 = cache_frame_8fe0fa05597a0817d0a94cd0c454e4b8;
// Push the new frame as the currently active one.
pushFrameStack( frame_8fe0fa05597a0817d0a94cd0c454e4b8 );
// Mark the frame object as in use, ref count 1 will be up for reuse.
assert( Py_REFCNT( frame_8fe0fa05597a0817d0a94cd0c454e4b8 ) == 2 ); // Frame stack
// Framed code:
tmp_source_name_1 = GET_STRING_DICT_VALUE( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain_settings );
if (unlikely( tmp_source_name_1 == NULL ))
{
tmp_source_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_settings );
}
if ( tmp_source_name_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "settings" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 36;
type_description_1 = "oooooo";
goto frame_exception_exit_1;
}
tmp_iter_arg_1 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_TEMPLATES );
if ( tmp_iter_arg_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 36;
type_description_1 = "oooooo";
goto frame_exception_exit_1;
}
tmp_assign_source_2 = MAKE_ITERATOR( tmp_iter_arg_1 );
Py_DECREF( tmp_iter_arg_1 );
if ( tmp_assign_source_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 36;
type_description_1 = "oooooo";
goto frame_exception_exit_1;
}
assert( tmp_for_loop_1__for_iterator == NULL );
tmp_for_loop_1__for_iterator = tmp_assign_source_2;
// Tried code:
loop_start_1:;
tmp_next_source_1 = tmp_for_loop_1__for_iterator;
CHECK_OBJECT( tmp_next_source_1 );
tmp_assign_source_3 = ITERATOR_NEXT( tmp_next_source_1 );
if ( tmp_assign_source_3 == NULL )
{
if ( CHECK_AND_CLEAR_STOP_ITERATION_OCCURRED() )
{
goto loop_end_1;
}
else
{
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
type_description_1 = "oooooo";
exception_lineno = 36;
goto try_except_handler_2;
}
}
{
PyObject *old = tmp_for_loop_1__iter_value;
tmp_for_loop_1__iter_value = tmp_assign_source_3;
Py_XDECREF( old );
}
tmp_assign_source_4 = tmp_for_loop_1__iter_value;
CHECK_OBJECT( tmp_assign_source_4 );
{
PyObject *old = var_conf;
var_conf = tmp_assign_source_4;
Py_INCREF( var_conf );
Py_XDECREF( old );
}
tmp_called_instance_2 = var_conf;
CHECK_OBJECT( tmp_called_instance_2 );
tmp_call_arg_element_1 = const_str_plain_OPTIONS;
tmp_call_arg_element_2 = PyDict_New();
frame_8fe0fa05597a0817d0a94cd0c454e4b8->m_frame.f_lineno = 37;
{
PyObject *call_args[] = { tmp_call_arg_element_1, tmp_call_arg_element_2 };
tmp_called_instance_1 = CALL_METHOD_WITH_ARGS2( tmp_called_instance_2, const_str_plain_get, call_args );
}
Py_DECREF( tmp_call_arg_element_2 );
if ( tmp_called_instance_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 37;
type_description_1 = "oooooo";
goto try_except_handler_2;
}
frame_8fe0fa05597a0817d0a94cd0c454e4b8->m_frame.f_lineno = 37;
tmp_assign_source_5 = CALL_METHOD_WITH_ARGS2( tmp_called_instance_1, const_str_plain_get, &PyTuple_GET_ITEM( const_tuple_str_plain_string_if_invalid_str_empty_tuple, 0 ) );
Py_DECREF( tmp_called_instance_1 );
if ( tmp_assign_source_5 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 37;
type_description_1 = "oooooo";
goto try_except_handler_2;
}
{
PyObject *old = var_string_if_invalid;
var_string_if_invalid = tmp_assign_source_5;
Py_XDECREF( old );
}
tmp_isinstance_inst_1 = var_string_if_invalid;
CHECK_OBJECT( tmp_isinstance_inst_1 );
tmp_source_name_2 = GET_STRING_DICT_VALUE( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain_six );
if (unlikely( tmp_source_name_2 == NULL ))
{
tmp_source_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_six );
}
if ( tmp_source_name_2 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "six" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 38;
type_description_1 = "oooooo";
goto try_except_handler_2;
}
tmp_isinstance_cls_1 = LOOKUP_ATTRIBUTE( tmp_source_name_2, const_str_plain_string_types );
if ( tmp_isinstance_cls_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 38;
type_description_1 = "oooooo";
goto try_except_handler_2;
}
tmp_res = Nuitka_IsInstance( tmp_isinstance_inst_1, tmp_isinstance_cls_1 );
Py_DECREF( tmp_isinstance_cls_1 );
if ( tmp_res == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 38;
type_description_1 = "oooooo";
goto try_except_handler_2;
}
if ( tmp_res == 1 )
{
goto branch_no_1;
}
else
{
goto branch_yes_1;
}
branch_yes_1:;
tmp_source_name_3 = GET_STRING_DICT_VALUE( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain_copy );
if (unlikely( tmp_source_name_3 == NULL ))
{
tmp_source_name_3 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_copy );
}
if ( tmp_source_name_3 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "copy" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 39;
type_description_1 = "oooooo";
goto try_except_handler_2;
}
tmp_called_name_1 = LOOKUP_ATTRIBUTE( tmp_source_name_3, const_str_plain_copy );
if ( tmp_called_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 39;
type_description_1 = "oooooo";
goto try_except_handler_2;
}
tmp_args_element_name_1 = GET_STRING_DICT_VALUE( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain_E002 );
if (unlikely( tmp_args_element_name_1 == NULL ))
{
tmp_args_element_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_E002 );
}
if ( tmp_args_element_name_1 == NULL )
{
Py_DECREF( tmp_called_name_1 );
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "E002" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 39;
type_description_1 = "oooooo";
goto try_except_handler_2;
}
frame_8fe0fa05597a0817d0a94cd0c454e4b8->m_frame.f_lineno = 39;
{
PyObject *call_args[] = { tmp_args_element_name_1 };
tmp_assign_source_6 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_1, call_args );
}
Py_DECREF( tmp_called_name_1 );
if ( tmp_assign_source_6 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 39;
type_description_1 = "oooooo";
goto try_except_handler_2;
}
{
PyObject *old = var_error;
var_error = tmp_assign_source_6;
Py_XDECREF( old );
}
tmp_source_name_5 = var_error;
CHECK_OBJECT( tmp_source_name_5 );
tmp_source_name_4 = LOOKUP_ATTRIBUTE( tmp_source_name_5, const_str_plain_msg );
if ( tmp_source_name_4 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 40;
type_description_1 = "oooooo";
goto try_except_handler_2;
}
tmp_called_name_2 = LOOKUP_ATTRIBUTE( tmp_source_name_4, const_str_plain_format );
Py_DECREF( tmp_source_name_4 );
if ( tmp_called_name_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 40;
type_description_1 = "oooooo";
goto try_except_handler_2;
}
tmp_args_element_name_2 = var_string_if_invalid;
if ( tmp_args_element_name_2 == NULL )
{
Py_DECREF( tmp_called_name_2 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "string_if_invalid" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 40;
type_description_1 = "oooooo";
goto try_except_handler_2;
}
tmp_type_arg_1 = var_string_if_invalid;
if ( tmp_type_arg_1 == NULL )
{
Py_DECREF( tmp_called_name_2 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "string_if_invalid" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 40;
type_description_1 = "oooooo";
goto try_except_handler_2;
}
tmp_source_name_6 = BUILTIN_TYPE1( tmp_type_arg_1 );
if ( tmp_source_name_6 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_2 );
exception_lineno = 40;
type_description_1 = "oooooo";
goto try_except_handler_2;
}
tmp_args_element_name_3 = LOOKUP_ATTRIBUTE( tmp_source_name_6, const_str_plain___name__ );
Py_DECREF( tmp_source_name_6 );
if ( tmp_args_element_name_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_2 );
exception_lineno = 40;
type_description_1 = "oooooo";
goto try_except_handler_2;
}
frame_8fe0fa05597a0817d0a94cd0c454e4b8->m_frame.f_lineno = 40;
{
PyObject *call_args[] = { tmp_args_element_name_2, tmp_args_element_name_3 };
tmp_assattr_name_1 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_2, call_args );
}
Py_DECREF( tmp_called_name_2 );
Py_DECREF( tmp_args_element_name_3 );
if ( tmp_assattr_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 40;
type_description_1 = "oooooo";
goto try_except_handler_2;
}
tmp_assattr_target_1 = var_error;
if ( tmp_assattr_target_1 == NULL )
{
Py_DECREF( tmp_assattr_name_1 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "error" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 40;
type_description_1 = "oooooo";
goto try_except_handler_2;
}
tmp_result = SET_ATTRIBUTE( tmp_assattr_target_1, const_str_plain_msg, tmp_assattr_name_1 );
if ( tmp_result == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_assattr_name_1 );
exception_lineno = 40;
type_description_1 = "oooooo";
goto try_except_handler_2;
}
Py_DECREF( tmp_assattr_name_1 );
tmp_source_name_7 = var_errors;
if ( tmp_source_name_7 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "errors" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 41;
type_description_1 = "oooooo";
goto try_except_handler_2;
}
tmp_called_name_3 = LOOKUP_ATTRIBUTE( tmp_source_name_7, const_str_plain_append );
if ( tmp_called_name_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 41;
type_description_1 = "oooooo";
goto try_except_handler_2;
}
tmp_args_element_name_4 = var_error;
if ( tmp_args_element_name_4 == NULL )
{
Py_DECREF( tmp_called_name_3 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "error" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 41;
type_description_1 = "oooooo";
goto try_except_handler_2;
}
frame_8fe0fa05597a0817d0a94cd0c454e4b8->m_frame.f_lineno = 41;
{
PyObject *call_args[] = { tmp_args_element_name_4 };
tmp_unused = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_3, call_args );
}
Py_DECREF( tmp_called_name_3 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 41;
type_description_1 = "oooooo";
goto try_except_handler_2;
}
Py_DECREF( tmp_unused );
branch_no_1:;
if ( CONSIDER_THREADING() == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 36;
type_description_1 = "oooooo";
goto try_except_handler_2;
}
goto loop_start_1;
loop_end_1:;
goto try_end_1;
// Exception handler code:
try_except_handler_2:;
exception_keeper_type_1 = exception_type;
exception_keeper_value_1 = exception_value;
exception_keeper_tb_1 = exception_tb;
exception_keeper_lineno_1 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( tmp_for_loop_1__iter_value );
tmp_for_loop_1__iter_value = NULL;
Py_XDECREF( tmp_for_loop_1__for_iterator );
tmp_for_loop_1__for_iterator = NULL;
// Re-raise.
exception_type = exception_keeper_type_1;
exception_value = exception_keeper_value_1;
exception_tb = exception_keeper_tb_1;
exception_lineno = exception_keeper_lineno_1;
goto frame_exception_exit_1;
// End of try:
try_end_1:;
Py_XDECREF( tmp_for_loop_1__iter_value );
tmp_for_loop_1__iter_value = NULL;
Py_XDECREF( tmp_for_loop_1__for_iterator );
tmp_for_loop_1__for_iterator = NULL;
tmp_return_value = var_errors;
if ( tmp_return_value == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "errors" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 42;
type_description_1 = "oooooo";
goto frame_exception_exit_1;
}
Py_INCREF( tmp_return_value );
goto frame_return_exit_1;
#if 0
RESTORE_FRAME_EXCEPTION( frame_8fe0fa05597a0817d0a94cd0c454e4b8 );
#endif
// Put the previous frame back on top.
popFrameStack();
goto frame_no_exception_1;
frame_return_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_8fe0fa05597a0817d0a94cd0c454e4b8 );
#endif
// Put the previous frame back on top.
popFrameStack();
goto try_return_handler_1;
frame_exception_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_8fe0fa05597a0817d0a94cd0c454e4b8 );
#endif
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( frame_8fe0fa05597a0817d0a94cd0c454e4b8, exception_lineno );
}
else if ( exception_tb->tb_frame != &frame_8fe0fa05597a0817d0a94cd0c454e4b8->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, frame_8fe0fa05597a0817d0a94cd0c454e4b8, exception_lineno );
}
// Attachs locals to frame if any.
Nuitka_Frame_AttachLocals(
(struct Nuitka_FrameObject *)frame_8fe0fa05597a0817d0a94cd0c454e4b8,
type_description_1,
par_app_configs,
par_kwargs,
var_errors,
var_conf,
var_string_if_invalid,
var_error
);
// Release cached frame.
if ( frame_8fe0fa05597a0817d0a94cd0c454e4b8 == cache_frame_8fe0fa05597a0817d0a94cd0c454e4b8 )
{
Py_DECREF( frame_8fe0fa05597a0817d0a94cd0c454e4b8 );
}
cache_frame_8fe0fa05597a0817d0a94cd0c454e4b8 = NULL;
assertFrameObject( frame_8fe0fa05597a0817d0a94cd0c454e4b8 );
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto try_except_handler_1;
frame_no_exception_1:;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( django$core$checks$templates$$$function_2_check_string_if_invalid_is_string );
return NULL;
// Return handler code:
try_return_handler_1:;
Py_XDECREF( par_app_configs );
par_app_configs = NULL;
Py_XDECREF( par_kwargs );
par_kwargs = NULL;
Py_XDECREF( var_errors );
var_errors = NULL;
Py_XDECREF( var_conf );
var_conf = NULL;
Py_XDECREF( var_string_if_invalid );
var_string_if_invalid = NULL;
Py_XDECREF( var_error );
var_error = NULL;
goto function_return_exit;
// Exception handler code:
try_except_handler_1:;
exception_keeper_type_2 = exception_type;
exception_keeper_value_2 = exception_value;
exception_keeper_tb_2 = exception_tb;
exception_keeper_lineno_2 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( par_app_configs );
par_app_configs = NULL;
Py_XDECREF( par_kwargs );
par_kwargs = NULL;
Py_XDECREF( var_errors );
var_errors = NULL;
Py_XDECREF( var_conf );
var_conf = NULL;
Py_XDECREF( var_string_if_invalid );
var_string_if_invalid = NULL;
Py_XDECREF( var_error );
var_error = NULL;
// Re-raise.
exception_type = exception_keeper_type_2;
exception_value = exception_keeper_value_2;
exception_tb = exception_keeper_tb_2;
exception_lineno = exception_keeper_lineno_2;
goto function_exception_exit;
// End of try:
// Return statement must have exited already.
NUITKA_CANNOT_GET_HERE( django$core$checks$templates$$$function_2_check_string_if_invalid_is_string );
return NULL;
function_exception_exit:
assert( exception_type );
RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
return NULL;
function_return_exit:
CHECK_OBJECT( tmp_return_value );
assert( had_error || !ERROR_OCCURRED() );
return tmp_return_value;
}
static PyObject *MAKE_FUNCTION_django$core$checks$templates$$$function_1_check_setting_app_dirs_loaders( )
{
struct Nuitka_FunctionObject *result = Nuitka_Function_New(
impl_django$core$checks$templates$$$function_1_check_setting_app_dirs_loaders,
const_str_plain_check_setting_app_dirs_loaders,
#if PYTHON_VERSION >= 330
NULL,
#endif
codeobj_e0642b55a5ed8b78b6f6fa2eadace110,
NULL,
#if PYTHON_VERSION >= 300
NULL,
const_dict_empty,
#endif
module_django$core$checks$templates,
Py_None,
0
);
return (PyObject *)result;
}
static PyObject *MAKE_FUNCTION_django$core$checks$templates$$$function_2_check_string_if_invalid_is_string( )
{
struct Nuitka_FunctionObject *result = Nuitka_Function_New(
impl_django$core$checks$templates$$$function_2_check_string_if_invalid_is_string,
const_str_plain_check_string_if_invalid_is_string,
#if PYTHON_VERSION >= 330
NULL,
#endif
codeobj_8fe0fa05597a0817d0a94cd0c454e4b8,
NULL,
#if PYTHON_VERSION >= 300
NULL,
const_dict_empty,
#endif
module_django$core$checks$templates,
Py_None,
0
);
return (PyObject *)result;
}
#if PYTHON_VERSION >= 300
static struct PyModuleDef mdef_django$core$checks$templates =
{
PyModuleDef_HEAD_INIT,
"django.core.checks.templates", /* m_name */
NULL, /* m_doc */
-1, /* m_size */
NULL, /* m_methods */
NULL, /* m_reload */
NULL, /* m_traverse */
NULL, /* m_clear */
NULL, /* m_free */
};
#endif
#if PYTHON_VERSION >= 300
extern PyObject *metapath_based_loader;
#endif
#if PYTHON_VERSION >= 330
extern PyObject *const_str_plain___loader__;
#endif
extern void _initCompiledCellType();
extern void _initCompiledGeneratorType();
extern void _initCompiledFunctionType();
extern void _initCompiledMethodType();
extern void _initCompiledFrameType();
#if PYTHON_VERSION >= 350
extern void _initCompiledCoroutineTypes();
#endif
#if PYTHON_VERSION >= 360
extern void _initCompiledAsyncgenTypes();
#endif
// The exported interface to CPython. On import of the module, this function
// gets called. It has to have an exact function name, in cases it's a shared
// library export. This is hidden behind the MOD_INIT_DECL.
MOD_INIT_DECL( django$core$checks$templates )
{
#if defined(_NUITKA_EXE) || PYTHON_VERSION >= 300
static bool _init_done = false;
// Modules might be imported repeatedly, which is to be ignored.
if ( _init_done )
{
return MOD_RETURN_VALUE( module_django$core$checks$templates );
}
else
{
_init_done = true;
}
#endif
#ifdef _NUITKA_MODULE
// In case of a stand alone extension module, need to call initialization
// the init here because that's the first and only time we are going to get
// called here.
// Initialize the constant values used.
_initBuiltinModule();
createGlobalConstants();
/* Initialize the compiled types of Nuitka. */
_initCompiledCellType();
_initCompiledGeneratorType();
_initCompiledFunctionType();
_initCompiledMethodType();
_initCompiledFrameType();
#if PYTHON_VERSION >= 350
_initCompiledCoroutineTypes();
#endif
#if PYTHON_VERSION >= 360
_initCompiledAsyncgenTypes();
#endif
#if PYTHON_VERSION < 300
_initSlotCompare();
#endif
#if PYTHON_VERSION >= 270
_initSlotIternext();
#endif
patchBuiltinModule();
patchTypeComparison();
// Enable meta path based loader if not already done.
setupMetaPathBasedLoader();
#if PYTHON_VERSION >= 300
patchInspectModule();
#endif
#endif
/* The constants only used by this module are created now. */
#ifdef _NUITKA_TRACE
puts("django.core.checks.templates: Calling createModuleConstants().");
#endif
createModuleConstants();
/* The code objects used by this module are created now. */
#ifdef _NUITKA_TRACE
puts("django.core.checks.templates: Calling createModuleCodeObjects().");
#endif
createModuleCodeObjects();
// puts( "in initdjango$core$checks$templates" );
// Create the module object first. There are no methods initially, all are
// added dynamically in actual code only. Also no "__doc__" is initially
// set at this time, as it could not contain NUL characters this way, they
// are instead set in early module code. No "self" for modules, we have no
// use for it.
#if PYTHON_VERSION < 300
module_django$core$checks$templates = Py_InitModule4(
"django.core.checks.templates", // Module Name
NULL, // No methods initially, all are added
// dynamically in actual module code only.
NULL, // No __doc__ is initially set, as it could
// not contain NUL this way, added early in
// actual code.
NULL, // No self for modules, we don't use it.
PYTHON_API_VERSION
);
#else
module_django$core$checks$templates = PyModule_Create( &mdef_django$core$checks$templates );
#endif
moduledict_django$core$checks$templates = MODULE_DICT( module_django$core$checks$templates );
CHECK_OBJECT( module_django$core$checks$templates );
// Seems to work for Python2.7 out of the box, but for Python3, the module
// doesn't automatically enter "sys.modules", so do it manually.
#if PYTHON_VERSION >= 300
{
int r = PyObject_SetItem( PySys_GetObject( (char *)"modules" ), const_str_digest_fa133991df808b3571d5fc7f23523a98, module_django$core$checks$templates );
assert( r != -1 );
}
#endif
// For deep importing of a module we need to have "__builtins__", so we set
// it ourselves in the same way than CPython does. Note: This must be done
// before the frame object is allocated, or else it may fail.
if ( GET_STRING_DICT_VALUE( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain___builtins__ ) == NULL )
{
PyObject *value = (PyObject *)builtin_module;
// Check if main module, not a dict then but the module itself.
#if !defined(_NUITKA_EXE) || !0
value = PyModule_GetDict( value );
#endif
UPDATE_STRING_DICT0( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain___builtins__, value );
}
#if PYTHON_VERSION >= 330
UPDATE_STRING_DICT0( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain___loader__, metapath_based_loader );
#endif
// Temp variables if any
PyObject *tmp_import_from_1__module = NULL;
PyObject *exception_type = NULL;
PyObject *exception_value = NULL;
PyTracebackObject *exception_tb = NULL;
NUITKA_MAY_BE_UNUSED int exception_lineno = 0;
PyObject *exception_keeper_type_1;
PyObject *exception_keeper_value_1;
PyTracebackObject *exception_keeper_tb_1;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1;
PyObject *tmp_args_element_name_1;
PyObject *tmp_args_element_name_2;
PyObject *tmp_args_element_name_3;
PyObject *tmp_args_element_name_4;
PyObject *tmp_args_element_name_5;
PyObject *tmp_args_element_name_6;
PyObject *tmp_args_name_1;
PyObject *tmp_args_name_2;
PyObject *tmp_assign_source_1;
PyObject *tmp_assign_source_2;
PyObject *tmp_assign_source_3;
PyObject *tmp_assign_source_4;
PyObject *tmp_assign_source_5;
PyObject *tmp_assign_source_6;
PyObject *tmp_assign_source_7;
PyObject *tmp_assign_source_8;
PyObject *tmp_assign_source_9;
PyObject *tmp_assign_source_10;
PyObject *tmp_assign_source_11;
PyObject *tmp_assign_source_12;
PyObject *tmp_assign_source_13;
PyObject *tmp_assign_source_14;
PyObject *tmp_assign_source_15;
PyObject *tmp_assign_source_16;
PyObject *tmp_assign_source_17;
PyObject *tmp_assign_source_18;
PyObject *tmp_called_name_1;
PyObject *tmp_called_name_2;
PyObject *tmp_called_name_3;
PyObject *tmp_called_name_4;
PyObject *tmp_called_name_5;
PyObject *tmp_called_name_6;
PyObject *tmp_called_name_7;
PyObject *tmp_fromlist_name_1;
PyObject *tmp_fromlist_name_2;
PyObject *tmp_fromlist_name_3;
PyObject *tmp_fromlist_name_4;
PyObject *tmp_globals_name_1;
PyObject *tmp_globals_name_2;
PyObject *tmp_globals_name_3;
PyObject *tmp_globals_name_4;
PyObject *tmp_import_name_from_1;
PyObject *tmp_import_name_from_2;
PyObject *tmp_import_name_from_3;
PyObject *tmp_import_name_from_4;
PyObject *tmp_import_name_from_5;
PyObject *tmp_import_name_from_6;
PyObject *tmp_kw_name_1;
PyObject *tmp_kw_name_2;
PyObject *tmp_level_name_1;
PyObject *tmp_level_name_2;
PyObject *tmp_level_name_3;
PyObject *tmp_level_name_4;
PyObject *tmp_locals_name_1;
PyObject *tmp_locals_name_2;
PyObject *tmp_locals_name_3;
PyObject *tmp_locals_name_4;
PyObject *tmp_name_name_1;
PyObject *tmp_name_name_2;
PyObject *tmp_name_name_3;
PyObject *tmp_name_name_4;
PyObject *tmp_source_name_1;
PyObject *tmp_source_name_2;
struct Nuitka_FrameObject *frame_256539fdcf3cf86e945099b24371975a;
NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;
// Module code.
tmp_assign_source_1 = Py_None;
UPDATE_STRING_DICT0( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain___doc__, tmp_assign_source_1 );
tmp_assign_source_2 = module_filename_obj;
UPDATE_STRING_DICT0( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain___file__, tmp_assign_source_2 );
tmp_assign_source_3 = metapath_based_loader;
UPDATE_STRING_DICT0( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain___loader__, tmp_assign_source_3 );
// Frame without reuse.
frame_256539fdcf3cf86e945099b24371975a = MAKE_MODULE_FRAME( codeobj_256539fdcf3cf86e945099b24371975a, module_django$core$checks$templates );
// Push the new frame as the currently active one, and we should be exclusively
// owning it.
pushFrameStack( frame_256539fdcf3cf86e945099b24371975a );
assert( Py_REFCNT( frame_256539fdcf3cf86e945099b24371975a ) == 2 );
// Framed code:
frame_256539fdcf3cf86e945099b24371975a->m_frame.f_lineno = 1;
{
PyObject *module = PyImport_ImportModule("importlib._bootstrap");
if (likely( module != NULL ))
{
tmp_called_name_1 = PyObject_GetAttr( module, const_str_plain_ModuleSpec );
}
else
{
tmp_called_name_1 = NULL;
}
}
if ( tmp_called_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 1;
goto frame_exception_exit_1;
}
tmp_args_element_name_1 = const_str_digest_fa133991df808b3571d5fc7f23523a98;
tmp_args_element_name_2 = metapath_based_loader;
frame_256539fdcf3cf86e945099b24371975a->m_frame.f_lineno = 1;
{
PyObject *call_args[] = { tmp_args_element_name_1, tmp_args_element_name_2 };
tmp_assign_source_4 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_1, call_args );
}
if ( tmp_assign_source_4 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 1;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain___spec__, tmp_assign_source_4 );
tmp_assign_source_5 = Py_None;
UPDATE_STRING_DICT0( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain___cached__, tmp_assign_source_5 );
tmp_assign_source_6 = const_str_digest_d7803f988ae9afc17e4a4fd2b91f50ce;
UPDATE_STRING_DICT0( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain___package__, tmp_assign_source_6 );
frame_256539fdcf3cf86e945099b24371975a->m_frame.f_lineno = 2;
tmp_import_name_from_1 = PyImport_ImportModule("__future__");
assert( tmp_import_name_from_1 != NULL );
tmp_assign_source_7 = IMPORT_NAME( tmp_import_name_from_1, const_str_plain_unicode_literals );
if ( tmp_assign_source_7 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 2;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain_unicode_literals, tmp_assign_source_7 );
tmp_name_name_1 = const_str_plain_copy;
tmp_globals_name_1 = (PyObject *)moduledict_django$core$checks$templates;
tmp_locals_name_1 = Py_None;
tmp_fromlist_name_1 = Py_None;
tmp_level_name_1 = const_int_0;
frame_256539fdcf3cf86e945099b24371975a->m_frame.f_lineno = 4;
tmp_assign_source_8 = IMPORT_MODULE5( tmp_name_name_1, tmp_globals_name_1, tmp_locals_name_1, tmp_fromlist_name_1, tmp_level_name_1 );
if ( tmp_assign_source_8 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 4;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain_copy, tmp_assign_source_8 );
tmp_name_name_2 = const_str_digest_e2cff0983efd969a5767cadcc9e9f0e8;
tmp_globals_name_2 = (PyObject *)moduledict_django$core$checks$templates;
tmp_locals_name_2 = Py_None;
tmp_fromlist_name_2 = const_tuple_str_plain_settings_tuple;
tmp_level_name_2 = const_int_0;
frame_256539fdcf3cf86e945099b24371975a->m_frame.f_lineno = 6;
tmp_import_name_from_2 = IMPORT_MODULE5( tmp_name_name_2, tmp_globals_name_2, tmp_locals_name_2, tmp_fromlist_name_2, tmp_level_name_2 );
if ( tmp_import_name_from_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 6;
goto frame_exception_exit_1;
}
tmp_assign_source_9 = IMPORT_NAME( tmp_import_name_from_2, const_str_plain_settings );
Py_DECREF( tmp_import_name_from_2 );
if ( tmp_assign_source_9 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 6;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain_settings, tmp_assign_source_9 );
tmp_name_name_3 = const_str_digest_467c9722f19d9d40d148689532cdc0b1;
tmp_globals_name_3 = (PyObject *)moduledict_django$core$checks$templates;
tmp_locals_name_3 = Py_None;
tmp_fromlist_name_3 = const_tuple_str_plain_six_tuple;
tmp_level_name_3 = const_int_0;
frame_256539fdcf3cf86e945099b24371975a->m_frame.f_lineno = 7;
tmp_import_name_from_3 = IMPORT_MODULE5( tmp_name_name_3, tmp_globals_name_3, tmp_locals_name_3, tmp_fromlist_name_3, tmp_level_name_3 );
if ( tmp_import_name_from_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 7;
goto frame_exception_exit_1;
}
tmp_assign_source_10 = IMPORT_NAME( tmp_import_name_from_3, const_str_plain_six );
Py_DECREF( tmp_import_name_from_3 );
if ( tmp_assign_source_10 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 7;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain_six, tmp_assign_source_10 );
tmp_name_name_4 = const_str_empty;
tmp_globals_name_4 = (PyObject *)moduledict_django$core$checks$templates;
tmp_locals_name_4 = Py_None;
tmp_fromlist_name_4 = const_tuple_str_plain_Error_str_plain_Tags_str_plain_register_tuple;
tmp_level_name_4 = const_int_pos_1;
frame_256539fdcf3cf86e945099b24371975a->m_frame.f_lineno = 9;
tmp_assign_source_11 = IMPORT_MODULE5( tmp_name_name_4, tmp_globals_name_4, tmp_locals_name_4, tmp_fromlist_name_4, tmp_level_name_4 );
if ( tmp_assign_source_11 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 9;
goto frame_exception_exit_1;
}
assert( tmp_import_from_1__module == NULL );
tmp_import_from_1__module = tmp_assign_source_11;
// Tried code:
tmp_import_name_from_4 = tmp_import_from_1__module;
CHECK_OBJECT( tmp_import_name_from_4 );
tmp_assign_source_12 = IMPORT_NAME( tmp_import_name_from_4, const_str_plain_Error );
if ( tmp_assign_source_12 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 9;
goto try_except_handler_1;
}
UPDATE_STRING_DICT1( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain_Error, tmp_assign_source_12 );
tmp_import_name_from_5 = tmp_import_from_1__module;
CHECK_OBJECT( tmp_import_name_from_5 );
tmp_assign_source_13 = IMPORT_NAME( tmp_import_name_from_5, const_str_plain_Tags );
if ( tmp_assign_source_13 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 9;
goto try_except_handler_1;
}
UPDATE_STRING_DICT1( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain_Tags, tmp_assign_source_13 );
tmp_import_name_from_6 = tmp_import_from_1__module;
CHECK_OBJECT( tmp_import_name_from_6 );
tmp_assign_source_14 = IMPORT_NAME( tmp_import_name_from_6, const_str_plain_register );
if ( tmp_assign_source_14 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 9;
goto try_except_handler_1;
}
UPDATE_STRING_DICT1( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain_register, tmp_assign_source_14 );
goto try_end_1;
// Exception handler code:
try_except_handler_1:;
exception_keeper_type_1 = exception_type;
exception_keeper_value_1 = exception_value;
exception_keeper_tb_1 = exception_tb;
exception_keeper_lineno_1 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( tmp_import_from_1__module );
tmp_import_from_1__module = NULL;
// Re-raise.
exception_type = exception_keeper_type_1;
exception_value = exception_keeper_value_1;
exception_tb = exception_keeper_tb_1;
exception_lineno = exception_keeper_lineno_1;
goto frame_exception_exit_1;
// End of try:
try_end_1:;
Py_XDECREF( tmp_import_from_1__module );
tmp_import_from_1__module = NULL;
tmp_called_name_2 = GET_STRING_DICT_VALUE( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain_Error );
if (unlikely( tmp_called_name_2 == NULL ))
{
tmp_called_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_Error );
}
if ( tmp_called_name_2 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "Error" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 11;
goto frame_exception_exit_1;
}
tmp_args_name_1 = const_tuple_str_digest_ca69c7a5bc6e5fe2f5e465fece629e50_tuple;
tmp_kw_name_1 = PyDict_Copy( const_dict_0766a052c7dd7e7e07d999dad0c36dee );
frame_256539fdcf3cf86e945099b24371975a->m_frame.f_lineno = 11;
tmp_assign_source_15 = CALL_FUNCTION( tmp_called_name_2, tmp_args_name_1, tmp_kw_name_1 );
Py_DECREF( tmp_kw_name_1 );
if ( tmp_assign_source_15 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 11;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain_E001, tmp_assign_source_15 );
tmp_called_name_3 = GET_STRING_DICT_VALUE( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain_Error );
if (unlikely( tmp_called_name_3 == NULL ))
{
tmp_called_name_3 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_Error );
}
if ( tmp_called_name_3 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "Error" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 16;
goto frame_exception_exit_1;
}
tmp_args_name_2 = const_tuple_str_digest_949ca64c12f36b488e23e58498115567_tuple;
tmp_kw_name_2 = PyDict_Copy( const_dict_75c1c3feca8e358eb7ad1551f99dbb12 );
frame_256539fdcf3cf86e945099b24371975a->m_frame.f_lineno = 16;
tmp_assign_source_16 = CALL_FUNCTION( tmp_called_name_3, tmp_args_name_2, tmp_kw_name_2 );
Py_DECREF( tmp_kw_name_2 );
if ( tmp_assign_source_16 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 16;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain_E002, tmp_assign_source_16 );
tmp_called_name_5 = GET_STRING_DICT_VALUE( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain_register );
if (unlikely( tmp_called_name_5 == NULL ))
{
tmp_called_name_5 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_register );
}
if ( tmp_called_name_5 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "register" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 22;
goto frame_exception_exit_1;
}
tmp_source_name_1 = GET_STRING_DICT_VALUE( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain_Tags );
if (unlikely( tmp_source_name_1 == NULL ))
{
tmp_source_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_Tags );
}
if ( tmp_source_name_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "Tags" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 22;
goto frame_exception_exit_1;
}
tmp_args_element_name_3 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_templates );
if ( tmp_args_element_name_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 22;
goto frame_exception_exit_1;
}
frame_256539fdcf3cf86e945099b24371975a->m_frame.f_lineno = 22;
{
PyObject *call_args[] = { tmp_args_element_name_3 };
tmp_called_name_4 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_5, call_args );
}
Py_DECREF( tmp_args_element_name_3 );
if ( tmp_called_name_4 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 22;
goto frame_exception_exit_1;
}
tmp_args_element_name_4 = MAKE_FUNCTION_django$core$checks$templates$$$function_1_check_setting_app_dirs_loaders( );
frame_256539fdcf3cf86e945099b24371975a->m_frame.f_lineno = 22;
{
PyObject *call_args[] = { tmp_args_element_name_4 };
tmp_assign_source_17 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_4, call_args );
}
Py_DECREF( tmp_called_name_4 );
Py_DECREF( tmp_args_element_name_4 );
if ( tmp_assign_source_17 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 22;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain_check_setting_app_dirs_loaders, tmp_assign_source_17 );
tmp_called_name_7 = GET_STRING_DICT_VALUE( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain_register );
if (unlikely( tmp_called_name_7 == NULL ))
{
tmp_called_name_7 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_register );
}
if ( tmp_called_name_7 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "register" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 33;
goto frame_exception_exit_1;
}
tmp_source_name_2 = GET_STRING_DICT_VALUE( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain_Tags );
if (unlikely( tmp_source_name_2 == NULL ))
{
tmp_source_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_Tags );
}
if ( tmp_source_name_2 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "Tags" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 33;
goto frame_exception_exit_1;
}
tmp_args_element_name_5 = LOOKUP_ATTRIBUTE( tmp_source_name_2, const_str_plain_templates );
if ( tmp_args_element_name_5 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 33;
goto frame_exception_exit_1;
}
frame_256539fdcf3cf86e945099b24371975a->m_frame.f_lineno = 33;
{
PyObject *call_args[] = { tmp_args_element_name_5 };
tmp_called_name_6 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_7, call_args );
}
Py_DECREF( tmp_args_element_name_5 );
if ( tmp_called_name_6 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 33;
goto frame_exception_exit_1;
}
tmp_args_element_name_6 = MAKE_FUNCTION_django$core$checks$templates$$$function_2_check_string_if_invalid_is_string( );
frame_256539fdcf3cf86e945099b24371975a->m_frame.f_lineno = 33;
{
PyObject *call_args[] = { tmp_args_element_name_6 };
tmp_assign_source_18 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_6, call_args );
}
Py_DECREF( tmp_called_name_6 );
Py_DECREF( tmp_args_element_name_6 );
if ( tmp_assign_source_18 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 33;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_django$core$checks$templates, (Nuitka_StringObject *)const_str_plain_check_string_if_invalid_is_string, tmp_assign_source_18 );
// Restore frame exception if necessary.
#if 0
RESTORE_FRAME_EXCEPTION( frame_256539fdcf3cf86e945099b24371975a );
#endif
popFrameStack();
assertFrameObject( frame_256539fdcf3cf86e945099b24371975a );
goto frame_no_exception_1;
frame_exception_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_256539fdcf3cf86e945099b24371975a );
#endif
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( frame_256539fdcf3cf86e945099b24371975a, exception_lineno );
}
else if ( exception_tb->tb_frame != &frame_256539fdcf3cf86e945099b24371975a->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, frame_256539fdcf3cf86e945099b24371975a, exception_lineno );
}
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto module_exception_exit;
frame_no_exception_1:;
return MOD_RETURN_VALUE( module_django$core$checks$templates );
module_exception_exit:
RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
return MOD_RETURN_VALUE( NULL );
}
| 34.632493 | 283 | 0.727058 | [
"object"
] |
9898de56dad402754e54bc77853b9e530e05abfc | 867 | cpp | C++ | solution/minimum_spanning_tree/1368/main.cpp | imnotmoon/baekjoon | 07e7f95316dcc578d065eb384553ae09530f95ac | [
"MIT"
] | 1 | 2021-05-25T11:24:35.000Z | 2021-05-25T11:24:35.000Z | solution/minimum_spanning_tree/1368/main.cpp | imnotmoon/baekjoon | 07e7f95316dcc578d065eb384553ae09530f95ac | [
"MIT"
] | null | null | null | solution/minimum_spanning_tree/1368/main.cpp | imnotmoon/baekjoon | 07e7f95316dcc578d065eb384553ae09530f95ac | [
"MIT"
] | 2 | 2021-09-18T05:47:41.000Z | 2021-12-30T14:42:27.000Z | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int uf[303];
int find(int x) {
if(uf[x] < 0) return x;
return uf[x] = find(uf[x]);
}
bool merge(int a, int b) {
a = find(a);
b = find(b);
if(a == b)return false;
uf[b] = a;
return true;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int N; cin >> N;
vector<tuple<ll, int, int>> w;
for(int i=0;i<=N;i++) uf[i] = -1;
for(int i=0;i<N;i++) {
int x;cin >> x;
w.emplace_back(x, i, N);
}
for(int i=0;i<N;i++) {
for(int j=0;j<N;j++) {
int x; cin >> x;
if(i >= j) continue;
w.emplace_back(x, i, j);
}
}
sort(w.begin(), w.end());
ll answer = 0;
for(auto &[W, a, b]: w) {
if(merge(a, b)) answer += W;
}
cout << answer;
return 0;
}
| 17.693878 | 37 | 0.456747 | [
"vector"
] |
989a3b2c2840f1d783f6e7684b68206fe7eb3299 | 15,117 | hpp | C++ | include/morphotree/attributes/smoothnessContourComputer.hpp | dennisjosesilva/morphotree | 3be4ff7f36de65772ef273a61b0bc5916e2904d9 | [
"MIT"
] | null | null | null | include/morphotree/attributes/smoothnessContourComputer.hpp | dennisjosesilva/morphotree | 3be4ff7f36de65772ef273a61b0bc5916e2904d9 | [
"MIT"
] | 3 | 2022-03-23T19:16:08.000Z | 2022-03-28T00:40:19.000Z | include/morphotree/attributes/smoothnessContourComputer.hpp | dennisjosesilva/morphotree | 3be4ff7f36de65772ef273a61b0bc5916e2904d9 | [
"MIT"
] | null | null | null | #pragma
#include "morphotree/core/alias.hpp"
#include "morphotree/attributes/attributeComputer.hpp"
#include "morphotree/core/box.hpp"
#include "morphotree/core/point.hpp"
// Implementation based on
// Connected Attribute Filtering Based on Contour Smoothness
// G. K. Ouzounis, E. R. Urbach, M. H. F. Wilkison
namespace morphotree
{
// ================= MAX-TREE ==============================================
template<class ValueType>
class MaxTreeSmoothnessContourComputer : public AttributeComputer<float, ValueType>
{
public:
using AttrType = float;
using TreeType = typename AttributeComputer<float, ValueType>::TreeType;
using NodePtr = typename TreeType::NodePtr;
MaxTreeSmoothnessContourComputer(Box domain, const std::vector<ValueType> &image);
std::vector<float> initAttributes(const TreeType &tree);
void computeInitialValue(std::vector<float> &attr, NodePtr node);
void mergeToParent(std::vector<float> &attr, NodePtr node, NodePtr parent);
void finaliseComputation(std::vector<float> &attr, NodePtr node);
private:
Box domain_;
const std::vector<ValueType> &image_;
std::vector<uint32> area_;
std::vector<uint32> perimeter_;
std::vector<int32> sumX_;
std::vector<int32> sumY_;
std::vector<int32> sumXAndYSquared_;
constexpr static float PiSquared = 9.86960440109f;
const std::array<I32Point, 4> offsets_ = {
I32Point{-1,0}, I32Point{0,-1}, I32Point{1, 0}, I32Point{0,1}};
};
// ======================[ MIN-TREE ]================================================
template<class ValueType>
class MinTreeSmoothnessContourComputer : public AttributeComputer<float, ValueType>
{
public:
using AttrType = float;
using TreeType = typename AttributeComputer<float, ValueType>::TreeType;
using NodePtr = typename TreeType::NodePtr;
MinTreeSmoothnessContourComputer(Box domain, const std::vector<ValueType> &image);
std::vector<float> initAttributes(const TreeType &tree);
void computeInitialValue(std::vector<float> &attr, NodePtr node);
void mergeToParent(std::vector<float> &attr, NodePtr node, NodePtr parent);
void finaliseComputation(std::vector<float> &attr, NodePtr node);
private:
Box domain_;
const std::vector<ValueType> &image_;
std::vector<uint32> area_;
std::vector<uint32> perimeter_;
std::vector<int32> sumX_;
std::vector<int32> sumY_;
std::vector<int32> sumXAndYSquared_;
constexpr static float PiSquared = 9.86960440109f;
const std::array<I32Point, 4> offsets_ = {
I32Point{-1,0}, I32Point{0,-1}, I32Point{1, 0}, I32Point{0,1}};
};
// ======================[ TREE OF SHAPES ] ================================================
template<class ValueType>
class TreeOfShapesSmoothnessContourComputer : public AttributeComputer<float, ValueType>
{
public:
using AttrType = float;
using TreeType = typename AttributeComputer<float, ValueType>::TreeType;
using NodePtr = typename TreeType::NodePtr;
TreeOfShapesSmoothnessContourComputer(Box domain, const std::vector<ValueType> &image);
std::vector<float> initAttributes(const TreeType &tree);
void computeInitialValue(std::vector<float> &attr, NodePtr node);
void mergeToParent(std::vector<float> &attr, NodePtr node, NodePtr parent);
void finaliseComputation(std::vector<float> &attr, NodePtr node);
private:
enum class NodeType { MaxTreeNodeType, MinTreeNodeType, Unknown };
NodeType nodeType(const NodePtr node);
void computeInitialPerimeterMaxTree(const NodePtr node);
void computeInitialPerimeterMinTree(const NodePtr node);
void computePerimeterRootNode(const NodePtr node);
private:
Box domain_;
std::vector<ValueType> image_;
std::vector<uint32> area_;
std::vector<uint32> perimeter_;
std::vector<int32> sumX_;
std::vector<int32> sumY_;
std::vector<int32> sumXAndYSquared_;
constexpr static float PiSquared = 9.86960440109f;
const std::array<I32Point, 4> offsets_ = {
I32Point{-1,0}, I32Point{0,-1}, I32Point{1, 0}, I32Point{0,1}};
};
// ======================[ Implementation ] ================================================
template<class ValueType>
MaxTreeSmoothnessContourComputer<ValueType>::MaxTreeSmoothnessContourComputer(Box domain,
const std::vector<ValueType> &image)
:domain_{domain}, image_{image}
{}
template<class ValueType>
std::vector<float> MaxTreeSmoothnessContourComputer<ValueType>::initAttributes(
const TreeType &tree)
{
area_.clear();
perimeter_.clear();
sumX_.clear();
sumY_.clear();
sumXAndYSquared_.clear();
area_.resize(tree.numberOfNodes(), 0);
perimeter_.resize(tree.numberOfNodes(), 0);
sumX_.resize(tree.numberOfNodes(), 0);
sumY_.resize(tree.numberOfNodes(), 0);
sumXAndYSquared_.resize(tree.numberOfNodes(), 0);
return std::vector<float>(tree.numberOfNodes(), 0.0f);
}
template<class ValueType>
void MaxTreeSmoothnessContourComputer<ValueType>::computeInitialValue(std::vector<float> &attr,
NodePtr node)
{
area_[node->id()] += node->cnps().size();
for (uint32 pidx : node->cnps()) {
int32 H = 0, L = 0;
I32Point p = domain_.indexToPoint(pidx);
for (const I32Point &offset : offsets_) {
I32Point q = p + offset;
if (!domain_.contains(q) || image_[domain_.pointToIndex(q)] < node->level()) {
L++;
}
else if (image_[domain_.pointToIndex(q)] > node->level()) {
H++;
}
}
perimeter_[node->id()] += L - H;
sumX_[node->id()] += p.x();
sumY_[node->id()] += p.y();
sumXAndYSquared_[node->id()] += (p.x() * p.x()) + (p.y() * p.y());
}
}
template<class ValueType>
void MaxTreeSmoothnessContourComputer<ValueType>::mergeToParent(std::vector<float> &attr,
NodePtr node, NodePtr parent)
{
area_[parent->id()] += area_[node->id()];
perimeter_[parent->id()] += perimeter_[node->id()];
sumX_[parent->id()] += sumX_[node->id()];
sumY_[parent->id()] += sumY_[node->id()];
sumXAndYSquared_[parent->id()] += sumXAndYSquared_[node->id()];
}
template<class ValueType>
void MaxTreeSmoothnessContourComputer<ValueType>::finaliseComputation(std::vector<float> &attr,
NodePtr node)
{
float I = float(sumXAndYSquared_[node->id()])
- (float(sumX_[node->id()] * sumX_[node->id()]) / float(area_[node->id()]))
- (float(sumY_[node->id()] * sumY_[node->id()]) / float(area_[node->id()]))
+ (float(area_[node->id()]) / 6.0f);
attr[node->id()] =
(float(area_[node->id()]) * float(perimeter_[node->id()] * perimeter_[node->id()])) /
(8.0f * I * PiSquared);
}
// =====================[ IMPLEMENTATION MIN-TREE ] ================================================
template<class ValueType>
MinTreeSmoothnessContourComputer<ValueType>::MinTreeSmoothnessContourComputer(Box domain,
const std::vector<ValueType> &image)
:domain_{domain}, image_{image}
{}
template<class ValueType>
std::vector<float> MinTreeSmoothnessContourComputer<ValueType>::initAttributes(
const TreeType &tree)
{
area_.clear();
perimeter_.clear();
sumX_.clear();
sumY_.clear();
sumXAndYSquared_.clear();
area_.resize(tree.numberOfNodes(), 0);
perimeter_.resize(tree.numberOfNodes(), 0);
sumX_.resize(tree.numberOfNodes(), 0);
sumY_.resize(tree.numberOfNodes(), 0);
sumXAndYSquared_.resize(tree.numberOfNodes(), 0);
return std::vector<float>(tree.numberOfNodes(), 0.0f);
}
template<class ValueType>
void MinTreeSmoothnessContourComputer<ValueType>::computeInitialValue(std::vector<float> &attr,
NodePtr node)
{
area_[node->id()] += node->cnps().size();
for (uint32 pidx : node->cnps()) {
int32 H = 0, L = 0;
I32Point p = domain_.indexToPoint(pidx);
for (const I32Point &offset : offsets_) {
I32Point q = p + offset;
if (!domain_.contains(q) || image_[domain_.pointToIndex(q)] > node->level()) {
H++;
}
else if (image_[domain_.pointToIndex(q)] < node->level()) {
L++;
}
}
perimeter_[node->id()] += H - L;
sumX_[node->id()] += p.x();
sumY_[node->id()] += p.y();
sumXAndYSquared_[node->id()] += ((p.x() * p.x()) + (p.y() * p.y()));
}
}
template<class ValueType>
void MinTreeSmoothnessContourComputer<ValueType>::mergeToParent(std::vector<float> &attr,
NodePtr node, NodePtr parent)
{
area_[parent->id()] += area_[node->id()];
perimeter_[parent->id()] += perimeter_[node->id()];
sumX_[parent->id()] += sumX_[node->id()];
sumY_[parent->id()] += sumY_[node->id()];
sumXAndYSquared_[parent->id()] += sumXAndYSquared_[node->id()];
}
template<class ValueType>
void MinTreeSmoothnessContourComputer<ValueType>::finaliseComputation(std::vector<float> &attr,
NodePtr node)
{
float I = float(sumXAndYSquared_[node->id()])
- (float(sumX_[node->id()] * sumX_[node->id()]) / float(area_[node->id()]))
- (float(sumY_[node->id()] * sumY_[node->id()]) / float(area_[node->id()]))
+ (float(area_[node->id()]) / 6.0f);
attr[node->id()] =
(float(area_[node->id()]) * float(perimeter_[node->id()] * perimeter_[node->id()])) /
(8.0f * I * PiSquared);
}
// ==================== [ IMPLEMENTATION - TREE OF SHAPES ] =============================================
template<class ValueType>
TreeOfShapesSmoothnessContourComputer<ValueType>::TreeOfShapesSmoothnessContourComputer(Box domain,
const std::vector<ValueType> &image)
:domain_{domain}, image_{image}
{}
template<class ValueType>
std::vector<float> TreeOfShapesSmoothnessContourComputer<ValueType>::initAttributes(
const TreeType &tree)
{
area_.clear();
perimeter_.clear();
sumX_.clear();
sumY_.clear();
sumXAndYSquared_.clear();
area_.resize(tree.numberOfNodes(), 0);
perimeter_.resize(tree.numberOfNodes(), 0);
sumX_.resize(tree.numberOfNodes(), 0);
sumY_.resize(tree.numberOfNodes(), 0);
sumXAndYSquared_.resize(tree.numberOfNodes(), 0);
return std::vector<float>(tree.numberOfNodes(), 0.0f);
}
template<class ValueType>
void TreeOfShapesSmoothnessContourComputer<ValueType>::computeInitialValue(std::vector<float> &attr,
NodePtr node)
{
area_[node->id()] += node->cnps().size();
if (nodeType(node) == NodeType::MaxTreeNodeType)
computeInitialPerimeterMaxTree(node);
else if (nodeType(node) == NodeType::MinTreeNodeType)
computeInitialPerimeterMinTree(node);
else {
for (uint32 pidx: node->cnps()) {
I32Point p = domain_.indexToPoint(pidx);
sumX_[node->id()] += p.x();
sumY_[node->id()] += p.y();
sumXAndYSquared_[node->id()] += ((p.x() * p.x()) + (p.y() * p.y()));
}
}
}
template<class ValueType>
typename TreeOfShapesSmoothnessContourComputer<ValueType>::NodeType
TreeOfShapesSmoothnessContourComputer<ValueType>::nodeType(const NodePtr node)
{
if (node->parent() == nullptr)
return NodeType::Unknown;
else if (node->parent()->level() < node->level())
return NodeType::MaxTreeNodeType;
else if (node->parent()->level() > node->level())
return NodeType::MinTreeNodeType;
return NodeType::Unknown;
}
template<class ValueType>
void TreeOfShapesSmoothnessContourComputer<ValueType>::computeInitialPerimeterMaxTree(
NodePtr node)
{
for (uint32 pidx : node->cnps()) {
int32 H = 0, L = 0;
I32Point p = domain_.indexToPoint(pidx);
for (const I32Point &offset : offsets_) {
I32Point q = p + offset;
if (!domain_.contains(q) || image_[domain_.pointToIndex(q)] < node->level()) {
L++;
}
else if (image_[domain_.pointToIndex(q)] > node->level()) {
H++;
}
}
perimeter_[node->id()] += L - H;
sumX_[node->id()] += p.x();
sumY_[node->id()] += p.y();
sumXAndYSquared_[node->id()] += (p.x() * p.x()) + (p.y() * p.y());
}
}
template<class ValueType>
void TreeOfShapesSmoothnessContourComputer<ValueType>::computeInitialPerimeterMinTree(
NodePtr node)
{
for (uint32 pidx : node->cnps()) {
int32 H = 0, L = 0;
I32Point p = domain_.indexToPoint(pidx);
for (const I32Point &offset : offsets_) {
I32Point q = p + offset;
if (!domain_.contains(q) || image_[domain_.pointToIndex(q)] > node->level()) {
H++;
}
else if (image_[domain_.pointToIndex(q)] < node->level()) {
L++;
}
}
perimeter_[node->id()] += H - L;
sumX_[node->id()] += p.x();
sumY_[node->id()] += p.y();
sumXAndYSquared_[node->id()] += ((p.x() * p.x()) + (p.y() * p.y()));
}
}
template<class ValueType>
void TreeOfShapesSmoothnessContourComputer<ValueType>::computePerimeterRootNode(
const NodePtr node)
{
perimeter_[node->id()] = (2*domain_.width()) + (2*domain_.height());
}
template<class ValueType>
void TreeOfShapesSmoothnessContourComputer<ValueType>::mergeToParent(std::vector<float> &attr,
NodePtr node, NodePtr parent)
{
area_[parent->id()] += area_[node->id()];
if (nodeType(node) == nodeType(parent))
perimeter_[parent->id()] += perimeter_[node->id()];
else
perimeter_[parent->id()] -= perimeter_[node->id()];
sumX_[parent->id()] += sumX_[node->id()];
sumY_[parent->id()] += sumY_[node->id()];
sumXAndYSquared_[parent->id()] += sumXAndYSquared_[node->id()];
}
template<class ValueType>
void TreeOfShapesSmoothnessContourComputer<ValueType>::finaliseComputation(std::vector<float> &attr,
NodePtr node)
{
if (node->parent() == nullptr) // if node is the root node.
computePerimeterRootNode(node);
float I = float(sumXAndYSquared_[node->id()])
- (float(sumX_[node->id()] * sumX_[node->id()]) / float(area_[node->id()]))
- (float(sumY_[node->id()] * sumY_[node->id()]) / float(area_[node->id()]))
+ (float(area_[node->id()]) / 6.0f);
// std::cout << "node id: " << node->id() << "; I: " << I
// << "; area: " << area_[node->id()] << "; perimeter: " << perimeter_[node->id()] << std::endl;
// std::cout << "sum x and y squared: " << sumXAndYSquared_[node->id()]
// << "; sumX: " << sumX_[node->id()] << "; sumY: " << sumY_[node->id()] << std::endl;
// std::cout << "sumX^2: " << (float(sumX_[node->id()] * sumX_[node->id()]) / float(area_[node->id()])) << "; sumY^2: "
// << (float(sumY_[node->id()] * sumY_[node->id()]) / float(area_[node->id()])) << "; A/6: "
// << (float(area_[node->id()]) / 6.0f) << std::endl;
// std::cout << (float(area_[node->id()]) * float(perimeter_[node->id()] * perimeter_[node->id()])) << " / "
// << (8.0f * I * PiSquared) << "\n\n";
attr[node->id()] =
(float(area_[node->id()]) * float(perimeter_[node->id()] * perimeter_[node->id()])) /
(8.0f * I * PiSquared);
}
} | 35.320093 | 123 | 0.614805 | [
"vector"
] |
f0f68ff6ca92686c6628bc0397cf6969aafbb1a3 | 12,297 | cpp | C++ | catkin_ws/src/srrg2_core/srrg2_core/tests/test_message_sources.cpp | laaners/progetto-labiagi_pick_e_delivery | 3453bfbc1dd7562c78ba06c0f79b069b0a952c0e | [
"MIT"
] | null | null | null | catkin_ws/src/srrg2_core/srrg2_core/tests/test_message_sources.cpp | laaners/progetto-labiagi_pick_e_delivery | 3453bfbc1dd7562c78ba06c0f79b069b0a952c0e | [
"MIT"
] | null | null | null | catkin_ws/src/srrg2_core/srrg2_core/tests/test_message_sources.cpp | laaners/progetto-labiagi_pick_e_delivery | 3453bfbc1dd7562c78ba06c0f79b069b0a952c0e | [
"MIT"
] | null | null | null | #include "srrg_messages/instances.h"
#include <srrg_data_structures/platform.h>
#include <srrg_messages/instances.h>
#include <srrg_messages/messages/grid_map_message.h>
#include <srrg_property/property_container.h>
#include <srrg_messages/messages/imu_message.h>
#include <srrg_messages/messages/joints_message.h>
#include <srrg_messages/messages/image_message.h>
#include <srrg_messages/messages/laser_message.h>
#include <srrg_messages/messages/range_message.h>
#include <srrg_messages/messages/camera_info_message.h>
#include <srrg_messages/messages/transform_events_message.h>
#include <srrg_messages/messages/odometry_message.h>
#include <srrg_messages/messages/point_cloud2_message.h>
#include <srrg_messages/messages/point_stamped_message.h>
#include <srrg_messages/messages/twist_stamped_message.h>
#include <srrg_messages/messages/navsat_fix_message.h>
#include <srrg_messages/messages/pose_stamped_message.h>
#include <srrg_messages/messages/pose_with_covariance_stamped_message.h>
#include <srrg_messages/messages/pose_array_message.h>
#include <srrg_messages/messages/path_message.h>
#include <srrg_messages/messages/cmd_vel_message.h>
#include <srrg_messages/message_handlers/message_file_source.h>
#include <srrg_messages/message_handlers/message_file_sink.h>
#include <srrg_messages/message_handlers/message_sorted_source.h>
#include <srrg_messages/message_handlers/message_synchronized_source.h>
#include <srrg_messages/message_handlers/message_pack.h>
#include "srrg_test/test_helper.hpp"
using namespace srrg2_core;
// ds test helper function
void generateMessagesOnDisk(const std::string& file_name_,
const size_t number_of_messages_,
const std::vector<std::string> topics_,
const std::vector<double>& time_offsets_,
bool alternate_topic_order = false) {
Serializer serializer;
serializer.setFilePath(file_name_);
for (size_t index_message = 0; index_message < number_of_messages_; ++index_message) {
const double timestamp_seconds = index_message / 10.0;
if (alternate_topic_order && index_message % 2) {
for (int64_t index_topic = topics_.size() - 1; index_topic >= 0; --index_topic) {
const std::string& topic = topics_[index_topic];
PointStampedMessagePtr message(new PointStampedMessage(
topic, topic, index_message, timestamp_seconds + time_offsets_[index_topic]));
serializer.writeObject(*message);
}
} else {
for (size_t index_topic = 0; index_topic < topics_.size(); ++index_topic) {
const std::string& topic = topics_[index_topic];
PointStampedMessagePtr message(new PointStampedMessage(
topic, topic, index_message, timestamp_seconds + time_offsets_[index_topic]));
serializer.writeObject(*message);
}
}
}
}
int main(int argc_, char** argv_) {
messages_registerTypes();
return srrg2_test::runTests(argc_, argv_);
}
TEST(MessageSynchronizedSource, ConstructionAndDestruction) {
MessageFileSourcePtr source(new MessageFileSource());
MessageSortedSourcePtr sorter(new MessageSortedSource());
MessageSynchronizedSourcePtr synchronized_source(new MessageSynchronizedSource());
}
TEST(MessageSynchronizedSource, ValidTopics_NoTimeOffset) {
const std::string message_file_name = "test_messages.json";
constexpr size_t number_of_messages = 10;
const std::vector<std::string> topics = {"/topic0", "/topic1"};
const std::vector<double> time_offsets = {0, 0};
generateMessagesOnDisk(message_file_name, number_of_messages, topics, time_offsets);
// ds configure a synchronized message source
MessageFileSourcePtr source(new MessageFileSource());
MessageSortedSourcePtr sorter(new MessageSortedSource());
sorter->param_source.setValue(source);
sorter->param_time_interval.setValue(1e-5);
MessageSynchronizedSourcePtr synchronized_source(new MessageSynchronizedSource());
synchronized_source->param_source.setValue(sorter);
synchronized_source->param_topics.value().push_back(topics[0]);
synchronized_source->param_topics.value().push_back(topics[1]);
synchronized_source->param_time_interval.setValue(1e-5);
// ds open a synthetic message file
source->open(message_file_name);
ASSERT_TRUE(source->isOpen());
ASSERT_EQ(source->param_filename.value(), message_file_name);
// ds process messages
size_t number_of_processed_message_packs = 0;
while (BaseSensorMessagePtr message = synchronized_source->getMessage()) {
// ASSERT_TRUE(synchronized_source->isOpen()); //ds TODO why is this FALSE?
MessagePackPtr message_pack = std::dynamic_pointer_cast<MessagePack>(message);
ASSERT_NOTNULL(message_pack);
++number_of_processed_message_packs;
}
ASSERT_EQ(number_of_processed_message_packs, number_of_messages);
ASSERT_EQ(synchronized_source->numDroppedMessages(), 0);
source->close();
ASSERT_FALSE(source->isOpen());
ASSERT_FALSE(synchronized_source->isOpen());
}
TEST(MessageSynchronizedSource, InvalidTopics_NoTimeOffset) {
const std::string message_file_name = "test_messages.json";
constexpr size_t number_of_messages = 10;
const std::vector<std::string> topics = {"/topic0", "/topic1"};
const std::vector<double> time_offsets = {0, 0};
generateMessagesOnDisk(message_file_name, number_of_messages, topics, time_offsets);
// ds configure a synchronized message source
MessageFileSourcePtr source(new MessageFileSource());
MessageSortedSourcePtr sorter(new MessageSortedSource());
sorter->param_source.setValue(source);
sorter->param_time_interval.setValue(1e-5);
MessageSynchronizedSourcePtr synchronized_source(new MessageSynchronizedSource());
synchronized_source->param_source.setValue(sorter);
synchronized_source->param_topics.value().push_back("/mirco");
synchronized_source->param_topics.value().push_back("/micro");
synchronized_source->param_time_interval.setValue(1e-5);
// ds open a synthetic message file
source->open(message_file_name);
ASSERT_TRUE(source->isOpen());
ASSERT_EQ(source->param_filename.value(), message_file_name);
// ds process messages
size_t number_of_processed_message_packs = 0;
while (BaseSensorMessagePtr message = synchronized_source->getMessage()) {
// ASSERT_TRUE(synchronized_source->isOpen()); //ds TODO why is this FALSE?
MessagePackPtr message_pack = std::dynamic_pointer_cast<MessagePack>(message);
ASSERT_NOTNULL(message_pack);
++number_of_processed_message_packs;
}
ASSERT_EQ(number_of_processed_message_packs, static_cast<size_t>(0));
ASSERT_EQ(synchronized_source->numDroppedMessages(), 0); // ds TODO no drops intended?
source->close();
ASSERT_FALSE(source->isOpen());
ASSERT_FALSE(synchronized_source->isOpen());
}
TEST(MessageSynchronizedSource, ValidTopics_TolerableTimeOffset) {
const std::string message_file_name = "test_messages.json";
constexpr size_t number_of_messages = 10;
const std::vector<std::string> topics = {"/topic0", "/topic1"};
const std::vector<double> time_offsets = {-1e-6, 1e-6};
generateMessagesOnDisk(message_file_name, number_of_messages, topics, time_offsets);
// ds configure a synchronized message source
MessageFileSourcePtr source(new MessageFileSource());
MessageSortedSourcePtr sorter(new MessageSortedSource());
sorter->param_source.setValue(source);
sorter->param_time_interval.setValue(1e-5);
MessageSynchronizedSourcePtr synchronized_source(new MessageSynchronizedSource());
synchronized_source->param_source.setValue(sorter);
synchronized_source->param_topics.value().push_back(topics[0]);
synchronized_source->param_topics.value().push_back(topics[1]);
synchronized_source->param_time_interval.setValue(1e-5);
// ds open a synthetic message file
source->open(message_file_name);
ASSERT_TRUE(source->isOpen());
ASSERT_EQ(source->param_filename.value(), message_file_name);
// ds process messages
size_t number_of_processed_message_packs = 0;
while (BaseSensorMessagePtr message = synchronized_source->getMessage()) {
// ASSERT_TRUE(synchronized_source->isOpen()); //ds TODO why is this FALSE?
MessagePackPtr message_pack = std::dynamic_pointer_cast<MessagePack>(message);
ASSERT_NOTNULL(message_pack);
++number_of_processed_message_packs;
}
ASSERT_EQ(number_of_processed_message_packs, number_of_messages);
ASSERT_EQ(synchronized_source->numDroppedMessages(), 0);
source->close();
ASSERT_FALSE(source->isOpen());
ASSERT_FALSE(synchronized_source->isOpen());
}
TEST(MessageSynchronizedSource, ValidTopics_IntolerableTimeOffset) {
const std::string message_file_name = "test_messages.json";
constexpr size_t number_of_messages = 10;
const std::vector<std::string> topics = {"/topic0", "/topic1"};
const std::vector<double> time_offsets = {-0.01, 0.01};
generateMessagesOnDisk(message_file_name, number_of_messages, topics, time_offsets);
// ds configure a synchronized message source
MessageFileSourcePtr source(new MessageFileSource());
MessageSortedSourcePtr sorter(new MessageSortedSource());
sorter->param_source.setValue(source);
sorter->param_time_interval.setValue(1e-5);
MessageSynchronizedSourcePtr synchronized_source(new MessageSynchronizedSource());
synchronized_source->param_source.setValue(sorter);
synchronized_source->param_topics.value().push_back(topics[0]);
synchronized_source->param_topics.value().push_back(topics[1]);
synchronized_source->param_time_interval.setValue(1e-5);
// ds open a synthetic message file
source->open(message_file_name);
ASSERT_TRUE(source->isOpen());
ASSERT_EQ(source->param_filename.value(), message_file_name);
// ds process messages
size_t number_of_processed_message_packs = 0;
while (BaseSensorMessagePtr message = synchronized_source->getMessage()) {
// ASSERT_TRUE(synchronized_source->isOpen()); //ds TODO why is this FALSE?
MessagePackPtr message_pack = std::dynamic_pointer_cast<MessagePack>(message);
ASSERT_NOTNULL(message_pack);
++number_of_processed_message_packs;
}
ASSERT_EQ(number_of_processed_message_packs, size_t(0));
// ds TODO why not 20 dropped messages?
ASSERT_EQ(static_cast<size_t>(synchronized_source->numDroppedMessages()),
2 * number_of_messages - 2);
source->close();
ASSERT_FALSE(source->isOpen());
ASSERT_FALSE(synchronized_source->isOpen());
}
TEST(MessageSynchronizedSource, ValidTopics_ShuffledTimeOffset) {
const std::string message_file_name = "test_messages.json";
constexpr size_t number_of_messages = 10;
const std::vector<std::string> topics = {"/topic0", "/topic1", "/topic2"};
const std::vector<double> time_offsets = {123456789.01, 123456789.02, 123456789.03};
generateMessagesOnDisk(message_file_name, number_of_messages, topics, time_offsets, true);
// ds configure a synchronized message source
MessageFileSourcePtr source(new MessageFileSource());
MessageSortedSourcePtr sorter(new MessageSortedSource());
sorter->param_source.setValue(source);
sorter->param_time_interval.setValue(0.05);
MessageSynchronizedSourcePtr synchronized_source(new MessageSynchronizedSource());
synchronized_source->param_source.setValue(sorter);
synchronized_source->param_topics.value().push_back(topics[0]);
synchronized_source->param_topics.value().push_back(topics[1]);
synchronized_source->param_topics.value().push_back(topics[2]);
synchronized_source->param_time_interval.setValue(0.05);
// ds open a synthetic message file
source->open(message_file_name);
ASSERT_TRUE(source->isOpen());
ASSERT_EQ(source->param_filename.value(), message_file_name);
// ds process messages
size_t number_of_processed_message_packs = 0;
while (BaseSensorMessagePtr message = synchronized_source->getMessage()) {
// ASSERT_TRUE(synchronized_source->isOpen()); //ds TODO why is this FALSE?
MessagePackPtr message_pack = std::dynamic_pointer_cast<MessagePack>(message);
ASSERT_NOTNULL(message_pack);
++number_of_processed_message_packs;
}
ASSERT_EQ(number_of_processed_message_packs, number_of_messages);
ASSERT_EQ(synchronized_source->numDroppedMessages(), 0);
source->close();
ASSERT_FALSE(source->isOpen());
ASSERT_FALSE(synchronized_source->isOpen());
}
| 45.884328 | 92 | 0.773847 | [
"vector"
] |
f0f7b50cbd3d59226931c26e590dbb54025e5be7 | 2,997 | hpp | C++ | IO/src/av/include/hwDevice.hpp | tlalexander/stitchEm | cdff821ad2c500703e6cb237ec61139fce7bf11c | [
"MIT"
] | 182 | 2019-04-19T12:38:30.000Z | 2022-03-20T16:48:20.000Z | IO/src/av/include/hwDevice.hpp | tlalexander/stitchEm | cdff821ad2c500703e6cb237ec61139fce7bf11c | [
"MIT"
] | 107 | 2019-04-23T10:49:35.000Z | 2022-03-02T18:12:28.000Z | IO/src/av/include/hwDevice.hpp | tlalexander/stitchEm | cdff821ad2c500703e6cb237ec61139fce7bf11c | [
"MIT"
] | 59 | 2019-06-04T11:27:25.000Z | 2022-03-17T23:49:49.000Z | /* ****************************************************************************** *\
INTEL CORPORATION PROPRIETARY INFORMATION
This software is supplied under the terms of a license agreement or nondisclosure
agreement with Intel Corporation and may not be copied or disclosed except in
accordance with the terms of that agreement
Copyright(c) 2013 Intel Corporation. All Rights Reserved.
\* ****************************************************************************** */
#pragma once
#include "mfxvideo.h"
#if defined(WIN32) || defined(WIN64)
#ifndef D3D_SURFACES_SUPPORT
#define D3D_SURFACES_SUPPORT 1
#endif
#if defined(_WIN32) && !defined(MFX_D3D11_SUPPORT)
#include <sdkddkver.h>
#if (NTDDI_VERSION >= NTDDI_VERSION_FROM_WIN32_WINNT2(0x0602)) // >= _WIN32_WINNT_WIN8
#define MFX_D3D11_SUPPORT 1 // Enable D3D11 support if SDK allows
#else
#define MFX_D3D11_SUPPORT 0
#endif
#endif // #if defined(WIN32) && !defined(MFX_D3D11_SUPPORT)
#endif // #if defined(WIN32) || defined(WIN64)
#define MSDK_ZERO_MEMORY(VAR) \
{ memset(&VAR, 0, sizeof(VAR)); }
#define MSDK_MEMCPY_VAR(dstVarName, src, count) memcpy_s(&(dstVarName), sizeof(dstVarName), (src), (count))
#define MSDK_SAFE_RELEASE(X) \
{ \
if (X) { \
X->Release(); \
X = NULL; \
} \
}
#define MSDK_CHECK_RESULT(P, X, ERR) \
{ \
if ((X) > (P)) { \
MSDK_PRINT_RET_MSG(ERR); \
return ERR; \
} \
}
#define MSDK_CHECK_POINTER(P, ...) \
{ \
if (!(P)) { \
return __VA_ARGS__; \
} \
}
#define MSDK_ARRAY_LEN(value) (sizeof(value) / sizeof(value[0]))
enum {
MFX_HANDLE_GFXS3DCONTROL = 0x100, /* A handle to the IGFXS3DControl instance */
MFX_HANDLE_DEVICEWINDOW = 0x101 /* A handle to the render window */
}; // mfxHandleType
/// Base class for hw device
class CHWDevice {
public:
virtual ~CHWDevice() {}
/** Initializes device for requested processing.
@param[in] hWindow Window handle to bundle device to.
@param[in] nViews Number of views to process.
@param[in] nAdapterNum Number of adapter to use
*/
virtual mfxStatus Init(mfxHDL hWindow, mfxU16 nViews, mfxU32 nAdapterNum) = 0;
/// Reset device.
virtual mfxStatus Reset() = 0;
/// Get handle can be used for MFX session SetHandle calls
virtual mfxStatus GetHandle(mfxHandleType type, mfxHDL *pHdl) = 0;
/** Set handle.
Particular device implementation may require other objects to operate.
*/
virtual mfxStatus SetHandle(mfxHandleType type, mfxHDL hdl) = 0;
virtual mfxStatus RenderFrame(mfxFrameSurface1 *pSurface, mfxFrameAllocator *pmfxAlloc) = 0;
virtual void UpdateTitle(double fps) = 0;
virtual void Close() = 0;
};
| 36.54878 | 107 | 0.585919 | [
"render"
] |
f0feb3f4834dafed79a1c65228e9e56851a3e870 | 51,379 | cpp | C++ | dev/Code/Framework/Tests/ComponentAddRemove.cpp | stickyparticles/lumberyard | dc523dd780f3cd1874251181b7cf6848b8db9959 | [
"AML"
] | 2 | 2018-03-29T10:56:36.000Z | 2020-12-12T15:28:14.000Z | dev/Code/Framework/Tests/ComponentAddRemove.cpp | JulianoCristian/Lumberyard-3 | dc523dd780f3cd1874251181b7cf6848b8db9959 | [
"AML"
] | null | null | null | dev/Code/Framework/Tests/ComponentAddRemove.cpp | JulianoCristian/Lumberyard-3 | dc523dd780f3cd1874251181b7cf6848b8db9959 | [
"AML"
] | 3 | 2019-05-13T09:41:33.000Z | 2021-04-09T12:12:38.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "Tests/TestTypes.h"
#include <AzToolsFramework/Application/ToolsApplication.h>
#include <AzToolsFramework/ToolsComponents/GenericComponentWrapper.h>
#include <AzCore/Outcome/Outcome.h>
#include <AzToolsFramework/Entity/EditorEntityHelpers.h>
#include <AzToolsFramework/ToolsComponents/EditorDisabledCompositionBus.h>
#include <AzToolsFramework/ToolsComponents/EditorPendingCompositionBus.h>
#include <AzToolsFramework/Entity/EditorEntityContextBus.h>
namespace UnitTest
{
//
// Declaring several clothing-themed components for use in tests.
//
// Shoes require socks
class LeatherBootsComponent
: public AZ::Component
{
public:
AZ_COMPONENT(LeatherBootsComponent, "{C2852908-0FC6-4BF6-9907-E390840F9897}");
void Activate() override {}
void Deactivate() override {}
static void Reflect(AZ::ReflectContext* reflection)
{
if (auto* serializeContext = azrtti_cast<AZ::SerializeContext*>(reflection))
{
serializeContext->Class<LeatherBootsComponent>()->SerializerForEmptyClass();
if (AZ::EditContext* editContext = serializeContext->GetEditContext())
{
editContext->Class<LeatherBootsComponent>("Leather Boots", "")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game"));
}
}
}
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
{
provided.push_back(AZ_CRC("ShoesService", 0xaa20aadf));
}
static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible)
{
incompatible.push_back(AZ_CRC("ShoesService", 0xaa20aadf));
}
static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required)
{
required.push_back(AZ_CRC("SocksService", 0x51e58440));
}
};
// Note that WoolSocksComponent is an "editor component".
// This is just to make sure we are testing with both "editor"
// and "non-editor" components.
class WoolSocksComponent
: public AzToolsFramework::Components::EditorComponentBase
{
public:
AZ_COMPONENT(WoolSocksComponent, "{6436A9A1-701E-4275-AF6F-82F53C7916C8}", EditorComponentBase);
void Activate() override {}
void Deactivate() override {}
static void Reflect(AZ::ReflectContext* reflection)
{
if (auto* serializeContext = azrtti_cast<AZ::SerializeContext*>(reflection))
{
serializeContext->Class<WoolSocksComponent, EditorComponentBase>()->SerializerForEmptyClass();
if (AZ::EditContext* editContext = serializeContext->GetEditContext())
{
editContext->Class<WoolSocksComponent>("Wool Socks", "")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game"));
}
}
}
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
{
provided.push_back(AZ_CRC("SocksService", 0x51e58440));
}
static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible)
{
incompatible.push_back(AZ_CRC("SocksService", 0x51e58440));
}
static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& /*required*/)
{
}
};
// Incompatible with socks
class HatesSocksComponent
: public AZ::Component
{
public:
AZ_COMPONENT(HatesSocksComponent, "{D359D446-A172-4854-8EA9-B95073FF5709}");
void Activate() override {}
void Deactivate() override {}
static void Reflect(AZ::ReflectContext* reflection)
{
if (auto* serializeContext = azrtti_cast<AZ::SerializeContext*>(reflection))
{
serializeContext->Class<HatesSocksComponent>()->SerializerForEmptyClass();
if (AZ::EditContext* editContext = serializeContext->GetEditContext())
{
editContext->Class<HatesSocksComponent>("Hates Socks", "")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game"));
}
}
}
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& /*provided*/)
{
}
static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible)
{
incompatible.push_back(AZ_CRC("SocksService", 0x51e58440));
}
static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& /*required*/)
{
}
};
// Pants require underwear
class BlueJeansComponent
: public AZ::Component
{
public:
AZ_COMPONENT(BlueJeansComponent, "{AEA4D69E-F02B-4F6D-A793-8DEE0C0E54E3}");
void Activate() override {}
void Deactivate() override {}
static void Reflect(AZ::ReflectContext* reflection)
{
if (auto* serializeContext = azrtti_cast<AZ::SerializeContext*>(reflection))
{
serializeContext->Class<BlueJeansComponent>()->SerializerForEmptyClass();
if (AZ::EditContext* editContext = serializeContext->GetEditContext())
{
editContext->Class<BlueJeansComponent>("Blue Jeans", "")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game"));
}
}
}
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
{
provided.push_back(AZ_CRC("TrousersService", 0x15edf105));
}
static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible)
{
incompatible.push_back(AZ_CRC("TrousersService", 0x15edf105));
}
static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required)
{
required.push_back(AZ_CRC("UnderwearService", 0x915ec03a));
}
};
// 1 of 2 underwear styles
class WhiteBriefsComponent
: public AZ::Component
{
public:
AZ_COMPONENT(WhiteBriefsComponent, "{8B095E11-082B-4EB1-A119-D1534323C956}");
void Activate() override {}
void Deactivate() override {}
static void Reflect(AZ::ReflectContext* reflection)
{
if (auto* serializeContext = azrtti_cast<AZ::SerializeContext*>(reflection))
{
serializeContext->Class<WhiteBriefsComponent>()->SerializerForEmptyClass();
if (AZ::EditContext* editContext = serializeContext->GetEditContext())
{
editContext->Class<WhiteBriefsComponent>("White Briefs", "")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game"));
}
}
}
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
{
provided.push_back(AZ_CRC("UnderwearService", 0x915ec03a));
}
static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible)
{
incompatible.push_back(AZ_CRC("UnderwearService", 0x915ec03a));
}
static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& /*required*/)
{
}
};
// 2 of 2 underwear styles
class HeartBoxersComponent
: public AZ::Component
{
public:
AZ_COMPONENT(HeartBoxersComponent, "{06071955-CC65-4C32-A4D8-1125D827C10B}");
void Activate() override {}
void Deactivate() override {}
static void Reflect(AZ::ReflectContext* reflection)
{
if (auto* serializeContext = azrtti_cast<AZ::SerializeContext*>(reflection))
{
serializeContext->Class<HeartBoxersComponent>()->SerializerForEmptyClass();
if (AZ::EditContext* editContext = serializeContext->GetEditContext())
{
editContext->Class<HeartBoxersComponent>("Heart Boxers", "")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game"));
}
}
}
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
{
provided.push_back(AZ_CRC("UnderwearService", 0x915ec03a));
}
static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible)
{
incompatible.push_back(AZ_CRC("UnderwearService", 0x915ec03a));
}
static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& /*required*/)
{
}
};
// Requires a belt (but no belt exists)
class KnifeSheathComponent
: public AZ::Component
{
public:
AZ_COMPONENT(KnifeSheathComponent, "{D99C3EF1-592F-4744-9D07-A5F2CE679870}");
void Activate() override {}
void Deactivate() override {}
static void Reflect(AZ::ReflectContext* reflection)
{
if (auto* serializeContext = azrtti_cast<AZ::SerializeContext*>(reflection))
{
serializeContext->Class<KnifeSheathComponent>()->SerializerForEmptyClass();
if (AZ::EditContext* editContext = serializeContext->GetEditContext())
{
editContext->Class<KnifeSheathComponent>("Knife Sheath", "")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game"));
}
}
}
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& /*provided*/)
{
}
static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& /*incompatible*/)
{
}
static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required)
{
required.push_back(AZ_CRC("BeltService", 0xba4df957));
}
};
// Count components of given type
template <typename ComponentType>
size_t CountComponentsOnEntity(AZ::Entity* entity)
{
EXPECT_NE(nullptr, entity);
if (!entity)
{
return 0;
}
size_t count = 0;
for (const auto component : entity->GetComponents())
{
if (AzToolsFramework::GetUnderlyingComponentType(*component) == azrtti_typeid<ComponentType>())
{
++count;
}
}
return count;
}
template <typename ComponentType>
size_t CountPendingComponentsOnEntity(AZ::Entity* entity)
{
EXPECT_NE(nullptr, entity);
if (!entity)
{
return 0;
}
AZ::Entity::ComponentArrayType pendingComponents;
AzToolsFramework::EditorPendingCompositionRequestBus::EventResult(pendingComponents, entity->GetId(), &AzToolsFramework::EditorPendingCompositionRequestBus::Events::GetPendingComponents);
size_t count = 0;
for (const auto pendingComponent : pendingComponents)
{
if (AzToolsFramework::GetUnderlyingComponentType(*pendingComponent) == azrtti_typeid<ComponentType>())
{
++count;
}
}
return count;
}
template <typename ComponentType>
size_t CountDisabledComponentsOnEntity(AZ::Entity* entity)
{
EXPECT_NE(nullptr, entity);
if (!entity)
{
return 0;
}
AZ::Entity::ComponentArrayType disabledComponents;
AzToolsFramework::EditorDisabledCompositionRequestBus::EventResult(disabledComponents, entity->GetId(), &AzToolsFramework::EditorDisabledCompositionRequestBus::Events::GetDisabledComponents);
size_t count = 0;
for (const auto disabledComponent : disabledComponents)
{
if (AzToolsFramework::GetUnderlyingComponentType(*disabledComponent) == azrtti_typeid<ComponentType>())
{
++count;
}
}
return count;
}
template <typename ComponentType>
AZStd::vector<AZ::Component*> GetComponentsForEntity(AZ::Entity* entity)
{
AZStd::vector<AZ::Component*> components = AzToolsFramework::GetAllComponentsForEntity(entity);
auto itr = AZStd::remove_if(components.begin(), components.end(), [](AZ::Component* component) {return AzToolsFramework::GetUnderlyingComponentType(*component) != azrtti_typeid<ComponentType>();});
components.erase(itr, components.end());
return components;
}
bool CheckAllAreTrue(std::initializer_list<bool> booleans)
{
for (auto boolean : booleans)
{
if (!boolean)
{
return false;
}
}
return true;
}
template <typename... BooleanTypes>
bool CheckAllAreTrue(BooleanTypes... booleans)
{
return CheckAllAreTrue({booleans...});
}
bool DoesComponentListHaveComponent(const AZ::Entity::ComponentArrayType& componentList, const AZ::Uuid& componentType)
{
for (const auto component : componentList)
{
if (AzToolsFramework::GetUnderlyingComponentType(*component) == componentType)
{
return true;
}
}
return false;
}
template <typename... AdditionalValidatedComponentTypes>
struct VerifyAdditionalValidatedComponents
{
static bool OnOutcomeForEntity(const AzToolsFramework::EntityCompositionRequestBus::Events::AddComponentsOutcome& outcome, AZ::Entity* entity)
{
auto iterEntityOutcome = outcome.GetValue().find(entity->GetId());
EXPECT_NE(iterEntityOutcome, outcome.GetValue().end());
return CheckAllAreTrue(DoesComponentListHaveComponent(iterEntityOutcome->second.m_additionalValidatedComponents, azrtti_typeid<AdditionalValidatedComponentTypes>())...);
}
};
template <typename... AddedPendingComponentTypes>
struct VerifyAddedPendingComponents
{
static bool OnOutcomeForEntity(const AzToolsFramework::EntityCompositionRequestBus::Events::AddComponentsOutcome& outcome, AZ::Entity* entity)
{
auto iterEntityOutcome = outcome.GetValue().find(entity->GetId());
EXPECT_NE(iterEntityOutcome, outcome.GetValue().end());
return CheckAllAreTrue(DoesComponentListHaveComponent(iterEntityOutcome->second.m_addedPendingComponents, azrtti_typeid<AddedPendingComponentTypes>())...);
}
};
template <typename... AddedValidComponentTypes>
struct VerifyAddedValidComponents
{
static bool OnOutcomeForEntity(const AzToolsFramework::EntityCompositionRequestBus::Events::AddComponentsOutcome& outcome, AZ::Entity* entity)
{
auto iterEntityOutcome = outcome.GetValue().find(entity->GetId());
EXPECT_NE(iterEntityOutcome, outcome.GetValue().end());
return CheckAllAreTrue(DoesComponentListHaveComponent(iterEntityOutcome->second.m_addedValidComponents, azrtti_typeid<AddedValidComponentTypes>())...);
}
template <typename... AdditionalValidatedComponentTypes>
struct AndAdditionalValidatedComponents
{
static bool OnOutcomeForEntity(const AzToolsFramework::EntityCompositionRequestBus::Events::AddComponentsOutcome& outcome, AZ::Entity* entity)
{
return CheckAllAreTrue(
VerifyAddedValidComponents<AddedValidComponentTypes...>::OnOutcomeForEntity(outcome, entity),
VerifyAdditionalValidatedComponents<AdditionalValidatedComponentTypes...>::OnOutcomeForEntity(outcome, entity)
);
}
};
template <typename... AddedPendingComponentTypes>
struct AndAddedPendingComponents
{
static bool OnOutcomeForEntity(const AzToolsFramework::EntityCompositionRequestBus::Events::AddComponentsOutcome& outcome, AZ::Entity* entity)
{
return CheckAllAreTrue(
VerifyAddedValidComponents<AddedValidComponentTypes...>::OnOutcomeForEntity(outcome, entity),
VerifyAddedPendingComponents<AndAddedPendingComponents...>::OnOutcomeForEntity(outcome, entity)
);
}
template <typename... AdditionalValidatedComponentTypes>
struct AndAdditionalValidatedComponents
{
static bool OnOutcomeForEntity(const AzToolsFramework::EntityCompositionRequestBus::Events::AddComponentsOutcome& outcome, AZ::Entity* entity)
{
return CheckAllAreTrue(
VerifyAddedValidComponents<AddedValidComponentTypes...>::OnOutcomeForEntity(outcome, entity),
VerifyAddedPendingComponents<AdditionalValidatedComponentTypes...>::OnOutcomeForEntity(outcome, entity),
VerifyAdditionalValidatedComponents<AdditionalValidatedComponentTypes...>::OnOutcomeForEntity(outcome, entity);
);
}
};
};
};
template <typename... InvalidatedComponentTypes>
struct VerifyRemovalInvalidatedComponents
{
static bool OnOutcomeForEntity(const AzToolsFramework::EntityCompositionRequestBus::Events::RemoveComponentsOutcome& outcome, AZ::Entity* entity)
{
auto iterEntityOutcome = outcome.GetValue().find(entity->GetId());
EXPECT_NE(iterEntityOutcome, outcome.GetValue().end());
return CheckAllAreTrue(DoesComponentListHaveComponent(iterEntityOutcome->second.m_invalidatedComponents, azrtti_typeid<InvalidatedComponentTypes>())...);
}
};
template <typename... ValidatedComponentTypes>
struct VerifyRemovalValidatedComponents
{
static bool OnOutcomeForEntity(const AzToolsFramework::EntityCompositionRequestBus::Events::RemoveComponentsOutcome& outcome, AZ::Entity* entity)
{
auto iterEntityOutcome = outcome.GetValue().find(entity->GetId());
EXPECT_NE(iterEntityOutcome, outcome.GetValue().end());
return CheckAllAreTrue(DoesComponentListHaveComponent(iterEntityOutcome->second.m_validatedComponents, azrtti_typeid<ValidatedComponentTypes>())...);
}
template <typename... InvalidatedComponentTypes>
struct AndInvalidatedComponents
{
static bool OnOutcomeForEntity(const AzToolsFramework::EntityCompositionRequestBus::Events::RemoveComponentsOutcome& outcome, AZ::Entity* entity)
{
return CheckAllAreTrue(
VerifyRemovalValidatedComponents<ValidatedComponentTypes...>::OnOutcomeForEntity(outcome, entity),
VerifyRemovalInvalidatedComponents<InvalidatedComponentTypes...>::OnOutcomeForEntity(outcome, entity)
);
}
};
};
class EntityComponentCounter
{
public:
void SetEntity(const AZ::Entity* entity)
{
m_entity = entity;
}
size_t GetCount() const
{
if (!m_entity)
{
return 0;
}
return GetComponentCount() - m_lastResetCount;
}
size_t GetPendingCount() const
{
if (!m_entity)
{
return 0;
}
return GetPendingComponentCount() - m_lastPendingResetCount;
}
size_t GetDisabledCount() const
{
if (!m_entity)
{
return 0;
}
return GetDisabledComponentCount() - m_lastDisabledResetCount;
}
void Reset()
{
m_lastResetCount = GetComponentCount();
m_lastPendingResetCount = GetPendingComponentCount();
m_lastDisabledResetCount = GetDisabledComponentCount();
}
private:
size_t GetComponentCount() const
{
return m_entity->GetComponents().size();
}
size_t GetPendingComponentCount() const
{
AZ::Entity::ComponentArrayType pendingComponents;
AzToolsFramework::EditorPendingCompositionRequestBus::EventResult(pendingComponents, m_entity->GetId(), &AzToolsFramework::EditorPendingCompositionRequestBus::Events::GetPendingComponents);
return pendingComponents.size();
}
size_t GetDisabledComponentCount() const
{
AZ::Entity::ComponentArrayType disabledComponents;
AzToolsFramework::EditorDisabledCompositionRequestBus::EventResult(disabledComponents, m_entity->GetId(), &AzToolsFramework::EditorDisabledCompositionRequestBus::Events::GetDisabledComponents);
return disabledComponents.size();
}
size_t m_lastResetCount = 0;
size_t m_lastPendingResetCount = 0;
size_t m_lastDisabledResetCount = 0;
const AZ::Entity* m_entity;
};
class AddComponentsTest
: public ::testing::Test
{
public:
void SetUp() override
{
m_app.Start(AzFramework::Application::Descriptor());
m_app.RegisterComponentDescriptor(LeatherBootsComponent::CreateDescriptor());
m_app.RegisterComponentDescriptor(WoolSocksComponent::CreateDescriptor());
m_app.RegisterComponentDescriptor(HatesSocksComponent::CreateDescriptor());
m_app.RegisterComponentDescriptor(BlueJeansComponent::CreateDescriptor());
m_app.RegisterComponentDescriptor(WhiteBriefsComponent::CreateDescriptor());
m_app.RegisterComponentDescriptor(HeartBoxersComponent::CreateDescriptor());
m_app.RegisterComponentDescriptor(KnifeSheathComponent::CreateDescriptor());
m_entity1 = new AZ::Entity("Entity1");
m_entity1Counter.SetEntity(m_entity1);
AzToolsFramework::EditorEntityContextRequestBus::Broadcast(&AzToolsFramework::EditorEntityContextRequestBus::Events::AddRequiredComponents, *m_entity1);
m_entity1->Init();
m_entity1Counter.Reset();
m_entity2 = new AZ::Entity("Entity2");
m_entity2Counter.SetEntity(m_entity2);
AzToolsFramework::EditorEntityContextRequestBus::Broadcast(&AzToolsFramework::EditorEntityContextRequestBus::Events::AddRequiredComponents, *m_entity2);
m_entity2->Init();
m_entity2Counter.Reset();
}
void TearDown() override
{
m_app.Stop();
}
AzToolsFramework::ToolsApplication m_app;
AZ::Entity* m_entity1 = nullptr;
EntityComponentCounter m_entity1Counter;
AZ::Entity* m_entity2 = nullptr;
EntityComponentCounter m_entity2Counter;
size_t m_initialComponentCount = 0;
};
TEST_F(AddComponentsTest, AddOneComponentToOneEntity)
{
auto outcome = AzToolsFramework::AddComponents<WoolSocksComponent>::ToEntities(m_entity1);
// Verify success
ASSERT_TRUE(outcome.IsSuccess());
// Check that the returned result was what we expected
ASSERT_TRUE(VerifyAddedValidComponents<WoolSocksComponent>::OnOutcomeForEntity(outcome, m_entity1));
// Check that we have the component added as expected
ASSERT_EQ(1, CountComponentsOnEntity<WoolSocksComponent>(m_entity1));
// We do separate count checks in case some other random components were added or something unexpected occurred
ASSERT_EQ(1, m_entity1Counter.GetCount());
// Verify nothing is pending
ASSERT_EQ(0, CountPendingComponentsOnEntity<WoolSocksComponent>(m_entity1));
ASSERT_EQ(0, m_entity1Counter.GetPendingCount());
// Verify nothing is disabled
ASSERT_EQ(0, CountDisabledComponentsOnEntity<WoolSocksComponent>(m_entity1));
ASSERT_EQ(0, m_entity1Counter.GetDisabledCount());
auto addComponentsResults = outcome.GetValue()[m_entity1->GetId()];
AzToolsFramework::DisableComponents(addComponentsResults.m_addedValidComponents);
ASSERT_EQ(0, CountComponentsOnEntity<WoolSocksComponent>(m_entity1));
ASSERT_EQ(0, m_entity1Counter.GetCount());
ASSERT_EQ(0, CountPendingComponentsOnEntity<WoolSocksComponent>(m_entity1));
ASSERT_EQ(0, m_entity1Counter.GetPendingCount());
ASSERT_EQ(1, CountDisabledComponentsOnEntity<WoolSocksComponent>(m_entity1));
ASSERT_EQ(1, m_entity1Counter.GetDisabledCount());
AzToolsFramework::EnableComponents(addComponentsResults.m_addedValidComponents);
ASSERT_EQ(1, CountComponentsOnEntity<WoolSocksComponent>(m_entity1));
ASSERT_EQ(1, m_entity1Counter.GetCount());
ASSERT_EQ(0, CountPendingComponentsOnEntity<WoolSocksComponent>(m_entity1));
ASSERT_EQ(0, m_entity1Counter.GetPendingCount());
ASSERT_EQ(0, CountDisabledComponentsOnEntity<WoolSocksComponent>(m_entity1));
ASSERT_EQ(0, m_entity1Counter.GetDisabledCount());
}
TEST_F(AddComponentsTest, AddOneComponentToMultipleEntities)
{
// have one entity activated, we must ensure that it is still activated after add operation
m_entity1->Activate();
// add a component to both the activated and inactive entities
auto outcome = AzToolsFramework::AddComponents<WoolSocksComponent>::ToEntities(m_entity1, m_entity2);
// Verify outcome
ASSERT_TRUE(outcome.IsSuccess());
ASSERT_TRUE(VerifyAddedValidComponents<WoolSocksComponent>::OnOutcomeForEntity(outcome, m_entity1));
ASSERT_TRUE(VerifyAddedValidComponents<WoolSocksComponent>::OnOutcomeForEntity(outcome, m_entity2));
// Should always be on entity, not pending since services are met
ASSERT_EQ(1, CountComponentsOnEntity<WoolSocksComponent>(m_entity1));
ASSERT_EQ(1, CountComponentsOnEntity<WoolSocksComponent>(m_entity2));
ASSERT_EQ(1, m_entity1Counter.GetCount());
ASSERT_EQ(1, m_entity2Counter.GetCount());
// Nothing is pending
ASSERT_EQ(0, CountPendingComponentsOnEntity<WoolSocksComponent>(m_entity1));
ASSERT_EQ(0, CountPendingComponentsOnEntity<WoolSocksComponent>(m_entity2));
ASSERT_EQ(0, m_entity1Counter.GetPendingCount());
ASSERT_EQ(0, m_entity2Counter.GetPendingCount());
// Nothing is disabled
ASSERT_EQ(0, CountDisabledComponentsOnEntity<WoolSocksComponent>(m_entity1));
ASSERT_EQ(0, CountDisabledComponentsOnEntity<WoolSocksComponent>(m_entity2));
ASSERT_EQ(0, m_entity1Counter.GetDisabledCount());
ASSERT_EQ(0, m_entity2Counter.GetDisabledCount());
// Still in original states
ASSERT_EQ(AZ::Entity::ES_ACTIVE, m_entity1->GetState());
ASSERT_EQ(AZ::Entity::ES_INIT, m_entity2->GetState());
}
// Add a component which requires another component
TEST_F(AddComponentsTest, ComponentRequiresService)
{
auto outcome = AzToolsFramework::AddComponents<LeatherBootsComponent>::ToEntities(m_entity1);
// Verify outcome
ASSERT_TRUE(outcome.IsSuccess());
ASSERT_TRUE(VerifyAddedPendingComponents<LeatherBootsComponent>::OnOutcomeForEntity(outcome, m_entity1));
// This will be pending since it is missing a socks service
ASSERT_EQ(0, CountComponentsOnEntity<LeatherBootsComponent>(m_entity1));
ASSERT_EQ(0, m_entity1Counter.GetCount());
ASSERT_EQ(1, CountPendingComponentsOnEntity<LeatherBootsComponent>(m_entity1));
ASSERT_EQ(1, m_entity1Counter.GetPendingCount());
ASSERT_EQ(0, CountDisabledComponentsOnEntity<LeatherBootsComponent>(m_entity1));
ASSERT_EQ(0, m_entity1Counter.GetDisabledCount());
// Satisfy the pending component with wool socks
outcome = AzToolsFramework::AddComponents<WoolSocksComponent>::ToEntities(m_entity1);
ASSERT_TRUE(outcome.IsSuccess());
ASSERT_TRUE(VerifyAddedValidComponents<WoolSocksComponent>::AndAdditionalValidatedComponents<LeatherBootsComponent>::OnOutcomeForEntity(outcome, m_entity1));
// Should have both on the entity now and no pending
ASSERT_EQ(1, CountComponentsOnEntity<LeatherBootsComponent>(m_entity1));
ASSERT_EQ(1, CountComponentsOnEntity<WoolSocksComponent>(m_entity1));
ASSERT_EQ(2, m_entity1Counter.GetCount());
ASSERT_EQ(0, CountPendingComponentsOnEntity<LeatherBootsComponent>(m_entity1));
ASSERT_EQ(0, CountPendingComponentsOnEntity<WoolSocksComponent>(m_entity1));
ASSERT_EQ(0, m_entity1Counter.GetPendingCount());
ASSERT_EQ(0, CountDisabledComponentsOnEntity<LeatherBootsComponent>(m_entity1));
ASSERT_EQ(0, CountDisabledComponentsOnEntity<WoolSocksComponent>(m_entity1));
ASSERT_EQ(0, m_entity1Counter.GetDisabledCount());
// LeatherBootsComponent should be wrapped in a GenericComponentWrapper
// because it is not an "editor component".
auto* wrapper = m_entity1->FindComponent<AzToolsFramework::Components::GenericComponentWrapper>();
ASSERT_TRUE(wrapper && wrapper->GetTemplate());
ASSERT_EQ(azrtti_typeid<LeatherBootsComponent>(), azrtti_typeid(wrapper->GetTemplate()));
// Try adding a component which requires a service
// that no other component provides.
outcome = AzToolsFramework::AddComponents<KnifeSheathComponent>::ToEntities(m_entity2);
ASSERT_TRUE(outcome.IsSuccess());
ASSERT_TRUE(VerifyAddedPendingComponents<KnifeSheathComponent>::OnOutcomeForEntity(outcome, m_entity2));
// This one will always be pending, never on entity as it will never be satisfied
ASSERT_EQ(0, CountComponentsOnEntity<KnifeSheathComponent>(m_entity2));
ASSERT_EQ(0, m_entity2Counter.GetCount());
ASSERT_EQ(1, CountPendingComponentsOnEntity<KnifeSheathComponent>(m_entity2));
ASSERT_EQ(1, m_entity2Counter.GetPendingCount());
ASSERT_EQ(0, CountDisabledComponentsOnEntity<KnifeSheathComponent>(m_entity2));
ASSERT_EQ(0, m_entity2Counter.GetDisabledCount());
// Check pending status
auto component = outcome.GetValue()[m_entity2->GetId()].m_addedPendingComponents[0];
AzToolsFramework::EntityCompositionRequestBus::Events::PendingComponentInfo pendingComponentInfo;
AzToolsFramework::EntityCompositionRequestBus::BroadcastResult(pendingComponentInfo, &AzToolsFramework::EntityCompositionRequestBus::Events::GetPendingComponentInfo, component);
// Should have one missing service
ASSERT_EQ(pendingComponentInfo.m_missingRequiredServices.size(), 1);
ASSERT_EQ(pendingComponentInfo.m_validComponentsThatAreIncompatible.size(), 0);
ASSERT_EQ(pendingComponentInfo.m_pendingComponentsWithRequiredServices.size(), 0);
// And that missing service should be the BeltService
ASSERT_EQ(pendingComponentInfo.m_missingRequiredServices[0], AZ_CRC("BeltService"));
// Entity 1 should remain untouched
ASSERT_EQ(2, m_entity1Counter.GetCount());
ASSERT_EQ(0, m_entity1Counter.GetPendingCount());
ASSERT_EQ(0, m_entity1Counter.GetDisabledCount());
}
// Add a component (jeans) which requires a service (underwear),
// and there are two viable options (boxers or briefs).
TEST_F(AddComponentsTest, ComponentRequiresServiceWithTwoViableOptions)
{
auto outcome = AzToolsFramework::AddComponents<BlueJeansComponent>::ToEntities(m_entity1);
ASSERT_TRUE(outcome.IsSuccess());
ASSERT_TRUE(VerifyAddedPendingComponents<BlueJeansComponent>::OnOutcomeForEntity(outcome, m_entity1));
ASSERT_EQ(0, CountComponentsOnEntity<BlueJeansComponent>(m_entity1));
ASSERT_EQ(0, m_entity1Counter.GetCount());
ASSERT_EQ(1, CountPendingComponentsOnEntity<BlueJeansComponent>(m_entity1));
ASSERT_EQ(1, m_entity1Counter.GetPendingCount());
ASSERT_EQ(0, CountDisabledComponentsOnEntity<BlueJeansComponent>(m_entity1));
ASSERT_EQ(0, m_entity1Counter.GetDisabledCount());
// Check pending status
auto component = outcome.GetValue()[m_entity1->GetId()].m_addedPendingComponents[0];
AzToolsFramework::EntityCompositionRequestBus::Events::PendingComponentInfo pendingComponentInfo;
AzToolsFramework::EntityCompositionRequestBus::BroadcastResult(pendingComponentInfo, &AzToolsFramework::EntityCompositionRequestBus::Events::GetPendingComponentInfo, component);
// Should have one missing service
ASSERT_EQ(pendingComponentInfo.m_missingRequiredServices.size(), 1);
ASSERT_EQ(pendingComponentInfo.m_validComponentsThatAreIncompatible.size(), 0);
ASSERT_EQ(pendingComponentInfo.m_pendingComponentsWithRequiredServices.size(), 0);
// And that missing service should be the "UnderwearService"
ASSERT_EQ(pendingComponentInfo.m_missingRequiredServices[0], AZ_CRC("UnderwearService"));
outcome = AzToolsFramework::AddComponents<WhiteBriefsComponent>::ToEntities(m_entity1);
ASSERT_TRUE(outcome.IsSuccess());
ASSERT_TRUE(VerifyAddedValidComponents<WhiteBriefsComponent>::AndAdditionalValidatedComponents<BlueJeansComponent>::OnOutcomeForEntity(outcome, m_entity1));
// Save this for later checks
auto whiteBriefsComponent = outcome.GetValue()[m_entity1->GetId()].m_addedValidComponents[0];
ASSERT_EQ(1, CountComponentsOnEntity<BlueJeansComponent>(m_entity1));
ASSERT_EQ(1, CountComponentsOnEntity<WhiteBriefsComponent>(m_entity1));
ASSERT_EQ(2, m_entity1Counter.GetCount());
ASSERT_EQ(0, CountPendingComponentsOnEntity<BlueJeansComponent>(m_entity1));
ASSERT_EQ(0, CountPendingComponentsOnEntity<WhiteBriefsComponent>(m_entity1));
ASSERT_EQ(0, m_entity1Counter.GetPendingCount());
ASSERT_EQ(0, CountDisabledComponentsOnEntity<BlueJeansComponent>(m_entity1));
ASSERT_EQ(0, CountDisabledComponentsOnEntity<WhiteBriefsComponent>(m_entity1));
ASSERT_EQ(0, m_entity1Counter.GetDisabledCount());
// Now try adding the second kind of underwear
// (it should be pending because entity already has underwear)
outcome = AzToolsFramework::AddComponents<HeartBoxersComponent>::ToEntities(m_entity1);
ASSERT_TRUE(outcome.IsSuccess());
ASSERT_TRUE(VerifyAddedPendingComponents<HeartBoxersComponent>::OnOutcomeForEntity(outcome, m_entity1));
ASSERT_EQ(1, CountComponentsOnEntity<BlueJeansComponent>(m_entity1));
ASSERT_EQ(1, CountComponentsOnEntity<WhiteBriefsComponent>(m_entity1));
ASSERT_EQ(0, CountComponentsOnEntity<HeartBoxersComponent>(m_entity1));
ASSERT_EQ(2, m_entity1Counter.GetCount());
ASSERT_EQ(0, CountPendingComponentsOnEntity<BlueJeansComponent>(m_entity1));
ASSERT_EQ(0, CountPendingComponentsOnEntity<WhiteBriefsComponent>(m_entity1));
ASSERT_EQ(1, CountPendingComponentsOnEntity<HeartBoxersComponent>(m_entity1));
ASSERT_EQ(1, m_entity1Counter.GetPendingCount());
ASSERT_EQ(0, CountDisabledComponentsOnEntity<BlueJeansComponent>(m_entity1));
ASSERT_EQ(0, CountDisabledComponentsOnEntity<WhiteBriefsComponent>(m_entity1));
ASSERT_EQ(0, CountDisabledComponentsOnEntity<HeartBoxersComponent>(m_entity1));
ASSERT_EQ(0, m_entity1Counter.GetDisabledCount());
// Check pending status
component = outcome.GetValue()[m_entity1->GetId()].m_addedPendingComponents[0];
AzToolsFramework::EntityCompositionRequestBus::BroadcastResult(pendingComponentInfo, &AzToolsFramework::EntityCompositionRequestBus::Events::GetPendingComponentInfo, component);
// Should have one incompatible component
ASSERT_EQ(pendingComponentInfo.m_missingRequiredServices.size(), 0);
ASSERT_EQ(pendingComponentInfo.m_validComponentsThatAreIncompatible.size(), 1);
ASSERT_EQ(pendingComponentInfo.m_pendingComponentsWithRequiredServices.size(), 0);
// And that incompatible component should be the WhiteBriefsComponent from earlier
ASSERT_EQ(pendingComponentInfo.m_validComponentsThatAreIncompatible[0], whiteBriefsComponent);
// disable white briefs component, which should resolve heart briefs, and check container counts
AzToolsFramework::DisableComponents(whiteBriefsComponent);
ASSERT_EQ(1, CountComponentsOnEntity<BlueJeansComponent>(m_entity1));
ASSERT_EQ(0, CountComponentsOnEntity<WhiteBriefsComponent>(m_entity1));
ASSERT_EQ(1, CountComponentsOnEntity<HeartBoxersComponent>(m_entity1));
ASSERT_EQ(2, m_entity1Counter.GetCount());
ASSERT_EQ(0, CountPendingComponentsOnEntity<BlueJeansComponent>(m_entity1));
ASSERT_EQ(0, CountPendingComponentsOnEntity<WhiteBriefsComponent>(m_entity1));
ASSERT_EQ(0, CountPendingComponentsOnEntity<HeartBoxersComponent>(m_entity1));
ASSERT_EQ(0, m_entity1Counter.GetPendingCount());
ASSERT_EQ(0, CountDisabledComponentsOnEntity<BlueJeansComponent>(m_entity1));
ASSERT_EQ(1, CountDisabledComponentsOnEntity<WhiteBriefsComponent>(m_entity1));
ASSERT_EQ(0, CountDisabledComponentsOnEntity<HeartBoxersComponent>(m_entity1));
ASSERT_EQ(1, m_entity1Counter.GetDisabledCount());
// re-enable white briefs component which is now pending because it's re-added after heart boxers was resolved
AzToolsFramework::EnableComponents(whiteBriefsComponent);
ASSERT_EQ(1, CountComponentsOnEntity<BlueJeansComponent>(m_entity1));
ASSERT_EQ(0, CountComponentsOnEntity<WhiteBriefsComponent>(m_entity1));
ASSERT_EQ(1, CountComponentsOnEntity<HeartBoxersComponent>(m_entity1));
ASSERT_EQ(2, m_entity1Counter.GetCount());
ASSERT_EQ(0, CountPendingComponentsOnEntity<BlueJeansComponent>(m_entity1));
ASSERT_EQ(1, CountPendingComponentsOnEntity<WhiteBriefsComponent>(m_entity1));
ASSERT_EQ(0, CountPendingComponentsOnEntity<HeartBoxersComponent>(m_entity1));
ASSERT_EQ(1, m_entity1Counter.GetPendingCount());
ASSERT_EQ(0, CountDisabledComponentsOnEntity<BlueJeansComponent>(m_entity1));
ASSERT_EQ(0, CountDisabledComponentsOnEntity<WhiteBriefsComponent>(m_entity1));
ASSERT_EQ(0, CountDisabledComponentsOnEntity<HeartBoxersComponent>(m_entity1));
ASSERT_EQ(0, m_entity1Counter.GetDisabledCount());
// Try removing pending component (should be uneventful, but it is a branch internally)
auto removalOutcome = AzToolsFramework::RemoveComponents(component);
ASSERT_TRUE(removalOutcome.IsSuccess());
ASSERT_EQ(1, CountComponentsOnEntity<BlueJeansComponent>(m_entity1));
ASSERT_EQ(1, CountComponentsOnEntity<WhiteBriefsComponent>(m_entity1));
ASSERT_EQ(0, CountComponentsOnEntity<HeartBoxersComponent>(m_entity1));
ASSERT_EQ(2, m_entity1Counter.GetCount());
ASSERT_EQ(0, CountPendingComponentsOnEntity<BlueJeansComponent>(m_entity1));
ASSERT_EQ(0, CountPendingComponentsOnEntity<WhiteBriefsComponent>(m_entity1));
ASSERT_EQ(0, CountPendingComponentsOnEntity<HeartBoxersComponent>(m_entity1));
ASSERT_EQ(0, m_entity1Counter.GetPendingCount());
ASSERT_EQ(0, CountDisabledComponentsOnEntity<BlueJeansComponent>(m_entity1));
ASSERT_EQ(0, CountDisabledComponentsOnEntity<WhiteBriefsComponent>(m_entity1));
ASSERT_EQ(0, CountDisabledComponentsOnEntity<HeartBoxersComponent>(m_entity1));
ASSERT_EQ(0, m_entity1Counter.GetDisabledCount());
}
// Add a component to two entities, where the component requires a service,
// and one entity already has that service, but the other entity does not.
TEST_F(AddComponentsTest, TwoEntitiesWhereOneHasRequiredServiceAndOneDoesNot)
{
// entity1 already has socks
auto outcome = AzToolsFramework::AddComponents<WoolSocksComponent>::ToEntities(m_entity1);
ASSERT_TRUE(outcome.IsSuccess());
ASSERT_TRUE(VerifyAddedValidComponents<WoolSocksComponent>::OnOutcomeForEntity(outcome, m_entity1));
ASSERT_EQ(1, CountComponentsOnEntity<WoolSocksComponent>(m_entity1));
ASSERT_EQ(1, m_entity1Counter.GetCount());
ASSERT_EQ(0, CountPendingComponentsOnEntity<WoolSocksComponent>(m_entity1));
ASSERT_EQ(0, m_entity1Counter.GetPendingCount());
ASSERT_EQ(0, CountDisabledComponentsOnEntity<WoolSocksComponent>(m_entity1));
ASSERT_EQ(0, m_entity1Counter.GetDisabledCount());
outcome = AzToolsFramework::AddComponents<LeatherBootsComponent>::ToEntities(m_entity1, m_entity2);
ASSERT_TRUE(outcome.IsSuccess());
ASSERT_TRUE(VerifyAddedValidComponents<LeatherBootsComponent>::OnOutcomeForEntity(outcome, m_entity1));
ASSERT_TRUE(VerifyAddedPendingComponents<LeatherBootsComponent>::OnOutcomeForEntity(outcome, m_entity2));
ASSERT_EQ(1, CountComponentsOnEntity<WoolSocksComponent>(m_entity1));
ASSERT_EQ(1, CountComponentsOnEntity<LeatherBootsComponent>(m_entity1));
ASSERT_EQ(2, m_entity1Counter.GetCount());
ASSERT_EQ(0, CountPendingComponentsOnEntity<WoolSocksComponent>(m_entity1));
ASSERT_EQ(0, CountPendingComponentsOnEntity<LeatherBootsComponent>(m_entity1));
ASSERT_EQ(0, m_entity1Counter.GetPendingCount());
ASSERT_EQ(0, CountDisabledComponentsOnEntity<WoolSocksComponent>(m_entity1));
ASSERT_EQ(0, CountDisabledComponentsOnEntity<LeatherBootsComponent>(m_entity1));
ASSERT_EQ(0, m_entity1Counter.GetDisabledCount());
ASSERT_EQ(0, CountComponentsOnEntity<LeatherBootsComponent>(m_entity2));
ASSERT_EQ(0, CountComponentsOnEntity<WoolSocksComponent>(m_entity2));
ASSERT_EQ(0, m_entity2Counter.GetCount());
ASSERT_EQ(1, CountPendingComponentsOnEntity<LeatherBootsComponent>(m_entity2));
ASSERT_EQ(0, CountPendingComponentsOnEntity<WoolSocksComponent>(m_entity2));
ASSERT_EQ(1, m_entity2Counter.GetPendingCount());
ASSERT_EQ(0, CountDisabledComponentsOnEntity<LeatherBootsComponent>(m_entity2));
ASSERT_EQ(0, CountDisabledComponentsOnEntity<WoolSocksComponent>(m_entity2));
ASSERT_EQ(0, m_entity2Counter.GetDisabledCount());
}
// Test adding a component which requires a service,
// but all candidates which provide that service conflicts with some existing component.
TEST_F(AddComponentsTest, RequiredServiceConflictsWithExistingComponents)
{
auto outcome = AzToolsFramework::AddComponents<HatesSocksComponent>::ToEntities(m_entity1);
ASSERT_TRUE(outcome.IsSuccess());
ASSERT_TRUE(VerifyAddedValidComponents<HatesSocksComponent>::OnOutcomeForEntity(outcome, m_entity1));
// Save this for tests and removal later
AZ::Component* hatesSocksComponent = outcome.GetValue()[m_entity1->GetId()].m_addedValidComponents[0];
// Adding boots
outcome = AzToolsFramework::AddComponents<LeatherBootsComponent>::ToEntities(m_entity1, m_entity2);
ASSERT_TRUE(outcome.IsSuccess());
ASSERT_TRUE(VerifyAddedPendingComponents<LeatherBootsComponent>::OnOutcomeForEntity(outcome, m_entity1));
ASSERT_TRUE(VerifyAddedPendingComponents<LeatherBootsComponent>::OnOutcomeForEntity(outcome, m_entity2));
auto leatherBootsComponent = outcome.GetValue()[m_entity1->GetId()].m_addedPendingComponents[0];
// Add socks to make it valid, but incompatible with HatesSocks on entity 1
outcome = AzToolsFramework::AddComponents<WoolSocksComponent>::ToEntities(m_entity1, m_entity2);
ASSERT_TRUE(VerifyAddedPendingComponents<WoolSocksComponent>::OnOutcomeForEntity(outcome, m_entity1));
// Socks will work on entity 2 and leather boots should be valid now because of it
ASSERT_TRUE(VerifyAddedValidComponents<WoolSocksComponent>::AndAdditionalValidatedComponents<LeatherBootsComponent>::OnOutcomeForEntity(outcome, m_entity2));
// Save this component for later
auto woolSocksComponent = outcome.GetValue()[m_entity1->GetId()].m_addedPendingComponents[0];
// Check pending status
AzToolsFramework::EntityCompositionRequestBus::Events::PendingComponentInfo pendingComponentInfo;
// First check leather boots, it should indicate it is waiting on woolSocksComponent
AzToolsFramework::EntityCompositionRequestBus::BroadcastResult(pendingComponentInfo, &AzToolsFramework::EntityCompositionRequestBus::Events::GetPendingComponentInfo, leatherBootsComponent);
// Should have one pending component
ASSERT_EQ(pendingComponentInfo.m_missingRequiredServices.size(), 0);
ASSERT_EQ(pendingComponentInfo.m_validComponentsThatAreIncompatible.size(), 0);
ASSERT_EQ(pendingComponentInfo.m_pendingComponentsWithRequiredServices.size(), 1);
// And that pending component should be the woolSocksComponent
ASSERT_EQ(pendingComponentInfo.m_pendingComponentsWithRequiredServices[0], woolSocksComponent);
// Now check the wool socks, they should be incompatible with Hates Socks
AzToolsFramework::EntityCompositionRequestBus::BroadcastResult(pendingComponentInfo, &AzToolsFramework::EntityCompositionRequestBus::Events::GetPendingComponentInfo, woolSocksComponent);
// Should have one incompatible component
ASSERT_EQ(pendingComponentInfo.m_missingRequiredServices.size(), 0);
ASSERT_EQ(pendingComponentInfo.m_validComponentsThatAreIncompatible.size(), 1);
ASSERT_EQ(pendingComponentInfo.m_pendingComponentsWithRequiredServices.size(), 0);
// And that incompatible component should be the hatesSocksComponent
ASSERT_EQ(pendingComponentInfo.m_validComponentsThatAreIncompatible[0], hatesSocksComponent);
// Remove HatesSocks from entity 1 to valid the entire entity
auto removalOutcome = AzToolsFramework::RemoveComponents(hatesSocksComponent);
ASSERT_TRUE(removalOutcome.IsSuccess());
ASSERT_TRUE((VerifyRemovalValidatedComponents<WoolSocksComponent, LeatherBootsComponent>::OnOutcomeForEntity(removalOutcome, m_entity1)));
}
// Test adding, enabling, disabling several components
TEST_F(AddComponentsTest, EnableDisableConflictingServices)
{
auto outcome = AzToolsFramework::AddComponents<LeatherBootsComponent>::ToEntities(m_entity1);
ASSERT_TRUE(outcome.IsSuccess());
ASSERT_EQ(0, m_entity1Counter.GetCount());
ASSERT_EQ(1, m_entity1Counter.GetPendingCount());
ASSERT_EQ(0, m_entity1Counter.GetDisabledCount());
outcome = AzToolsFramework::AddComponents<HatesSocksComponent>::ToEntities(m_entity1);
ASSERT_TRUE(outcome.IsSuccess());
ASSERT_EQ(1, m_entity1Counter.GetCount());
ASSERT_EQ(1, m_entity1Counter.GetPendingCount());
ASSERT_EQ(0, m_entity1Counter.GetDisabledCount());
outcome = AzToolsFramework::AddComponents<BlueJeansComponent>::ToEntities(m_entity1);
ASSERT_TRUE(outcome.IsSuccess());
ASSERT_EQ(1, m_entity1Counter.GetCount());
ASSERT_EQ(2, m_entity1Counter.GetPendingCount());
ASSERT_EQ(0, m_entity1Counter.GetDisabledCount());
outcome = AzToolsFramework::AddComponents<WhiteBriefsComponent>::ToEntities(m_entity1);
ASSERT_TRUE(outcome.IsSuccess());
ASSERT_EQ(3, m_entity1Counter.GetCount());
ASSERT_EQ(1, m_entity1Counter.GetPendingCount());
ASSERT_EQ(0, m_entity1Counter.GetDisabledCount());
outcome = AzToolsFramework::AddComponents<HeartBoxersComponent>::ToEntities(m_entity1);
ASSERT_TRUE(outcome.IsSuccess());
ASSERT_EQ(3, m_entity1Counter.GetCount());
ASSERT_EQ(2, m_entity1Counter.GetPendingCount());
ASSERT_EQ(0, m_entity1Counter.GetDisabledCount());
outcome = AzToolsFramework::AddComponents<KnifeSheathComponent>::ToEntities(m_entity1);
ASSERT_TRUE(outcome.IsSuccess());
ASSERT_EQ(3, m_entity1Counter.GetCount());
ASSERT_EQ(3, m_entity1Counter.GetPendingCount());
ASSERT_EQ(0, m_entity1Counter.GetDisabledCount());
outcome = AzToolsFramework::AddComponents<WoolSocksComponent>::ToEntities(m_entity1);
ASSERT_TRUE(outcome.IsSuccess());
ASSERT_EQ(3, m_entity1Counter.GetCount());
ASSERT_EQ(4, m_entity1Counter.GetPendingCount());
ASSERT_EQ(0, m_entity1Counter.GetDisabledCount());
AzToolsFramework::DisableComponents(GetComponentsForEntity<HatesSocksComponent>(m_entity1));
ASSERT_EQ(4, m_entity1Counter.GetCount());
ASSERT_EQ(2, m_entity1Counter.GetPendingCount());
ASSERT_EQ(1, m_entity1Counter.GetDisabledCount());
AzToolsFramework::DisableComponents(GetComponentsForEntity<HeartBoxersComponent>(m_entity1));
ASSERT_EQ(4, m_entity1Counter.GetCount());
ASSERT_EQ(1, m_entity1Counter.GetPendingCount());
ASSERT_EQ(2, m_entity1Counter.GetDisabledCount());
AzToolsFramework::DisableComponents(GetComponentsForEntity<KnifeSheathComponent>(m_entity1));
ASSERT_EQ(4, m_entity1Counter.GetCount());
ASSERT_EQ(0, m_entity1Counter.GetPendingCount());
ASSERT_EQ(3, m_entity1Counter.GetDisabledCount());
AzToolsFramework::DisableComponents(GetComponentsForEntity<WhiteBriefsComponent>(m_entity1));
ASSERT_EQ(2, m_entity1Counter.GetCount());
ASSERT_EQ(1, m_entity1Counter.GetPendingCount());
ASSERT_EQ(4, m_entity1Counter.GetDisabledCount());
AzToolsFramework::EnableComponents(GetComponentsForEntity<HeartBoxersComponent>(m_entity1));
ASSERT_EQ(4, m_entity1Counter.GetCount());
ASSERT_EQ(0, m_entity1Counter.GetPendingCount());
ASSERT_EQ(3, m_entity1Counter.GetDisabledCount());
}
} // namespace UnitTest
| 48.839354 | 205 | 0.698223 | [
"vector"
] |
0b038b3e1c30b43bdbe3a33aa5132d8444f39130 | 2,975 | cpp | C++ | third-party/llvm/llvm-src/lib/Analysis/ReleaseModeModelRunner.cpp | jhh67/chapel | f041470e9b88b5fc4914c75aa5a37efcb46aa08f | [
"ECL-2.0",
"Apache-2.0"
] | 250 | 2019-05-07T12:56:44.000Z | 2022-03-10T15:52:06.000Z | third-party/llvm/llvm-src/lib/Analysis/ReleaseModeModelRunner.cpp | jhh67/chapel | f041470e9b88b5fc4914c75aa5a37efcb46aa08f | [
"ECL-2.0",
"Apache-2.0"
] | 410 | 2019-06-06T20:52:32.000Z | 2022-01-18T14:21:48.000Z | third-party/llvm/llvm-src/lib/Analysis/ReleaseModeModelRunner.cpp | jhh67/chapel | f041470e9b88b5fc4914c75aa5a37efcb46aa08f | [
"ECL-2.0",
"Apache-2.0"
] | 50 | 2019-05-10T21:12:24.000Z | 2022-01-21T06:39:47.000Z | //===- ReleaseModeModelRunner.cpp - Fast, precompiled model runner -------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements a model runner wrapping an AOT compiled ML model.
// Only inference is supported.
//
//===----------------------------------------------------------------------===//
#include "llvm/Config/config.h"
#if defined(LLVM_HAVE_TF_AOT)
#include "llvm/Analysis/InlineModelFeatureMaps.h"
#include "llvm/Analysis/MLInlineAdvisor.h"
// codegen-ed file
#include "InlinerSizeModel.h" // NOLINT
#include <memory>
#include <vector>
using namespace llvm;
namespace {
const char FeedPrefix[] = "feed_";
const char FetchPrefix[] = "fetch_";
/// MLModelRunner - production mode implementation. It uses a AOT-compiled
/// SavedModel for efficient execution.
class ReleaseModeModelRunner final : public MLModelRunner {
public:
ReleaseModeModelRunner(LLVMContext &Ctx);
virtual ~ReleaseModeModelRunner() = default;
bool run() override;
void setFeature(FeatureIndex Index, int64_t Value) override;
int64_t getFeature(int Index) const override;
private:
std::vector<int32_t> FeatureIndices;
int32_t ResultIndex = -1;
std::unique_ptr<llvm::InlinerSizeModel> CompiledModel;
};
} // namespace
ReleaseModeModelRunner::ReleaseModeModelRunner(LLVMContext &Ctx)
: MLModelRunner(Ctx),
CompiledModel(std::make_unique<llvm::InlinerSizeModel>()) {
assert(CompiledModel && "The CompiledModel should be valid");
FeatureIndices.reserve(NumberOfFeatures);
for (size_t I = 0; I < NumberOfFeatures; ++I) {
const int Index =
CompiledModel->LookupArgIndex(FeedPrefix + FeatureNameMap[I]);
assert(Index >= 0 && "Cannot find Feature in inlining model");
FeatureIndices[I] = Index;
}
ResultIndex =
CompiledModel->LookupResultIndex(std::string(FetchPrefix) + DecisionName);
assert(ResultIndex >= 0 && "Cannot find DecisionName in inlining model");
}
int64_t ReleaseModeModelRunner::getFeature(int Index) const {
return *static_cast<int64_t *>(
CompiledModel->arg_data(FeatureIndices[Index]));
}
void ReleaseModeModelRunner::setFeature(FeatureIndex Index, int64_t Value) {
*static_cast<int64_t *>(CompiledModel->arg_data(
FeatureIndices[static_cast<size_t>(Index)])) = Value;
}
bool ReleaseModeModelRunner::run() {
CompiledModel->Run();
return static_cast<bool>(
*static_cast<int64_t *>(CompiledModel->result_data(ResultIndex)));
}
std::unique_ptr<InlineAdvisor>
llvm::getReleaseModeAdvisor(Module &M, ModuleAnalysisManager &MAM) {
auto AOTRunner = std::make_unique<ReleaseModeModelRunner>(M.getContext());
return std::make_unique<MLInlineAdvisor>(M, MAM, std::move(AOTRunner));
}
#endif // defined(LLVM_HAVE_TF_AOT)
| 32.692308 | 80 | 0.702521 | [
"vector",
"model"
] |
0b0ab91e3cc35ae98bf9d1a7335e5a87a2386f45 | 7,593 | cpp | C++ | Src/oDropDown.cpp | BastiaanOlij/omnis.xcomp.widget | 629b203f4bd6d1e1e408f1b2ed3de4eaf45d0e1a | [
"MIT"
] | 1 | 2018-08-09T23:44:54.000Z | 2018-08-09T23:44:54.000Z | Src/oDropDown.cpp | BastiaanOlij/omnis.xcomp.widget | 629b203f4bd6d1e1e408f1b2ed3de4eaf45d0e1a | [
"MIT"
] | 2 | 2015-01-20T03:51:53.000Z | 2020-03-27T04:45:38.000Z | Src/oDropDown.cpp | BastiaanOlij/omnis.xcomp.widget | 629b203f4bd6d1e1e408f1b2ed3de4eaf45d0e1a | [
"MIT"
] | 1 | 2018-09-13T05:07:08.000Z | 2018-09-13T05:07:08.000Z | /*
* omnis.xcomp.widget
* ===================
*
* oDropDown.cpp
* Source for our dropdown list object
*
* Omnis' drop down build in dropdown list now supports styled text but it seems lacking
* I've also needed a proper multi select dropdown list control for awhile where we
* can show which lines are selected and show more info in the control itself
*
* Bastiaan Olij
*/
#include "oDropDown.h"
// Constructor to initialize object
oDropDown::oDropDown(void) {
mObjType = cObjType_DropList;
mBKTheme = WND_BK_CONTROL;
mDisplayCalc = "";
};
// Destructor to clean up
oDropDown::~oDropDown(void) {
};
// instantiate a new object
oDropDown * oDropDown::newObject(void) {
oDropDown *lvNewDropDown = new oDropDown();
return lvNewDropDown;
};
// Do our list content drawing here (what we see when the list is collapsed, for cObjType_DropList only)
bool oDropDown::drawListContents(EXTListLineInfo *pInfo, EXTCompInfo* pECI) {
// Draw our text
EXTfldval * calcFld;
if (mDisplayCalc.length()==0) {
EXTfldval fval;
ECOgetProperty(mHWnd,anumListCalc,fval);
qstring calculation(fval);
calcFld = newCalculation(calculation, pECI);
} else {
calcFld = newCalculation(mDisplayCalc, pECI);
};
if (calcFld != NULL) {
GDItextSpecStruct textSpec = mCanvas->textSpec();
qpoint leftTop(pInfo->mLineRect.left+10, pInfo->mLineRect.top);
EXTfldval result;
calcFld->evalCalculation(result, pECI->mLocLocp, NULL, qfalse);
qstring text(result);
mCanvas->drawText(text.cString(), leftTop, textSpec);
delete calcFld;
};
return true;
};
// Do our list line drawing here (for cObjType_List or cObjType_DropList)
bool oDropDown::drawListLine(EXTListLineInfo *pInfo, EXTCompInfo* pECI) {
// Omnis seems to already have put a tick infront of our current line. grmbl grmbl grmbl
// Whenever selecting a line to toggle you'll need to react appropriately
qbool isSelected = pInfo->mListPtr->isRowSelected(pInfo->mLine,qfalse);
if (isSelected && mShowSelected) {
mCanvas->drawIcon(1655+cBMPicon16x16, pInfo->mLineRect);
};
// draw our text
qstring * text = newStringFromParam(1, pECI); // first parameter contains our calculated text :)
if (text!=NULL) {
GDItextSpecStruct textSpec = mCanvas->textSpec();
qpoint leftTop(pInfo->mLineRect.left+20, pInfo->mLineRect.top);
mCanvas->drawText(text->cString(), leftTop, textSpec);
delete text;
};
return true; // we have drawn this...
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// properties
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ECOproperty oDropDownProperties[] = {
// ID ResID Type Flags ExFlags EnumStart EnumEnd
anumShowselected, 0, fftBoolean, EXTD_FLAG_PROPACT, 0, 0, 0, // $multiselect
oDD_displayCalc, 4200, fftCharacter, EXTD_FLAG_PROPGENERAL, 0, 0, 0, // $displaycalc
};
qProperties * oDropDown::properties(void) {
qProperties * lvProperties = oBaseComponent::properties(); // we skip the properties in oBaseVisComponent, Omnis implements those in the background for drop down controls
// Add the property definition for our visual component here...
lvProperties->addElements(oDropDownProperties, sizeof(oDropDownProperties) / sizeof(ECOproperty));
return lvProperties;
};
// set the value of a property
qbool oDropDown::setProperty(qlong pPropID,EXTfldval &pNewValue,EXTCompInfo* pECI) {
// most anum properties are managed by Omnis but some we need to do ourselves, no idea why...
switch (pPropID) {
case anumShowselected: {
mShowSelected = pNewValue.getBool()==2;
WNDinvalidateRect(mHWnd, NULL);
return qtrue;
}; break;
case oDD_displayCalc: {
mDisplayCalc = pNewValue;
WNDinvalidateRect(mHWnd, NULL);
return qtrue;
}; break;
default:
return oBaseVisComponent::setProperty(pPropID, pNewValue, pECI);
break;
};
};
// get the value of a property
qbool oDropDown::getProperty(qlong pPropID,EXTfldval &pGetValue,EXTCompInfo* pECI) {
// most anum properties are managed by Omnis but some we need to do ourselves...
switch (pPropID) {
case anumShowselected: {
pGetValue.setBool(mShowSelected ? 2 : 1);
return true;
}; break;
case oDD_displayCalc: {
pGetValue.setChar((qchar *) mDisplayCalc.cString(), mDisplayCalc.length());
return true;
}; break;
default:
return oBaseVisComponent::getProperty(pPropID, pGetValue, pECI);
break;
};
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// This is our array of methods we support
// ECOmethodEvent oDropDownMethods[] = {
// ID Resource Return type Paramcount Params Flags ExFlags
// 1, 8000, fftCharacter, 0, NULL, 0, 0, // $testMethod
// };
// return an array of method meta data
qMethods * oDropDown::methods(void) {
qMethods * lvMethods = oBaseVisComponent::methods();
// lvMethods->addElements(oDropDownMethods, sizeof(oDropDownMethods) / sizeof(ECOmethodEvent));
return lvMethods;
};
// invoke a method
int oDropDown::invokeMethod(qlong pMethodId, EXTCompInfo* pECI) {
/* switch (pMethodId) {
case 1: {
EXTfldval lvResult;
str255 lvString(QTEXT("Hello world from our visual object!"));
lvResult.setChar(lvString);
ECOaddParam(pECI, &lvResult);
return 1L;
}; break;
default: {
return oBaseVisComponent::invokeMethod(pMethodId, pECI);
}; break;
}*/
return 1L;
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// events
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ECOmethodEvent oDropDownEvents[] = {
// ID Resource Return type Paramcount Params Flags ExFlags
oDD_evClick, 5000, 0, 0, 0, 0, 0,
};
// return an array of events meta data
qEvents * oDropDown::events(void) {
qEvents * lvEvents = oBaseNVComponent::events();
// Add the event definition for our visual component here...
lvEvents->addElements(oDropDownEvents, sizeof(oDropDownEvents) / sizeof(ECOmethodEvent));
return lvEvents;
};
void oDropDown::evClick(qpoint pAt, EXTCompInfo* pECI) {
// !BAS! I don't think this is called as we're leaving it up to Omnis to handle the mouse events...
bool enabled = (isEnabled() && isActive() && ECOisOMNISinTrueRuntime(mHWnd));
if (enabled) {
// need to find out if Omnis has an internal ID for its standard evClick
ECOsendEvent(mHWnd, oDD_evClick, 0, 0, EEN_EXEC_IMMEDIATE);
};
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// mouse
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// mouse left button pressed down (return true if we finished handling this, false if we want Omnis internal logic)
bool oDropDown::evMouseLDown(qpoint pDownAt) {
return false; // let omnis do its thing
};
// mouse left button released (return true if we finished handling this, false if we want Omnis internal logic)
bool oDropDown::evMouseLUp(qpoint pUpAt) {
return false; // let omnis do its thing
};
| 32.310638 | 171 | 0.611748 | [
"object"
] |
0b0c1372db29104da072ad034a75af98cf6953b1 | 1,476 | cpp | C++ | interviewPractice/sortLLof012s.cpp | xenowits/cp | 963b3c7df65b5328d5ce5ef894a46691afefb98c | [
"MIT"
] | null | null | null | interviewPractice/sortLLof012s.cpp | xenowits/cp | 963b3c7df65b5328d5ce5ef894a46691afefb98c | [
"MIT"
] | null | null | null | interviewPractice/sortLLof012s.cpp | xenowits/cp | 963b3c7df65b5328d5ce5ef894a46691afefb98c | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
#define fori(i,a,b) for (long int i = a; i <= b ; ++i)
#define ford(i,a,b) for(long int i = a;i >= b ; --i)
#define mk make_pair
#define mod 1000000007
#define pb push_back
#define ll long long
#define rnd mt19937_64 rng(chrono::high_resolution_clock::now().time_since_epoch().count())
#define pi pair<int,int>
#define f first
#define s second
class Node{
public:
int data;
Node* next;
Node(int x)
{
data = x;
next = NULL;
}
};
void push(int x, Node** head)
{
if (*head == NULL)
{
*head = new Node(x);
return;
}
Node* temp = *head;
while (temp->next != NULL)
temp = temp->next;
Node* tp = new Node(x);
temp->next = tp;
}
void print(Node *head)
{
while (head != NULL)
{
cout << head->data << " ";
head = head->next;
}
cout << endl;
}
void countAndModify(Node** nd, vector<ll> &v)
{
Node* node = *nd;
while(node != NULL)
{
v[node->data] += 1;
node = node->next;
}
ll i = 0;
//cout << v[0] << " " << v[1] << " " << v[2] << endl;
node = *nd;
while (node != NULL)
{
if (v[i] > 0)
{
node->data = i;
v[i] -= 1;
node = node->next;
}
else
i+=1;
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
vector<ll> v(3,0);
Node* a = NULL;
push(1,&a);
push(2,&a);
push(0,&a);
push(1,&a);
push(0,&a);
push(1,&a);
print(a);
countAndModify(&a,v);
print(a);
return 0;
}
| 15.216495 | 91 | 0.53252 | [
"vector"
] |
0b0f22a6fb7dce4b9072fca16fc1094a5867a7a9 | 5,062 | cpp | C++ | Code/Framework/AzToolsFramework/Tests/Entity/EditorEntityContextComponentTests.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-20T12:39:24.000Z | 2021-07-20T12:39:24.000Z | Code/Framework/AzToolsFramework/Tests/Entity/EditorEntityContextComponentTests.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | null | null | null | Code/Framework/AzToolsFramework/Tests/Entity/EditorEntityContextComponentTests.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-20T11:07:25.000Z | 2021-07-20T11:07:25.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <AzTest/AzTest.h>
#include <AzCore/UserSettings/UserSettingsComponent.h>
#include <AzToolsFramework/Entity/EditorEntityContextComponent.h>
#include <AzToolsFramework/UnitTest/ToolsTestApplication.h>
namespace AzToolsFramework
{
class EditorEntityContextComponentTests
: public ::testing::Test
{
protected:
void SetUp() override
{
m_app.Start(m_descriptor);
// Without this, the user settings component would attempt to save on finalize/shutdown. Since the file is
// shared across the whole engine, if multiple tests are run in parallel, the saving could cause a crash
// in the unit tests.
AZ::UserSettingsComponentRequestBus::Broadcast(&AZ::UserSettingsComponentRequests::DisableSaveOnFinalize);
}
void TearDown() override
{
m_app.Stop();
}
UnitTest::ToolsTestApplication m_app{ "EditorEntityContextComponent" }; // Shorted because Settings Registry specializations
// are 32 characters max.
AZ::ComponentApplication::Descriptor m_descriptor;
};
TEST_F(EditorEntityContextComponentTests, EditorEntityContextTests_CreateEditorEntity_CreatesValidEntity)
{
AZStd::string entityName("TestName");
AZ::EntityId createdEntityId;
AzToolsFramework::EditorEntityContextRequestBus::BroadcastResult(
createdEntityId,
&AzToolsFramework::EditorEntityContextRequests::CreateNewEditorEntity,
entityName.c_str());
EXPECT_TRUE(createdEntityId.IsValid());
AZ::Entity* createdEntity = nullptr;
AZ::ComponentApplicationBus::BroadcastResult(createdEntity, &AZ::ComponentApplicationRequests::FindEntity, createdEntityId);
EXPECT_NE(createdEntity, nullptr);
EXPECT_EQ(entityName.compare(createdEntity->GetName()), 0);
EXPECT_EQ(createdEntity->GetId(), createdEntityId);
}
TEST_F(EditorEntityContextComponentTests, EditorEntityContextTests_CreateEditorEntityWithValidId_CreatesValidEntity)
{
AZ::EntityId validId(AZ::Entity::MakeId());
EXPECT_TRUE(validId.IsValid());
AZStd::string entityName("TestName");
AZ::EntityId createdEntityId;
AzToolsFramework::EditorEntityContextRequestBus::BroadcastResult(
createdEntityId,
&AzToolsFramework::EditorEntityContextRequestBus::Events::CreateNewEditorEntityWithId,
entityName.c_str(),
validId);
EXPECT_TRUE(createdEntityId.IsValid());
EXPECT_EQ(createdEntityId, validId);
AZ::Entity* createdEntity = nullptr;
AZ::ComponentApplicationBus::BroadcastResult(createdEntity, &AZ::ComponentApplicationRequests::FindEntity, createdEntityId);
EXPECT_NE(createdEntity, nullptr);
EXPECT_EQ(entityName.compare(createdEntity->GetName()), 0);
EXPECT_EQ(createdEntity->GetId(), validId);
}
TEST_F(EditorEntityContextComponentTests, EditorEntityContextTests_CreateEditorEntityWithInvalidId_NoEntityCreated)
{
AZ::EntityId invalidId;
EXPECT_FALSE(invalidId.IsValid());
AZStd::string entityName("TestName");
AZ::EntityId createdEntityId;
AzToolsFramework::EditorEntityContextRequestBus::BroadcastResult(
createdEntityId,
&AzToolsFramework::EditorEntityContextRequestBus::Events::CreateNewEditorEntityWithId,
entityName.c_str(),
invalidId);
EXPECT_FALSE(createdEntityId.IsValid());
AZ::Entity* createdEntity = nullptr;
AZ::ComponentApplicationBus::BroadcastResult(createdEntity, &AZ::ComponentApplicationRequests::FindEntity, createdEntityId);
EXPECT_EQ(createdEntity, nullptr);
}
TEST_F(EditorEntityContextComponentTests, EditorEntityContextTests_CreateEditorEntityWithInUseId_NoEntityCreated)
{
// Create an entity so we can grab an in-use entity ID.
AZStd::string entityName("TestName");
AZ::EntityId createdEntityId;
AzToolsFramework::EditorEntityContextRequestBus::BroadcastResult(
createdEntityId,
&AzToolsFramework::EditorEntityContextRequestBus::Events::CreateNewEditorEntity,
entityName.c_str());
EXPECT_TRUE(createdEntityId.IsValid());
// Attempt to create another entity with the same ID, and verify this call fails.
AZ::EntityId secondEntityId;
AzToolsFramework::EditorEntityContextRequestBus::BroadcastResult(
secondEntityId,
&AzToolsFramework::EditorEntityContextRequestBus::Events::CreateNewEditorEntityWithId,
entityName.c_str(),
createdEntityId);
EXPECT_FALSE(secondEntityId.IsValid());
}
}
| 44.79646 | 158 | 0.697155 | [
"3d"
] |
0b10ad7ccdb6689ed63df12d099af4394b772250 | 5,146 | cpp | C++ | aws-cpp-sdk-inspector/source/model/NoSuchEntityErrorCode.cpp | ploki/aws-sdk-cpp | 17074e3e48c7411f81294e2ee9b1550c4dde842c | [
"Apache-2.0"
] | 1 | 2020-07-16T19:03:13.000Z | 2020-07-16T19:03:13.000Z | aws-cpp-sdk-inspector/source/model/NoSuchEntityErrorCode.cpp | ploki/aws-sdk-cpp | 17074e3e48c7411f81294e2ee9b1550c4dde842c | [
"Apache-2.0"
] | 18 | 2018-05-15T16:41:07.000Z | 2018-05-21T00:46:30.000Z | aws-cpp-sdk-inspector/source/model/NoSuchEntityErrorCode.cpp | ploki/aws-sdk-cpp | 17074e3e48c7411f81294e2ee9b1550c4dde842c | [
"Apache-2.0"
] | 1 | 2021-10-01T15:29:44.000Z | 2021-10-01T15:29:44.000Z | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/inspector/model/NoSuchEntityErrorCode.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 Inspector
{
namespace Model
{
namespace NoSuchEntityErrorCodeMapper
{
static const int ASSESSMENT_TARGET_DOES_NOT_EXIST_HASH = HashingUtils::HashString("ASSESSMENT_TARGET_DOES_NOT_EXIST");
static const int ASSESSMENT_TEMPLATE_DOES_NOT_EXIST_HASH = HashingUtils::HashString("ASSESSMENT_TEMPLATE_DOES_NOT_EXIST");
static const int ASSESSMENT_RUN_DOES_NOT_EXIST_HASH = HashingUtils::HashString("ASSESSMENT_RUN_DOES_NOT_EXIST");
static const int FINDING_DOES_NOT_EXIST_HASH = HashingUtils::HashString("FINDING_DOES_NOT_EXIST");
static const int RESOURCE_GROUP_DOES_NOT_EXIST_HASH = HashingUtils::HashString("RESOURCE_GROUP_DOES_NOT_EXIST");
static const int RULES_PACKAGE_DOES_NOT_EXIST_HASH = HashingUtils::HashString("RULES_PACKAGE_DOES_NOT_EXIST");
static const int SNS_TOPIC_DOES_NOT_EXIST_HASH = HashingUtils::HashString("SNS_TOPIC_DOES_NOT_EXIST");
static const int IAM_ROLE_DOES_NOT_EXIST_HASH = HashingUtils::HashString("IAM_ROLE_DOES_NOT_EXIST");
NoSuchEntityErrorCode GetNoSuchEntityErrorCodeForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == ASSESSMENT_TARGET_DOES_NOT_EXIST_HASH)
{
return NoSuchEntityErrorCode::ASSESSMENT_TARGET_DOES_NOT_EXIST;
}
else if (hashCode == ASSESSMENT_TEMPLATE_DOES_NOT_EXIST_HASH)
{
return NoSuchEntityErrorCode::ASSESSMENT_TEMPLATE_DOES_NOT_EXIST;
}
else if (hashCode == ASSESSMENT_RUN_DOES_NOT_EXIST_HASH)
{
return NoSuchEntityErrorCode::ASSESSMENT_RUN_DOES_NOT_EXIST;
}
else if (hashCode == FINDING_DOES_NOT_EXIST_HASH)
{
return NoSuchEntityErrorCode::FINDING_DOES_NOT_EXIST;
}
else if (hashCode == RESOURCE_GROUP_DOES_NOT_EXIST_HASH)
{
return NoSuchEntityErrorCode::RESOURCE_GROUP_DOES_NOT_EXIST;
}
else if (hashCode == RULES_PACKAGE_DOES_NOT_EXIST_HASH)
{
return NoSuchEntityErrorCode::RULES_PACKAGE_DOES_NOT_EXIST;
}
else if (hashCode == SNS_TOPIC_DOES_NOT_EXIST_HASH)
{
return NoSuchEntityErrorCode::SNS_TOPIC_DOES_NOT_EXIST;
}
else if (hashCode == IAM_ROLE_DOES_NOT_EXIST_HASH)
{
return NoSuchEntityErrorCode::IAM_ROLE_DOES_NOT_EXIST;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<NoSuchEntityErrorCode>(hashCode);
}
return NoSuchEntityErrorCode::NOT_SET;
}
Aws::String GetNameForNoSuchEntityErrorCode(NoSuchEntityErrorCode enumValue)
{
switch(enumValue)
{
case NoSuchEntityErrorCode::ASSESSMENT_TARGET_DOES_NOT_EXIST:
return "ASSESSMENT_TARGET_DOES_NOT_EXIST";
case NoSuchEntityErrorCode::ASSESSMENT_TEMPLATE_DOES_NOT_EXIST:
return "ASSESSMENT_TEMPLATE_DOES_NOT_EXIST";
case NoSuchEntityErrorCode::ASSESSMENT_RUN_DOES_NOT_EXIST:
return "ASSESSMENT_RUN_DOES_NOT_EXIST";
case NoSuchEntityErrorCode::FINDING_DOES_NOT_EXIST:
return "FINDING_DOES_NOT_EXIST";
case NoSuchEntityErrorCode::RESOURCE_GROUP_DOES_NOT_EXIST:
return "RESOURCE_GROUP_DOES_NOT_EXIST";
case NoSuchEntityErrorCode::RULES_PACKAGE_DOES_NOT_EXIST:
return "RULES_PACKAGE_DOES_NOT_EXIST";
case NoSuchEntityErrorCode::SNS_TOPIC_DOES_NOT_EXIST:
return "SNS_TOPIC_DOES_NOT_EXIST";
case NoSuchEntityErrorCode::IAM_ROLE_DOES_NOT_EXIST:
return "IAM_ROLE_DOES_NOT_EXIST";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return "";
}
}
} // namespace NoSuchEntityErrorCodeMapper
} // namespace Model
} // namespace Inspector
} // namespace Aws
| 41.837398 | 130 | 0.698601 | [
"model"
] |
0b1483aa0a812ce9589d67e146c4e73939d9c8bb | 6,652 | cpp | C++ | libs/spirit/test/karma/pattern.cpp | oudream/boost_1_42_0 | e92227bf374e478030e89876ec353de6eecaeac0 | [
"BSL-1.0"
] | 3 | 2019-06-25T23:20:19.000Z | 2021-03-14T19:38:34.000Z | libs/spirit/test/karma/pattern.cpp | jonstewart/boost-svn | 7f6dc0c0cb807b28072c7bdd3d77bb01ab290c59 | [
"BSL-1.0"
] | null | null | null | libs/spirit/test/karma/pattern.cpp | jonstewart/boost-svn | 7f6dc0c0cb807b28072c7bdd3d77bb01ab290c59 | [
"BSL-1.0"
] | 3 | 2016-07-26T08:07:09.000Z | 2019-06-25T23:20:21.000Z | // Copyright (c) 2001-2010 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/config/warning_disable.hpp>
#include <boost/detail/lightweight_test.hpp>
#include <boost/spirit/include/karma_operator.hpp>
#include <boost/spirit/include/karma_char.hpp>
#include <boost/spirit/include/karma_auxiliary.hpp>
#include <boost/spirit/include/karma_string.hpp>
#include <boost/spirit/include/karma_numeric.hpp>
#include <boost/spirit/include/karma_nonterminal.hpp>
#include <boost/spirit/include/karma_action.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_statement.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include "test.hpp"
using namespace spirit_test;
///////////////////////////////////////////////////////////////////////////////
int main()
{
using namespace boost;
using namespace boost::spirit;
using namespace boost::spirit::ascii;
typedef spirit_test::output_iterator<char>::type outiter_type;
// test rule parameter propagation
{
using boost::phoenix::at_c;
karma::rule<outiter_type, fusion::vector<char, int, double>()> start;
fusion::vector<char, int, double> vec('a', 10, 12.4);
start %= char_ << int_ << double_;
BOOST_TEST(test("a1012.4", start, vec));
karma::rule<outiter_type, char()> a;
karma::rule<outiter_type, int()> b;
karma::rule<outiter_type, double()> c;
a %= char_ << eps;
b %= int_;
c %= double_;
start = a[_1 = at_c<0>(_r0)] << b[_1 = at_c<1>(_r0)] << c[_1 = at_c<2>(_r0)];
BOOST_TEST(test("a1012.4", start, vec));
start = (a << b << c)[_1 = at_c<0>(_r0), _2 = at_c<1>(_r0), _3 = at_c<2>(_r0)];
BOOST_TEST(test("a1012.4", start, vec));
start = a << b << c;
BOOST_TEST(test("a1012.4", start, vec));
start %= a << b << c;
BOOST_TEST(test("a1012.4", start, vec));
}
{
using boost::phoenix::at_c;
karma::rule<outiter_type, space_type, fusion::vector<char, int, double>()> start;
fusion::vector<char, int, double> vec('a', 10, 12.4);
start %= char_ << int_ << double_;
BOOST_TEST(test_delimited("a 10 12.4 ", start, vec, space));
karma::rule<outiter_type, space_type, char()> a;
karma::rule<outiter_type, space_type, int()> b;
karma::rule<outiter_type, space_type, double()> c;
a %= char_ << eps;
b %= int_;
c %= double_;
start = a[_1 = at_c<0>(_r0)] << b[_1 = at_c<1>(_r0)] << c[_1 = at_c<2>(_r0)];
BOOST_TEST(test_delimited("a 10 12.4 ", start, vec, space));
start = (a << b << c)[_1 = at_c<0>(_r0), _2 = at_c<1>(_r0), _3 = at_c<2>(_r0)];
BOOST_TEST(test_delimited("a 10 12.4 ", start, vec, space));
start = a << b << c;
BOOST_TEST(test_delimited("a 10 12.4 ", start, vec, space));
start %= a << b << c;
BOOST_TEST(test_delimited("a 10 12.4 ", start, vec, space));
}
// test direct initalization
{
using boost::phoenix::at_c;
fusion::vector<char, int, double> vec('a', 10, 12.4);
karma::rule<outiter_type, space_type, fusion::vector<char, int, double>()>
start = char_ << int_ << double_;;
BOOST_TEST(test_delimited("a 10 12.4 ", start, vec, space));
karma::rule<outiter_type, space_type, char()> a = char_ << eps;
karma::rule<outiter_type, space_type, int()> b = int_;
karma::rule<outiter_type, space_type, double()> c = double_;
start = a[_1 = at_c<0>(_r0)] << b[_1 = at_c<1>(_r0)] << c[_1 = at_c<2>(_r0)];
BOOST_TEST(test_delimited("a 10 12.4 ", start, vec, space));
}
// locals test
{
karma::rule<outiter_type, locals<std::string> > start;
start = string[_1 = "abc", _a = _1] << int_[_1 = 10] << string[_1 = _a];
BOOST_TEST(test("abc10abc", start));
}
{
karma::rule<outiter_type, space_type, locals<std::string> > start;
start = string[_1 = "abc", _a = _1] << int_[_1 = 10] << string[_1 = _a];
BOOST_TEST(test_delimited("abc 10 abc ", start, space));
}
// alias tests
{
typedef variant<char, int, double> var_type;
karma::rule<outiter_type, var_type()> d, start;
d = start.alias(); // d will always track start
start = (char_ | int_ | double_)[_1 = _val];
var_type v ('a');
BOOST_TEST(test("a", d, v));
v = 10;
BOOST_TEST(test("10", d, v));
v = 12.4;
BOOST_TEST(test("12.4", d, v));
}
{
typedef variant<char, int, double> var_type;
karma::rule<outiter_type, space_type, var_type()> d, start;
d = start.alias(); // d will always track start
start = (char_ | int_ | double_)[_1 = _val];
var_type v ('a');
BOOST_TEST(test_delimited("a ", d, v, space));
v = 10;
BOOST_TEST(test_delimited("10 ", d, v, space));
v = 12.4;
BOOST_TEST(test_delimited("12.4 ", d, v, space));
}
{
typedef variant<char, int, double> var_type;
karma::rule<outiter_type, var_type()> d, start;
d = start.alias(); // d will always track start
start %= char_ | int_ | double_;
var_type v ('a');
BOOST_TEST(test("a", d, v));
v = 10;
BOOST_TEST(test("10", d, v));
v = 12.4;
BOOST_TEST(test("12.4", d, v));
start = char_ | int_ | double_;
v = 'a';
BOOST_TEST(test("a", d, v));
v = 10;
BOOST_TEST(test("10", d, v));
v = 12.4;
BOOST_TEST(test("12.4", d, v));
}
{
typedef variant<char, int, double> var_type;
karma::rule<outiter_type, space_type, var_type()> d, start;
d = start.alias(); // d will always track start
start %= char_ | int_ | double_;
var_type v ('a');
BOOST_TEST(test_delimited("a ", d, v, space));
v = 10;
BOOST_TEST(test_delimited("10 ", d, v, space));
v = 12.4;
BOOST_TEST(test_delimited("12.4 ", d, v, space));
start = char_ | int_ | double_;
v = 'a';
BOOST_TEST(test_delimited("a ", d, v, space));
v = 10;
BOOST_TEST(test_delimited("10 ", d, v, space));
v = 12.4;
BOOST_TEST(test_delimited("12.4 ", d, v, space));
}
return boost::report_errors();
}
| 30.796296 | 89 | 0.558779 | [
"vector"
] |
0b18d11930ef2cfee2d9e8a53b5973665702a52d | 9,758 | cpp | C++ | automated-tests/src/dali-toolkit-internal/utc-Dali-TextEditor-internal.cpp | dalihub/dali-toolk | 980728a7e35b8ddd28f70c090243e8076e21536e | [
"Apache-2.0",
"BSD-3-Clause"
] | 7 | 2016-11-18T10:26:51.000Z | 2021-01-28T13:51:59.000Z | automated-tests/src/dali-toolkit-internal/utc-Dali-TextEditor-internal.cpp | dalihub/dali-toolk | 980728a7e35b8ddd28f70c090243e8076e21536e | [
"Apache-2.0",
"BSD-3-Clause"
] | 13 | 2020-07-15T11:33:03.000Z | 2021-04-09T21:29:23.000Z | automated-tests/src/dali-toolkit-internal/utc-Dali-TextEditor-internal.cpp | dalihub/dali-toolk | 980728a7e35b8ddd28f70c090243e8076e21536e | [
"Apache-2.0",
"BSD-3-Clause"
] | 10 | 2019-05-17T07:15:09.000Z | 2021-05-24T07:28:08.000Z | /*
* Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <iostream>
#include <stdlib.h>
#include <dali-toolkit-test-suite-utils.h>
#include <dali-toolkit/dali-toolkit.h>
#include <dali-toolkit/internal/text/rendering/atlas/atlas-glyph-manager.h>
#include <dali-toolkit/internal/controls/text-controls/text-editor-impl.h>
#include <dali-toolkit/internal/text/text-controller.h>
#include <dali-toolkit/internal/text/text-controller-impl.h>
using namespace Dali;
using namespace Toolkit;
using namespace Text;
int UtcDaliTextEditorSelectText(void)
{
ToolkitTestApplication application;
tet_infoline( "UtcDaliTextEditorSelectText" );
// Create a text editor
TextEditor textEditor = TextEditor::New();
textEditor.SetProperty( Actor::Property::SIZE, Vector2( 400.f, 60.f ) );
textEditor.SetProperty( TextEditor::Property::TEXT, "Hello World" );
// Add the text editor to the stage
application.GetScene().Add( textEditor );
application.SendNotification();
application.Render();
Toolkit::Internal::TextEditor& textEditorImpl = GetImpl( textEditor );
application.SendNotification();
application.Render();
// Highlight the whole text
textEditorImpl.SelectWholeText();
application.SendNotification();
application.Render();
std::string selectedText = textEditorImpl.GetSelectedText();
DALI_TEST_CHECK( selectedText == "Hello World" );
// Select None
textEditorImpl.SelectNone();
application.SendNotification();
application.Render();
selectedText = textEditorImpl.GetSelectedText();
DALI_TEST_CHECK( selectedText == "" );
END_TEST;
}
int UtcDaliTextEditorMarkupUnderline(void)
{
ToolkitTestApplication application;
tet_infoline(" UtcDaliTextEditorMarkupUnderline ");
TextEditor textEditor = TextEditor::New();
application.GetScene().Add( textEditor );
textEditor.SetProperty( TextEditor::Property::TEXT, "<u>ABC</u>EF<u>GH</u>" );
textEditor.SetProperty( TextEditor ::Property::ENABLE_MARKUP, true );
application.SendNotification();
application.Render();
uint32_t expectedNumberOfUnderlinedGlyphs = 5u;
Toolkit::Internal::TextEditor& textEditorImpl = GetImpl( textEditor );
const Text::Length numberOfUnderlineRuns = textEditorImpl.GetTextController()->GetTextModel()->GetNumberOfUnderlineRuns();
DALI_TEST_EQUALS( numberOfUnderlineRuns, expectedNumberOfUnderlinedGlyphs, TEST_LOCATION );
Vector<GlyphRun> underlineRuns;
underlineRuns.Resize(numberOfUnderlineRuns);
textEditorImpl.GetTextController()->GetTextModel()->GetUnderlineRuns(underlineRuns.Begin(), 0u, numberOfUnderlineRuns);
//ABC are underlined
DALI_TEST_EQUALS( underlineRuns[0u].glyphIndex, 0u, TEST_LOCATION);
DALI_TEST_EQUALS( underlineRuns[1u].glyphIndex, 1u, TEST_LOCATION);
DALI_TEST_EQUALS( underlineRuns[2u].glyphIndex, 2u, TEST_LOCATION);
//GH are underlined
DALI_TEST_EQUALS( underlineRuns[3u].glyphIndex, 5u, TEST_LOCATION);
DALI_TEST_EQUALS( underlineRuns[4u].glyphIndex, 6u, TEST_LOCATION);
END_TEST;
}
int UtcDaliTextEditorFontPointSizeLargerThanAtlas(void)
{
ToolkitTestApplication application;
tet_infoline(" UtcDaliTextEditorFontPointSizeLargerThanAtlas ");
// Create a text editor
TextEditor textEditor = TextEditor::New();
//Set size to avoid automatic eliding
textEditor.SetProperty( Actor::Property::SIZE, Vector2(1025, 1025));
//Set very large font-size using point-size
textEditor.SetProperty( TextEditor::Property::POINT_SIZE, 1000);
//Specify font-family
textEditor.SetProperty( TextEditor::Property::FONT_FAMILY, "DejaVu Sans");
//Set text to check if appear or not
textEditor.SetProperty(TextEditor::Property::TEXT, "A");
application.GetScene().Add( textEditor );
application.SendNotification();
application.Render();
//Check if Glyph is added to AtlasGlyphManger or not
int countAtlas = AtlasGlyphManager::Get().GetMetrics().mAtlasMetrics.mAtlasCount;
DALI_TEST_EQUALS( countAtlas, 1, TEST_LOCATION );
END_TEST;
}
int UtcDaliTextEditorFontPointSizeLargerThanAtlasPlaceholderCase(void)
{
ToolkitTestApplication application;
tet_infoline(" UtcDaliTextEditorFontPointSizeLargerThanAtlasPlaceholderCase ");
//Set Map of placeholder: text, font-family and point-size
Property::Map placeholderMapSet;
placeholderMapSet["text"] = "A";
placeholderMapSet["fontFamily"] = "DejaVu Sans";
placeholderMapSet["pixelSize"] = 1000.0f;
// Create a text editor
TextEditor textEditor = TextEditor::New();
//Set size to avoid automatic eliding
textEditor.SetProperty( Actor::Property::SIZE, Vector2(1025, 1025));
//Set placeholder
textEditor.SetProperty( TextEditor::Property::PLACEHOLDER, placeholderMapSet) ;
application.GetScene().Add( textEditor );
application.SendNotification();
application.Render();
//Check if Glyph is added to AtlasGlyphManger or not
int countAtlas = AtlasGlyphManager::Get().GetMetrics().mAtlasMetrics.mAtlasCount;
DALI_TEST_EQUALS( countAtlas, 1, TEST_LOCATION );
END_TEST;
}
int UtcDaliTextEditorBackgroundTag(void)
{
ToolkitTestApplication application;
tet_infoline("UtcDaliTextEditorBackgroundTag\n");
TextEditor editor = TextEditor::New();
DALI_TEST_CHECK( editor );
editor.SetProperty( TextEditor ::Property::ENABLE_MARKUP, true );
editor.SetProperty( TextEditor::Property::TEXT, "H<background color='red'>e</background> Worl<background color='yellow'>d</background>" );
application.GetScene().Add( editor );
application.SendNotification();
application.Render();
Toolkit::Internal::TextEditor& editorImpl = GetImpl( editor );
const ColorIndex* const backgroundColorIndicesBuffer = editorImpl.GetTextController()->GetTextModel()->GetBackgroundColorIndices();
DALI_TEST_CHECK( backgroundColorIndicesBuffer );
//default color
DALI_TEST_EQUALS( backgroundColorIndicesBuffer[0], 0u, TEST_LOCATION);
//red color
DALI_TEST_EQUALS( backgroundColorIndicesBuffer[1], 1u, TEST_LOCATION);
//yellow color
DALI_TEST_EQUALS( backgroundColorIndicesBuffer[7], 2u, TEST_LOCATION);
END_TEST;
}
int UtcDaliTextEditorTextWithSpan(void)
{
ToolkitTestApplication application;
tet_infoline("UtcDaliTextEditorTextWithSpan\n");
TextEditor editor = TextEditor::New();
DALI_TEST_CHECK( editor );
editor.SetProperty( TextEditor ::Property::ENABLE_MARKUP, true );
editor.SetProperty( TextEditor::Property::TEXT, "Hello Span" );
application.GetScene().Add( editor );
application.SendNotification();
application.Render();
Vector3 originalSize = editor.GetNaturalSize();
editor.SetProperty( TextEditor::Property::TEXT, "H<span font-size='45' font-family='DejaVu Sans' font-width='condensed' font-slant='italic' text-color='red'>ello</span> Span" );
application.SendNotification();
application.Render();
Vector3 spanSize = editor.GetNaturalSize();
DALI_TEST_GREATER(spanSize.width, originalSize.width, TEST_LOCATION);
Toolkit::Internal::TextEditor& editorImpl = GetImpl( editor );
const ColorIndex* const colorIndicesBuffer1 = editorImpl.GetTextController()->GetTextModel()->GetColorIndices();
DALI_TEST_CHECK( colorIndicesBuffer1 );
//default color
DALI_TEST_EQUALS( colorIndicesBuffer1[0], 0u, TEST_LOCATION);
//span color
DALI_TEST_EQUALS( colorIndicesBuffer1[1], 1u, TEST_LOCATION);
//default color
DALI_TEST_EQUALS( colorIndicesBuffer1[6], 0u, TEST_LOCATION);
editor.SetProperty( TextEditor::Property::TEXT, "<span font-size='45'>H</span>ello <span text-color='red'>S</span>pan" );
application.SendNotification();
application.Render();
const ColorIndex* const colorIndicesBuffer2 = editorImpl.GetTextController()->GetTextModel()->GetColorIndices();
DALI_TEST_CHECK( colorIndicesBuffer2 );
//default color
DALI_TEST_EQUALS( colorIndicesBuffer2[0], 0u, TEST_LOCATION);
//default color
DALI_TEST_EQUALS( colorIndicesBuffer2[1], 0u, TEST_LOCATION);
//span color
DALI_TEST_EQUALS( colorIndicesBuffer2[6], 1u, TEST_LOCATION);
//default color
DALI_TEST_EQUALS( colorIndicesBuffer2[7], 0u, TEST_LOCATION);
END_TEST;
}
int UtcDaliTextEditorControlBackgroundColor(void)
{
ToolkitTestApplication application;
tet_infoline(" UtcDaliTextEditorControlBackgroundColor\n");
TextEditor editor = TextEditor::New();
DALI_TEST_CHECK(editor);
Vector4 backgroundColor;
editor.SetProperty(TextEditor::Property::TEXT, "Background Color");
application.GetScene().Add(editor);
application.SendNotification();
application.Render();
Toolkit::Internal::TextEditor& editorImpl = GetImpl(editor);
ControllerPtr controller = editorImpl.GetTextController();
Controller::Impl& controllerImpl = Controller::Impl::GetImplementation(*controller.Get());
// Default color is transparent
controllerImpl.mEditableControlInterface->GetControlBackgroundColor(backgroundColor);
DALI_TEST_EQUALS(backgroundColor, Color::TRANSPARENT, TEST_LOCATION);
// Set background color to red
editor.SetBackgroundColor(Color::RED);
application.SendNotification();
application.Render();
// Should be red
controllerImpl.mEditableControlInterface->GetControlBackgroundColor(backgroundColor);
DALI_TEST_EQUALS(backgroundColor, Color::RED, TEST_LOCATION);
END_TEST;
}
| 32.418605 | 179 | 0.767575 | [
"render",
"vector"
] |
0b1ab5e96ab9a081c739ac81de3319efc077d05e | 5,394 | hpp | C++ | stan/math/prim/scal/prob/frechet_lpdf.hpp | jrmie/math | 2850ec262181075a5843968e805dc9ad1654e069 | [
"BSD-3-Clause"
] | null | null | null | stan/math/prim/scal/prob/frechet_lpdf.hpp | jrmie/math | 2850ec262181075a5843968e805dc9ad1654e069 | [
"BSD-3-Clause"
] | null | null | null | stan/math/prim/scal/prob/frechet_lpdf.hpp | jrmie/math | 2850ec262181075a5843968e805dc9ad1654e069 | [
"BSD-3-Clause"
] | null | null | null | #ifndef STAN_MATH_PRIM_SCAL_PROB_FRECHET_LPDF_HPP
#define STAN_MATH_PRIM_SCAL_PROB_FRECHET_LPDF_HPP
#include <boost/random/weibull_distribution.hpp>
#include <boost/random/variate_generator.hpp>
#include <stan/math/prim/scal/meta/operands_and_partials.hpp>
#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>
#include <stan/math/prim/scal/err/check_nonnegative.hpp>
#include <stan/math/prim/scal/err/check_not_nan.hpp>
#include <stan/math/prim/scal/err/check_positive.hpp>
#include <stan/math/prim/scal/err/check_positive_finite.hpp>
#include <stan/math/prim/scal/fun/size_zero.hpp>
#include <stan/math/prim/scal/fun/log1m.hpp>
#include <stan/math/prim/scal/fun/multiply_log.hpp>
#include <stan/math/prim/scal/fun/value_of.hpp>
#include <stan/math/prim/scal/meta/length.hpp>
#include <stan/math/prim/scal/meta/is_constant_struct.hpp>
#include <stan/math/prim/scal/meta/scalar_seq_view.hpp>
#include <stan/math/prim/scal/meta/VectorBuilder.hpp>
#include <stan/math/prim/scal/meta/partials_return_type.hpp>
#include <stan/math/prim/scal/meta/return_type.hpp>
#include <stan/math/prim/scal/fun/constants.hpp>
#include <stan/math/prim/scal/meta/include_summand.hpp>
#include <cmath>
namespace stan {
namespace math {
// Frechet(y|alpha, sigma) [y > 0; alpha > 0; sigma > 0]
// FIXME: document
template <bool propto, typename T_y, typename T_shape, typename T_scale>
typename return_type<T_y, T_shape, T_scale>::type frechet_lpdf(
const T_y& y, const T_shape& alpha, const T_scale& sigma) {
static const char* function = "frechet_lpdf";
typedef typename stan::partials_return_type<T_y, T_shape, T_scale>::type
T_partials_return;
using std::log;
if (size_zero(y, alpha, sigma))
return 0.0;
T_partials_return logp(0.0);
check_positive(function, "Random variable", y);
check_positive_finite(function, "Shape parameter", alpha);
check_positive_finite(function, "Scale parameter", sigma);
check_consistent_sizes(function, "Random variable", y, "Shape parameter",
alpha, "Scale parameter", sigma);
if (!include_summand<propto, T_y, T_shape, T_scale>::value)
return 0.0;
scalar_seq_view<T_y> y_vec(y);
scalar_seq_view<T_shape> alpha_vec(alpha);
scalar_seq_view<T_scale> sigma_vec(sigma);
size_t N = max_size(y, alpha, sigma);
VectorBuilder<include_summand<propto, T_shape>::value, T_partials_return,
T_shape>
log_alpha(length(alpha));
for (size_t i = 0; i < length(alpha); i++)
if (include_summand<propto, T_shape>::value)
log_alpha[i] = log(value_of(alpha_vec[i]));
VectorBuilder<include_summand<propto, T_y, T_shape>::value, T_partials_return,
T_y>
log_y(length(y));
for (size_t i = 0; i < length(y); i++)
if (include_summand<propto, T_y, T_shape>::value)
log_y[i] = log(value_of(y_vec[i]));
VectorBuilder<include_summand<propto, T_shape, T_scale>::value,
T_partials_return, T_scale>
log_sigma(length(sigma));
for (size_t i = 0; i < length(sigma); i++)
if (include_summand<propto, T_shape, T_scale>::value)
log_sigma[i] = log(value_of(sigma_vec[i]));
VectorBuilder<include_summand<propto, T_y, T_shape, T_scale>::value,
T_partials_return, T_y>
inv_y(length(y));
for (size_t i = 0; i < length(y); i++)
if (include_summand<propto, T_y, T_shape, T_scale>::value)
inv_y[i] = 1.0 / value_of(y_vec[i]);
VectorBuilder<include_summand<propto, T_y, T_shape, T_scale>::value,
T_partials_return, T_y, T_shape, T_scale>
sigma_div_y_pow_alpha(N);
for (size_t i = 0; i < N; i++)
if (include_summand<propto, T_y, T_shape, T_scale>::value) {
const T_partials_return alpha_dbl = value_of(alpha_vec[i]);
sigma_div_y_pow_alpha[i]
= pow(inv_y[i] * value_of(sigma_vec[i]), alpha_dbl);
}
operands_and_partials<T_y, T_shape, T_scale> ops_partials(y, alpha, sigma);
for (size_t n = 0; n < N; n++) {
const T_partials_return alpha_dbl = value_of(alpha_vec[n]);
if (include_summand<propto, T_shape>::value)
logp += log_alpha[n];
if (include_summand<propto, T_y, T_shape>::value)
logp -= (alpha_dbl + 1.0) * log_y[n];
if (include_summand<propto, T_shape, T_scale>::value)
logp += alpha_dbl * log_sigma[n];
if (include_summand<propto, T_y, T_shape, T_scale>::value)
logp -= sigma_div_y_pow_alpha[n];
if (!is_constant_struct<T_y>::value) {
const T_partials_return inv_y_dbl = value_of(inv_y[n]);
ops_partials.edge1_.partials_[n]
+= -(alpha_dbl + 1.0) * inv_y_dbl
+ alpha_dbl * sigma_div_y_pow_alpha[n] * inv_y_dbl;
}
if (!is_constant_struct<T_shape>::value)
ops_partials.edge2_.partials_[n]
+= 1.0 / alpha_dbl
+ (1.0 - sigma_div_y_pow_alpha[n]) * (log_sigma[n] - log_y[n]);
if (!is_constant_struct<T_scale>::value)
ops_partials.edge3_.partials_[n] += alpha_dbl / value_of(sigma_vec[n])
* (1 - sigma_div_y_pow_alpha[n]);
}
return ops_partials.build(logp);
}
template <typename T_y, typename T_shape, typename T_scale>
inline typename return_type<T_y, T_shape, T_scale>::type frechet_lpdf(
const T_y& y, const T_shape& alpha, const T_scale& sigma) {
return frechet_lpdf<false>(y, alpha, sigma);
}
} // namespace math
} // namespace stan
#endif
| 40.253731 | 80 | 0.692807 | [
"shape"
] |
0b1ce7d431b2f60765e9d764586638d28158614f | 1,021 | hh | C++ | TEvtGen/EvtGen/EvtGenBase/EvtAmpIndex.hh | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | TEvtGen/EvtGen/EvtGenBase/EvtAmpIndex.hh | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | TEvtGen/EvtGen/EvtGenBase/EvtAmpIndex.hh | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | //--------------------------------------------------------------------------
//
// Environment:
// This software is part of the EvtGen package developed jointly
// for the BaBar and CLEO collaborations. If you use all or part
// of it, please give an appropriate acknowledgement.
//
// Copyright Information: See EvtGen/COPYRIGHT
// Copyright (C) 2002 Caltech, UCSB
//
// Module: EvtGen/EvtAmpIndex.hh
//
// Description:This class keeps track of indices on amplitude objects.
//
// Modification history:
//
// Ryd Nov 22, 2002 Module created
//
//------------------------------------------------------------------------
#ifndef EVTAMPINDEX_HH
#define EVTAMPINDEX_HH
#include <vector>
class EvtAmpIndex {
friend class EvtAmpSubIndex;
public:
EvtAmpIndex(std::vector<int> ind);
virtual ~EvtAmpIndex() {}
void reset();
bool next();
int index();
private:
std::vector<int> _ind;
int _size;
std::vector<int> _state;
std::vector<int> _nstate;
};
#endif
| 19.634615 | 76 | 0.572968 | [
"vector"
] |
0b22c393b393f7da2b22f25c20822ae3e9abad49 | 870 | cpp | C++ | 202011/17/_654_MaximumBinaryTree.cpp | uaniheng/leetcode-cpp | d7b4c9ef43cca8ecb703da5a910d79af61eb3394 | [
"Apache-2.0"
] | null | null | null | 202011/17/_654_MaximumBinaryTree.cpp | uaniheng/leetcode-cpp | d7b4c9ef43cca8ecb703da5a910d79af61eb3394 | [
"Apache-2.0"
] | null | null | null | 202011/17/_654_MaximumBinaryTree.cpp | uaniheng/leetcode-cpp | d7b4c9ef43cca8ecb703da5a910d79af61eb3394 | [
"Apache-2.0"
] | null | null | null | //
// Created by gyc on 2020/11/17.
//
#include "../../common.h"
class Solution {
private:
TreeNode *build(vector<int> &nums, int begin, int end) {
if (begin >= end) {
return nullptr;
} else {
auto max = max_element(nums.begin() + begin, nums.begin() + end);
int index = max - nums.begin();
auto node = new TreeNode(*max);
node->left = build(nums, begin, index);
node->right = build(nums, index + 1, end);
return node;
}
}
public:
TreeNode *constructMaximumBinaryTree(vector<int> &nums) {
return build(nums, 0, nums.size());
}
};
int main() {
vector<int> vec{3, 2, 1, 6, 0, 5};
auto res = Solution().constructMaximumBinaryTree(vec);
cout << res->val << endl;
vector<int> v{1, 2, 3, 4};
cout << true << endl;
} | 22.307692 | 77 | 0.527586 | [
"vector"
] |
0b34291b72ea6235c5db347c236925b5531e620e | 2,416 | cpp | C++ | MoravaEngine/src/Platform/DX11/DX11PixelShader.cpp | dtrajko/MoravaEngine | dab8a9e84bde6bdb5e979596c29cabccb566b9d4 | [
"Apache-2.0"
] | 168 | 2020-07-18T04:20:27.000Z | 2022-03-31T23:39:38.000Z | MoravaEngine/src/Platform/DX11/DX11PixelShader.cpp | dtrajko/MoravaEngine | dab8a9e84bde6bdb5e979596c29cabccb566b9d4 | [
"Apache-2.0"
] | 5 | 2020-11-23T12:33:06.000Z | 2022-01-05T15:15:30.000Z | MoravaEngine/src/Platform/DX11/DX11PixelShader.cpp | dtrajko/MoravaEngine | dab8a9e84bde6bdb5e979596c29cabccb566b9d4 | [
"Apache-2.0"
] | 8 | 2020-09-07T03:04:18.000Z | 2022-03-25T13:47:16.000Z | #include "DX11PixelShader.h"
#include "DX11Context.h"
#include <exception>
DX11PixelShader::DX11PixelShader(const wchar_t* pixelShaderPath)
{
ID3D11Device* dx11Device = DX11Context::Get()->GetDX11Device();
CompileDX11Shader(pixelShaderPath);
HRESULT hr = dx11Device->CreatePixelShader(m_BytecodePointer, m_BytecodeLength, nullptr, &m_DX11PixelShader);
if (FAILED(hr))
{
throw std::exception("DX11PixelShader initialization failed.");
}
// ReleaseCompiledDX11Shader();
Log::GetLogger()->info("DX11PixelShader '{0}' has been successfully created!", Util::to_str(pixelShaderPath));
}
DX11PixelShader::~DX11PixelShader()
{
// ReleaseCompiledDX11Shader();
if (m_DX11PixelShader) m_DX11PixelShader->Release();
Log::GetLogger()->info("DX11PixelShader destroyed!");
}
void DX11PixelShader::Bind()
{
DX11Context::Get()->GetDX11DeviceContext()->PSSetShader(m_DX11PixelShader, nullptr, 0);
}
void DX11PixelShader::BindConstantBuffer(Hazel::Ref<DX11ConstantBuffer> constantBuffer)
{
DX11Context::Get()->GetDX11DeviceContext()->PSSetConstantBuffers(0, 1, &constantBuffer->m_Buffer);
}
void DX11PixelShader::SetTextures(const std::vector<Hazel::Ref<Hazel::HazelTexture>>& textures)
{
size_t textureCount = textures.size();
ID3D11ShaderResourceView* list_res[32];
ID3D11SamplerState* list_sampler[32];
for (unsigned int i = 0; i < textureCount; i++)
{
list_res[i] = textures[i].As<DX11Texture2D>()->m_ShaderResourceViewDX11;
list_sampler[i] = textures[i].As<DX11Texture2D>()->m_SamplerStateDX11;
}
DX11Context::Get()->GetDX11DeviceContext()->PSSetShaderResources(0, (UINT)textureCount, list_res);
DX11Context::Get()->GetDX11DeviceContext()->PSSetSamplers(0, (UINT)textureCount, list_sampler);
}
bool DX11PixelShader::CompileDX11Shader(const wchar_t* fileName)
{
const char* entryPointName = "psmain";
const char* entryPoint = "ps_5_0";
ID3DBlob* errorBlob = nullptr;
HRESULT hr = ::D3DCompileFromFile(fileName, nullptr, nullptr, entryPointName, entryPoint, 0, 0, &m_Blob, &errorBlob);
if (FAILED(hr))
{
if (errorBlob)
{
errorBlob->Release();
}
return false;
}
m_BytecodePointer = m_Blob->GetBufferPointer();
m_BytecodeLength = m_Blob->GetBufferSize();
Log::GetLogger()->info("DX11PixelShader '{0}' has been successfully compiled!", Util::to_str(fileName));
return true;
}
void DX11PixelShader::ReleaseCompiledDX11Shader()
{
if (m_Blob) m_Blob->Release();
}
| 26.844444 | 118 | 0.750414 | [
"vector"
] |
0b367a643ea15ccbdeaf25c0ac170df3a05c78cd | 7,936 | cc | C++ | acc_unit_test/acc_unit_test.cc | gicLAB/SECDA | 5ee8ec5032657ddd05798e98075e654bdd5a0041 | [
"Apache-2.0"
] | 5 | 2021-09-30T14:22:49.000Z | 2022-03-01T01:24:03.000Z | acc_unit_test/acc_unit_test.cc | gicLAB/SECDA | 5ee8ec5032657ddd05798e98075e654bdd5a0041 | [
"Apache-2.0"
] | 1 | 2022-02-03T01:07:53.000Z | 2022-02-03T01:07:53.000Z | acc_unit_test/acc_unit_test.cc | gicLAB/SECDA | 5ee8ec5032657ddd05798e98075e654bdd5a0041 | [
"Apache-2.0"
] | 1 | 2022-01-27T13:15:06.000Z | 2022-01-27T13:15:06.000Z |
#include <fcntl.h>
#include <getopt.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <iostream>
#include <sys/mman.h>
#include <fstream>
#include <cstdio>
#include <string>
#include <vector>
#include "helper.h"
bool file_check(const std::string& name) {
struct stat buffer;
return (stat (name.c_str(), &buffer) == 0);
}
bool check_data(const std::string& name) {
bool i0 = file_check(name+"/input_0.txt");
bool i1 = file_check(name+"/input_1.txt");
bool i2 = file_check(name+"/input_2.txt");
bool i3 = file_check(name+"/input_3.txt");
bool w0 = file_check(name+"/weight_0.txt");
bool w1 = file_check(name+"/weight_1.txt");
bool w2 = file_check(name+"/weight_2.txt");
bool w3 = file_check(name+"/weight_3.txt");
return (i0 && i1 && i2 && i3 && w0 && w1 && w2 && w3);
}
struct Settings {
string input_base = "aData/model_l0_w0_i0";
string weight_base = "aData/model0_w0_i0";
string output_base = "aData/out";
bool vm = false;
};
void display_usage() {
cout<< "Nothing to see here\n"<< "\n";
}
int main(int argc, char *argv[]){
Settings s;
int c;
while (1) {
static struct option long_options[] = {
{"input", required_argument, nullptr, 'i'},
{"systolic", required_argument, nullptr, 's'},
{nullptr, 0, nullptr, 0}};
/* getopt_long stores the option index here. */
int option_index = 0;
c = getopt_long(argc, argv,
"i:s:", long_options,
&option_index);
/* Detect the end of the options. */
if (c == -1) break;
switch (c) {
case 'i':
s.input_base = optarg;
break;
case 's':
s.vm = strtol(optarg, nullptr, 10);
break;
case 'h':
case '?':
/* getopt_long already printed an error message. */
display_usage();
exit(-1);
default:
exit(-1);
}
}
int* gemm = getArray(acc_address,page_size);
int dh = open("/dev/mem", O_RDWR | O_SYNC); // Open /dev/mem which represents the whole physical memory
gemm[0]=1;
void *dma_mm0 = mmap(NULL, page_size, PROT_READ | PROT_WRITE, MAP_SHARED, dh, dma_addr0); // Memory map AXI Lite register block
void *dma_mm1 = mmap(NULL, page_size, PROT_READ | PROT_WRITE, MAP_SHARED, dh, dma_addr1); // Memory map AXI Lite register block
void *dma_mm2 = mmap(NULL, page_size, PROT_READ | PROT_WRITE, MAP_SHARED, dh, dma_addr2); // Memory map AXI Lite register block
void *dma_mm3 = mmap(NULL, page_size, PROT_READ | PROT_WRITE, MAP_SHARED, dh, dma_addr3); // Memory map AXI Lite register block
void *dma_in_mm0 = mmap(NULL, dma_buffer_len, PROT_READ | PROT_WRITE, MAP_SHARED, dh, dma_addr_in0); // Memory map source address
void *dma_in_mm1 = mmap(NULL, dma_buffer_len, PROT_READ | PROT_WRITE, MAP_SHARED, dh, dma_addr_in1); // Memory map source address
void *dma_in_mm2 = mmap(NULL, dma_buffer_len, PROT_READ | PROT_WRITE, MAP_SHARED, dh, dma_addr_in2); // Memory map source address
void *dma_in_mm3 = mmap(NULL, dma_buffer_len, PROT_READ | PROT_WRITE, MAP_SHARED, dh, dma_addr_in3); // Memory map source address
void *dma_out_mm0 = mmap(NULL, dma_buffer_len, PROT_READ, MAP_SHARED, dh, dma_addr_out0); // Memory map destination address
void *dma_out_mm1 = mmap(NULL, dma_buffer_len, PROT_READ, MAP_SHARED, dh, dma_addr_out1); // Memory map destination address
void *dma_out_mm2 = mmap(NULL, dma_buffer_len, PROT_READ, MAP_SHARED, dh, dma_addr_out2); // Memory map destination address
void *dma_out_mm3 = mmap(NULL, dma_buffer_len, PROT_READ, MAP_SHARED, dh, dma_addr_out3); // Memory map destination address
close(dh);
unsigned int* dma0 =reinterpret_cast<unsigned int*> (dma_mm0);
unsigned int* dma1 =reinterpret_cast<unsigned int*> (dma_mm1);
unsigned int* dma2 =reinterpret_cast<unsigned int*> (dma_mm2);
unsigned int* dma3 =reinterpret_cast<unsigned int*> (dma_mm3);
unsigned int* dma_in0 =reinterpret_cast<unsigned int*> (dma_in_mm0);
unsigned int* dma_in1 =reinterpret_cast<unsigned int*> (dma_in_mm1);
unsigned int* dma_in2 =reinterpret_cast<unsigned int*> (dma_in_mm2);
unsigned int* dma_in3 =reinterpret_cast<unsigned int*> (dma_in_mm3);
int* dma_out0 =reinterpret_cast<int*> (dma_out_mm0);
int* dma_out1 =reinterpret_cast<int*> (dma_out_mm1);
int* dma_out2 =reinterpret_cast<int*> (dma_out_mm2);
int* dma_out3 =reinterpret_cast<int*> (dma_out_mm3);
initDMA(dma0,dma_addr_in0,dma_addr_out0);
initDMA(dma1,dma_addr_in1,dma_addr_out1);
initDMA(dma2,dma_addr_in2,dma_addr_out2);
initDMA(dma3,dma_addr_in3,dma_addr_out3);
struct accelerator acc = {
gemm,
dma0,dma1,dma2,dma3,
dma_in0,dma_in1,dma_in2,dma_in3,
dma_out0,dma_out1,dma_out2,dma_out3,
};
if(!check_data(s.input_base)){
cout << "Data files missing or not specified" << endl;
return 0;
}
cout << s.input_base+"/weight" << endl;
cout << "Running" << endl;
rec_out(acc);
read_in(s.input_base+"/weight",acc);
read_in(s.input_base+"/input",acc);
dma_s2mm_sync<int>(acc.dma0);
dma_s2mm_sync<int>(acc.dma1);
dma_s2mm_sync<int>(acc.dma2);
dma_s2mm_sync<int>(acc.dma3);
cout << "Done" << endl;
if (s.vm){
cout << "====================VECTOR_MAC========================" << endl;
cout << "RMax: " << gemm[43] << endl;
cout << "LMax: " << gemm[45] << endl;
cout << "Loading Cycles: " << gemm[7] << endl;
cout << "Processing Cycles: " << gemm[9] << endl;
cout << "==================================================" << endl;
cout << "G1 Idle Cycles: " << gemm[11] << endl;
cout << "G2 Idle Cycles: " << gemm[13] << endl;
cout << "G3 Idle Cycles: " << gemm[15] << endl;
cout << "G4 Idle Cycles: " << gemm[17] << endl;
cout << "==================================================" << endl;
cout << "G1 Write Cycles: " << gemm[19] << endl;
cout << "G2 Write Cycles: " << gemm[21] << endl;
cout << "G3 Write Cycles: " << gemm[23] << endl;
cout << "G4 Write Cycles: " << gemm[25] << endl;
cout << "==================================================" << endl;
cout << "G1 WStall Cycles: " << gemm[35] << endl;
cout << "G2 WStall Cycles: " << gemm[37] << endl;
cout << "G3 WStall Cycles: " << gemm[39] << endl;
cout << "G4 WStall Cycles: " << gemm[41] << endl;
cout << "==================================================" << endl;
cout << "G1 GEMM Cycles: " << gemm[27] << endl;
cout << "G2 GEMM Cycles: " << gemm[29] << endl;
cout << "G3 GEMM Cycles: " << gemm[31] << endl;
cout << "G4 GEMM Cycles: " << gemm[33] << endl;
cout << "==================================================" << endl;
}else{
cout << "====================SYSTOLIC_ARRAY========================" << endl;
cout << "RMax: " << gemm[19] << endl;
cout << "LMax: " << gemm[21] << endl;
cout << "Loading Cycles: " << gemm[7] << endl;
cout << "Processing Cycles: " << gemm[9] << endl;
cout << "==================================================" << endl;
cout << "G1 Idle Cycles: " << gemm[11] << endl;
cout << "G1 Write Cycles: " << gemm[13] << endl;
cout << "G1 WStall Cycles: " << gemm[17] << endl;
cout << "G1 GEMM Cycles: " << gemm[15] << endl;
cout << "==================================================" << endl;
}
munmap(dma_in_mm0,dma_buffer_len);
munmap(dma_in_mm1,dma_buffer_len);
munmap(dma_in_mm2,dma_buffer_len);
munmap(dma_in_mm3,dma_buffer_len);
munmap(dma_out_mm0,dma_buffer_len);
munmap(dma_out_mm1,dma_buffer_len);
munmap(dma_out_mm2,dma_buffer_len);
munmap(dma_out_mm3,dma_buffer_len);
return 0;
} | 41.333333 | 136 | 0.583669 | [
"vector"
] |
0b3b408b54fe0e292bfff2b20aae920d89ddd30c | 5,177 | hpp | C++ | s32v234_sdk/libs/apexcv_pro/hough/graphs/hough_10x4_graph.hpp | intesight/Panorama4AIWAYS | 46e1988e54a5155be3b3b47c486b3f722be00b5c | [
"WTFPL"
] | null | null | null | s32v234_sdk/libs/apexcv_pro/hough/graphs/hough_10x4_graph.hpp | intesight/Panorama4AIWAYS | 46e1988e54a5155be3b3b47c486b3f722be00b5c | [
"WTFPL"
] | null | null | null | s32v234_sdk/libs/apexcv_pro/hough/graphs/hough_10x4_graph.hpp | intesight/Panorama4AIWAYS | 46e1988e54a5155be3b3b47c486b3f722be00b5c | [
"WTFPL"
] | 2 | 2021-01-21T02:06:16.000Z | 2021-01-28T10:47:37.000Z | /*****************************************************************************
*
* NXP Confidential Proprietary
*
* Copyright (c) 2014-2016 Freescale Semiconductor
* Copyright 2017-2018 NXP
* All Rights Reserved
*
******************************************************************************
*
* THIS SOFTWARE IS PROVIDED BY NXP "AS IS" AND ANY EXPRESSED OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL NXP OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/*!*********************************************************************************
* \file
* \brief ACF graph for Hough Transform.
***********************************************************************************/
#ifndef HOUGH10X4GRAPH_HPP
#define HOUGH10X4GRAPH_HPP
#include <acf_graph.hpp>
#include "hough_acf.h"
/*!*********************************************************************************
* \brief ACF graph for Hough Transform.
***********************************************************************************/
class Hough_Graph : public ACF_Graph
{
public:
Hough_Graph() : ACF_Graph()
{
XREGISTER_ACF_KERNEL(HOUGH_INIT_PIXEL_OFFSET_K)
XREGISTER_ACF_KERNEL(HOUGH_PIXEL_THRESHOLD_K)
XREGISTER_ACF_KERNEL(HOUGH_SCALARIZE_PIXELS_K)
XREGISTER_ACF_KERNEL(HOUGH_ACCUMULATE_K)
XREGISTER_ACF_KERNEL(HOUGH_INIT_CU_INDEX_K)
XREGISTER_ACF_KERNEL(HOUGH_GET_LINES_K)
}
/*!*********************************************************************************
* \brief Create the ACF graph.
*
* In this function we
* - set the graph's unique identifier.
* - add the column filter kernel
* - add graph ports for the source image, filter coefficients and destination image
* - connect graph ports to kernel ports
***********************************************************************************/
void Create()
{
//set identifier for graph
SetIdentifier("Hough_Graph");
// Add kernels
AddKernel("initPixelOffset", HOUGH_INIT_PIXEL_OFFSET_KN);
AddKernel("pixelThreshold", HOUGH_PIXEL_THRESHOLD_KN);
AddKernel("scalarizePixels", HOUGH_SCALARIZE_PIXELS_KN);
AddKernel("accumulate", HOUGH_ACCUMULATE_KN);
AddKernel("initCuIndex", HOUGH_INIT_CU_INDEX_KN);
AddKernel("getLines", HOUGH_GET_LINES_KN);
// Graph ports input
AddInputPort("IMAGE");
AddInputPort("PIXEL_THRESHOLD");
AddInputPort("PIXEL_OFFSET_PARAMS");
AddInputPort("CU_COUNT");
AddInputPort("COS_TABLE");
AddInputPort("SIN_TABLE");
AddInputPort("RHO_COUNT");
AddInputPort("CU_INDEX_PARAMS");
AddInputPort("LINE_THRESHOLD_PARAMS");
// Graph ports output
AddOutputPort("LINES");
AddOutputPort("LINE_COUNT");
// Connect input ports
Connect(GraphPort("IMAGE"), KernelPort("pixelThreshold", "IMAGE"));
Connect(GraphPort("PIXEL_THRESHOLD"), KernelPort("pixelThreshold", "THRESHOLD"));
Connect(GraphPort("PIXEL_OFFSET_PARAMS"), KernelPort("initPixelOffset", "PARAMS"));
Connect(GraphPort("CU_COUNT"), KernelPort("scalarizePixels", "CU_COUNT"));
Connect(GraphPort("COS_TABLE"), KernelPort("accumulate", "COS_TABLE"));
Connect(GraphPort("SIN_TABLE"), KernelPort("accumulate", "SIN_TABLE"));
Connect(GraphPort("RHO_COUNT"), KernelPort("accumulate", "RHO_COUNT"));
Connect(GraphPort("CU_INDEX_PARAMS"), KernelPort("initCuIndex", "PARAMS"));
Connect(GraphPort("LINE_THRESHOLD_PARAMS"), KernelPort("getLines", "PARAMS"));
// Connect kernel ports
Connect(KernelPort("initPixelOffset", "OFFSET_X"), KernelPort("pixelThreshold", "OFFSET_X"));
Connect(KernelPort("initPixelOffset", "OFFSET_Y"), KernelPort("pixelThreshold", "OFFSET_Y"));
Connect(KernelPort("pixelThreshold", "PIXELS_X"), KernelPort("scalarizePixels", "VEC_PIXELS_X"));
Connect(KernelPort("pixelThreshold", "PIXELS_Y"), KernelPort("scalarizePixels", "VEC_PIXELS_Y"));
Connect(KernelPort("pixelThreshold", "PIXEL_COUNT"), KernelPort("scalarizePixels", "VEC_PIXEL_COUNT"));
Connect(KernelPort("scalarizePixels", "SCL_PIXELS_X"), KernelPort("accumulate", "PIXELS_X"));
Connect(KernelPort("scalarizePixels", "SCL_PIXELS_Y"), KernelPort("accumulate", "PIXELS_Y"));
Connect(KernelPort("scalarizePixels", "SCL_PIXEL_COUNT"), KernelPort("accumulate", "PIXEL_COUNT"));
Connect(KernelPort("accumulate", "ACCUMULATOR"), KernelPort("getLines", "ACCUMULATOR"));
Connect(KernelPort("initCuIndex", "CU_INDEX"), KernelPort("getLines", "CU_INDEX"));
// Connect output ports
Connect(KernelPort("getLines", "LINES"), GraphPort("LINES"));
Connect(KernelPort("getLines", "LINE_COUNT"), GraphPort("LINE_COUNT"));
}
};
#endif /* HOUGH10X4GRAPH_HPP */
| 43.872881 | 105 | 0.647672 | [
"transform"
] |
0b5688757d632b6ba54667c0bc7640374d11da7e | 3,300 | cpp | C++ | Semantic/SymbolTable/Entries/Function.cpp | mori-ahk/Sky | b8b27a3d5e63905c95d2305ee931821737a56d12 | [
"MIT"
] | 1 | 2020-04-29T02:11:42.000Z | 2020-04-29T02:11:42.000Z | Semantic/SymbolTable/Entries/Function.cpp | mori-ahk/Sky | b8b27a3d5e63905c95d2305ee931821737a56d12 | [
"MIT"
] | null | null | null | Semantic/SymbolTable/Entries/Function.cpp | mori-ahk/Sky | b8b27a3d5e63905c95d2305ee931821737a56d12 | [
"MIT"
] | null | null | null | //
// Created by Morteza Ahmadi on 2020-03-05.
//
#include "Function.h"
#include <utility>
#include "../../Error/Error.h"
Function::Function(Enums::Visibility visibility, std::string name, std::string returnType, std::vector<Variable *> params,
std::vector<Variable *> localVars, int position) {
this->visibility = visibility;
this->name = std::move(name);
this->returnType = std::move(returnType);
this->params = std::move(params);
this->localVars = std::move(localVars);
this->position = position;
this->isDefined = false;
this->offset = 0;
this->size = 0;
}
const std::string &Function::getName() const {
return name;
}
const std::string &Function::getReturnType() const {
return returnType;
}
std::string Function::getVisibilityString() const {
if (getVisibility() == Enums::Visibility::PUBLIC) return "public";
else return "private";
}
const std::vector<Variable *> &Function::getParams() const {
return params;
}
const std::vector<Variable *> &Function::getLocalVars() const {
return localVars;
}
Variable *Function::getVariable(std::string &varName) const {
for (const auto& var : localVars) {
if (var->getName() == varName) return var;
}
throw Semantic::Err::UndeclaredLocalVariable(varName);
}
Enums::Visibility Function::getVisibility() const {
return visibility;
}
void Function::addParam(Variable *variable) {
for (auto param : params)
if (param->getName() == variable->getName())
throw Semantic::Err::DuplicateFuncParam(variable->getPosition());
params.push_back(variable);
addVariable(variable);
}
void Function::addVariable(Variable *variable) {
for (auto var: localVars)
if (var->getName() == variable->getName())
throw Semantic::Err::DuplicateDataMember(variable->getName(), variable->getPosition());
localVars.push_back(variable);
}
std::ostream &operator<<(std::ostream &os, Function &f) {
std::string visibility = f.getVisibilityString();
os << "FUNCTION:\n";
os << "\t[ " << "visibility: " << visibility << " | name: " << f.getName() << " | returns: " << f.getReturnType()
<< " ]" << std::endl;
os << "\t\tVARIABLE(S): \n";
for (auto &var : f.getLocalVars()) {
os << "\t\t" << *var;
}
return os;
}
bool Function::isParamsEqual(Function &lhs, Function &rhs) {
if (lhs.getParams().size() != rhs.getParams().size()) return false;
for (int i = 0; i < lhs.getParams().size(); i++) {
auto lParam = *lhs.getParams().at(i);
auto rParam = *rhs.getParams().at(i);
if (lParam == rParam) continue;
else return false;
}
return true;
}
int Function::getOffset() const {
return offset;
}
void Function::setOffset(int _offset) {
Function::offset = _offset;
}
int Function::getSize() const {
return size;
}
void Function::setSize(int size) {
Function::size = size;
}
int Function::getVariableOffset() const {
if (sizes.size() == 1) return 0;
int toReturn = 0;
for (int i = 0; i < sizes.size() - 1; i++) toReturn += sizes.at(i);
return toReturn;
}
const std::string &Function::getTag() const {
return tag;
}
void Function::setTag(const std::string &tag) {
Function::tag = tag;
}
| 26.190476 | 122 | 0.627273 | [
"vector"
] |
0b5b60a8165abf0aa281365599b2e5d28616df9b | 4,549 | cc | C++ | tensorflow/contrib/lite/kernels/transpose_test.cc | jhabikal21/tensorflow | 98d20962172301385aae694141801a375debd2bc | [
"Apache-2.0"
] | null | null | null | tensorflow/contrib/lite/kernels/transpose_test.cc | jhabikal21/tensorflow | 98d20962172301385aae694141801a375debd2bc | [
"Apache-2.0"
] | null | null | null | tensorflow/contrib/lite/kernels/transpose_test.cc | jhabikal21/tensorflow | 98d20962172301385aae694141801a375debd2bc | [
"Apache-2.0"
] | null | null | null | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <gtest/gtest.h>
#include "tensorflow/contrib/lite/interpreter.h"
#include "tensorflow/contrib/lite/kernels/internal/reference/reference_ops.h"
#include "tensorflow/contrib/lite/kernels/internal/tensor.h"
#include "tensorflow/contrib/lite/kernels/test_util.h"
namespace tflite {
namespace {
void RunTestPermutation(const std::vector<int>& shape,
const std::vector<int>& perms,
std::vector<float>* input_transposed) {
// Count elements and allocate output.
int count = 1;
for (auto factor : shape) count *= factor;
input_transposed->resize(count);
// Create the dummy data
std::vector<float> input(count);
for (int i = 0; i < input.size(); i++) {
input[i] = i;
}
// Create reversed and padded perms.
int reversed_perms[4];
for (int output_k = 0, input_k = shape.size() - 1; output_k < shape.size();
output_k++, input_k--) {
reversed_perms[output_k] = shape.size() - perms[input_k] - 1;
}
// Unused dimensions should not be permuted so pad with identity transform
// subset.
for (int k = shape.size(); k < 4; k++) {
reversed_perms[k] = k;
}
// Make input and output dims (i.e. reversed shape and dest_shape).
Dims<4> input_dims = GetTensorDims(shape);
Dims<4> output_dims;
for (int i = 0; i < 4; i++) {
output_dims.sizes[i] = input_dims.sizes[reversed_perms[i]];
}
output_dims.strides[0] = 1;
for (int k = 1; k < 4; k++) {
output_dims.strides[k] =
output_dims.strides[k - 1] * output_dims.sizes[k - 1];
}
reference_ops::Transpose<float>(input.data(), input_dims,
input_transposed->data(), output_dims,
reversed_perms);
}
TEST(TransposeTest, Test1D) {
// Basic 1D identity.
std::vector<float> out;
RunTestPermutation({3}, {0}, &out);
ASSERT_EQ(out, std::vector<float>({0, 1, 2}));
}
TEST(TransposeTest, Test2D) {
std::vector<float> out;
// Basic 2D.
RunTestPermutation({3, 2}, {1, 0}, &out);
ASSERT_EQ(out, std::vector<float>({0, 2, 4, 1, 3, 5}));
// Identity.
RunTestPermutation({3, 2}, {0, 1}, &out);
ASSERT_EQ(out, std::vector<float>({0, 1, 2, 3, 4, 5}));
}
TEST(TransposeTest, Test3D) {
std::vector<float> out;
// Test 3 dimensional
{
std::vector<float> ref({0, 4, 8, 12, 16, 20, 1, 5, 9, 13, 17, 21,
2, 6, 10, 14, 18, 22, 3, 7, 11, 15, 19, 23});
RunTestPermutation({2, 3, 4}, {2, 0, 1}, &out);
ASSERT_EQ(out, ref);
}
// Test 3 dimensional identity transform
{
RunTestPermutation({2, 3, 4}, {0, 1, 2}, &out);
std::vector<float> ref(out.size());
for (int k = 0; k < ref.size(); k++) ref[k] = k;
ASSERT_EQ(out, ref);
}
}
TEST(TransposeTest, Test4D) {
std::vector<float> out;
// Basic 4d.
RunTestPermutation({2, 3, 4, 5}, {2, 0, 1, 3}, &out);
ASSERT_EQ(
out,
std::vector<float>(
{0, 1, 2, 3, 4, 20, 21, 22, 23, 24, 40, 41, 42, 43, 44,
60, 61, 62, 63, 64, 80, 81, 82, 83, 84, 100, 101, 102, 103, 104,
5, 6, 7, 8, 9, 25, 26, 27, 28, 29, 45, 46, 47, 48, 49,
65, 66, 67, 68, 69, 85, 86, 87, 88, 89, 105, 106, 107, 108, 109,
10, 11, 12, 13, 14, 30, 31, 32, 33, 34, 50, 51, 52, 53, 54,
70, 71, 72, 73, 74, 90, 91, 92, 93, 94, 110, 111, 112, 113, 114,
15, 16, 17, 18, 19, 35, 36, 37, 38, 39, 55, 56, 57, 58, 59,
75, 76, 77, 78, 79, 95, 96, 97, 98, 99, 115, 116, 117, 118, 119}));
RunTestPermutation({2, 3, 4, 5}, {0, 1, 2, 3}, &out);
// Basic identity.
std::vector<float> ref(out.size());
for (int k = 0; k < ref.size(); k++) ref[k] = k;
ASSERT_EQ(out, ref);
}
} // namespace
} // namespace tflite
int main(int argc, char** argv) {
::tflite::LogToStderr();
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 34.462121 | 80 | 0.588261 | [
"shape",
"vector",
"transform"
] |
0b5ca96bf4050d1df8d93a47457efa14ae1bfa84 | 4,523 | cpp | C++ | inference-engine/tools/calibration_tool/statistics_collector/data_stats.cpp | zhoub/dldt | e42c01cf6e1d3aefa55e2c5df91f1054daddc575 | [
"Apache-2.0"
] | null | null | null | inference-engine/tools/calibration_tool/statistics_collector/data_stats.cpp | zhoub/dldt | e42c01cf6e1d3aefa55e2c5df91f1054daddc575 | [
"Apache-2.0"
] | null | null | null | inference-engine/tools/calibration_tool/statistics_collector/data_stats.cpp | zhoub/dldt | e42c01cf6e1d3aefa55e2c5df91f1054daddc575 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2019 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <stdlib.h>
#include <cfloat>
#include <cmath>
#include <iostream>
#include <limits>
#include <vector>
#include <algorithm>
#include <stdint.h>
#include <string>
#include "data_stats.hpp"
//----- dataStats -----//
void dataStats::registerLayer(const std::string& name, size_t batch, size_t channels) {
_registeredLayers.push_back({name, batch, channels});
}
void dataStats::addStatistics(const std::string &name, size_t channel, uint8_t *data, size_t count) {
float* dst = new float[count];
for (size_t i = 0lu; i < count; i++) {
dst[i] = static_cast<float>(data[i]);
}
addStatistics(name, channel, dst, count);
delete[] dst;
}
void dataStats::addStatistics(const std::string &name, size_t channel, short *data, size_t count) {
float* dst = new float[count];
for (size_t i = 0lu; i < count; i++) {
dst[i] = static_cast<float>(data[i]);
}
addStatistics(name, channel, dst, count);
delete[] dst;
}
//----- simpleDataStats -----//
void simpleDataStats::registerLayer(const std::string& name, size_t batch, size_t channels) {
dataStats::registerLayer(name, batch, channels);
_data[name];
}
size_t simpleDataStats::getNumberChannels(const std::string& name) const {
auto it = _data.find(name);
if (it != _data.end()) {
return it->second.size();
}
return 0lu;
}
void simpleDataStats::addStatistics(const std::string& name, size_t channel, float* data, size_t count) {
auto& byChannel = _data[name][channel];
// TODO: Investigate synchronization of _data usage
// add_mutex.lock();
for (size_t i = 0lu; i < count; i++) {
if (byChannel._min > data[i]) {
byChannel._min = data[i];
}
if (byChannel._max < data[i]) {
byChannel._max = data[i];
}
}
// add_mutex.unlock();
}
void simpleDataStats::getDataMinMax(const std::string& name, size_t channel, float& min, float& max, float threshold) {
auto it = _data.find(name);
if (it != _data.end()) {
min = it->second[channel]._min;
max = it->second[channel]._max;
} else {
min = max = 0.f;
}
}
//----- TensorStatistic -----//
TensorStatistic::TensorStatistic(float* data, size_t count, size_t nbuckets) {
_min = std::numeric_limits<float>::max();
_max = std::numeric_limits<float>::min();
for (size_t i = 0; i < count; i++) {
float val = static_cast<float>(data[i]);
if (_min > val) {
_min = val;
}
if (_max < val) {
_max = val;
}
}
if (_min == _max) {
return;
}
}
float TensorStatistic::getMaxValue() const {
return _max;
}
float TensorStatistic::getMinValue() const {
return _min;
}
//----- AggregatedDataStats -----//
void AggregatedDataStats::registerLayer(const std::string& name, size_t batch, size_t channels) {
dataStats::registerLayer(name , batch, channels);
_data[name];
}
void AggregatedDataStats::addStatistics(const std::string& name, size_t channel, float* data, size_t count) {
auto&& byChannel = _data[name];
byChannel[channel].push_back(TensorStatistic(data, count));
}
size_t AggregatedDataStats::getNumberChannels(const std::string& name) const {
auto it = _data.find(name);
if (it != _data.end()) {
return it->second.size();
}
return 0lu;
}
void AggregatedDataStats::getDataMinMax(const std::string& name, size_t channel, float& min, float& max, float threshold) {
// take data by name
auto it = _data.find(name);
if (it != _data.end()) {
auto stats = it->second[channel];
// having absolute min/max values, we can create new statistic
std::vector<float> maxValues;
std::vector<float> minValues;
for (size_t i = 0; i < stats.size(); i++) {
const TensorStatistic& tsS = stats[i];
maxValues.push_back(tsS.getMaxValue());
minValues.push_back(tsS.getMinValue());
}
// define number of elements to throw out
size_t elementToTake = static_cast<size_t>(maxValues.size() * (threshold / 100));
int elementsToThrow = maxValues.size() - elementToTake;
std::sort(maxValues.begin(), maxValues.end());
std::sort(minValues.begin(), minValues.end());
min = minValues[elementsToThrow];
max = maxValues[elementToTake - 1];
} else {
min = max = 0.f;
}
}
| 29.953642 | 123 | 0.619721 | [
"vector"
] |
0b60f7df115bc34086bc287a720aca38fe43c811 | 267 | cpp | C++ | String reverse.cpp | jahnvisrivastava100/Leetcode-Solutions | d3acdb1fac94afc704c233235c8914004fe4c846 | [
"CC0-1.0"
] | null | null | null | String reverse.cpp | jahnvisrivastava100/Leetcode-Solutions | d3acdb1fac94afc704c233235c8914004fe4c846 | [
"CC0-1.0"
] | null | null | null | String reverse.cpp | jahnvisrivastava100/Leetcode-Solutions | d3acdb1fac94afc704c233235c8914004fe4c846 | [
"CC0-1.0"
] | null | null | null | class Solution {
public:
void rev(vector<char>& s,int l,int n){
if(l>=n){
return;
}
rev(s,l+1,n-1);
swap(s[l],s[n]);
}
void reverseString(vector<char>& s) {
rev(s,0,(size(s)-1));
}
};
| 14.833333 | 42 | 0.411985 | [
"vector"
] |
0b6b823d66fd0580c943857f17916908185984b9 | 2,923 | cpp | C++ | Engine/Source/Developer/FunctionalTesting/Private/GroundTruthData.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Developer/FunctionalTesting/Private/GroundTruthData.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Developer/FunctionalTesting/Private/GroundTruthData.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "GroundTruthData.h"
#include "UObject/UnrealType.h"
#include "UObject/Package.h"
#include "Misc/PackageName.h"
#include "AssetData.h"
#if WITH_EDITOR
#include "ISourceControlModule.h"
#include "ISourceControlProvider.h"
#include "ISourceControlOperation.h"
#endif
DEFINE_LOG_CATEGORY_STATIC(GroundTruthLog, Log, Log)
UGroundTruthData::UGroundTruthData()
: bResetGroundTruth(false)
{
}
bool UGroundTruthData::CanModify() const
{
return ObjectData == nullptr;
}
UObject* UGroundTruthData::LoadObject()
{
UE_LOG(GroundTruthLog, Log, TEXT("Loaded Ground Truth, '%s'."), *GetPathName());
return ObjectData;
}
void UGroundTruthData::SaveObject(UObject* GroundTruth)
{
FAssetData GroundTruthAssetData(this);
UPackage* GroundTruthPackage = GetOutermost();
FString GroundTruthPackageName = GroundTruthAssetData.PackageName.ToString();
#if WITH_EDITOR
if (!CanModify())
{
UE_LOG(GroundTruthLog, Warning, TEXT("Ground Truth, '%s' already set, unable to save changes. Open and use bResetGroundTruth to reset the ground truth."), *GroundTruthPackageName);
return;
}
if (GroundTruth == nullptr)
{
UE_LOG(GroundTruthLog, Error, TEXT("Ground Truth, '%s' can not store a null object."), *GroundTruthPackageName);
return;
}
if (GIsBuildMachine)
{
UE_LOG(GroundTruthLog, Error, TEXT("Ground Truth, '%s' can not be modified on the build machine."), *GroundTruthPackageName);
return;
}
if (ISourceControlModule::Get().IsEnabled())
{
ISourceControlProvider& SourceControlProvider = ISourceControlModule::Get().GetProvider();
SourceControlProvider.Execute(ISourceControlOperation::Create<FMarkForAdd>(), GroundTruthPackage);
SourceControlProvider.Execute(ISourceControlOperation::Create<FCheckOut>(), GroundTruthPackage);
}
ObjectData = GroundTruth;
GroundTruth->Rename(nullptr, this);
MarkPackageDirty();
if (!UPackage::SavePackage(GroundTruthPackage, NULL, RF_Standalone, *FPackageName::LongPackageNameToFilename(GroundTruthPackageName, FPackageName::GetAssetPackageExtension()), GError, nullptr, false, true, SAVE_NoError))
{
UE_LOG(GroundTruthLog, Error, TEXT("Failed to save ground truth data! %s"), *GroundTruthPackageName);
}
UE_LOG(GroundTruthLog, Log, TEXT("Saved Ground Truth, '%s'."), *GroundTruthPackageName);
#else
UE_LOG(GroundTruthLog, Error, TEXT("Can't save ground truth data outside of the editor, '%s'."), *GroundTruthPackageName);
#endif
}
#if WITH_EDITOR
void UGroundTruthData::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent)
{
Super::PostEditChangeProperty(PropertyChangedEvent);
if (PropertyChangedEvent.GetPropertyName() == GET_MEMBER_NAME_CHECKED(UGroundTruthData, bResetGroundTruth))
{
bResetGroundTruth = false;
if (ObjectData)
{
ObjectData->Rename(nullptr, GetTransientPackage());
ObjectData = nullptr;
}
MarkPackageDirty();
}
}
#endif | 28.105769 | 221 | 0.767362 | [
"object"
] |
0b6c16dc79382ce2a7ab00814bf1bb34449438fb | 1,420 | cpp | C++ | test/record/init.cpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 13 | 2015-02-21T18:35:14.000Z | 2019-12-29T14:08:29.000Z | test/record/init.cpp | cpreh/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 5 | 2016-08-27T07:35:47.000Z | 2019-04-21T10:55:34.000Z | test/record/init.cpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 8 | 2015-01-10T09:22:37.000Z | 2019-12-01T08:31:12.000Z | // Copyright Carl Philipp Reh 2009 - 2021.
// 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 <fcppt/catch/begin.hpp>
#include <fcppt/catch/end.hpp>
#include <fcppt/record/comparison.hpp>
#include <fcppt/record/element.hpp>
#include <fcppt/record/element_to_type.hpp>
#include <fcppt/record/get.hpp>
#include <fcppt/record/init.hpp>
#include <fcppt/record/label_value_type.hpp>
#include <fcppt/record/make_label.hpp>
#include <fcppt/record/object_impl.hpp>
#include <fcppt/record/output.hpp>
#include <fcppt/config/external_begin.hpp>
#include <catch2/catch.hpp>
#include <fcppt/config/external_end.hpp>
namespace
{
FCPPT_RECORD_MAKE_LABEL(int_label);
template <typename Record>
struct init_function
{
template <typename Type>
fcppt::record::label_value_type<Record, int_label>
operator()(fcppt::record::element<int_label, Type>) const
{
return 1;
}
};
template <typename Record>
void init_test()
{
auto const record(fcppt::record::init<Record>(init_function<Record>{}));
CHECK(fcppt::record::get<int_label>(record) == 1);
CHECK(Record{int_label{} = 1} == record);
}
}
FCPPT_CATCH_BEGIN
TEST_CASE("record::init", "[record]")
{
using my_record = fcppt::record::object<fcppt::record::element<int_label, int>>;
init_test<my_record>();
}
FCPPT_CATCH_END
| 24.482759 | 82 | 0.732394 | [
"object"
] |
0b83b8ba99d052557c75c0457e12e66574c50747 | 1,853 | cc | C++ | SimCalorimetry/EcalTrigPrimAlgos/src/EcalFenixMaxof2.cc | Purva-Chaudhari/cmssw | 32e5cbfe54c4d809d60022586cf200b7c3020bcf | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | SimCalorimetry/EcalTrigPrimAlgos/src/EcalFenixMaxof2.cc | Purva-Chaudhari/cmssw | 32e5cbfe54c4d809d60022586cf200b7c3020bcf | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | SimCalorimetry/EcalTrigPrimAlgos/src/EcalFenixMaxof2.cc | Purva-Chaudhari/cmssw | 32e5cbfe54c4d809d60022586cf200b7c3020bcf | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #include <SimCalorimetry/EcalTrigPrimAlgos/interface/EcalFenixMaxof2.h>
// global type definitions for class implementation in source file defined by
// Tag entries in ArgoUML Result: typedef <typedef_global_source> <tag_value>;
EcalFenixMaxof2::EcalFenixMaxof2(int maxNrSamples, int nbMaxStrips) : nbMaxStrips_(nbMaxStrips) {
std::vector<int> vec(maxNrSamples, 0);
for (int i2strip = 0; i2strip < nbMaxStrips_ - 1; ++i2strip)
sumby2_.push_back(vec);
}
EcalFenixMaxof2::~EcalFenixMaxof2() {}
void EcalFenixMaxof2::process(
std::vector<std::vector<int>> &bypasslinout, int nstrip, int bitMask, int bitOddEven, std::vector<int> &output) {
int mask = (1 << bitMask) - 1;
bool strip_oddmask[nstrip][output.size()];
for (int i2strip = 0; i2strip < nstrip - 1; ++i2strip)
for (unsigned int i = 0; i < output.size(); i++)
sumby2_[i2strip][i] = 0;
for (unsigned int i = 0; i < output.size(); i++)
output[i] = 0;
// Prepare also the mask of strips to be avoided because of the odd>even energy flag
for (int istrip = 0; istrip < nstrip; ++istrip) {
for (unsigned int i = 0; i < output.size(); i++) {
if ((bypasslinout[istrip][i] >> bitOddEven) & 1)
strip_oddmask[istrip][i] = false;
else
strip_oddmask[istrip][i] = true;
}
}
for (unsigned int i = 0; i < output.size(); i++) {
if (nstrip - 1 == 0) {
output[i] = strip_oddmask[0][i] * ((bypasslinout[0][i]) & mask);
} else {
for (int i2strip = 0; i2strip < nstrip - 1; ++i2strip) {
sumby2_[i2strip][i] = strip_oddmask[i2strip][i] * ((bypasslinout[i2strip][i]) & mask) +
strip_oddmask[i2strip + 1][i] * ((bypasslinout[i2strip + 1][i]) & mask);
if (sumby2_[i2strip][i] > output[i]) {
output[i] = sumby2_[i2strip][i];
}
}
}
}
return;
}
| 37.816327 | 117 | 0.619536 | [
"vector"
] |
0b9ecf588e8b25ae01a10a913e9e1051f36377e8 | 3,453 | cpp | C++ | plugins/core/client/src/Madgine/render/rendertarget.cpp | MadManRises/Madgine | c9949bc9cf8b30d63db0da2382c9fbc5b60bcd0f | [
"MIT"
] | 5 | 2018-05-16T14:09:34.000Z | 2019-10-24T19:01:15.000Z | plugins/core/client/src/Madgine/render/rendertarget.cpp | MadManRises/Madgine | c9949bc9cf8b30d63db0da2382c9fbc5b60bcd0f | [
"MIT"
] | 71 | 2017-06-20T06:41:42.000Z | 2021-01-11T11:18:53.000Z | plugins/core/client/src/Madgine/render/rendertarget.cpp | MadManRises/Madgine | c9949bc9cf8b30d63db0da2382c9fbc5b60bcd0f | [
"MIT"
] | 2 | 2018-05-16T13:57:25.000Z | 2018-05-16T13:57:51.000Z | #include "../clientlib.h"
#include "rendercontext.h"
#include "renderpass.h"
#include "rendertarget.h"
#include "Meta/keyvalue/metatable_impl.h"
#include "gpumeshloader.h"
#include "meshdata.h"
METATABLE_BEGIN(Engine::Render::RenderTarget)
METATABLE_END(Engine::Render::RenderTarget)
namespace Engine {
namespace Render {
RenderTarget::RenderTarget(RenderContext *context, bool global, std::string name, size_t iterations)
: mContext(context)
, mIterations(iterations)
, mGlobal(global)
, mName(std::move(name))
{
if (global)
mContext->addRenderTarget(this);
}
RenderTarget::~RenderTarget()
{
for (RenderPass *pass : mRenderPasses) {
pass->shutdown();
}
if (mGlobal)
mContext->removeRenderTarget(this);
}
void RenderTarget::render()
{
if (mContext->frame() == mFrame)
return;
mFrame = mContext->frame();
beginFrame();
for (RenderPass *pass : mRenderPasses)
pass->preRender();
for (size_t iteration = 0; iteration < mIterations; ++iteration) {
beginIteration(iteration);
for (RenderPass *pass : mRenderPasses)
pass->render(this, iteration);
endIteration(iteration);
}
endFrame();
}
void RenderTarget::renderQuad(Program *program)
{
renderMesh(GPUMeshLoader::loadManual("quad", {}, [](Render::GPUMeshLoader *loader, Render::GPUMeshData &data, Render::GPUMeshLoader::ResourceDataInfo &info) {
std::vector<Compound<Render::VertexPos_3D>> vertices {
{ { -1, -1, 0 } },
{ { 1, -1, 0 } },
{ { -1, 1, 0 } },
{ { 1, 1, 0 } }
};
std::vector<unsigned short> indices {
0, 1, 2, 1, 2, 3
};
return loader->generate(data, { 3, std::move(vertices), std::move(indices) });
}),
program);
}
void RenderTarget::addRenderPass(RenderPass *pass)
{
mRenderPasses.insert(
std::upper_bound(mRenderPasses.begin(), mRenderPasses.end(), pass,
[](RenderPass *first, RenderPass *second) { return first->priority() < second->priority(); }),
pass);
pass->setup(this);
}
void RenderTarget::removeRenderPass(RenderPass *pass)
{
pass->shutdown();
mRenderPasses.erase(std::find(mRenderPasses.begin(), mRenderPasses.end(), pass));
}
const std::vector<RenderPass *> &RenderTarget::renderPasses()
{
return mRenderPasses;
}
void RenderTarget::beginFrame()
{
if (!mName.empty())
pushAnnotation(mName.c_str());
}
void RenderTarget::endFrame()
{
if (!mName.empty())
popAnnotation();
}
void RenderTarget::beginIteration(size_t iteration)
{
}
void RenderTarget::endIteration(size_t iteration)
{
}
size_t RenderTarget::iterations() const
{
return mIterations;
}
RenderContext *RenderTarget::context() const
{
return mContext;
}
bool RenderTarget::resize(const Vector2i &size)
{
bool resized = resizeImpl(size);
if (resized) {
for (RenderPass *pass : mRenderPasses)
pass->onResize(size);
}
return resized;
}
}
} | 25.021739 | 166 | 0.562699 | [
"render",
"vector"
] |
0ba3fdbb2c9dd9f295484a3fc343b90b17e421a4 | 1,198 | cc | C++ | textQuery/v3/TextQuery.cc | snow-tyan/learn-cpp | ecab0fae7999005ed7fdb60ff4954b4014b2c2e6 | [
"MulanPSL-1.0"
] | null | null | null | textQuery/v3/TextQuery.cc | snow-tyan/learn-cpp | ecab0fae7999005ed7fdb60ff4954b4014b2c2e6 | [
"MulanPSL-1.0"
] | null | null | null | textQuery/v3/TextQuery.cc | snow-tyan/learn-cpp | ecab0fae7999005ed7fdb60ff4954b4014b2c2e6 | [
"MulanPSL-1.0"
] | null | null | null | #include "TextQuery.hh"
#include <ctype.h>
#include <sstream>
TextQuery::TextQuery(ifstream &ifs)
: _file(new vector<string>)
{
string line;
int lineNum = 0;
while (getline(ifs, line))
{
_file->push_back(line);
++lineNum;
istringstream iss(line);
string word;
while (iss >> word)
{
word = cleanup_str(word);
auto &lineSet = _map[word]; // lineSet是个shared_ptr
if (!lineSet) // 指针为空,申请一个set
lineSet.reset(new set<int>);
lineSet->insert(lineNum);
}
}
cout << "读取文件成功,共" << lineNum << "行" << endl;
}
string TextQuery::cleanup_str(const string &word)
{
string cleanWord;
for (auto it = word.begin(); it != word.end(); ++it)
{
if (!ispunct(*it)) // 非标点
cleanWord += tolower(*it); // 转小写
}
return cleanWord;
}
QueryResult TextQuery::query(const string &word) const
{
static shared_ptr<set<int>> nodata(new set<int>); //指向空set的shared_ptr
auto it = _map.find(word);
if (it != _map.end())
return QueryResult(word, it->second, _file);
return QueryResult(word, nodata, _file);
}
| 24.44898 | 73 | 0.5601 | [
"vector"
] |
2438e3340259fa3b5098d940c86680eb6e77ed84 | 8,236 | cpp | C++ | examples/nn/4_NLP/5_nlp_text_generation.cpp | lauracanalini/eddl | c5efac642e8e1f99b31dfaaacd0a5a058b09923b | [
"MIT"
] | null | null | null | examples/nn/4_NLP/5_nlp_text_generation.cpp | lauracanalini/eddl | c5efac642e8e1f99b31dfaaacd0a5a058b09923b | [
"MIT"
] | null | null | null | examples/nn/4_NLP/5_nlp_text_generation.cpp | lauracanalini/eddl | c5efac642e8e1f99b31dfaaacd0a5a058b09923b | [
"MIT"
] | null | null | null | /*
* EDDL Library - European Distributed Deep Learning Library.
* Version: 1.0
* copyright (c) 2021, Universitat Politècnica de València (UPV), PRHLT Research Centre
* Date: November 2021
* Author: PRHLT Research Centre, UPV, (rparedes@prhlt.upv.es), (jon@prhlt.upv.es)
* All rights reserved
*/
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include "eddl/apis/eddl.h"
#include "eddl/serialization/onnx/eddl_onnx.h" // Not allowed
using namespace eddl;
//////////////////////////////////
// Text generation
// Only Decoder
//////////////////////////////////
Tensor *onehot(Tensor *in, int vocs)
{
int n=in->shape[0];
int l=in->shape[1];
int c=0;
Tensor *out=new Tensor({n,l,vocs});
out->fill_(0.0);
int p=0;
for(int i=0;i<n*l;i++,p+=vocs) {
int w=in->ptr[i];
if (w==0) c++;
out->ptr[p+w]=1.0;
}
cout<<"padding="<<(100.0*c)/(n*l)<<"%"<<endl;
return out;
}
int main(int argc, char **argv) {
bool testing = false;
bool use_cpu = false;
for (int i = 1; i < argc; ++i) {
if (strcmp(argv[i], "--testing") == 0) testing = true;
else if (strcmp(argv[i], "--cpu") == 0) use_cpu = true;
}
download_flickr();
// Settings
int epochs = testing ? 2 : 50;
int batch_size = 24;
int olength=20;
int outvs=2000;
int embdim=32;
model net=download_resnet18(true,{3, 256, 256});
// true: remove last layers and set new top=flatten
// new input_size {3,256,256} from {224,224,3}
layer lreshape=getLayer(net,"top");
// create a new model from input output
layer image_in=getLayer(net,"input");
// Decoder
layer ldecin = Input({outvs});
layer ldec = ReduceArgMax(ldecin,{0});
ldec = RandomUniform(Embedding(ldec, outvs, 1,embdim,true),-0.05,0.05);
ldec = Concat({ldec,lreshape});
layer l = LSTM(ldec,512,true);
layer out = Softmax(Dense(l, outvs));
setDecoder(ldecin);
model old_net = net;
net = Model({image_in}, {out});
delete old_net;
plot(net, "model.pdf");
optimizer opt=adam(0.01);
//opt->set_clip_val(0.01);
compserv cs = nullptr;
if (use_cpu) {
cs = CS_CPU();
} else {
//cs = CS_GPU({1}, "low_mem"); // one GPU
cs = CS_GPU({1}); // one GPU
// cs = CS_GPU({1,1},100); // two GPU with weight sync every 100 batches
// cs = CS_CPU();
}
// Build model
build(net,
opt, // Optimizer
{"softmax_cross_entropy"}, // Losses
{"accuracy"}, // Metrics
cs);
// View model
summary(net);
// Load dataset
Tensor *x_train=Tensor::load("flickr_trX.bin","bin");
//x_train->info(); //1000,256,256,3
Tensor *y_train=Tensor::load("flickr_trY.bin","bin");
//y_train->info();
if (testing) {
x_train->info();
y_train->info();
std::string _range_ = "0:" + std::to_string(2 * batch_size);
Tensor* x_mini_train = x_train->select({_range_, ":", ":", ":"});
Tensor* y_mini_train = y_train->select({_range_, ":"});
//Tensor* x_mini_test = x_test->select({_range_, ":", ":", ":"});
//Tensor* y_mini_test = y_test->select({_range_, ":"});
delete x_train;
delete y_train;
//delete x_test;
//delete y_test;
x_train = x_mini_train;
y_train = y_mini_train;
//x_test = x_mini_test;
//y_test = y_mini_test;
}
Tensor *xtrain = Tensor::permute(x_train,{0,3,1,2});//1000,3,256,256
Tensor *ytrain = y_train;
y_train=onehot(ytrain,outvs);
y_train->reshape_({y_train->shape[0],olength,outvs}); //batch x timesteps x input_dim
//y_train->info();
//load(net,"img2text.bin","bin");
// Train model
fit(net, {xtrain}, {y_train}, batch_size, epochs);
save(net,"img2text.bin","bin");
/////////////////////////////////////////////
// INFERENCE
/////////////////////////////////////////////
cout<<"==================================\n";
cout<<"=== INFERENCE ===\n";
cout<<"==================================\n";
/////////////////////////////////////////////
/// Get all the reshapes of the images
/// Only use the CNN
/////////////////////////////////////////////
Tensor *timage=new Tensor({x_train->shape[0], 512}); //images reshape
model cnn=Model({image_in},{lreshape});
cs = nullptr;
if (use_cpu) {
cs = CS_CPU();
} else {
//cs = CS_GPU({1}, "low_mem"); // one GPU
cs = CS_GPU({1}); // one GPU
// cs = CS_GPU({1,1},100); // two GPU with weight sync every 100 batches
// cs = CS_CPU();
}
build(cnn,
adam(0.001), // not relevant
{"mse"}, // not relevant
{"mse"}, // not relevant
cs
);
summary(cnn);
plot(cnn,"cnn.pdf");
// forward images
Tensor* xbatch = new Tensor({batch_size,3,256,256});
int numbatches=x_train->shape[0]/batch_size;
for(int j=0;j<1;j++) {
cout<<"batch "<<j<<endl;
next_batch({x_train},{xbatch});
forward(cnn,{xbatch});
Tensor* ybatch=getOutput(lreshape);
string sample=to_string(j*batch_size)+":"+to_string((j+1)*batch_size);
timage->set_select({sample,":"},ybatch);
delete ybatch;
}
delete xbatch;
/////////////////////////////////////////////
/// Create Decoder non recurrent for n-best
/////////////////////////////////////////////
ldecin = Input({outvs});
layer image = Input({512});
layer lstate = States({2,512});
ldec = ReduceArgMax(ldecin,{0});
ldec = RandomUniform(Embedding(ldec, outvs, 1,embdim),-0.05,0.05);
ldec = Concat({ldec,image});
layer lstm = LSTM({ldec,lstate},512,true);
lstm->isrecurrent=false; // Important
out = Softmax(Dense(lstm, outvs));
model decoder=Model({ldecin,image,lstate},{out});
cs = nullptr;
if (use_cpu) {
cs = CS_CPU();
} else {
//cs = CS_GPU({1}, "low_mem"); // one GPU
cs = CS_GPU({1}); // one GPU
// cs = CS_GPU({1,1},100); // two GPU with weight sync every 100 batches
// cs = CS_CPU();
}
// Build model
build(decoder,
adam(0.001), // not relevant
{"softmax_cross_entropy"}, // not relevant
{"accuracy"}, // not relevant
cs
);
// View model
summary(decoder);
plot(decoder, "decoder.pdf");
// Copy params from trained net
copyParam(getLayer(net,"LSTM1"),getLayer(decoder,"LSTM2"));
copyParam(getLayer(net,"dense1"),getLayer(decoder,"dense2"));
copyParam(getLayer(net,"embedding1"),getLayer(decoder,"embedding2"));
////// N-best for sample s
int s = testing ? 1 : 100; //sample 100
// three input tensors with batch_size=1 (one sentence)
Tensor *treshape=timage->select({to_string(s),":"});
Tensor *text=y_train->select({to_string(s),":",":"}); //1 x olength x outvs
//Tensor *state=Tensor::zeros({1,2,512}); // batch x num_states x dim_states
for(int j=0;j<olength;j++) {
cout<<"Word:"<<j<<endl;
Tensor *word;
if (j==0) word=Tensor::zeros({1,outvs});
else {
word=text->select({"0",to_string(j-1),":"});
word->reshape_({1,outvs}); // batch=1
}
treshape->reshape_({1,512}); // batch=1
Tensor *state=Tensor::zeros({1,2,512}); // batch=1
vtensor input;
input.push_back(word);
input.push_back(treshape);
input.push_back(state);
forward(decoder, input);
// forward(decoder,(vtensor){word,treshape,state});
Tensor *outword=getOutput(out);
vector<Tensor*> vstates=getStates(lstm);
for(int i=0;i<vstates.size();i++) {
Tensor * temp = vstates[i]->reshape({1,1,512});
state->set_select({":",to_string(i),":"}, temp);
delete temp;
delete vstates[i];
}
vstates.clear();
delete state;
delete word;
delete outword;
}
delete xtrain;
delete ytrain;
delete x_train;
delete y_train;
//delete lstate;
delete decoder;
delete cnn;
delete net;
delete timage;
delete treshape;
delete text;
return EXIT_SUCCESS;
}
| 25.109756 | 89 | 0.538854 | [
"shape",
"vector",
"model"
] |
243cd90d0f4402c14796b6a6530b23631bb65867 | 19,637 | cpp | C++ | test/testprevalidation.cpp | evgeniums/cpp-validator | e4feccdce19c249369ddb631571b60613926febd | [
"BSL-1.0"
] | 27 | 2020-09-18T13:45:33.000Z | 2022-03-16T21:14:37.000Z | test/testprevalidation.cpp | evgeniums/cpp-validator | e4feccdce19c249369ddb631571b60613926febd | [
"BSL-1.0"
] | 7 | 2020-08-07T21:48:14.000Z | 2021-01-14T12:25:37.000Z | test/testprevalidation.cpp | evgeniums/cpp-validator | e4feccdce19c249369ddb631571b60613926febd | [
"BSL-1.0"
] | 1 | 2021-03-30T09:17:58.000Z | 2021-03-30T09:17:58.000Z | #include <set>
#include <iterator>
#include <boost/test/unit_test.hpp>
#include <dracosha/validator/validator.hpp>
#include <dracosha/validator/adapters/prevalidation_adapter.hpp>
#include <dracosha/validator/prevalidation/set_validated.hpp>
namespace hana=boost::hana;
namespace
{
DRACOSHA_VALIDATOR_PROPERTY(val1)
DRACOSHA_VALIDATOR_PROPERTY(val2)
struct NonCopyable
{
NonCopyable()=default;
~NonCopyable()=default;
NonCopyable(const NonCopyable&)=delete;
NonCopyable(NonCopyable&&)=default;
NonCopyable& operator= (const NonCopyable&)=delete;
NonCopyable& operator= (NonCopyable&&)=default;
std::string val1;
int val2=0;
};
}
using namespace DRACOSHA_VALIDATOR_NAMESPACE;
BOOST_AUTO_TEST_SUITE(TestPrevalidation)
#if 1
BOOST_AUTO_TEST_CASE(CheckPrevalidationReport)
{
std::string rep1;
auto v1=validator(
_[size](ne,100),
_["field1"](gte,"1"),
_["field10"](size(lt,3)),
_[10](gte,1000),
_["field100"]["subfield100"](contains,"value10")
);
auto sa1=make_prevalidation_adapter(_["field1"],"value10",rep1);
auto&& val1=sa1.traits().get();
BOOST_CHECK_EQUAL(val1,"value10");
BOOST_CHECK(v1.apply(sa1));
rep1.clear();
auto sa2=make_prevalidation_adapter(_["field10"],std::string("value10"),rep1);
BOOST_CHECK(!v1.apply(sa2));
BOOST_CHECK_EQUAL(rep1,"size of field10 must be less than 3");
rep1.clear();
auto sa3=make_prevalidation_adapter(_["field1"],"0",rep1);
BOOST_CHECK(!v1.apply(sa3));
BOOST_CHECK_EQUAL(rep1,"field1 must be greater than or equal to 1");
rep1.clear();
std::string str4="0";
auto sa4=make_prevalidation_adapter(_["field100"],str4,rep1);
BOOST_CHECK(v1.apply(sa4));
rep1.clear();
auto sa5=make_prevalidation_adapter(_["field200"],100,rep1);
BOOST_CHECK(v1.apply(sa5));
rep1.clear();
auto sa6=make_prevalidation_adapter(_[100],NonCopyable(),rep1);
BOOST_CHECK(v1.apply(sa6));
rep1.clear();
NonCopyable nc;
auto sa7=make_prevalidation_adapter(_["field300"],nc,rep1);
BOOST_CHECK(v1.apply(sa7));
rep1.clear();
auto sa8=make_prevalidation_adapter(_[10],5000,rep1);
BOOST_CHECK(v1.apply(sa8));
rep1.clear();
auto sa9=make_prevalidation_adapter(_[10],100,rep1);
BOOST_CHECK(!v1.apply(sa9));
BOOST_CHECK_EQUAL(rep1,"element #10 must be greater than or equal to 1000");
rep1.clear();
BOOST_CHECK(check_contains(value_as_container("value10"),"value10"));
auto sa10=make_prevalidation_adapter(_["field100"]["subfield100"],value_as_container("value1"),rep1);
BOOST_CHECK(!v1.apply(sa10));
BOOST_CHECK_EQUAL(rep1,"subfield100 of field100 must contain value10");
auto sa11=make_prevalidation_adapter(_["field100"]["subfield100"],value_as_container("value10"),rep1);
BOOST_CHECK(v1.apply(sa11));
rep1.clear();
auto v2=validator(
_["field1"](contains,10)
);
auto sa21=make_prevalidation_adapter(_["field1"],20,rep1);
BOOST_CHECK(!check_contains(20,10));
BOOST_CHECK(!v2.apply(sa21));
}
#endif
BOOST_AUTO_TEST_CASE(CheckAggregationPrevalidationReport)
{
auto v1=validator(
_[size](eq,1),
_["field1"](gte,"value1"),
_["field10"](value(gte,"10") ^AND^ size(lt,3)),
_["field100"](value(gt,"how are you") ^OR^ size(lte,5))
);
std::string rep1;
auto sa1=make_prevalidation_adapter(_["field10"],"hi",rep1);
BOOST_CHECK(v1.apply(sa1));
rep1.clear();
auto sa2=make_prevalidation_adapter(_["field10"],"01",rep1);
BOOST_CHECK(!v1.apply(sa2));
BOOST_CHECK_EQUAL(rep1,"field10 must be greater than or equal to 10");
rep1.clear();
#if 1
auto sa3=make_prevalidation_adapter(_["field10"],"1000",rep1);
BOOST_CHECK(!v1.apply(sa3));
BOOST_CHECK_EQUAL(rep1,"size of field10 must be less than 3");
rep1.clear();
auto sa4=make_prevalidation_adapter(_[10],5000,rep1);
BOOST_CHECK(v1.apply(sa4));
rep1.clear();
auto sa5=make_prevalidation_adapter(_["field100"],"zzzzzzzzz",rep1);
BOOST_CHECK(v1.apply(sa5));
rep1.clear();
auto sa6=make_prevalidation_adapter(_["field100"],"0123",rep1);
BOOST_CHECK(v1.apply(sa6));
rep1.clear();
auto sa7=make_prevalidation_adapter(_["field100"],"01234567890",rep1);
BOOST_CHECK(!v1.apply(sa7));
BOOST_CHECK_EQUAL(rep1,"field100 must be greater than how are you OR size of field100 must be less than or equal to 5");
rep1.clear();
auto v2=validator(
_["field10"](gte,"value1")
^OR^
_["field10"](eq,"10")
);
auto sa8=make_prevalidation_adapter(_["field10"],"zzzzzzz",rep1);
BOOST_CHECK(v2.apply(sa8));
rep1.clear();
auto sa9=make_prevalidation_adapter(_["field10"],"10",rep1);
BOOST_CHECK(v2.apply(sa9));
rep1.clear();
auto sa10=make_prevalidation_adapter(_["field10"],"100",rep1);
BOOST_CHECK(!v2.apply(sa10));
BOOST_CHECK_EQUAL(rep1,"field10 must be greater than or equal to value1 OR field10 must be equal to 10");
rep1.clear();
auto v3=validator(
_["field10"](NOT(value(gte,"value1"))),
_["field100"](value(gt,"how are you") ^OR^ size(lte,5))
);
auto sa11=make_prevalidation_adapter(_["field10"],"10",rep1);
BOOST_CHECK(v3.apply(sa11));
rep1.clear();
auto sa12=make_prevalidation_adapter(_["field10"],"value100",rep1);
BOOST_CHECK(!v3.apply(sa12));
BOOST_CHECK_EQUAL(rep1,"NOT field10 must be greater than or equal to value1");
rep1.clear();
auto v4=validator(
NOT(_["field10"](gte,"value1"))
);
BOOST_CHECK(v4.apply(sa11));
rep1.clear();
BOOST_CHECK(!v4.apply(sa12));
BOOST_CHECK_EQUAL(rep1,"NOT field10 must be greater than or equal to value1");
rep1.clear();
#endif
}
#if 1
BOOST_AUTO_TEST_CASE(CheckNestedPrevalidationReport)
{
std::vector<float> vec1;
auto v1=validator(
_[size](eq,1),
_["field1"][vec1](gte,"value1"),
_["field10"]["field20"](value(gte,"10") ^AND^ size(lt,3))
);
std::string rep1;
auto sa1=make_prevalidation_adapter(_["field1000"][100],"hi",rep1);
BOOST_CHECK(v1.apply(sa1));
rep1.clear();
auto sa2=make_prevalidation_adapter(_["field10"][100],"hello",rep1);
BOOST_CHECK(v1.apply(sa2));
rep1.clear();
auto sa3=make_prevalidation_adapter(_["field10"]["field200"],"hello",rep1);
BOOST_CHECK(v1.apply(sa3));
rep1.clear();
auto sa4=make_prevalidation_adapter(_["field10"]["field20"],"99",rep1);
BOOST_CHECK(v1.apply(sa4));
rep1.clear();
auto sa5=make_prevalidation_adapter(_["field10"]["field20"],"0",rep1);
BOOST_CHECK(!v1.apply(sa5));
BOOST_CHECK_EQUAL(rep1,"field20 of field10 must be greater than or equal to 10");
rep1.clear();
auto sa6=make_prevalidation_adapter(_["field10"]["field20"],"999",rep1);
BOOST_CHECK(!v1.apply(sa6));
BOOST_CHECK_EQUAL(rep1,"size of field20 of field10 must be less than 3");
rep1.clear();
}
BOOST_AUTO_TEST_CASE(CheckSampleObjectPrevalidationReport)
{
std::map<size_t,size_t> sample={
{1,10},
{2,20},
{3,30}
};
auto v1=validator(
_[size](eq,1),
_[1](gte,_(sample)),
_[10](eq,_(sample)),
_["hello"](eq,_(sample)),
_[100](eq,_(sample))
);
std::string rep1;
auto sa1=make_prevalidation_adapter(_[1],100,rep1);
BOOST_CHECK(v1.apply(sa1));
rep1.clear();
auto sa2=make_prevalidation_adapter(_[20],1000,rep1);
BOOST_CHECK(v1.apply(sa1));
rep1.clear();
auto sa3=make_prevalidation_adapter(_[1],5,rep1);
BOOST_CHECK(!v1.apply(sa3));
BOOST_CHECK_EQUAL(rep1,"element #1 must be greater than or equal to element #1 of sample");
rep1.clear();
auto sa4=make_prevalidation_adapter(_["hello"],5,rep1);
BOOST_CHECK(v1.apply(sa4));
auto sa5=make_prevalidation_adapter(_[100],5,rep1);
BOOST_CHECK(v1.apply(sa5));
auto v2=validator(
_[size](eq,1),
_[1](gte,_(_(sample),"sample object")),
_[10](eq,_(_(sample),"sample object"))
);
BOOST_CHECK(!v2.apply(sa3));
BOOST_CHECK_EQUAL(rep1,"element #1 must be greater than or equal to element #1 of sample object");
rep1.clear();
}
BOOST_AUTO_TEST_CASE(CheckPropertyPrevalidation)
{
auto v=validator(
_[val1](eq,"value"),
_[val2](lt,100)
);
std::string rep;
auto sa1=make_prevalidation_adapter(_[val1],"hello",rep);
BOOST_CHECK(!v.apply(sa1));
rep.clear();
auto sa2=make_prevalidation_adapter(_[val1],"value",rep);
BOOST_CHECK(v.apply(sa2));
rep.clear();
}
BOOST_AUTO_TEST_CASE(CheckSingleMemberAnyAllReport)
{
std::string rep1;
auto v0=validator(
_['a'](ALL(value(gte,9)))
);
auto v0_1=validator(
_['a'][ALL](gte,9)
);
auto pa0=make_prevalidation_adapter(_['a'],10,rep1);
BOOST_CHECK(v0.apply(pa0));
rep1.clear();
BOOST_CHECK(v0_1.apply(pa0));
rep1.clear();
auto v1=validator(
_["field1"](ALL(value(gte,9))),
_["field2"](size(gte,100))
);
auto v1_1=validator(
_["field1"][ALL](gte,9),
_["field2"](size(gte,100))
);
auto pa1=make_prevalidation_adapter(_["field1"],10,rep1);
BOOST_CHECK(v1.apply(pa1));
rep1.clear();
BOOST_CHECK(v1_1.apply(pa1));
rep1.clear();
auto v2=validator(
_["field1"]["field1_1"](ALL(value(gte,9))),
_["field2"](size(gte,100))
);
auto v2_1=validator(
_["field1"]["field1_1"][ALL](gte,9),
_["field2"](size(gte,100))
);
auto pa2=make_prevalidation_adapter(_["field1"]["field1_1"][0],10,rep1);
BOOST_CHECK(v2.apply(pa2));
rep1.clear();
BOOST_CHECK(v2_1.apply(pa2));
rep1.clear();
auto pa3=make_prevalidation_adapter(_["field1"]["field1_1"][0],5,rep1);
BOOST_CHECK(!v2.apply(pa3));
BOOST_CHECK_EQUAL(rep1,std::string("each element of field1_1 of field1 must be greater than or equal to 9"));
rep1.clear();
BOOST_CHECK(!v2_1.apply(pa3));
BOOST_CHECK_EQUAL(rep1,std::string("each element of field1_1 of field1 must be greater than or equal to 9"));
rep1.clear();
static_assert(is_container_t<std::vector<int>>::value,"");
auto member1=_["field1"]["field1_1"];
auto member2=_["field1"]["field1_1"][value];
static_assert(hana::not_(hana::is_a<element_aggregation_tag,std::string>),"");
static_assert(hana::not_(hana::is_a<element_aggregation_tag,decltype(size)>),"");
static_assert(
!decltype(same_member_path_types(_[std::string("A")],_[size]))::value,
"");
static_assert(
decltype(same_member_path_types(member1[size],member2))::value,
"");
auto pa4=make_prevalidation_adapter(_["field1"]["field1_1"],range({10,11,12}),rep1);
BOOST_CHECK(v2.apply(pa4));
rep1.clear();
BOOST_CHECK(v2_1.apply(pa4));
rep1.clear();
BOOST_CHECK(safe_compare_equal(ALL,ALL));
BOOST_CHECK(safe_compare_equal(ANY,ANY));
BOOST_CHECK(safe_compare_equal(ALL,ANY));
BOOST_CHECK(safe_compare_equal(ANY,ALL));
BOOST_CHECK(ALL==ALL);
BOOST_CHECK(ANY==ANY);
BOOST_CHECK(ALL==ANY);
BOOST_CHECK(ANY==ALL);
BOOST_CHECK(10==ALL);
BOOST_CHECK(ALL==10);
BOOST_CHECK(10==ANY);
BOOST_CHECK(ANY==10);
auto pa5=make_prevalidation_adapter(_["field1"]["field1_1"],range({1}),rep1);
BOOST_CHECK(!v2.apply(pa5));
BOOST_CHECK_EQUAL(rep1,std::string("each element of field1_1 of field1 must be greater than or equal to 9"));
rep1.clear();
BOOST_CHECK(!v2_1.apply(pa5));
BOOST_CHECK_EQUAL(rep1,std::string("each element of field1_1 of field1 must be greater than or equal to 9"));
rep1.clear();
auto pa6=make_prevalidation_adapter(_["field1"]["field1_1"],range({10,11,12,1}),rep1);
BOOST_CHECK(!v2.apply(pa6));
BOOST_CHECK_EQUAL(rep1,std::string("each element of field1_1 of field1 must be greater than or equal to 9"));
rep1.clear();
BOOST_CHECK(!v2_1.apply(pa6));
BOOST_CHECK_EQUAL(rep1,std::string("each element of field1_1 of field1 must be greater than or equal to 9"));
rep1.clear();
static_assert(std::is_base_of<any_tag,decltype(wrap_it(1,string_any,values))>::value,"");
static_assert(detail::is_member_with_any<size_t,decltype(ANY)>::value,"");
static_assert(decltype(_["field1"]["field1_1"][wrap_it(1,string_any,values)])::is_with_any::value,"");
auto v3=validator(
_["field1"]["field1_1"](ANY(value(gte,9))),
_["field2"](size(gte,100))
);
auto v3_1=validator(
_["field1"]["field1_1"][ANY](gte,9),
_["field2"](size(gte,100))
);
BOOST_CHECK(v3.apply(pa2));
rep1.clear();
BOOST_CHECK(v3.apply(pa3)); // must be ok because ANY is not strict
rep1.clear();
BOOST_CHECK(v3_1.apply(pa2));
rep1.clear();
BOOST_CHECK(v3_1.apply(pa3)); // must be ok because ANY is not strict
rep1.clear();
BOOST_CHECK(v3.apply(pa6));
rep1.clear();
BOOST_CHECK(v3.apply(pa5)); // must be ok because ANY is not strict
rep1.clear();
BOOST_CHECK(v3_1.apply(pa6));
rep1.clear();
BOOST_CHECK(v3_1.apply(pa5)); // must be ok because ANY is not strict
rep1.clear();
//"check that there is no extra copy in strict_any()"
{
std::ignore=make_prevalidation_adapter(_["field1"]["field1_1"],strict_any(NonCopyable{}),rep1);
NonCopyable nc;
std::ignore=make_prevalidation_adapter(_["field1"]["field1_1"],strict_any(nc),rep1);
}
// check strict ANY
int val8=8;
auto pa8=make_prevalidation_adapter(_["field1"]["field1_1"][1],strict_any(val8),rep1);
BOOST_CHECK(!v3.apply(pa8));
BOOST_CHECK_EQUAL(rep1,std::string("at least one element of field1_1 of field1 must be greater than or equal to 9"));
rep1.clear();
BOOST_CHECK(!v3_1.apply(pa8));
BOOST_CHECK_EQUAL(rep1,std::string("at least one element of field1_1 of field1 must be greater than or equal to 9"));
rep1.clear();
int val10=10;
auto pa10=make_prevalidation_adapter(_["field1"]["field1_1"][2],strict_any(val10),rep1);
BOOST_CHECK(v3.apply(pa10));
rep1.clear();
BOOST_CHECK(v3_1.apply(pa10));
rep1.clear();
auto pa11=make_prevalidation_adapter(_["field1"]["field1_1"][3],strict_any(11),rep1);
BOOST_CHECK(v3.apply(pa11));
rep1.clear();
BOOST_CHECK(v3_1.apply(pa11));
rep1.clear();
auto pa11_1=make_prevalidation_adapter(_["field1"]["field1_1"][4],strict_any(7),rep1);
BOOST_CHECK(!v3.apply(pa11_1));
BOOST_CHECK_EQUAL(rep1,std::string("at least one element of field1_1 of field1 must be greater than or equal to 9"));
rep1.clear();
BOOST_CHECK(!v3_1.apply(pa11_1));
BOOST_CHECK_EQUAL(rep1,std::string("at least one element of field1_1 of field1 must be greater than or equal to 9"));
rep1.clear();
static_assert(hana::is_a<element_aggregation_tag,decltype(ANY)>,"");
static_assert(hana::is_a<element_aggregation_tag,decltype(ALL)>,"");
auto eq1=path_types_equal(ANY,ALL);
static_assert(decltype(eq1)::value,"");
auto eq2=same_member_path_types(_["field1"]["field1_1"][ANY],_["field1"]["field1_1"][ALL]);
static_assert(decltype(eq2)::value,"");
// validation with vector
auto vec7=std::vector<int>{1,2,3,4};
auto pa7=make_prevalidation_adapter(_["field1"]["field1_1"],strict_any(range(vec7)),rep1);
BOOST_CHECK(!v3.apply(pa7));
BOOST_CHECK_EQUAL(rep1,std::string("at least one element of field1_1 of field1 must be greater than or equal to 9"));
rep1.clear();
BOOST_CHECK(!v3_1.apply(pa7));
BOOST_CHECK_EQUAL(rep1,std::string("at least one element of field1_1 of field1 must be greater than or equal to 9"));
rep1.clear();
auto vec9=std::vector<int>{1,2,3,4,9};
auto pa9=make_prevalidation_adapter(_["field1"]["field1_1"],strict_any(range(vec9)),rep1);
BOOST_CHECK(v3.apply(pa9));
rep1.clear();
BOOST_CHECK(v3_1.apply(pa9));
rep1.clear();
auto pa12=make_prevalidation_adapter(_["field1"]["field1_1"],strict_any(range({1,2,3,4})),rep1);
BOOST_CHECK(!v3.apply(pa12));
BOOST_CHECK_EQUAL(rep1,std::string("at least one element of field1_1 of field1 must be greater than or equal to 9"));
rep1.clear();
BOOST_CHECK(!v3_1.apply(pa12));
BOOST_CHECK_EQUAL(rep1,std::string("at least one element of field1_1 of field1 must be greater than or equal to 9"));
rep1.clear();
// check literals
auto v4=validator(
_["field1"]["field1_1"](ANY(value(gte,"Hello"))),
_["field2"](size(gte,100))
);
auto pa13=make_prevalidation_adapter(_["field1"]["field1_1"][0],strict_any("Hello"),rep1);
auto pa14=make_prevalidation_adapter(_["field1"]["field1_1"][1],"Hello",rep1);
auto pa14_1=make_prevalidation_adapter(_["field1"]["field1_1"][2],strict_any("Aaa"),rep1);
BOOST_CHECK(v4.apply(pa13));
rep1.clear();
BOOST_CHECK(v4.apply(pa14));
rep1.clear();
BOOST_CHECK(!v4.apply(pa14_1));
BOOST_CHECK_EQUAL(std::string("at least one element of field1_1 of field1 must be greater than or equal to Hello"),rep1);
rep1.clear();
auto v5=validator(
_["field1"]["field1_1"](ALL(value(gte,"Hello"))),
_["field2"](size(gte,100))
);
auto pa15=make_prevalidation_adapter(_["field1"]["field1_1"][0],"Zzz",rep1);
BOOST_CHECK(v5.apply(pa15));
rep1.clear();
auto pa16=make_prevalidation_adapter(_["field1"]["field1_1"][1],"Aaa",rep1);
BOOST_CHECK(!v5.apply(pa16));
BOOST_CHECK_EQUAL(std::string("each element of field1_1 of field1 must be greater than or equal to Hello"),rep1);
rep1.clear();
}
BOOST_AUTO_TEST_CASE(CheckUpdateValidatedWithSample)
{
error_report err;
std::map<std::string,std::string> m6{
{"field1","value1"},
{"field2","value2"},
{"field3","value3"}
};
auto v6=validator(
_["field3"](value(gte,_(m6)))
);
set_validated(m6,_["field3"],"aaaaa",v6,err);
BOOST_CHECK(err);
BOOST_CHECK_EQUAL(err.message(),std::string("field3 must be greater than or equal to field3 of sample"));
set_validated(m6,_["field3"],"zzzzz",v6,err);
BOOST_CHECK(!err);
std::map<std::string,std::vector<std::string>> sample7{
{"field1",{"value1"}},
{"field2",{"value2"}},
{"field3",{"value3"}}
};
// test member not existing in sample
std::map<std::string,std::vector<std::string>> m7{
{"field1",{"value1"}},
{"field2",{"value2"}},
{"field3",{"0"}}
};
auto v7=validator(
_["field3"](ALL(value(gte,_(sample7))))
);
set_validated(m7,_["field3"][0],"aaaaa",v7,err);
BOOST_CHECK(!err);
auto v8=validator(
_["field3"](ANY(value(gte,_(sample7))))
);
set_validated(m7,_["field3"][0],"aaaaa",strict_any(v8),err);
BOOST_CHECK(!err); // not existing member in sample is ignored
set_validated(m7,_["field3"][0],"zzzzz",strict_any(v8),err);
BOOST_CHECK(!err);
BOOST_CHECK_EQUAL(m7["field3"][0],"zzzzz");
}
#endif
BOOST_AUTO_TEST_SUITE_END()
| 33.798623 | 125 | 0.639864 | [
"object",
"vector"
] |
243eb5560001976771faecdc640eb682be093a0f | 4,262 | hpp | C++ | thirdparty/hiir-1.33/hiir/test/TestPhaseHalfPi.hpp | jpcima/spectacle | 540d98ac381400bbf58084e3434cb4f300ad7232 | [
"0BSD"
] | 44 | 2020-04-16T19:20:00.000Z | 2022-02-27T00:10:13.000Z | thirdparty/hiir-1.33/hiir/test/TestPhaseHalfPi.hpp | jpcima/spectacle | 540d98ac381400bbf58084e3434cb4f300ad7232 | [
"0BSD"
] | 18 | 2020-04-16T03:28:55.000Z | 2021-11-15T19:49:12.000Z | thirdparty/hiir-1.33/hiir/test/TestPhaseHalfPi.hpp | jpcima/spectral | 540d98ac381400bbf58084e3434cb4f300ad7232 | [
"0BSD"
] | 3 | 2020-04-16T01:22:48.000Z | 2021-08-10T20:34:30.000Z | /*****************************************************************************
TestPhaseHalfPi.hpp
Author: Laurent de Soras, 2005
--- Legal stuff ---
This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What The Fuck You Want
To Public License, Version 2, as published by Sam Hocevar. See
http://sam.zoy.org/wtfpl/COPYING for more details.
*Tab=3***********************************************************************/
#if defined (hiir_test_TestPhaseHalfPi_CURRENT_CODEHEADER)
#error Recursive inclusion of TestPhaseHalfPi code header.
#endif
#define hiir_test_TestPhaseHalfPi_CURRENT_CODEHEADER
#if ! defined (hiir_test_TestPhaseHalfPi_CODEHEADER_INCLUDED)
#define hiir_test_TestPhaseHalfPi_CODEHEADER_INCLUDED
/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
#include "hiir/test/BlockSplitter.h"
#include "hiir/test/FileOp.h"
#include "hiir/test/ResultCheck.h"
#include "hiir/test/SweepingSine.h"
#include <type_traits>
#include <cassert>
#include <cstdio>
namespace hiir
{
namespace test
{
/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
template <class TO>
int TestPhaseHalfPi <TO>::perform_test (TO &phaser, const double coef_arr [NBR_COEFS], const SweepingSine &ss, const char *type_0, double transition_bw)
{
assert (coef_arr != nullptr);
assert (type_0 != nullptr);
assert (transition_bw > 0);
assert (transition_bw < 0.5);
typedef typename TO::DataType DataType;
const int nbr_chn = TO::_nbr_chn;
const char * datatype_0 =
std::is_same <DataType, double>::value ? "double"
: std::is_same <DataType, float >::value ? "float"
: "<unknown type>";
printf (
"Test: PhaseHalfPi, %s, %d chn, %s implementation, %d coefficients.\n",
datatype_0, nbr_chn, type_0, NBR_COEFS
);
const long len = ss.get_len ();
std::vector <DataType> src (len * nbr_chn);
printf ("Generating sweeping sine... ");
fflush (stdout);
if (nbr_chn == 1)
{
ss.generate (&src [0]);
}
else
{
std::vector <DataType> src_base (len);
ss.generate (&src_base [0]);
for (long pos = 0; pos <len; ++pos)
{
for (int chn = 0; chn < nbr_chn; ++chn)
{
src [pos * nbr_chn + chn] = src_base [pos];
}
}
}
printf ("Done.\n");
phaser.set_coefs (coef_arr);
phaser.clear_buffers ();
std::vector <DataType> dest_0 (len * nbr_chn, 0);
std::vector <DataType> dest_1 (len * nbr_chn, 0);
printf ("Phasing... ");
fflush (stdout);
BlockSplitter bs (64);
for (bs.start (len); bs.is_continuing (); bs.set_next_block ())
{
const long b_pos = bs.get_pos ();
const long b_len = bs.get_len ();
const int idx = b_pos * nbr_chn;
phaser.process_block (
&dest_0 [idx], &dest_1 [idx], &src [idx], b_len
);
}
printf ("Done.\n");
int ret_val = 0;
std::vector <DataType> dst_chk_0 (len);
std::vector <DataType> dst_chk_1 (len);
for (int chn = 0; chn < nbr_chn && ret_val == 0; ++chn)
{
for (long pos = 0; pos < len; ++pos)
{
const int idx = pos * nbr_chn + chn;
dst_chk_0 [pos] = dest_0 [idx];
dst_chk_1 [pos] = dest_1 [idx];
}
ret_val = ResultCheck <DataType>::check_phase (
ss,
transition_bw,
&dst_chk_0 [0],
&dst_chk_1 [0]
);
char filename_0 [255+1];
sprintf (
filename_0, "phaser_%02d_%s_%dx-%01d.raw",
TestedType::NBR_COEFS, type_0, nbr_chn, chn
);
FileOp <DataType>::save_raw_data_16_stereo (
filename_0, &dst_chk_0 [0], &dst_chk_1 [0], len, 1
);
}
printf ("\n");
return ret_val;
}
/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
} // namespace test
} // namespace hiir
#endif // hiir_test_TestPhaseHalfPi_CODEHEADER_INCLUDED
#undef hiir_test_TestPhaseHalfPi_CURRENT_CODEHEADER
/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
| 24.923977 | 153 | 0.556781 | [
"vector"
] |
2446456f74990856453db5c97a9e07882bbdf731 | 10,192 | cc | C++ | ash/shelf/login_shelf_gesture_controller.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ash/shelf/login_shelf_gesture_controller.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ash/shelf/login_shelf_gesture_controller.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/shelf/login_shelf_gesture_controller.h"
#include "ash/session/session_controller_impl.h"
#include "ash/shelf/contextual_nudge.h"
#include "ash/shelf/drag_handle.h"
#include "ash/shelf/shelf.h"
#include "ash/shelf/shelf_widget.h"
#include "ash/shell.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animation_observer.h"
#include "ui/compositor/scoped_layer_animation_settings.h"
#include "ui/events/event.h"
#include "ui/events/types/event_type.h"
#include "ui/gfx/color_palette.h"
#include "ui/views/widget/widget.h"
namespace ash {
namespace {
// The upward velocity threshold for the swipe up from the login shelf to be
// reported as fling gesture.
constexpr float kVelocityToHomeScreenThreshold = 1000.f;
// The delay between the time the login shelf gesture nudge is shown, and the
// time it starts animating.
constexpr base::TimeDelta kNudgeAnimationEntranceDelay =
base::TimeDelta::FromMilliseconds(500);
// The duration of different parts of the nudge animation.
constexpr base::TimeDelta kNudgeAnimationStageDuration =
base::TimeDelta::FromMilliseconds(600);
// The duration of the animation that moves the drag handle and the contextual
// nudge to their initial position when the user cancels the nudge animation by
// tapping the contextual nudge.
constexpr base::TimeDelta kNudgeStopAnimationDuration =
base::TimeDelta::FromMilliseconds(150);
// The interval between the end of one nudge animation sequence, and the start
// of the next nudge animation sequence.
constexpr base::TimeDelta kAnimationInterval = base::TimeDelta::FromSeconds(5);
// The offset drag handle and nudge widget have from the default position during
// the nudge animation sequence.
constexpr int kNudgeAnimationBaseOffset = -8;
// The number of times drag handle is moved up and down during single nudge
// animation cycle.
constexpr int kNudgeAnimationThrobIntervals = 3;
// The maximal offset drag handle has from the base position during throb
// section of the nudge animation.
constexpr int kNudgeAnimationThrobAmplitude = 6;
// Implicit animation observer that runs a callback once the animations
// complete, and then deletes itself.
class ImplicitAnimationCallbackRunner : public ui::ImplicitAnimationObserver {
public:
explicit ImplicitAnimationCallbackRunner(base::OnceClosure callback)
: callback_(std::move(callback)) {}
~ImplicitAnimationCallbackRunner() override {
StopObservingImplicitAnimations();
}
// ui::ImplicitAnimationObserver:
void OnImplicitAnimationsCompleted() override {
StopObservingImplicitAnimations();
std::move(callback_).Run();
delete this;
}
private:
base::OnceClosure callback_;
};
} // namespace
LoginShelfGestureController::LoginShelfGestureController(
Shelf* shelf,
DragHandle* drag_handle,
const base::string16& gesture_nudge,
const base::RepeatingClosure fling_handler,
base::OnceClosure exit_handler)
: shelf_(shelf),
drag_handle_(drag_handle),
fling_handler_(fling_handler),
exit_handler_(std::move(exit_handler)) {
DCHECK(fling_handler_);
DCHECK(exit_handler_);
const bool is_oobe = Shell::Get()->session_controller()->GetSessionState() ==
session_manager::SessionState::OOBE;
const SkColor nudge_text_color =
is_oobe ? gfx::kGoogleGrey700 : gfx::kGoogleGrey100;
nudge_ = new ContextualNudge(
drag_handle, nullptr /*parent_window*/, ContextualNudge::Position::kTop,
gfx::Insets(8), gesture_nudge, nudge_text_color,
base::BindRepeating(&LoginShelfGestureController::HandleNudgeTap,
weak_factory_.GetWeakPtr()));
nudge_->GetWidget()->Show();
nudge_->GetWidget()->AddObserver(this);
ScheduleNudgeAnimation(kNudgeAnimationEntranceDelay);
}
LoginShelfGestureController::~LoginShelfGestureController() {
if (nudge_) {
nudge_->GetWidget()->RemoveObserver(this);
nudge_->GetWidget()->CloseWithReason(
views::Widget::ClosedReason::kUnspecified);
}
nudge_ = nullptr;
std::move(exit_handler_).Run();
}
bool LoginShelfGestureController::HandleGestureEvent(
const ui::GestureEvent& event_in_screen) {
if (event_in_screen.type() == ui::ET_GESTURE_SCROLL_BEGIN)
return MaybeStartGestureDrag(event_in_screen);
// If the previous events in the gesture sequence did not start handling the
// gesture, try again.
if (event_in_screen.type() == ui::ET_GESTURE_SCROLL_UPDATE)
return active_ || MaybeStartGestureDrag(event_in_screen);
if (!active_)
return false;
if (event_in_screen.type() == ui::ET_SCROLL_FLING_START) {
EndDrag(event_in_screen);
return true;
}
// Ending non-fling gesture, or unexpected event (if different than
// SCROLL_END), mark the controller as inactive, but report the event as
// handled in the former case only.
active_ = false;
return event_in_screen.type() == ui::ET_GESTURE_SCROLL_END;
}
void LoginShelfGestureController::OnWidgetDestroying(views::Widget* widget) {
nudge_ = nullptr;
nudge_animation_timer_.Stop();
}
bool LoginShelfGestureController::MaybeStartGestureDrag(
const ui::GestureEvent& event_in_screen) {
DCHECK(event_in_screen.type() == ui::ET_GESTURE_SCROLL_BEGIN ||
event_in_screen.type() == ui::ET_GESTURE_SCROLL_UPDATE);
// Ignore downward swipe for scroll begin.
if (event_in_screen.type() == ui::ET_GESTURE_SCROLL_BEGIN &&
event_in_screen.details().scroll_y_hint() >= 0) {
return false;
}
// Ignore downward swipe for scroll update.
if (event_in_screen.type() == ui::ET_GESTURE_SCROLL_UPDATE &&
event_in_screen.details().scroll_y() >= 0) {
return false;
}
// Ignore swipes that are outside of the shelf bounds.
if (event_in_screen.location().y() <
shelf_->shelf_widget()->GetWindowBoundsInScreen().y()) {
return false;
}
active_ = true;
return true;
}
void LoginShelfGestureController::EndDrag(
const ui::GestureEvent& event_in_screen) {
DCHECK_EQ(event_in_screen.type(), ui::ET_SCROLL_FLING_START);
active_ = false;
// If the drag ends below the shelf, do not go to home screen (theoratically
// it may happen in kExtended hotseat case when drag can start and end below
// the shelf).
if (event_in_screen.location().y() >=
shelf_->shelf_widget()->GetWindowBoundsInScreen().y()) {
return;
}
const int velocity_y = event_in_screen.details().velocity_y();
if (velocity_y > -kVelocityToHomeScreenThreshold)
return;
fling_handler_.Run();
}
void LoginShelfGestureController::ScheduleNudgeAnimation(
base::TimeDelta delay) {
if (!nudge_ || animation_stopped_)
return;
nudge_animation_timer_.Start(
FROM_HERE, delay,
base::BindOnce(
&LoginShelfGestureController::RunNudgeAnimation,
base::Unretained(this),
base::BindOnce(&LoginShelfGestureController::ScheduleNudgeAnimation,
weak_factory_.GetWeakPtr(), kAnimationInterval)));
}
void LoginShelfGestureController::RunNudgeAnimation(
base::OnceClosure callback) {
auto animate_entrance = [](ui::Layer* layer) {
ui::ScopedLayerAnimationSettings settings(layer->GetAnimator());
settings.SetTweenType(gfx::Tween::LINEAR_OUT_SLOW_IN);
settings.SetTransitionDuration(kNudgeAnimationStageDuration);
settings.SetPreemptionStrategy(
ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
gfx::Transform transform;
transform.Translate(0, kNudgeAnimationBaseOffset);
layer->SetTransform(transform);
};
animate_entrance(nudge_->GetWidget()->GetLayer());
animate_entrance(drag_handle_->layer());
auto animate_throb = [](ui::Layer* layer, bool down) {
ui::ScopedLayerAnimationSettings settings(layer->GetAnimator());
settings.SetTweenType(gfx::Tween::EASE_IN_OUT_2);
settings.SetTransitionDuration(kNudgeAnimationStageDuration);
settings.SetPreemptionStrategy(ui::LayerAnimator::ENQUEUE_NEW_ANIMATION);
gfx::Transform transform;
transform.Translate(0, kNudgeAnimationBaseOffset +
kNudgeAnimationThrobAmplitude * (down ? 1 : 0));
layer->SetTransform(transform);
};
for (int i = 0; i < kNudgeAnimationThrobIntervals; ++i) {
animate_throb(drag_handle_->layer(), /*down=*/true);
animate_throb(drag_handle_->layer(), /*down=*/false);
// Keep the animation going for the nudge, even though it's kept in place
// The primary goal is to "pause" the animation while drag handle is
// throbbing, and prevent the last animation stage from starting too soon.
animate_throb(nudge_->GetWidget()->GetLayer(), /*down=*/false);
animate_throb(nudge_->GetWidget()->GetLayer(), /*down=*/false);
}
auto animate_exit = [](ui::Layer* layer, base::OnceClosure callback) {
ui::ScopedLayerAnimationSettings settings(layer->GetAnimator());
settings.SetTweenType(gfx::Tween::EASE_IN_OUT_2);
settings.SetTransitionDuration(kNudgeAnimationStageDuration);
settings.SetPreemptionStrategy(ui::LayerAnimator::ENQUEUE_NEW_ANIMATION);
if (callback) {
settings.AddObserver(
new ImplicitAnimationCallbackRunner(std::move(callback)));
}
layer->SetTransform(gfx::Transform());
};
animate_exit(nudge_->GetWidget()->GetLayer(), base::OnceClosure());
animate_exit(drag_handle_->layer(), std::move(callback));
}
void LoginShelfGestureController::HandleNudgeTap() {
if (animation_stopped_)
return;
animation_stopped_ = true;
nudge_animation_timer_.Stop();
auto animate_exit = [](ui::Layer* layer) {
ui::ScopedLayerAnimationSettings settings(layer->GetAnimator());
settings.SetTweenType(gfx::Tween::FAST_OUT_LINEAR_IN);
settings.SetTransitionDuration(kNudgeStopAnimationDuration);
settings.SetPreemptionStrategy(
ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
layer->SetTransform(gfx::Transform());
};
animate_exit(nudge_->GetWidget()->GetLayer());
animate_exit(drag_handle_->layer());
}
} // namespace ash
| 34.666667 | 80 | 0.736362 | [
"transform"
] |
2448f3fa98abd2d666f057fef80156d2f4ec41ec | 1,484 | cc | C++ | compiler_gym/envs/llvm/service/ActionSpace.cc | sahirgomez1/CompilerGym | 9987fbdfcf8ac9af076baf0ffd695e48f0e804cf | [
"MIT"
] | 562 | 2020-12-21T14:10:20.000Z | 2022-03-31T21:23:55.000Z | compiler_gym/envs/llvm/service/ActionSpace.cc | sahirgomez1/CompilerGym | 9987fbdfcf8ac9af076baf0ffd695e48f0e804cf | [
"MIT"
] | 433 | 2020-12-22T03:40:41.000Z | 2022-03-31T18:16:17.000Z | compiler_gym/envs/llvm/service/ActionSpace.cc | sahirgomez1/CompilerGym | 9987fbdfcf8ac9af076baf0ffd695e48f0e804cf | [
"MIT"
] | 88 | 2020-12-22T08:22:00.000Z | 2022-03-20T19:00:40.000Z | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
#include "compiler_gym/envs/llvm/service/ActionSpace.h"
#include <fmt/format.h>
#include <magic_enum.hpp>
#include "compiler_gym/util/EnumUtil.h"
#include "compiler_gym/util/Unreachable.h"
namespace compiler_gym::llvm_service {
std::vector<ActionSpace> getLlvmActionSpaceList() {
std::vector<ActionSpace> spaces;
spaces.reserve(magic_enum::enum_count<LlvmActionSpace>());
for (const auto& value : magic_enum::enum_values<LlvmActionSpace>()) {
ActionSpace space;
space.set_name(util::enumNameToPascalCase<LlvmActionSpace>(value));
switch (value) {
case LlvmActionSpace::PASSES_ALL: {
ChoiceSpace* flagChoice = space.add_choice();
flagChoice->set_name("flag");
NamedDiscreteSpace* flagChoiceSpace = flagChoice->mutable_named_discrete_space();
flagChoiceSpace->set_is_commandline(true);
for (const auto& value : magic_enum::enum_values<LlvmAction>()) {
flagChoiceSpace->add_value(util::enumNameToCommandlineFlag<LlvmAction>(value));
}
} break;
default:
UNREACHABLE(fmt::format("Unknown LLVM action space {}",
util::enumNameToPascalCase<LlvmActionSpace>(value)));
}
spaces.push_back(space);
}
return spaces;
}
} // namespace compiler_gym::llvm_service
| 33.727273 | 89 | 0.703504 | [
"vector"
] |
244b46f76283d82ef19f223d901007dad5d52459 | 2,449 | hpp | C++ | src/utils/input_reads_profiler.hpp | Schaudge/octopus | d0cc5d0840aefdfefae5af8595e3330620106054 | [
"MIT"
] | 278 | 2016-10-03T16:30:49.000Z | 2022-03-25T05:59:32.000Z | src/utils/input_reads_profiler.hpp | Schaudge/octopus | d0cc5d0840aefdfefae5af8595e3330620106054 | [
"MIT"
] | 229 | 2016-10-13T14:07:35.000Z | 2022-03-19T18:59:58.000Z | src/utils/input_reads_profiler.hpp | Schaudge/octopus | d0cc5d0840aefdfefae5af8595e3330620106054 | [
"MIT"
] | 37 | 2016-10-28T22:47:54.000Z | 2022-03-20T07:28:43.000Z | // Copyright (c) 2015-2021 Daniel Cooke
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.
#ifndef input_reads_profiler_hpp
#define input_reads_profiler_hpp
#include <cstddef>
#include <vector>
#include <iosfwd>
#include <boost/optional.hpp>
#include "config/common.hpp"
#include "basics/aligned_read.hpp"
#include "io/reference/reference_genome.hpp"
#include "io/read/read_manager.hpp"
#include "thread_pool.hpp"
namespace octopus {
struct ReadSetProfileConfig
{
std::size_t max_draws_per_sample = 500;
std::size_t target_reads_per_draw = 10'000;
std::size_t min_draws_per_contig = 10;
boost::optional<AlignedRead::NucleotideSequence::size_type> fragment_size = boost::none;
unsigned min_read_lengths = 20;
};
struct ReadSetProfile
{
template <typename T>
struct SummaryStats
{
T max, min, mean, median, stdev;
};
using DepthSummaryStats = SummaryStats<std::size_t>;
struct DepthStats
{
using DiscreteDistribution = std::vector<double>;
DiscreteDistribution distribution;
DepthSummaryStats all, positive;
};
struct GenomeContigDepthStatsPair
{
using ContigDepthStatsMap = std::unordered_map<GenomicRegion::ContigName, DepthStats>;
ContigDepthStatsMap contig;
DepthStats genome;
};
struct SampleCombinedDepthStatsPair
{
std::unordered_map<SampleName, GenomeContigDepthStatsPair> sample;
GenomeContigDepthStatsPair combined;
};
using MappingQualityStats = SummaryStats<AlignedRead::MappingQuality>;
using ReadLengthStats = SummaryStats<AlignedRead::NucleotideSequence::size_type>;
using ReadMemoryStats = SummaryStats<MemoryFootprint>;
SampleCombinedDepthStatsPair depth_stats;
ReadMemoryStats memory_stats;
boost::optional<ReadMemoryStats> fragmented_memory_stats;
ReadLengthStats length_stats;
MappingQualityStats mapping_quality_stats;
};
boost::optional<ReadSetProfile>
profile_reads(const std::vector<SampleName>& samples,
const ReferenceGenome& reference,
const InputRegionMap& regions,
const ReadManager& source,
ReadSetProfileConfig config = ReadSetProfileConfig {},
boost::optional<ThreadPool&> workers = boost::none);
std::ostream& operator<<(std::ostream& os, const ReadSetProfile& profile);
} // namespace octopus
#endif
| 30.6125 | 96 | 0.727236 | [
"vector"
] |
244c202c20d5da86dc50c75a805aeb8c4289d168 | 10,580 | cpp | C++ | PanelSwCustomActions/Telemetry.cpp | jozefizso/PanelSwWixExtension | 08f1c9a803d94911d06f5d24d8dc43423b13aaa6 | [
"Apache-2.0"
] | null | null | null | PanelSwCustomActions/Telemetry.cpp | jozefizso/PanelSwWixExtension | 08f1c9a803d94911d06f5d24d8dc43423b13aaa6 | [
"Apache-2.0"
] | null | null | null | PanelSwCustomActions/Telemetry.cpp | jozefizso/PanelSwWixExtension | 08f1c9a803d94911d06f5d24d8dc43423b13aaa6 | [
"Apache-2.0"
] | null | null | null | #include "Telemetry.h"
#include "../CaCommon/WixString.h"
#include <Winhttp.h>
#pragma comment (lib, "Winhttp.lib")
#define TELEMETRY_QUERY L"SELECT `Id`, `Url`, `Page`, `Method`, `Data`, `Flags`, `Condition` FROM `PSW_Telemetry`"
enum TelemetryQuery { Id=1, Url=2, Page = 3, Method=4, Data=5, Flags=6, Condition=7 };
enum TelemetryFlags
{
None = 0,
OnExecute = 1,
OnCommit = 2,
OnRollback = 4,
Secure = 8
};
extern "C" __declspec(dllexport) UINT Telemetry(MSIHANDLE hInstall)
{
HRESULT hr = S_OK;
UINT er = ERROR_SUCCESS;
PMSIHANDLE hView;
PMSIHANDLE hRecord;
CTelemetry oRollbackTelemetry;
CTelemetry oCommitTelemetry;
CTelemetry oDeferredTelemetry;
CComBSTR szCustomActionData;
hr = WcaInitialize(hInstall, __FUNCTION__);
BreakExitOnFailure(hr, "Failed to initialize");
WcaLog(LOGMSG_STANDARD, "Initialized.");
// Ensure table PSW_Telemetry exists.
hr = WcaTableExists(L"PSW_Telemetry");
BreakExitOnFailure(hr, "Table does not exist 'PSW_Telemetry'. Have you authored 'PanelSw:Telemetry' entries in WiX code?");
// Execute view
hr = WcaOpenExecuteView(TELEMETRY_QUERY, &hView);
BreakExitOnFailure1(hr, "Failed to execute SQL query '%ls'.", TELEMETRY_QUERY);
WcaLog(LOGMSG_STANDARD, "Executed query.");
// Iterate records
while ((hr = WcaFetchRecord(hView, &hRecord)) != E_NOMOREITEMS)
{
BreakExitOnFailure(hr, "Failed to fetch record.");
// Get fields
CWixString szId, szUrl, szPage, szMethod, szData, szCondition;
int nFlags = 0;
BOOL bSecure = FALSE;
hr = WcaGetRecordString(hRecord, TelemetryQuery::Id, (LPWSTR*)szId);
BreakExitOnFailure(hr, "Failed to get Id.");
hr = WcaGetRecordFormattedString(hRecord, TelemetryQuery::Url, (LPWSTR*)szUrl);
BreakExitOnFailure(hr, "Failed to get URL.");
hr = WcaGetRecordFormattedString(hRecord, TelemetryQuery::Page, (LPWSTR*)szPage);
BreakExitOnFailure(hr, "Failed to get Page.");
hr = WcaGetRecordFormattedString(hRecord, TelemetryQuery::Method, (LPWSTR*)szMethod);
BreakExitOnFailure(hr, "Failed to get Method.");
hr = WcaGetRecordFormattedString(hRecord, TelemetryQuery::Data, (LPWSTR*)szData);
BreakExitOnFailure(hr, "Failed to get Data.");
hr = WcaGetRecordInteger(hRecord, TelemetryQuery::Flags, &nFlags);
BreakExitOnFailure(hr, "Failed to get Flags.");
hr = WcaGetRecordString(hRecord, TelemetryQuery::Condition, (LPWSTR*)szCondition);
BreakExitOnFailure(hr, "Failed to get Condition.");
WcaLog(LOGLEVEL::LOGMSG_VERBOSE, "Will post telemetry: Id=%ls\nUrl=%ls\nPage=%ls\nData=%ls\nFlags=%i\nCondition=%ls"
, (LPCWSTR)szId
, (LPCWSTR)szUrl
, (LPCWSTR)szPage
, (LPCWSTR)szData
, (LPCWSTR)nFlags
, (LPCWSTR)szCondition
);
// Test condition
MSICONDITION condRes = ::MsiEvaluateConditionW(hInstall, szCondition);
switch (condRes)
{
case MSICONDITION::MSICONDITION_NONE:
case MSICONDITION::MSICONDITION_TRUE:
WcaLog(LOGMSG_STANDARD, "Condition evaluated to true / none.");
break;
case MSICONDITION::MSICONDITION_FALSE:
WcaLog(LOGMSG_STANDARD, "Skipping. Condition evaluated to false");
continue;
case MSICONDITION::MSICONDITION_ERROR:
hr = E_FAIL;
BreakExitOnFailure(hr, "Bad Condition field");
}
if ((nFlags & TelemetryFlags::Secure) == TelemetryFlags::Secure)
{
bSecure = TRUE;
}
if ((nFlags & TelemetryFlags::OnExecute) == TelemetryFlags::OnExecute)
{
hr = oDeferredTelemetry.AddPost(szUrl, szPage, szMethod, szData, bSecure);
BreakExitOnFailure(hr, "Failed creating custom action data for deferred action.");
}
if ((nFlags & TelemetryFlags::OnCommit) == TelemetryFlags::OnCommit)
{
hr = oCommitTelemetry.AddPost(szUrl, szPage, szMethod, szData, bSecure);
BreakExitOnFailure(hr, "Failed creating custom action data for commit action.");
}
if ((nFlags & TelemetryFlags::OnRollback) == TelemetryFlags::OnRollback)
{
hr = oRollbackTelemetry.AddPost(szUrl, szPage, szMethod, szData, bSecure);
BreakExitOnFailure(hr, "Failed creating custom action data for rollback action.");
}
}
// Schedule actions.
hr = oRollbackTelemetry.GetCustomActionData(&szCustomActionData);
BreakExitOnFailure(hr, "Failed getting custom action data for rollback action.");
hr = WcaDoDeferredAction(L"Telemetry_rollback", szCustomActionData, oRollbackTelemetry.GetCost());
BreakExitOnFailure(hr, "Failed scheduling rollback action.");
szCustomActionData.Empty();
hr = oDeferredTelemetry.GetCustomActionData(&szCustomActionData);
BreakExitOnFailure(hr, "Failed getting custom action data for deferred action.");
hr = WcaDoDeferredAction(L"Telemetry_deferred", szCustomActionData, oDeferredTelemetry.GetCost());
BreakExitOnFailure(hr, "Failed scheduling deferred action.");
szCustomActionData.Empty();
hr = oCommitTelemetry.GetCustomActionData(&szCustomActionData);
BreakExitOnFailure(hr, "Failed getting custom action data for commit action.");
hr = WcaDoDeferredAction(L"Telemetry_commit", szCustomActionData, oCommitTelemetry.GetCost());
BreakExitOnFailure(hr, "Failed scheduling commit action.");
LExit:
er = SUCCEEDED(hr) ? ERROR_SUCCESS : ERROR_INSTALL_FAILURE;
return WcaFinalize(er);
}
HRESULT CTelemetry::AddPost(LPCWSTR szUrl, LPCWSTR szPage, LPCWSTR szMethod, LPCWSTR szData, BOOL bSecure)
{
HRESULT hr = S_OK;
CComPtr<IXMLDOMElement> pElem;
hr = AddElement(L"PostTelemetry", L"CTelemetry", 1, &pElem);
BreakExitOnFailure(hr, "Failed to add XML element");
hr = pElem->setAttribute(CComBSTR("Url"), CComVariant(szUrl));
BreakExitOnFailure(hr, "Failed to add XML attribute 'Url'");
hr = pElem->setAttribute(CComBSTR("Page"), CComVariant(szPage));
BreakExitOnFailure(hr, "Failed to add XML attribute 'Page'");
hr = pElem->setAttribute(CComBSTR("Method"), CComVariant(szMethod));
BreakExitOnFailure(hr, "Failed to add XML attribute 'Method'");
hr = pElem->setAttribute(CComBSTR("Data"), CComVariant(szData));
BreakExitOnFailure(hr, "Failed to add XML attribute 'Data'");
hr = pElem->setAttribute(CComBSTR("Secure"), CComVariant(bSecure));
BreakExitOnFailure(hr, "Failed to add XML attribute 'Secure'");
LExit:
return hr;
}
// Execute the command object (XML element)
HRESULT CTelemetry::DeferredExecute(IXMLDOMElement* pElem)
{
HRESULT hr = S_OK;
CComVariant vTag;
CComVariant vUrl;
CComVariant vPage;
CComVariant vData;
CComVariant vMethod;
CComVariant vSecure;
int nSecure = 0;
// Get URL
hr = pElem->getAttribute(CComBSTR(L"Url"), &vUrl);
BreakExitOnFailure(hr, "Failed to get URL");
// Get URL
hr = pElem->getAttribute(CComBSTR(L"Page"), &vPage);
BreakExitOnFailure(hr, "Failed to get Page");
// Get Method
hr = pElem->getAttribute(CComBSTR(L"Method"), &vMethod);
BreakExitOnFailure(hr, "Failed to get Method");
// Get Data
hr = pElem->getAttribute(CComBSTR(L"Data"), &vData);
BreakExitOnFailure(hr, "Failed to get Data");
// Get Secure
hr = pElem->getAttribute(CComBSTR(L"Secure"), &vSecure);
BreakExitOnFailure(hr, "Failed to get Secure");
nSecure = _ttoi(vSecure.bstrVal);
WcaLog(LOGLEVEL::LOGMSG_VERBOSE, "Posting telemetry: Url=%ls Page=%ls Method=%ls Data=%ls Secure=%ls"
, vUrl.bstrVal
, vPage.bstrVal
, vMethod.bstrVal
, vData.bstrVal
, vSecure.bstrVal);
hr = Post(vUrl.bstrVal, vPage.bstrVal, vMethod.bstrVal, vData.bstrVal, nSecure != 0);
BreakExitOnFailure3(hr, "Failed to post Data '%ls' to URL '%ls%ls'", vData.bstrVal, vUrl.bstrVal, vPage.bstrVal);
LExit:
return hr;
}
HRESULT CTelemetry::Post(LPCWSTR szUrl, LPCWSTR szPage, LPCWSTR szMethod, LPCWSTR szData, BOOL bSecure)
{
HRESULT hr = S_OK;
DWORD dwSize = 0;
DWORD dwPrevSize = 0;
DWORD dwDownloaded = 0;
LPSTR pszOutBuffer = NULL;
BOOL bResults = FALSE;
HINTERNET hSession = NULL;
HINTERNET hConnect = NULL;
HINTERNET hRequest = NULL;
// Use WinHttpOpen to obtain a session handle.
hSession = ::WinHttpOpen(L"PanelSwCustomActions/1.0",
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS, 0);
BreakExitOnNullWithLastError(hSession, hr, "Failed openning HTTP session");
// Specify an HTTP server.
hConnect = ::WinHttpConnect(hSession, szUrl,
bSecure ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT, 0);
BreakExitOnNullWithLastError(hConnect, hr, "Failed connecting to URL");
// Create an HTTP request handle.
hRequest = ::WinHttpOpenRequest(hConnect, szMethod, szPage, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES,
bSecure ? WINHTTP_FLAG_SECURE : 0);
BreakExitOnNullWithLastError(hRequest, hr, "Failed openning request");
// Get data size
if(( szData != NULL) && ((*szData) != NULL))
{
dwSize = ::wcslen( szData);
}
// Send a request.
bResults = ::WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, (LPVOID)szData, dwSize, dwSize, 0);
BreakExitOnNull(bResults, hr, E_FAIL, "Failed sending HTTP request");
// End the request.
bResults = ::WinHttpReceiveResponse(hRequest, NULL);
BreakExitOnNull(bResults, hr, E_FAIL, "Failed receiving HTTP response");
// Keep checking for data until there is nothing left.
do
{
// Check for available data.
dwSize = 0;
bResults = ::WinHttpQueryDataAvailable(hRequest, &dwSize);
BreakExitOnNullWithLastError(bResults, hr, "Failed querying available data.");
// No more data.
if (dwSize == 0)
{
break;
}
// Allocate space for the buffer.
if (dwSize > dwPrevSize)
{
// Release previous buffer.
if( pszOutBuffer != NULL)
{
delete[] pszOutBuffer;
pszOutBuffer = NULL;
}
pszOutBuffer = new char[dwSize + 1];
BreakExitOnNull(pszOutBuffer, hr, E_FAIL, "Failed allocating memory");
dwPrevSize = dwSize;
}
// Read the Data.
::ZeroMemory(pszOutBuffer, dwSize + 1);
bResults = ::WinHttpReadData(hRequest, (LPVOID)pszOutBuffer, dwSize, &dwDownloaded);
BreakExitOnNullWithLastError(bResults, hr, "Failed reading data");
BreakExitOnNull(dwDownloaded, hr, E_FAIL, "Failed reading data (dwDownloaded=0)");
WcaLog(LOGLEVEL::LOGMSG_STANDARD, "%s", pszOutBuffer);
} while (dwSize > 0);
LExit:
// Close any open handles.
if (hRequest != NULL)
{
::WinHttpCloseHandle(hRequest);
}
if (hConnect != NULL)
{
::WinHttpCloseHandle(hConnect);
}
if (hSession != NULL)
{
::WinHttpCloseHandle(hSession);
}
if (pszOutBuffer != NULL)
{
delete[] pszOutBuffer;
}
return hr;
} | 33.27044 | 125 | 0.711153 | [
"object"
] |
244d7f2f42bcb398c7348a8c2b7c6e299c87b920 | 1,181 | cpp | C++ | cf/Div2/D/Greg and Graph/Greg and Graph.cpp | wdjpng/soi | dd565587ae30985676f7f374093ec0687436b881 | [
"MIT"
] | null | null | null | cf/Div2/D/Greg and Graph/Greg and Graph.cpp | wdjpng/soi | dd565587ae30985676f7f374093ec0687436b881 | [
"MIT"
] | null | null | null | cf/Div2/D/Greg and Graph/Greg and Graph.cpp | wdjpng/soi | dd565587ae30985676f7f374093ec0687436b881 | [
"MIT"
] | null | null | null | #include<soi>
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define rep(i,n) for (int i = 0; i < n; ++i)
signed main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int INF = 1e11;
int n;
cin >> n;
vector<vector<int>>dist(n, vector<int>(n, INF));
vector<vector<int>>G(n, vector<int>(n));
rep(i, n){
dist[i][i]=0;
rep(j, n){
cin >> i >> j;
}
}
int sum = 0;
vector<int>out;
vector<int>in(n);
rep(i,n){cin >> in[i];}
vector<bool>disc(n);
reverse(in.begin(), in.end());
for(int i : in){
i--;
rep(j,n){
rep(k,n){
if(disc[j]||disc[k])continue;
if(dist[j][k]>G[j][i]+G[i][k]){
sum-=dist[j][k]-G[j][i]-G[i][k];
dist[j][k]=G[j][i]-G[i][k];
}
dist[i][j]=min(dist[j][k]+dist[k][i], dist[i][j]);
}
}
rep(j, n){
sum+=dist[i][j];
}
out.push_back(sum);
disc[i]=true;
}
reverse(out.begin(), out.end());
rep(i,n){
cout << out[i];
}
}
| 21.472727 | 66 | 0.414056 | [
"vector"
] |
244e3bfbdf29d8f22aaa86537547b285d9a8a5b9 | 8,127 | hpp | C++ | openstudiocore/src/shared_gui_components/OSComboBox.hpp | Acidburn0zzz/OpenStudio | 8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd | [
"MIT"
] | null | null | null | openstudiocore/src/shared_gui_components/OSComboBox.hpp | Acidburn0zzz/OpenStudio | 8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd | [
"MIT"
] | null | null | null | openstudiocore/src/shared_gui_components/OSComboBox.hpp | Acidburn0zzz/OpenStudio | 8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd | [
"MIT"
] | null | null | null | /***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY 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(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***********************************************************************************************************************/
#ifndef SHAREDGUICOMPONENTS_OSCOMBOBOX_HPP
#define SHAREDGUICOMPONENTS_OSCOMBOBOX_HPP
#include "FieldMethodTypedefs.hpp"
#include "OSConcepts.hpp"
#include <nano/nano_signal_slot.hpp> // Signal-Slot replacement
#include "../model/Model.hpp"
#include "../model/ModelObject.hpp"
#include "../utilities/idf/WorkspaceObject.hpp"
#include <QComboBox>
#include <QList>
#include <vector>
namespace openstudio {
class OSComboBoxDataSource : public QObject, public Nano::Observer
{
Q_OBJECT
public:
virtual ~OSComboBoxDataSource() {}
virtual int numberOfItems() = 0;
virtual QString valueAt(int i) = 0;
signals:
void itemChanged(int);
void itemAdded(int);
void itemRemoved(int);
};
class OSObjectListCBDS : public OSComboBoxDataSource
{
Q_OBJECT
public:
OSObjectListCBDS(const IddObjectType & type, const model::Model & model);
OSObjectListCBDS(const std::vector<IddObjectType> & types, const model::Model & model);
virtual ~OSObjectListCBDS() {}
int numberOfItems() override;
QString valueAt(int i) override;
protected:
bool m_allowEmptySelection;
private slots:
void onObjectAdded(const WorkspaceObject&, const openstudio::IddObjectType& type, const openstudio::UUID& uuid);
void onObjectWillBeRemoved(const WorkspaceObject&, const openstudio::IddObjectType& type, const openstudio::UUID& uuid);
void onObjectChanged();
private:
void initialize();
std::vector<IddObjectType> m_types;
model::Model m_model;
QList<WorkspaceObject> m_workspaceObjects;
};
class OSComboBox2 : public QComboBox, public Nano::Observer {
Q_OBJECT
public:
OSComboBox2( QWidget * parent = nullptr, bool editable = false );
virtual ~OSComboBox2();
void enableClickFocus() { this->setFocusPolicy(Qt::ClickFocus); }
bool hasData() { return !this->currentText().isEmpty(); }
// interface for direct bind
template<typename ChoiceType>
void bind(model::ModelObject& modelObject,
std::function<std::string (ChoiceType)> toString,
std::function<std::vector<ChoiceType> ()> choices,
std::function<ChoiceType ()> getter,
std::function<bool (ChoiceType)> setter,
boost::optional<NoFailAction> reset=boost::none,
boost::optional<BasicQuery> isDefaulted=boost::none)
{
m_modelObject = modelObject;
m_choiceConcept = std::shared_ptr<ChoiceConcept>(
new RequiredChoiceConceptImpl<ChoiceType>(toString,
choices,
getter,
setter,
reset,
isDefaulted));
clear();
completeBind();
}
// interface for direct bind
template<typename ChoiceType>
void bind(model::ModelObject& modelObject,
std::function<std::string (ChoiceType)> toString,
std::function<std::vector<ChoiceType> ()> choices,
std::function<boost::optional<ChoiceType> ()> getter,
std::function<bool (ChoiceType)> setter,
boost::optional<NoFailAction> reset=boost::none)
{
m_modelObject = modelObject;
m_choiceConcept = std::shared_ptr<ChoiceConcept>(
new OptionalChoiceConceptImpl<ChoiceType>(toString,
choices,
getter,
setter,
reset));
clear();
completeBind();
}
// interface for OSGridController bind
void bind(model::ModelObject& modelObject,
std::shared_ptr<ChoiceConcept> choiceConcept)
{
m_modelObject = modelObject;
m_choiceConcept = choiceConcept;
clear();
completeBind();
}
// Bind to an OSComboBoxDataSource
void bind(std::shared_ptr<OSComboBoxDataSource> dataSource);
void unbind();
protected:
bool event( QEvent * e ) override;
signals:
void inFocus(bool inFocus, bool hasData);
private slots:
void onModelObjectChanged();
void onModelObjectRemoved(const Handle& handle);
void onCurrentIndexChanged(const QString & text);
void onEditTextChanged(const QString & text);
void onChoicesRefreshTrigger();
void onDataSourceChange(int);
void onDataSourceAdd(int);
void onDataSourceRemove(int);
private:
std::shared_ptr<OSComboBoxDataSource> m_dataSource;
boost::optional<model::ModelObject> m_modelObject;
std::shared_ptr<ChoiceConcept> m_choiceConcept;
std::vector<std::string> m_values;
void completeBind();
};
/**
* OSComboBox is a derived class of QComboBox that is made to easily bind to an OpenStudio
* model choice field.
*
* Alternatively, a OSComboBoxDataSource can be set to provide data to OSComoboBox.
**/
// class OSComboBox : public QComboBox, public Nano::Observer {
// Q_OBJECT
// public:
// OSComboBox( QWidget * parent = nullptr );
// virtual ~OSComboBox() {}
// void bind(model::ModelObject & modelObject, const char * property);
// void unbind();
// void setDataSource(std::shared_ptr<OSComboBoxDataSource> dataSource);
// protected:
// bool event( QEvent * e ) override;
// private slots:
// void onDataSourceChange(int);
// void onDataSourceAdd(int);
// void onDataSourceRemove(int);
// void onModelObjectChanged();
// void onModelObjectRemoved(const Handle& handle);
// void onCurrentIndexChanged(const QString & text);
// private:
// std::shared_ptr<OSComboBoxDataSource> m_dataSource;
// boost::optional<model::ModelObject> m_modelObject;
// std::string m_property;
// std::vector<std::string> m_values;
// };
} // openstudio
#endif // SHAREDGUICOMPONENTS_OSCOMBOBOX_HPP
| 30.324627 | 124 | 0.665805 | [
"vector",
"model"
] |
244eaa429b7eda0dc88bf5ed31c44f22078e6951 | 15,950 | cpp | C++ | indra/newview/llviewerjointattachment.cpp | SaladDais/LLUDP-Encryption | 8a426cd0dd154e1a10903e0e6383f4deb2a6098a | [
"ISC"
] | 1 | 2022-01-29T07:10:03.000Z | 2022-01-29T07:10:03.000Z | indra/newview/llviewerjointattachment.cpp | bloomsirenix/Firestorm-manikineko | 67e1bb03b2d05ab16ab98097870094a8cc9de2e7 | [
"Unlicense"
] | null | null | null | indra/newview/llviewerjointattachment.cpp | bloomsirenix/Firestorm-manikineko | 67e1bb03b2d05ab16ab98097870094a8cc9de2e7 | [
"Unlicense"
] | 1 | 2021-10-01T22:22:27.000Z | 2021-10-01T22:22:27.000Z | /**
* @file llviewerjointattachment.cpp
* @brief Implementation of LLViewerJointAttachment class
*
* $LicenseInfo:firstyear=2002&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llviewerjointattachment.h"
// [SL:KB] - Patch: Appearance-PhantomAttach | Checked: Catznip-5.0
#include "llagent.h"
// [/SL:KB]
#include "llviewercontrol.h"
#include "lldrawable.h"
#include "llgl.h"
#include "llhudtext.h"
#include "llrender.h"
#include "llvoavatarself.h"
#include "llvolume.h"
#include "pipeline.h"
#include "llspatialpartition.h"
#include "llinventorymodel.h"
#include "llviewerobjectlist.h"
#include "llface.h"
#include "llvoavatar.h"
#include "llglheaders.h"
extern LLPipeline gPipeline;
// <FS:Ansariel> Moved to header file
//const F32 MAX_ATTACHMENT_DIST = 3.5f; // meters?
//-----------------------------------------------------------------------------
// LLViewerJointAttachment()
//-----------------------------------------------------------------------------
LLViewerJointAttachment::LLViewerJointAttachment() :
mVisibleInFirst(FALSE),
mGroup(0),
mIsHUDAttachment(FALSE),
mPieSlice(-1)
{
mValid = FALSE;
mUpdateXform = FALSE;
mAttachedObjects.clear();
}
//-----------------------------------------------------------------------------
// ~LLViewerJointAttachment()
//-----------------------------------------------------------------------------
LLViewerJointAttachment::~LLViewerJointAttachment()
{
}
//-----------------------------------------------------------------------------
// isTransparent()
//-----------------------------------------------------------------------------
BOOL LLViewerJointAttachment::isTransparent()
{
return FALSE;
}
//-----------------------------------------------------------------------------
// drawShape()
//-----------------------------------------------------------------------------
U32 LLViewerJointAttachment::drawShape( F32 pixelArea, BOOL first_pass, BOOL is_dummy )
{
if (LLVOAvatar::sShowAttachmentPoints)
{
LLGLDisable cull_face(GL_CULL_FACE);
gGL.color4f(1.f, 1.f, 1.f, 1.f);
// <FS:Ansariel> Remove QUADS rendering mode
//gGL.begin(LLRender::QUADS);
//{
// gGL.vertex3f(-0.1f, 0.1f, 0.f);
// gGL.vertex3f(-0.1f, -0.1f, 0.f);
// gGL.vertex3f(0.1f, -0.1f, 0.f);
// gGL.vertex3f(0.1f, 0.1f, 0.f);
//}gGL.end();
gGL.begin(LLRender::TRIANGLES);
{
gGL.vertex3f(-0.1f, 0.1f, 0.f);
gGL.vertex3f(-0.1f, -0.1f, 0.f);
gGL.vertex3f(0.1f, -0.1f, 0.f);
gGL.vertex3f(-0.1f, 0.1f, 0.f);
gGL.vertex3f(0.1f, -0.1f, 0.f);
gGL.vertex3f(0.1f, 0.1f, 0.f);
}
gGL.end();
// </FS:Ansariel>
}
return 0;
}
void LLViewerJointAttachment::setupDrawable(LLViewerObject *object)
{
if (!object->mDrawable)
return;
if (object->mDrawable->isActive())
{
object->mDrawable->makeStatic(FALSE);
}
object->mDrawable->mXform.setParent(getXform()); // LLViewerJointAttachment::lazyAttach
object->mDrawable->makeActive();
LLVector3 current_pos = object->getRenderPosition();
LLQuaternion current_rot = object->getRenderRotation();
LLQuaternion attachment_pt_inv_rot = ~(getWorldRotation());
current_pos -= getWorldPosition();
current_pos.rotVec(attachment_pt_inv_rot);
current_rot = current_rot * attachment_pt_inv_rot;
object->mDrawable->mXform.setPosition(current_pos);
object->mDrawable->mXform.setRotation(current_rot);
gPipeline.markMoved(object->mDrawable);
gPipeline.markTextured(object->mDrawable); // face may need to change draw pool to/from POOL_HUD
object->mDrawable->setState(LLDrawable::USE_BACKLIGHT);
if(mIsHUDAttachment)
{
for (S32 face_num = 0; face_num < object->mDrawable->getNumFaces(); face_num++)
{
LLFace *face = object->mDrawable->getFace(face_num);
if (face)
{
face->setState(LLFace::HUD_RENDER);
}
}
}
LLViewerObject::const_child_list_t& child_list = object->getChildren();
for (LLViewerObject::child_list_t::const_iterator iter = child_list.begin();
iter != child_list.end(); ++iter)
{
LLViewerObject* childp = *iter;
if (childp && childp->mDrawable.notNull())
{
childp->mDrawable->setState(LLDrawable::USE_BACKLIGHT);
gPipeline.markTextured(childp->mDrawable); // face may need to change draw pool to/from POOL_HUD
gPipeline.markMoved(childp->mDrawable);
if(mIsHUDAttachment)
{
for (S32 face_num = 0; face_num < childp->mDrawable->getNumFaces(); face_num++)
{
LLFace * face = childp->mDrawable->getFace(face_num);
if (face)
{
face->setState(LLFace::HUD_RENDER);
}
}
}
}
}
}
//-----------------------------------------------------------------------------
// addObject()
//-----------------------------------------------------------------------------
BOOL LLViewerJointAttachment::addObject(LLViewerObject* object)
{
// object->extractAttachmentItemID();
// Same object reattached
if (isObjectAttached(object))
{
LL_INFOS() << "(same object re-attached)" << LL_ENDL;
removeObject(object);
// Pass through anyway to let setupDrawable()
// re-connect object to the joint correctly
}
// [SL:KB] - Patch: Appearance-Misc | Checked: 2011-01-13 (Catznip-2.4)
// LLViewerJointAttachment::removeObject() sets the object's item to the NULL UUID so we need to extract it *after* the block above
object->extractAttachmentItemID();
// [/SL:KB]
// Two instances of the same inventory item attached --
// Request detach, and kill the object in the meantime.
// [SL:KB] - Patch: Appearance-PhantomAttach | Checked: Catznip-5.0
if (LLViewerObject* pAttachObj = getAttachedObject(object->getAttachmentItemID()))
{
LL_INFOS() << "(same object re-attached)" << LL_ENDL;
pAttachObj->markDead();
if (pAttachObj->permYouOwner())
{
gMessageSystem->newMessage("ObjectDetach");
gMessageSystem->nextBlockFast(_PREHASH_AgentData);
gMessageSystem->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
gMessageSystem->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
gMessageSystem->nextBlockFast(_PREHASH_ObjectData);
gMessageSystem->addU32Fast(_PREHASH_ObjectLocalID, pAttachObj->getLocalID());
gMessageSystem->sendReliable(gAgent.getRegionHost());
}
}
// [/SL:KB]
// if (getAttachedObject(object->getAttachmentItemID()))
// {
// LL_INFOS() << "(same object re-attached)" << LL_ENDL;
// object->markDead();
//
// // If this happens to be attached to self, then detach.
// LLVOAvatarSelf::detachAttachmentIntoInventory(object->getAttachmentItemID());
// return FALSE;
// }
mAttachedObjects.push_back(object);
setupDrawable(object);
if (mIsHUDAttachment)
{
if (object->mText.notNull())
{
object->mText->setOnHUDAttachment(TRUE);
}
LLViewerObject::const_child_list_t& child_list = object->getChildren();
for (LLViewerObject::child_list_t::const_iterator iter = child_list.begin();
iter != child_list.end(); ++iter)
{
LLViewerObject* childp = *iter;
if (childp && childp->mText.notNull())
{
childp->mText->setOnHUDAttachment(TRUE);
}
}
}
calcLOD();
mUpdateXform = TRUE;
return TRUE;
}
//-----------------------------------------------------------------------------
// removeObject()
//-----------------------------------------------------------------------------
void LLViewerJointAttachment::removeObject(LLViewerObject *object)
{
attachedobjs_vec_t::iterator iter;
for (iter = mAttachedObjects.begin();
iter != mAttachedObjects.end();
++iter)
{
LLViewerObject *attached_object = iter->get();
if (attached_object == object)
{
break;
}
}
if (iter == mAttachedObjects.end())
{
LL_WARNS() << "Could not find object to detach" << LL_ENDL;
return;
}
// force object visibile
setAttachmentVisibility(TRUE);
mAttachedObjects.erase(iter);
if (object->mDrawable.notNull())
{
//if object is active, make it static
if(object->mDrawable->isActive())
{
object->mDrawable->makeStatic(FALSE);
}
LLVector3 cur_position = object->getRenderPosition();
LLQuaternion cur_rotation = object->getRenderRotation();
object->mDrawable->mXform.setPosition(cur_position);
object->mDrawable->mXform.setRotation(cur_rotation);
gPipeline.markMoved(object->mDrawable, TRUE);
gPipeline.markTextured(object->mDrawable); // face may need to change draw pool to/from POOL_HUD
object->mDrawable->clearState(LLDrawable::USE_BACKLIGHT);
if (mIsHUDAttachment)
{
for (S32 face_num = 0; face_num < object->mDrawable->getNumFaces(); face_num++)
{
LLFace * face = object->mDrawable->getFace(face_num);
if (face)
{
face->clearState(LLFace::HUD_RENDER);
}
}
}
}
LLViewerObject::const_child_list_t& child_list = object->getChildren();
for (LLViewerObject::child_list_t::const_iterator iter = child_list.begin();
iter != child_list.end(); ++iter)
{
LLViewerObject* childp = *iter;
if (childp && childp->mDrawable.notNull())
{
childp->mDrawable->clearState(LLDrawable::USE_BACKLIGHT);
gPipeline.markTextured(childp->mDrawable); // face may need to change draw pool to/from POOL_HUD
if (mIsHUDAttachment)
{
for (S32 face_num = 0; face_num < childp->mDrawable->getNumFaces(); face_num++)
{
LLFace * face = childp->mDrawable->getFace(face_num);
if (face)
{
face->clearState(LLFace::HUD_RENDER);
}
}
}
}
}
if (mIsHUDAttachment)
{
if (object->mText.notNull())
{
object->mText->setOnHUDAttachment(FALSE);
}
LLViewerObject::const_child_list_t& child_list = object->getChildren();
for (LLViewerObject::child_list_t::const_iterator iter = child_list.begin();
iter != child_list.end(); ++iter)
{
LLViewerObject* childp = *iter;
if (childp->mText.notNull())
{
childp->mText->setOnHUDAttachment(FALSE);
}
}
}
if (mAttachedObjects.size() == 0)
{
mUpdateXform = FALSE;
}
object->setAttachmentItemID(LLUUID::null);
}
//-----------------------------------------------------------------------------
// setAttachmentVisibility()
//-----------------------------------------------------------------------------
void LLViewerJointAttachment::setAttachmentVisibility(BOOL visible)
{
for (attachedobjs_vec_t::const_iterator iter = mAttachedObjects.begin();
iter != mAttachedObjects.end();
++iter)
{
LLViewerObject *attached_obj = iter->get();
if (!attached_obj || attached_obj->mDrawable.isNull() ||
!(attached_obj->mDrawable->getSpatialBridge()))
continue;
if (visible)
{
// Hack to make attachments not visible by disabling their type mask!
// This will break if you can ever attach non-volumes! - djs 02/14/03
attached_obj->mDrawable->getSpatialBridge()->mDrawableType =
attached_obj->isHUDAttachment() ? LLPipeline::RENDER_TYPE_HUD : LLPipeline::RENDER_TYPE_VOLUME;
}
else
{
attached_obj->mDrawable->getSpatialBridge()->mDrawableType = 0;
}
}
}
//-----------------------------------------------------------------------------
// setOriginalPosition()
//-----------------------------------------------------------------------------
void LLViewerJointAttachment::setOriginalPosition(LLVector3& position)
{
mOriginalPos = position;
// SL-315
setPosition(position);
}
//-----------------------------------------------------------------------------
// getNumAnimatedObjects()
//-----------------------------------------------------------------------------
S32 LLViewerJointAttachment::getNumAnimatedObjects() const
{
S32 count = 0;
for (attachedobjs_vec_t::const_iterator iter = mAttachedObjects.begin();
iter != mAttachedObjects.end();
++iter)
{
const LLViewerObject *attached_object = iter->get();
if (attached_object->isAnimatedObject())
{
count++;
}
}
return count;
}
//-----------------------------------------------------------------------------
// clampObjectPosition()
//-----------------------------------------------------------------------------
void LLViewerJointAttachment::clampObjectPosition()
{
for (attachedobjs_vec_t::const_iterator iter = mAttachedObjects.begin();
iter != mAttachedObjects.end();
++iter)
{
if (LLViewerObject *attached_object = iter->get())
{
// *NOTE: object can drift when hitting maximum radius
LLVector3 attachmentPos = attached_object->getPosition();
F32 dist = attachmentPos.normVec();
dist = llmin(dist, MAX_ATTACHMENT_DIST);
attachmentPos *= dist;
attached_object->setPosition(attachmentPos);
}
}
}
//-----------------------------------------------------------------------------
// calcLOD()
//-----------------------------------------------------------------------------
void LLViewerJointAttachment::calcLOD()
{
F32 maxarea = 0;
for (attachedobjs_vec_t::const_iterator iter = mAttachedObjects.begin();
iter != mAttachedObjects.end();
++iter)
{
if (LLViewerObject *attached_object = iter->get())
{
maxarea = llmax(maxarea,attached_object->getMaxScale() * attached_object->getMidScale());
LLViewerObject::const_child_list_t& child_list = attached_object->getChildren();
for (LLViewerObject::child_list_t::const_iterator iter = child_list.begin();
iter != child_list.end(); ++iter)
{
LLViewerObject* childp = *iter;
F32 area = childp->getMaxScale() * childp->getMidScale();
maxarea = llmax(maxarea, area);
}
}
}
maxarea = llclamp(maxarea, .01f*.01f, 1.f);
F32 avatar_area = (4.f * 4.f); // pixels for an avatar sized attachment
F32 min_pixel_area = avatar_area / maxarea;
setLOD(min_pixel_area);
}
//-----------------------------------------------------------------------------
// updateLOD()
//-----------------------------------------------------------------------------
BOOL LLViewerJointAttachment::updateLOD(F32 pixel_area, BOOL activate)
{
BOOL res = FALSE;
if (!mValid)
{
setValid(TRUE, TRUE);
res = TRUE;
}
return res;
}
BOOL LLViewerJointAttachment::isObjectAttached(const LLViewerObject *viewer_object) const
{
for (attachedobjs_vec_t::const_iterator iter = mAttachedObjects.begin();
iter != mAttachedObjects.end();
++iter)
{
const LLViewerObject* attached_object = iter->get();
if (attached_object == viewer_object)
{
return TRUE;
}
}
return FALSE;
}
const LLViewerObject *LLViewerJointAttachment::getAttachedObject(const LLUUID &object_id) const
{
for (attachedobjs_vec_t::const_iterator iter = mAttachedObjects.begin();
iter != mAttachedObjects.end();
++iter)
{
const LLViewerObject* attached_object = iter->get();
// if (attached_object->getAttachmentItemID() == object_id)
// [SL:KB] - Patch: Appearance-PhantomAttach | Checked: Catznip-5.0
if ( (attached_object->getAttachmentItemID() == object_id) && (!attached_object->isDead()) )
// [/SL:KB]
{
return attached_object;
}
}
return NULL;
}
LLViewerObject *LLViewerJointAttachment::getAttachedObject(const LLUUID &object_id)
{
for (attachedobjs_vec_t::iterator iter = mAttachedObjects.begin();
iter != mAttachedObjects.end();
++iter)
{
LLViewerObject* attached_object = iter->get();
if (attached_object->getAttachmentItemID() == object_id)
{
return attached_object;
}
}
return NULL;
}
| 30.208333 | 132 | 0.621818 | [
"object"
] |
2450a43b5602dc53f1536037a5e4fd5921c7702e | 5,144 | cc | C++ | alljoyn/services/controlpanel/cpp/src/ControlPanelControlleeUnit.cc | octoblu/alljoyn | a74003fa25af1d0790468bf781a4d49347ec05c4 | [
"ISC"
] | 37 | 2015-01-18T21:27:23.000Z | 2018-01-12T00:33:43.000Z | alljoyn/services/controlpanel/cpp/src/ControlPanelControlleeUnit.cc | octoblu/alljoyn | a74003fa25af1d0790468bf781a4d49347ec05c4 | [
"ISC"
] | 14 | 2015-02-24T11:44:01.000Z | 2020-07-20T18:48:44.000Z | alljoyn/services/controlpanel/cpp/src/ControlPanelControlleeUnit.cc | octoblu/alljoyn | a74003fa25af1d0790468bf781a4d49347ec05c4 | [
"ISC"
] | 29 | 2015-01-23T16:40:52.000Z | 2019-10-21T12:22:30.000Z | /******************************************************************************
* Copyright AllSeen Alliance. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
******************************************************************************/
#include <alljoyn/controlpanel/ControlPanelControlleeUnit.h>
#include <alljoyn/controlpanel/ControlPanelDevice.h>
#include <alljoyn/controlpanel/ControlPanel.h>
#include <alljoyn/controlpanel/NotificationAction.h>
#include <alljoyn/controlpanel/LanguageSets.h>
#include <alljoyn/controlpanel/ControlPanelService.h>
#include "ControlPanelConstants.h"
#include <alljoyn/controlpanel/LogModule.h>
namespace ajn {
namespace services {
using namespace cpsConsts;
ControlPanelControlleeUnit::ControlPanelControlleeUnit(qcc::String const& unitName) :
m_UnitName(unitName), m_HttpControl(0)
{
}
ControlPanelControlleeUnit::~ControlPanelControlleeUnit()
{
}
const qcc::String& ControlPanelControlleeUnit::getUnitName() const
{
return m_UnitName;
}
QStatus ControlPanelControlleeUnit::addControlPanel(ControlPanel* controlPanel)
{
if (!controlPanel) {
QCC_DbgHLPrintf(("Could not add a NULL controlPanel"));
return ER_BAD_ARG_1;
}
m_ControlPanels.push_back(controlPanel);
return ER_OK;
}
const std::vector<ControlPanel*>& ControlPanelControlleeUnit::getControlPanels() const
{
return m_ControlPanels;
}
QStatus ControlPanelControlleeUnit::addNotificationAction(NotificationAction* notificationAction)
{
if (!notificationAction) {
QCC_DbgHLPrintf(("Could not add a NULL notificationAction"));
return ER_BAD_ARG_1;
}
m_NotificationActions.push_back(notificationAction);
return ER_OK;
}
const std::vector<NotificationAction*>& ControlPanelControlleeUnit::getNotificationActions() const
{
return m_NotificationActions;
}
QStatus ControlPanelControlleeUnit::setHttpControl(HttpControl* httpControl)
{
if (!httpControl) {
QCC_DbgHLPrintf(("Could not add a NULL httpControl"));
return ER_BAD_ARG_1;
}
if (m_HttpControl) {
QCC_DbgHLPrintf(("Could not set httpControl. HttpControl already set"));
return ER_BUS_PROPERTY_ALREADY_EXISTS;
}
m_HttpControl = httpControl;
return ER_OK;
}
const HttpControl* ControlPanelControlleeUnit::getHttpControl() const
{
return m_HttpControl;
}
QStatus ControlPanelControlleeUnit::registerObjects(BusAttachment* bus)
{
QStatus status = ER_OK;
if (m_HttpControl) {
status = m_HttpControl->registerObjects(bus, m_UnitName);
if (status != ER_OK) {
QCC_LogError(status, ("Could not register the HttpControl"));
return status;
}
}
for (size_t indx = 0; indx < m_ControlPanels.size(); indx++) {
status = m_ControlPanels[indx]->registerObjects(bus, m_UnitName);
if (status != ER_OK) {
QCC_LogError(status, ("Could not register Objects for the ControlPanels"));
return status;
}
}
for (size_t indx = 0; indx < m_NotificationActions.size(); indx++) {
status = m_NotificationActions[indx]->registerObjects(bus, m_UnitName);
if (status != ER_OK) {
QCC_LogError(status, ("Could not register Objects for the ControlPanels"));
return status;
}
}
return status;
}
QStatus ControlPanelControlleeUnit::unregisterObjects(BusAttachment* bus)
{
QStatus returnStatus = ER_OK;
if (m_HttpControl) {
QStatus status = m_HttpControl->unregisterObjects(bus);
if (status != ER_OK) {
QCC_LogError(status, ("Could not unregister the HttpControl"));
returnStatus = status;
}
}
for (size_t indx = 0; indx < m_ControlPanels.size(); indx++) {
QStatus status = m_ControlPanels[indx]->unregisterObjects(bus);
if (status != ER_OK) {
QCC_LogError(status, ("Could not register Objects for the ControlPanels"));
returnStatus = status;
}
}
for (size_t indx = 0; indx < m_NotificationActions.size(); indx++) {
QStatus status = m_NotificationActions[indx]->unregisterObjects(bus);
if (status != ER_OK) {
QCC_LogError(status, ("Could not register Objects for the ControlPanels"));
returnStatus = status;
}
}
return returnStatus;
}
} /* namespace services */
} /* namespace ajn */
| 31.950311 | 98 | 0.6771 | [
"vector"
] |
245848d20d8b8f53d886974bf76dc3e3c54ccdee | 5,074 | cpp | C++ | main.cpp | NoYavy/RPG | 886ed348bc9c5159220921b8ef9ef9e8b721b456 | [
"MIT"
] | null | null | null | main.cpp | NoYavy/RPG | 886ed348bc9c5159220921b8ef9ef9e8b721b456 | [
"MIT"
] | null | null | null | main.cpp | NoYavy/RPG | 886ed348bc9c5159220921b8ef9ef9e8b721b456 | [
"MIT"
] | null | null | null | /*
* main.cpp
*
* Created on: 19.02.2022
* Author: Noyavy
*/
#include <ncurses.h>
#include "main.h"
#include "Player.h"
#include "Room.h"
#include "Interactable.h"
#include "Text.h"
#include "Item.h"
#include "Portal.h"
#include <iostream>
using namespace std;
int roomx;
int roomy;
Player pl();
void tutorial() {
clear();
mvwprintw(stdscr, 15, 10, "Du bist ein Archäologe und musst die Artefakte (X) finden. Hebe sie auf mit \"E\".");
mvwprintw(stdscr, 16, 10, "Bewege dich mit \"WASD\" und weiche den Wänden (#) aus, oder nutze die uralte Magie in");
mvwprintw(stdscr, 17, 10, "diesem antiken Tempel. Sie bewirkt, dass man in einem bestimmten Winkel durch Wände");
mvwprintw(stdscr, 18, 10, "hindurch gehen kann, du solltest das zu deinem Vorteil nutzen! * Benutze \"M\", falls");
mvwprintw(stdscr, 19, 10, "du feststeckst, es bringt dich zurück zum Menü. Doch Obacht alle Artefakte kehren");
mvwprintw(stdscr, 20, 10, "an ihre ursprüngliche Stelle zurück. Portale (0) kannst du ohne Gefahr nutzen.");
mvwprintw(stdscr, 36, 69, "* it's not a bug it's a feature");
}
void quit() {
clear();
endwin(); /* End curses mode */
exit(1);
}
void initInters(Room* room) {
room->clearInteractables();
room->addInteractable(new Item(47, 36, stdscr));
room->addInteractable(new Item(60, 26, stdscr));
room->addInteractable(new Item(13, 19, stdscr));
room->addInteractable(new Item(75, 16, stdscr));
room->addInteractable(new Text(6, 1, stdscr, "x Instructions", &tutorial));
room->addInteractable(new Text(6, 3, stdscr, "x Quit game", &quit));
room->addInteractable(new Text(9, 2, stdscr, "<- enter to start", &quit));
room->addInteractable(new Portal(7, 2, stdscr, (roomx/2), (roomy/2)));
room->addInteractable(new Portal(50, 36, stdscr, (roomx/2), (roomy/2)));
}
int main() {
int ch; /* characters typed */
initscr(); /* Start curses mode */
start_color(); /* Start color functionality */
init_pair(1, COLOR_CYAN, COLOR_BLACK);
init_pair(2, COLOR_RED, COLOR_BLACK);
cbreak(); /* Line buffering disabled,
* Pass on everything */
keypad(stdscr, TRUE); /* Activate additional keys like F1 */
curs_set(0); /* hide cursor */
int row, col;
getmaxyx(stdscr,row,col); /* Terminal size */
roomx = 100;
roomy = 37;
if (col < roomx || row < roomy) {cout << "please resize your window to at least " << roomx << " by " << roomy << " as it currently is " << col << " by " << row; quit();}
Room room(roomx-1, roomy-1); /* adjust for counting from 1 */
Player pl(2, 2, stdscr, &room);
/* set this to something you'd like
* default: */
const int user_up = 'w';
const int user_down = 's';
const int user_left = 'a';
const int user_right = 'd';
initInters(&room);
// add walls
// top left
room.addWall(0, 6, 99, 6);
room.addWall(47, 17, 47, 20);
room.addWall(37, 17, 47, 17);
room.addWall(37, 17, 37, 19);
room.addWall(37, 19, 43, 19);
room.addWall(33, 12, 33, 20);
room.addWall(21, 12, 33, 12);
room.addWall(21, 10, 33, 10);
room.addWall(33, 8, 33, 10);
room.addWall(17, 8, 33, 8);
room.addWall(17, 8, 17, 14);
room.addWall(13, 17, 25, 14);
room.addWall(17, 6, 17, 16);
room.addWall(17, 18, 17, 20);
room.addWall(5, 18, 17, 18);
room.addWall(13, 8, 13, 18);
room.addWall(9, 6, 9, 16);
room.addWall(5, 8, 5, 18);
room.addWall(25, 15, 25, 20);
// top right
room.addWall(53, 8, 53, 20);
room.addWall(53, 8, 95, 8);
room.addWall(95, 8, 95, 18);
room.addWall(58, 13, 90, 13);
room.addWall(58, 18, 95, 18);
room.addWall(58, 13, 58, 18);
// bottom left
room.addWall(0, 21, 48, 21);
room.addWall(3, 23, 52, 23);
room.addWall(0, 25, 46, 25); room.addWall(50, 25, 52, 25);
room.addWall(0, 27, 26, 27); room.addWall(30, 27, 48, 27);
room.addWall(3, 29, 28, 29); room.addWall(32, 29, 40, 29); room.addWall(44, 29, 48, 29);
room.addWall(40, 27, 40, 35);
room.addWall(3, 35, 52, 35);
room.addWall(3, 29, 3, 33); room.addWall(0, 33, 3, 33);
room.addWall(7, 31, 40, 31);
room.addWall(3, 33, 36, 33);
room.addWall(46, 29, 46, 33);
// bottom right
room.addWall(52, 21, 99, 21);
room.addWall(52, 22, 52, 22);
room.addWall(52, 23, 53, 36);
tutorial();
while((ch = getch()) != KEY_F(1)) { /* F1 as exit key */
clear();
room.render();
mvwprintw(stdscr, roomy/2, roomx/2, "+");
switch(ch) {
case user_left:
pl.moveLeft();
break;
case user_right:
pl.moveRight();
break;
case user_up:
pl.moveUp();
break;
case user_down:
pl.moveDown();
break;
case 'e':
pl.interact();
break;
case 'm':
pl.teleport(2, 2);
pl.clearInventory();
initInters(&room);
default:
pl.render('~'); /* prevent player from turning invisible */
continue;
}
if (pl.score == 4) {
clear();
mvwprintw(stdscr, roomy/2, roomx/2, "You won! Press any key to quit");
if (getch()) {quit();}
}
refresh();
}
quit();
return 0;
}
| 30.023669 | 171 | 0.606031 | [
"render"
] |
245cb001f50eb89c4999459c3f5dad3a117070b3 | 1,526 | cpp | C++ | src/classwork/11_assign/vector.cpp | acc-cosc-1337-spring-2020-hl/acc-cosc-1337-spring-2020-nikkig124 | d68d1719698e574d1a8f9b159ac2b2079aa21025 | [
"MIT"
] | null | null | null | src/classwork/11_assign/vector.cpp | acc-cosc-1337-spring-2020-hl/acc-cosc-1337-spring-2020-nikkig124 | d68d1719698e574d1a8f9b159ac2b2079aa21025 | [
"MIT"
] | null | null | null | src/classwork/11_assign/vector.cpp | acc-cosc-1337-spring-2020-hl/acc-cosc-1337-spring-2020-nikkig124 | d68d1719698e574d1a8f9b159ac2b2079aa21025 | [
"MIT"
] | null | null | null | #include "vector.h"
//allocate dynamic memory for array of size
//initalized all array elemenrts to 0
Vector::Vector(size_t sz)
:size{ sz }, nums{ new int[sz] }
{
for (size_t i = 0; i < sz; ++i)
{
nums[i] = 0;
}
}
//COPY CONSTRUCT
//set ner class size to teh original array size
//allocated a dynamic memory array of size elements
//initalized all elements to value of original class
Vector::Vector(const Vector & v)
: size{v.size}, nums{new int[v.size]}
{
for (size_t i = 0; i < size ++i)
{
nums[i] = v[i];
}
}
Vector & Vector::operator=(const Vector & v)
{
int* temp = new int[v.size];
for (size_t i = 0; i < v.size; ++i)
{
temp[i] = v[i];
}
delete[]nums;
nums = temp;
size = v.size;
return *this;
}
//use move source pointer
//point move source pointer to nothing
Vector::Vector(Vector && v)
: size{ v.size }, nums{ v.nums }
{
v.size = 0;
v.nums = nullptr;
}
Vector & Vector::operator=(Vector && v)
{
//dont create memory
delete nums;
nums = v.nums;
size = v.size;
//changing pointers to help code run faster
v.nums = nullptr;
v.size = 0;
return *this;
}
Vector::~Vector()
{
std::cout << "release memory";
delete[] nums;
}
//void use_vector()
//{
// Vector v(3);
//}
void use_vector()
{
Vector *v = new Vector(3); // does not call the destructor.
// If you allocate dynamic memory, you should release the moemery manually.
}
Vector get_vector()
{
Vector v = Vector(3);
return v;
}
| 17.54023 | 77 | 0.598296 | [
"vector"
] |
245dcdcb6f1d8d46e4a33d27bf5f65bf7d440d22 | 2,440 | cpp | C++ | globals.cpp | azarrias/zork | cf9fcf7e8f79e64f32efcef73fde5b7f986ff7c6 | [
"FTL"
] | null | null | null | globals.cpp | azarrias/zork | cf9fcf7e8f79e64f32efcef73fde5b7f986ff7c6 | [
"FTL"
] | null | null | null | globals.cpp | azarrias/zork | cf9fcf7e8f79e64f32efcef73fde5b7f986ff7c6 | [
"FTL"
] | null | null | null | #include "globals.h"
#include <string>
#include <sstream>
#include <vector>
#include <unordered_set>
#include <algorithm>
#include <iostream>
using namespace std;
Style::Modifier stFgRed(Style::FG_RED);
Style::Modifier stFgBlue(Style::FG_BLUE);
Style::Modifier stFgYellow(Style::FG_YELLOW);
Style::Modifier stBold(Style::BOLD);
Style::Modifier stReset(Style::RESET);
Style::Modifier stBgWhite(Style::BG_LIGHT_GRAY);
Style::Modifier stBgCyan(Style::BG_CYAN);
Style::Modifier stBgRed(Style::BG_RED);
Style::Modifier stBgYellow(Style::BG_YELLOW);
void setStyles(bool useStyles) {
stFgRed.setUseStyles(useStyles);
stFgBlue.setUseStyles(useStyles);
stFgYellow.setUseStyles(useStyles);
stBold.setUseStyles(useStyles);
stReset.setUseStyles(useStyles);
stBgWhite.setUseStyles(useStyles);
stBgCyan.setUseStyles(useStyles);
stBgRed.setUseStyles(useStyles);
stBgYellow.setUseStyles(useStyles);
}
void tokenize(const string& s, vector<string>& vect) {
if (vect.size() > 0) vect.clear();
stringstream stringStream(s);
string item;
while (getline(stringStream, item, ' ')) {
if (!item.empty()) {
transform(item.begin(), item.end(), item.begin(), toupper);
vect.push_back(item);
}
}
}
const Direction getOppositeDirection(const Direction& direction) {
if (direction % 2 == 0) return (Direction)(direction + 1);
else return (Direction)(direction - 1);
}
const string toString(const Direction& direction) {
switch (direction) {
case Direction::U: return "UP"; break;
case Direction::D: return "DOWN"; break;
case Direction::N: return "NORTH"; break;
case Direction::S: return "SOUTH"; break;
case Direction::E: return "EAST"; break;
case Direction::W: return "WEST"; break;
case Direction::IN: return "INSIDE"; break;
case Direction::OUT: return "OUTSIDE"; break;
default: return "I don't know where!!!";
}
}
const Direction toDirection(const string& st) {
if (st == "U" || st == "UP") return Direction::U;
else if (st == "D" || st == "DOWN") return Direction::D;
else if (st == "N" || st == "NORTH") return Direction::N;
else if (st == "S" || st == "SOUTH") return Direction::S;
else if (st == "E" || st == "EAST") return Direction::E;
else if (st == "W" || st == "WEST") return Direction::W;
else if (st == "IN") return Direction::IN;
else if (st == "OUT") return Direction::OUT;
return Direction::OUT;
}
ostream& operator<<(ostream& output, Direction const& dir) {
return output << toString(dir);
}
| 30.886076 | 66 | 0.701639 | [
"vector",
"transform"
] |
24601bdc6b7f5e1a26128123943b7a1f4bd77409 | 6,731 | hh | C++ | src/gui/plugins/plotting/Plotting.hh | knoedler/ign-gazebo | c37e4822c1cf59f7302358d0b4dc7b8ba3db5a1d | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/gui/plugins/plotting/Plotting.hh | knoedler/ign-gazebo | c37e4822c1cf59f7302358d0b4dc7b8ba3db5a1d | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/gui/plugins/plotting/Plotting.hh | knoedler/ign-gazebo | c37e4822c1cf59f7302358d0b4dc7b8ba3db5a1d | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2020-05-07T09:04:39.000Z | 2020-05-07T09:04:39.000Z | /*
* Copyright (C) 2020 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.
*
*/
#ifndef IGNITION_GUI_PLUGINS_PLOTTING_HH_
#define IGNITION_GUI_PLUGINS_PLOTTING_HH_
#include <ignition/gui/qt.h>
#include <ignition/gui/Application.hh>
#include <ignition/gui/PlottingInterface.hh>
#include <ignition/gazebo/gui/GuiSystem.hh>
#include <ignition/math/Vector3.hh>
#include <ignition/math/Pose3.hh>
#include "sdf/Physics.hh"
#include <map>
#include <string>
#include <memory>
namespace ignition {
namespace gazebo {
class PlotComponentPrivate;
/// \brief A container of the component data that keeps track of the registered
/// attributes and update their values and their registered charts
class PlotComponent
{
/// \brief Constructor
/// \param[in] _type component data type (Pose3d, Vector3d, double)
/// \param [in] _entity entity id of that component
/// \param [in] _typeId type identifier unique to each component type
public: PlotComponent(const std::string &_type,
ignition::gazebo::Entity _entity,
ComponentTypeId _typeId);
/// \brief Destructor
public: ~PlotComponent();
/// \brief Add a registered chart to the attribute
/// \param[in] _attribute component attribute to add the chart to it
/// \param[in] _chart chart ID to be added to the attribute
public: void RegisterChart(std::string _attribute, int _chart);
/// \brief Remove a registered chart from the attribute
/// \param[in] _attribute component attribute to remove the chart from it
/// \param[in] _chart chart ID to be removed from the attribute
public: void UnRegisterChart(std::string _attribute, int _chart);
/// \brief Check if any of the component attributes has any chart
/// \return true if any attribute has a chart
/// false if all attributes are empty from the charts
public: bool HasCharts();
/// \brief Set a value of specefic component attribute
/// \param[in] _attribute component attribute to set its value
/// ex : yaw attribute in Pose3d type Component
/// \param[in] _value value to be set to the attribute
public: void SetAttributeValue(std::string _attribute, const double &_value);
/// \brief Get all attributes of the component
/// \return component attributes
public: std::map<std::string, std::shared_ptr<ignition::gui::PlotData>>
Data() const;
/// \brief Get the Component entity ID
/// \return Entity ID
public: ignition::gazebo::Entity Entity();
/// \brief Get the Component type ID
/// \return component type ID
public: ComponentTypeId TypeId();
/// \brief dataPtr holds Abstraction data of PlottingPrivate
private: std::unique_ptr<PlotComponentPrivate> dataPtr;
};
class PlottingPrivate;
/// \brief Physics data plotting handler that keeps track of the
/// registered components, update them and update the plot
class Plotting : public ignition::gazebo::GuiSystem
{
Q_OBJECT
/// \brief Constructor
public: Plotting();
/// \brief Destructor
public: ~Plotting();
// Documentation inherited
public: void LoadConfig(const tinyxml2::XMLElement *) override;
// Documentation inherited
public: void Update(const ignition::gazebo::UpdateInfo &_info,
ignition::gazebo::EntityComponentManager &_ecm) override;
/// \brief Set the Component data of giving id to the giving vector
/// \param [in] _Id Component Key of the components map
/// \param [in] _vector Vector Data to be set to the component
public: void SetData(std::string _Id,
const ignition::math::Vector3d &_vector);
/// \brief Set the Component data of giving id to the giving pose
/// \param [in] _Id Component Key of the components map
/// \param [in] _pose Position Data to be set to the component
public: void SetData(std::string _Id,
const ignition::math::Pose3d &_pose);
/// \brief Set the Component data of giving id to the giving
/// physics properties
/// \param [in] _Id Component Key of the components map
/// \param [in] _value physics Data to be set to the component
public: void SetData(std::string _Id, const sdf::Physics &_physics);
/// \brief Set the Component data of giving id to the giving number
/// \param [in] _Id Component Key of the components map
/// \param [in] _value double Data to be set to the component
/// valid for types (double, float, int, bool)
public: void SetData(std::string _Id, const double &_value);
/// \brief Add a chart to a specefic component attribute
/// \param[in] _entity entity id in the simulation
/// \param[in] _typeId type identifier unique to each component type
/// \param[in] _type Component Datatype ("Pose3d","Vector3d","double")
/// \param[in] _attribute component attribute to add the chart to it
/// ex: x attribute in Pose3d Component will be "x"
/// \param [in] _chart chart ID to be registered
public slots: void RegisterChartToComponent(uint64_t _entity,
uint64_t _typeId,
std::string _type,
std::string _attribute,
int _chart);
/// \brief Remove a chart from a specefic component attribute
/// \param[in] _entity entity id in the simulation
/// \param[in] _typeId type identifier unique to each component type
/// \param[in] _attribute component attribute to remove the chart from it
/// ex: x attribute in Pose3d Component will be "x"
/// \param[in] _chart chart ID to be unregistered
public slots: void UnRegisterChartFromComponent(uint64_t _entity,
uint64_t _typeId,
std::string _attribute,
int _chart);
/// \brief Get Component Name based on its type Id
/// \param[in] _typeId type Id of the component
/// \return Component name
public slots: std::string ComponentName(const uint64_t &_typeId);
/// \brief dataPtr holds Abstraction data of PlottingPrivate
private: std::unique_ptr<PlottingPrivate> dataPtr;
};
}
}
#endif
| 39.133721 | 79 | 0.682662 | [
"vector"
] |
2461b24fedb742bfb1e1c8f47851d7bdd29d1682 | 14,593 | cc | C++ | bwidgets/bwPainter.cc | julianeisel/bWidgets | 35695df104f77b35992013a5602adf2723ab1022 | [
"MIT"
] | 72 | 2018-03-26T20:13:47.000Z | 2022-03-08T15:59:55.000Z | bwidgets/bwPainter.cc | julianeisel/bWidgets | 35695df104f77b35992013a5602adf2723ab1022 | [
"MIT"
] | 12 | 2018-03-30T12:54:15.000Z | 2021-05-30T23:33:01.000Z | bwidgets/bwPainter.cc | julianeisel/bWidgets | 35695df104f77b35992013a5602adf2723ab1022 | [
"MIT"
] | 10 | 2018-03-26T23:04:06.000Z | 2021-11-17T21:04:27.000Z | #include <algorithm>
#include <cassert>
#include <cmath>
#include <iostream>
#include "bwPaintEngine.h"
#include "bwPoint.h"
#include "bwPolygon.h"
#include "bwRange.h"
#include "bwStyle.h"
#include "bwUtil.h"
#include "bwWidgetBaseStyle.h"
#include "bwPainter.h"
namespace bWidgets {
std::unique_ptr<bwPaintEngine> bwPainter::s_paint_engine = nullptr;
bwPainter::bwPainter() : active_drawtype(DrawType::FILLED), active_gradient(nullptr)
{
}
static auto painter_check_paint_engine() -> bool
{
if (bwPainter::s_paint_engine == nullptr) {
std::cout << PRETTY_FUNCTION << "-- Error: No paint-engine set!" << std::endl;
return false;
}
return true;
}
void bwPainter::drawPolygon(const bwPolygon& poly)
{
if (!painter_check_paint_engine()) {
return;
}
if (poly.isDrawable()) {
s_paint_engine->drawPolygon(*this, poly);
}
if (isGradientEnabled()) {
vert_colors.clear();
}
}
void bwPainter::drawText(const std::string& text,
const bwRectanglePixel& rectangle,
const TextAlignment alignment) const
{
if (!painter_check_paint_engine()) {
return;
}
if (!text.empty()) {
s_paint_engine->drawText(*this, text, rectangle, alignment);
}
}
void bwPainter::drawIcon(const bwIconInterface& icon_interface, const bwRectanglePixel& rect) const
{
if (!painter_check_paint_engine()) {
return;
}
if (!rect.isEmpty() && icon_interface.isValid()) {
s_paint_engine->drawIcon(*this, icon_interface, rect);
}
}
void bwPainter::setActiveColor(const bwColor& color)
{
active_color = color;
active_gradient = nullptr;
}
auto bwPainter::getActiveColor() const -> const bwColor&
{
return active_color;
}
auto bwPainter::getVertexColor(const size_t vertex_index) const -> const bwColor&
{
return vert_colors[vertex_index];
}
void bwPainter::setContentMask(const bwRectanglePixel& value)
{
content_mask = value;
}
auto bwPainter::getContentMask() const -> const bwRectanglePixel&
{
return content_mask;
}
void bwPainter::enableGradient(const bwGradient& gradient)
{
if (!active_gradient) {
active_gradient = std::make_unique<bwGradient>();
}
*active_gradient = gradient;
}
bool bwPainter::isGradientEnabled() const
{
return active_gradient != nullptr;
}
void bwPainter::drawTextAndIcon(const std::string& text,
const bwIconInterface* icon,
const bwRectanglePixel& rectangle,
const TextAlignment alignment,
float dpi_fac) const
{
bwRectanglePixel icon_rect{rectangle};
bwRectanglePixel text_rect{rectangle};
if (icon) {
const float icon_size = std::round(bwIconInterface::ICON_DEFAULT_SIZE * dpi_fac);
icon_rect.xmax = int(icon_rect.xmin + icon_size);
icon_rect.ymax = int(icon_rect.ymin + icon_size);
drawIcon(*icon, icon_rect);
text_rect.xmin = icon_rect.xmax;
}
drawText(text, text_rect, alignment);
}
// ------------------ Primitives ------------------
static const std::vector<bwPoint> check_mark_verts = {{-0.578579f, 0.253369f},
{-0.392773f, 0.412794f},
{-0.004241f, -0.328551f},
{-0.003001f, 0.034320f},
{1.055313f, 0.864744f},
{0.866408f, 1.026895f}};
void bwPainter::drawCheckMark(const bwRectanglePixel& rect)
{
const bwPoint center{(float)rect.centerX(), (float)rect.centerY()};
const float size = 0.5f * rect.height();
bwPolygon polygon;
for (const bwPoint& point : check_mark_verts) {
polygon.addVertex(size * point + center);
}
if (isGradientEnabled()) {
fillVertexColorsWithGradient(polygon, rect);
}
use_antialiasing = true;
drawPolygon(polygon);
}
void bwPainter::drawTriangle(const bwRectanglePixel& rect, Direction direction)
{
bwPolygon polygon{3};
switch (direction) {
case Direction::UP:
polygon.addVertex(rect.xmin, rect.ymin);
polygon.addVertex(int(rect.xmin + (rect.width() * 0.5f)), rect.ymax);
polygon.addVertex(rect.xmax, rect.ymin);
break;
case Direction::DOWN:
polygon.addVertex(rect.xmin, rect.ymax);
polygon.addVertex(int(rect.xmin + (rect.width() * 0.5f)), rect.ymin);
polygon.addVertex(rect.xmax, rect.ymax);
break;
case Direction::LEFT:
polygon.addVertex(rect.xmax, rect.ymax);
polygon.addVertex(rect.xmin, int(rect.ymin + (rect.height() * 0.5f)));
polygon.addVertex(rect.xmax, rect.ymin);
break;
case Direction::RIGHT:
polygon.addVertex(rect.xmin, rect.ymax);
polygon.addVertex(rect.xmax, int(rect.ymin + (rect.height() * 0.5f)));
polygon.addVertex(rect.xmin, rect.ymin);
break;
}
if (isGradientEnabled()) {
fillVertexColorsWithGradient(polygon, rect);
}
use_antialiasing = true;
drawPolygon(polygon);
}
void bwPainter::drawLine(const bwPoint& from, const bwPoint& to)
{
bwPolygon polygon{2};
active_drawtype = bwPainter::DrawType::LINE;
polygon.addVertex(from.x, from.y);
polygon.addVertex(to.x, to.y);
drawPolygon(polygon);
}
class PolygonRoundboxCreator {
public:
PolygonRoundboxCreator(const bwRectanglePixel& rect,
unsigned int corners,
float _radius,
bool is_outline);
void addVerts(bwPolygon& polygon);
private:
void startRoundbox(const bwPolygon& polygon);
void endRoundbox(bwPolygon& polygon) const;
void addVertsBottomLeft(bwPolygon& polygon) const;
void addVertsBottomRight(bwPolygon& polygon) const;
void addVertsTopRight(bwPolygon& polygon) const;
void addVertsTopLeft(bwPolygon& polygon) const;
static const int ROUNDCORNER_RESOLUTION = 9;
static constexpr float cornervec[ROUNDCORNER_RESOLUTION][2] = {{0.0f, 0.0f},
{0.195f, 0.02f},
{0.383f, 0.067f},
{0.55f, 0.169f},
{0.707f, 0.293f},
{0.831f, 0.45f},
{0.924f, 0.617f},
{0.98f, 0.805f},
{1.0f, 1.0f}};
bwRectanglePixel rect;
bwRectanglePixel rect_inner;
float vec_outer[ROUNDCORNER_RESOLUTION][2] = {};
float vec_inner[ROUNDCORNER_RESOLUTION][2] = {};
int start_vertex_count = 0;
unsigned int corners = 0;
float radius = 0.0f;
float radius_inner = 0.0f;
bool is_outline = false;
};
constexpr float PolygonRoundboxCreator::cornervec[ROUNDCORNER_RESOLUTION][2];
void PolygonRoundboxCreator::addVertsBottomLeft(bwPolygon& polygon) const
{
if (corners & BOTTOM_LEFT) {
for (int i = 0; i < ROUNDCORNER_RESOLUTION; i++) {
polygon.addVertex(rect.xmin + vec_outer[i][1], rect.ymin + radius - vec_outer[i][0]);
if (is_outline) {
polygon.addVertex(rect_inner.xmin + vec_inner[i][1],
rect_inner.ymin + radius_inner - vec_inner[i][0]);
}
}
}
else {
polygon.addVertex(rect.xmin, rect.ymin);
if (is_outline) {
polygon.addVertex(rect_inner.xmin, rect_inner.ymin);
}
}
}
void PolygonRoundboxCreator::addVertsBottomRight(bwPolygon& polygon) const
{
if (corners & BOTTOM_RIGHT) {
for (int i = 0; i < ROUNDCORNER_RESOLUTION; i++) {
polygon.addVertex(rect.xmax - radius + vec_outer[i][0], rect.ymin + vec_outer[i][1]);
if (is_outline) {
polygon.addVertex(rect_inner.xmax - radius_inner + vec_inner[i][0],
rect_inner.ymin + vec_inner[i][1]);
}
}
}
else {
polygon.addVertex(rect.xmax, rect.ymin);
if (is_outline) {
polygon.addVertex(rect_inner.xmax, rect_inner.ymin);
}
}
}
void PolygonRoundboxCreator::addVertsTopRight(bwPolygon& polygon) const
{
if (corners & TOP_RIGHT) {
for (int i = 0; i < ROUNDCORNER_RESOLUTION; i++) {
polygon.addVertex(rect.xmax - vec_outer[i][1], rect.ymax - radius + vec_outer[i][0]);
if (is_outline) {
polygon.addVertex(rect_inner.xmax - vec_inner[i][1],
rect_inner.ymax - radius_inner + vec_inner[i][0]);
}
}
}
else {
polygon.addVertex(rect.xmax, rect.ymax);
if (is_outline) {
polygon.addVertex(rect_inner.xmax, rect_inner.ymax);
}
}
}
void PolygonRoundboxCreator::addVertsTopLeft(bwPolygon& polygon) const
{
if (corners & TOP_LEFT) {
for (int i = 0; i < ROUNDCORNER_RESOLUTION; i++) {
polygon.addVertex(rect.xmin + radius - vec_outer[i][0], rect.ymax - vec_outer[i][1]);
if (is_outline) {
polygon.addVertex(rect_inner.xmin + radius_inner - vec_inner[i][0],
rect_inner.ymax - vec_inner[i][1]);
}
}
}
else {
polygon.addVertex(rect.xmin, rect.ymax);
if (is_outline) {
polygon.addVertex(rect_inner.xmin, rect_inner.ymax);
}
}
}
PolygonRoundboxCreator::PolygonRoundboxCreator(const bwRectanglePixel& rect,
unsigned int corners,
float _radius,
bool is_outline)
: rect(rect),
rect_inner(rect),
corners(corners),
radius(_radius),
radius_inner(_radius - 1.0f),
is_outline(is_outline)
{
for (int i = 0; i < ROUNDCORNER_RESOLUTION; i++) {
vec_outer[i][0] = radius * cornervec[i][0];
vec_outer[i][1] = radius * cornervec[i][1];
vec_inner[i][0] = radius_inner * cornervec[i][0];
vec_inner[i][1] = radius_inner * cornervec[i][1];
}
rect_inner.resize(-1);
}
void PolygonRoundboxCreator::startRoundbox(const bwPolygon& polygon)
{
start_vertex_count = int(polygon.getVertices().size());
}
void PolygonRoundboxCreator::endRoundbox(bwPolygon& polygon) const
{
unsigned int first_vert_index = std::max(0, start_vertex_count - 1);
// Back to start
polygon.addVertex(polygon[first_vert_index]);
if (is_outline) {
polygon.addVertex(polygon[first_vert_index + 1]);
}
}
void PolygonRoundboxCreator::addVerts(bwPolygon& polygon)
{
// Assumes all corners are rounded so may reserve more than needed. That's fine though.
polygon.reserve((ROUNDCORNER_RESOLUTION * 4 + 1) * (is_outline ? 2 : 1));
startRoundbox(polygon);
addVertsBottomLeft(polygon);
addVertsBottomRight(polygon);
addVertsTopRight(polygon);
addVertsTopLeft(polygon);
endRoundbox(polygon);
}
static auto getRoundboxMinsize(const bwRectanglePixel& rect, unsigned int corners) -> unsigned int
{
const int hnum = ((corners & (TOP_LEFT | TOP_RIGHT)) == (TOP_LEFT | TOP_RIGHT) ||
(corners & (BOTTOM_RIGHT | BOTTOM_LEFT)) == (BOTTOM_RIGHT | BOTTOM_LEFT)) ?
1 :
2;
const int vnum = ((corners & (TOP_LEFT | BOTTOM_LEFT)) == (TOP_LEFT | BOTTOM_LEFT) ||
(corners & (TOP_RIGHT | BOTTOM_RIGHT)) == (TOP_RIGHT | BOTTOM_RIGHT)) ?
1 :
2;
return std::min(rect.width() * hnum, rect.height() * vnum);
}
void bwPainter::drawRoundbox(const bwRectanglePixel& rect,
unsigned int corners,
const float radius)
{
bwPolygon polygon;
const unsigned int minsize = getRoundboxMinsize(rect, corners);
float validated_radius = radius;
bwRange<float>::clampValue(validated_radius, 0.0f, minsize * 0.5f);
PolygonRoundboxCreator roundbox_creator{
rect, corners, validated_radius, active_drawtype == DrawType::OUTLINE};
roundbox_creator.addVerts(polygon);
if (active_drawtype == DrawType::OUTLINE) {
use_antialiasing = true;
}
if (isGradientEnabled()) {
fillVertexColorsWithGradient(polygon, rect);
}
drawPolygon(polygon);
}
void bwPainter::drawRectangle(const bwRectanglePixel& rect)
{
bwPolygon polygon;
polygon.addVertex(rect.xmin, rect.ymin);
polygon.addVertex(rect.xmax, rect.ymin);
polygon.addVertex(rect.xmax, rect.ymax);
polygon.addVertex(rect.xmin, rect.ymax);
if (isGradientEnabled()) {
fillVertexColorsWithGradient(polygon, rect);
}
drawPolygon(polygon);
}
/**
* \param rect: The bounding box of the polygon based on which the gradient is drawn. It could be
* calculated just now since there's access to \a polygon, but it's usually available when calling
* this function anyway.
*/
void bwPainter::fillVertexColorsWithGradient(const bwPolygon& polygon,
const bwRectanglePixel& bounding_box)
{
const bwPointVec& vertices = polygon.getVertices();
const bool is_single_color = active_gradient->begin == active_gradient->end;
assert(isGradientEnabled());
vert_colors.reserve(vertices.size());
for (const bwPoint& vertex : vertices) {
const bwColor& col = is_single_color ? active_gradient->begin :
active_gradient->calcPointColor(vertex, bounding_box);
vert_colors.push_back(col);
}
assert(vert_colors.size() == vertices.size());
}
void bwPainter::drawRoundboxWidgetBase(const bwWidgetBaseStyle& base_style,
const bwStyle& style,
const bwRectanglePixel& rectangle,
const bwGradient& gradient,
const float radius)
{
bwRectanglePixel inner_rect = rectangle;
const float radius_pixel = radius * style.dpi_fac;
assert(bwRange<int>::isInside(base_style.shade_top, -255, 255, true));
assert(bwRange<int>::isInside(base_style.shade_bottom, -255, 255, true));
// Inner - "inside" of outline, so scale down
inner_rect.resize(-1);
setContentMask(inner_rect); // Not sure if we should set this here.
active_drawtype = bwPainter::DrawType::FILLED;
enableGradient(gradient);
drawRoundbox(inner_rect, base_style.roundbox_corners, radius_pixel - 1.0f);
// Outline
active_drawtype = bwPainter::DrawType::OUTLINE;
setActiveColor(base_style.borderColor());
drawRoundbox(rectangle, base_style.roundbox_corners, radius_pixel);
}
} // namespace bWidgets
| 30.465553 | 99 | 0.622353 | [
"vector"
] |
2462bed5a1740e5f765303c5488d6b7522605eaa | 1,827 | cpp | C++ | plainECS/example_usage/main.cpp | NistBox/plainECS | e06c975d2658350165c22b31ef9d0c6253ac5284 | [
"MIT"
] | 1 | 2019-09-10T12:43:06.000Z | 2019-09-10T12:43:06.000Z | plainECS/example_usage/main.cpp | NistBox/plainECS | e06c975d2658350165c22b31ef9d0c6253ac5284 | [
"MIT"
] | null | null | null | plainECS/example_usage/main.cpp | NistBox/plainECS | e06c975d2658350165c22b31ef9d0c6253ac5284 | [
"MIT"
] | null | null | null | #include <iostream>
#include "ecs.h"
#include "systems.h"
#include "components.h"
#ifdef _DEBUG
#pragma comment(lib, "plainECS_Debug.lib")
#else
#pragma comment(lib, "plainECS_Release.lib")
#endif
/*
Imagine a simple 1-dimentional world. Objects are born in the air, falls
due to gravity and are removed from the world once they hit the ground.
*/
int main()
{
ecs::EntityComponentSystem world;
/*
-- CREATE SYSTEMS --
Create the systems for the world. Order matters.
GravitySystem - Updates the position of each objects that
has a GravityComponent and a PositionComponent.
GroundHitSystem - Checks the position of each object with a
PositionComponent, removes those who has hit
the ground.
These systems are found in 'systems.h' and 'systems.cpp'
*/
world.createSystem<ecs::systems::GravitySystem>();
world.createSystem<ecs::systems::GroundHitSystem>();
/*
-- CREATE ENTITIES --
PhysicsComponent - Holds information about its object's mass and
velocity.
PositionComponent - Holds information about its object's height
in the world.
These components are found in 'components.h'
*/
PhysicsComponent physics_desc;
physics_desc.mass = 1.0f;
physics_desc.velocity = 0.0f;
PositionComponent position_desc;
// Create 10 entitites
for (int i = 1; i <= 10; i++)
{
position_desc.height = float(i);
world.createEntity(physics_desc, position_desc);
}
/*
-- MAIN LOOP --
Simulate a world with 60 ticks (updates) per second
*/
const float delta = 1.f / 60.f;
float elapsed = 0.f;
while (world.getTotalEntityCount() > 0)
{
world.update(delta);
elapsed += delta;
std::cout << "Elapsed time: " << elapsed << "\nEntity count: " << world.getTotalEntityCount() << "\n\n";
}
system("pause");
return 0;
} | 20.761364 | 106 | 0.686371 | [
"object"
] |
2471159980402a6bdb6c9df1ef90a449b7e9de6b | 1,775 | cpp | C++ | src/io/github/technicalnotes/programming/problems/29-01-2020/generatespiralmatrix.cpp | chiragbhatia94/programming-cpp | efd6aa901deacf416a3ab599e6599845a8111eac | [
"MIT"
] | null | null | null | src/io/github/technicalnotes/programming/problems/29-01-2020/generatespiralmatrix.cpp | chiragbhatia94/programming-cpp | efd6aa901deacf416a3ab599e6599845a8111eac | [
"MIT"
] | null | null | null | src/io/github/technicalnotes/programming/problems/29-01-2020/generatespiralmatrix.cpp | chiragbhatia94/programming-cpp | efd6aa901deacf416a3ab599e6599845a8111eac | [
"MIT"
] | null | null | null | #include "bits/stdc++.h"
using namespace std;
void generateMatrix(int);
void fill(vector<vector<int>> &, int, bool, int, bool);
int main()
{
generateMatrix(4);
}
static int cell = 1;
void generateMatrix(int A)
{
int rowSeq[A];
int colSeq[A];
vector<vector<int>> spiralMatrix;
spiralMatrix.resize(A, std::vector<int>(A, 0));
// Generating row seq
bool start = true;
for (int i = 0, j = 0; i < A; i++)
{
if (start)
{
rowSeq[i] = j;
}
else
{
rowSeq[i] = A - 1 - j;
j++;
}
start = !start;
}
// Generating col seq
start = false;
for (int i = 0, j = 0; i < A; i++)
{
if (start)
{
colSeq[i] = j;
j++;
}
else
{
colSeq[i] = A - 1 - j;
}
start = !start;
}
for (size_t i = 0; i < A; i++)
{
spiralMatrix[0][i] = cell++;
}
bool straight = true;
for (size_t i = 3; i > 0; i--)
{
fill(spiralMatrix, rowSeq[A - i], true, i, straight);
straight = !straight;
fill(spiralMatrix, rowSeq[A - i], false, i, straight);
}
for (int i = 0; i < A; i++)
{
for (int j = 0; j < A; j++)
{
cout << spiralMatrix[i][j] << " ";
}
cout << endl;
}
}
void fill(vector<vector<int>> &spiralMatrix, int currentRowCol, bool fixCol, int count, bool sequence)
{
if (sequence)
{
for (size_t i = spiralMatrix.size() - count; i <= count; i++)
{
if (fixCol)
spiralMatrix[i][currentRowCol] = cell++;
else
spiralMatrix[currentRowCol][i] = cell++;
}
}
else
{
for (size_t i = spiralMatrix.size() - count; i <= count; i++)
{
if (fixCol)
spiralMatrix[count - i][currentRowCol] = cell++;
else
spiralMatrix[currentRowCol][count - i] = cell++;
}
}
}
| 17.929293 | 102 | 0.516056 | [
"vector"
] |
2471b1e0739f55506dc76d5ece4c25b3ab368007 | 2,923 | hpp | C++ | kv/cardano-ferrari.hpp | soonho-tri/kv | 4963be6560d8600cdc9ff22d004b2b965ae7b1df | [
"MIT"
] | 67 | 2017-01-04T15:30:54.000Z | 2022-03-31T05:45:02.000Z | src/interval/kv/cardano-ferrari.hpp | takafumihoriuchi/HyLaGI | 26b9f32a84611ee62d9cbbd903773d224088c959 | [
"BSL-1.0"
] | 4 | 2017-02-10T02:59:45.000Z | 2019-10-10T14:17:08.000Z | src/interval/kv/cardano-ferrari.hpp | takafumihoriuchi/HyLaGI | 26b9f32a84611ee62d9cbbd903773d224088c959 | [
"BSL-1.0"
] | 5 | 2021-09-29T02:27:46.000Z | 2022-03-31T05:45:04.000Z | /*
* Copyright (c) 2013-2014 Masahide Kashiwagi (kashi@waseda.jp)
*/
#ifndef CARDANO_HPP
#define CARDANO_HPP
// Solve polynomial equations of degree 3/4
// by Cardano/Ferrari's methods
#include <kv/interval.hpp>
#include <kv/rdouble.hpp>
#include <kv/complex.hpp>
#include <boost/numeric/ublas/vector.hpp>
namespace kv {
namespace ub = boost::numeric::ublas;
template <class T> bool cardano(const ub::vector< complex< interval<T> > > &in, ub::vector< complex< interval<T> > >& out)
{
complex< interval<T> > a, b, c, p, q, w, m, n, nt, nn, tmp;
int i;
bool flag;
if (in.size() != 4) return false;
if (zero_in(in(3).real()) && zero_in(in(3).imag())) return false;
a = in(2) / in(3);
b = in(1) / in(3);
c = in(0) / in(3);
p = b - pow(a, 2) / 3.;
q = 2 * pow(a, 3) /27. - a * b / 3. + c;
w = complex< interval<T> >(-1., sqrt(interval<T>(3.))) / 2.;
tmp = sqrt(pow(q, 2)/4. + pow(p, 3) / 27.) ;
m = pow(-q / 2. + tmp, 1. / interval<T>(3.));
n = pow(-q / 2. - tmp, 1. / interval<T>(3.));
nt = n;
flag = false;
for (i=0; i<3; i++) {
tmp = m * nt + p/3.;
if (zero_in(tmp.real()) && zero_in(tmp.imag())) {
if (flag == false) {
nn = nt;
flag = true;
} else {
nn.real() = interval<T>::hull(nn.real(), nt.real());
nn.imag() = interval<T>::hull(nn.imag(), nt.imag());
}
}
nt = w * nt;
}
out.resize(3);
out(0) = m + nn - a / 3.;
out(1) = w * m + w * w * nn - a / 3.;
out(2) = w * w * m + w * nn - a / 3.;
return true;
}
template <class T> bool ferrari(const ub::vector< complex< interval<T> > > &in, ub::vector< complex< interval<T> > >& out)
{
complex< interval<T> > a, b, c, d, p, q, r, tmp;
ub::vector< complex< interval<T> > > ci, co;
complex< interval<T> > l, m, n, nt, nn;
int i;
bool flag;
if (in.size() != 5) return false;
if (zero_in(in(4).real()) && zero_in(in(3).imag())) return false;
a = in(3) / in(4);
b = in(2) / in(4);
c = in(1) / in(4);
d = in(0) / in(4);
p = b - pow(a, 2) * 3. / 8.;
q = c - b * a / 2. + pow(a, 3) / 8.;
r = d - c * a / 4. + b * pow(a, 2) / 16. - pow(a, 4) * 3. / 256.;
ci.resize(4);
ci(3) = 1.;
ci(2) = -p / 2.;
ci(1) = -r;
ci(0) = r * p / 2. - pow(q, 2) / 8.;
cardano(ci, co);
l = co(0);
m = sqrt(2. * l - p);
n = sqrt(pow(l, 2) - r);
nt = n;
flag = false;
for (i=0; i<2; i++) {
tmp = 2. * m * nt + q;
if (zero_in(tmp.real()) && zero_in(tmp.imag())) {
if (flag == false) {
nn = nt;
flag = true;
} else {
nn.real() = interval<T>::hull(nn.real(), nt.real());
nn.imag() = interval<T>::hull(nn.imag(), nt.imag());
}
}
nt = -nt;
}
out.resize(4);
out(0) = (m + sqrt(pow(m, 2) - 4. * (l - nn))) / 2. - a / 4.;
out(1) = (m - sqrt(pow(m, 2) - 4. * (l - nn))) / 2. - a / 4.;
out(2) = (-m + sqrt(pow(m, 2) - 4. * (l + nn))) / 2. - a / 4.;
out(3) = (-m - sqrt(pow(m, 2) - 4. * (l + nn))) / 2. - a / 4.;
return true;
}
} // namespace kv
#endif // CARDANO_HPP
| 22.658915 | 123 | 0.496066 | [
"vector"
] |
24724200e2614ea9982eaa731c4549d756a315bb | 17,619 | cpp | C++ | Source/src/core/rendering/Skybox.cpp | AkitaInteractive/Hachiko-Engine | 9d682ed7e00e1f6b889e6e73afa36f290cfb2222 | [
"MIT"
] | 4 | 2022-02-17T11:44:39.000Z | 2022-03-10T02:20:05.000Z | Source/src/core/rendering/Skybox.cpp | AkitaInteractive/Hachiko-Engine | 9d682ed7e00e1f6b889e6e73afa36f290cfb2222 | [
"MIT"
] | 26 | 2022-02-17T20:02:51.000Z | 2022-03-31T22:52:14.000Z | Source/src/core/rendering/Skybox.cpp | AkitaInteractive/Hachiko-Engine | 9d682ed7e00e1f6b889e6e73afa36f290cfb2222 | [
"MIT"
] | null | null | null | #include "core/hepch.h"
#include "Skybox.h"
#include "modules/ModuleProgram.h"
#include "components/ComponentCamera.h"
#include "modules/ModuleResources.h"
#include "modules/ModuleRender.h"
#include "resources/ResourceTexture.h"
#include "resources/ResourceSkybox.h"
#include "MathGeoLib.h"
Hachiko::Skybox::Skybox()
{
cube = ModuleTexture::LoadCubeMap(cube);
CreateBuffers();
}
Hachiko::Skybox::Skybox(TextureCube new_cube) : cube(new_cube)
{
cube = ModuleTexture::LoadCubeMap(cube);
CreateBuffers();
}
Hachiko::Skybox::~Skybox()
{
glDeleteBuffers(1, &vbo);
ReleaseCubemap();
glDeleteTextures(1, &diffuse_ibl_id);
}
void Hachiko::Skybox::Draw(ComponentCamera* camera) const
{
// Use for optimized version (draw at the end) glDepthFunc(GL_LEQUAL);
OPTICK_CATEGORY("Draw", Optick::Category::Rendering);
glDepthFunc(GL_LEQUAL);
glClearDepth(1.0);
Program* program = App->program->GetSkyboxProgram();
program->Activate();
// Draw skybox
glBindVertexArray(vao);
program->BindUniformInt("skybox", 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, cube.id);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);
Program::Deactivate();
glDepthFunc(GL_LESS);
}
void Hachiko::Skybox::ReleaseCubemap()
{
glDeleteTextures(1, &cube.id);
for (unsigned i = 0; i < static_cast<unsigned>(TextureCube::Side::COUNT); ++i)
{
App->resources->ReleaseResource(cube.resources[i]);
}
cube.loaded = false;
}
void Hachiko::Skybox::DrawImGui()
{
ImGui::PushID(this);
ImGui::Text("Skybox");
ImGui::TextDisabled("Keep in mind that all images \nneed to have the same format!");
if (ImGui::CollapsingHeader("Resources"))
{
SelectSkyboxTexture(TextureCube::Side::RIGHT);
SelectSkyboxTexture(TextureCube::Side::LEFT);
SelectSkyboxTexture(TextureCube::Side::BOTTOM);
SelectSkyboxTexture(TextureCube::Side::TOP);
SelectSkyboxTexture(TextureCube::Side::CENTER);
SelectSkyboxTexture(TextureCube::Side::BACK);
}
ImGui::Checkbox("Activate IBL", &activate_ibl);
if (ImGui::Button("Build precomputed IBL"))
{
BuildIBL();
}
if (ImGui::Button("Diffuse"))
{
cube.id = diffuse_ibl_id;
}
if (ImGui::Button("Prefiltered"))
{
cube.id = prefiltered_ibl_id;
}
ImGui::PopID();
}
void Hachiko::Skybox::BindImageBasedLightingUniforms(Program* program) const
{
if (activate_ibl)
{
program->BindUniformUInt("activate_IBL", 1);
if (App->renderer->IsDeferred())
{
glActiveTexture(GL_TEXTURE5);
glBindTexture(GL_TEXTURE_CUBE_MAP, diffuse_ibl_id);
program->BindUniformInt("diffuseIBL", 5);
glActiveTexture(GL_TEXTURE6);
glBindTexture(GL_TEXTURE_CUBE_MAP, prefiltered_ibl_id);
program->BindUniformInt("prefilteredIBL", 6);
glActiveTexture(GL_TEXTURE7);
glBindTexture(GL_TEXTURE_2D, environment_brdf_id);
program->BindUniformInt("environmentBRDF", 7);
}
else
{
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_CUBE_MAP, diffuse_ibl_id);
program->BindUniformInt("diffuseIBL", 1);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_CUBE_MAP, prefiltered_ibl_id);
program->BindUniformInt("prefilteredIBL", 2);
glActiveTexture(GL_TEXTURE3);
glBindTexture(GL_TEXTURE_2D, environment_brdf_id);
program->BindUniformInt("environmentBRDF", 3);
}
program->BindUniformUInt("prefilteredIBL_numLevels", prefiltered_ibl_number_of_levels);
}
else
{
program->BindUniformUInt("activate_IBL", 0);
}
}
const std::string TextureCubeSideToString(Hachiko::TextureCube::Side cube_side)
{
switch (cube_side)
{
case Hachiko::TextureCube::Side::RIGHT:
return "Right";
case Hachiko::TextureCube::Side::LEFT:
return "Left";
case Hachiko::TextureCube::Side::BOTTOM:
return "Bottom";
case Hachiko::TextureCube::Side::TOP:
return "Top";
case Hachiko::TextureCube::Side::CENTER:
return "Center";
case Hachiko::TextureCube::Side::BACK:
return "Back";
}
}
void Hachiko::Skybox::SelectSkyboxTexture(TextureCube::Side cube_side)
{
const std::string title = Hachiko::StringUtils::Concat("Select texture ", TextureCubeSideToString(cube_side));
const char* filters = "Image files{.png,.tif,.jpg,.tga}";
if (ImGui::Button(Hachiko::StringUtils::Concat(TextureCubeSideToString(cube_side).c_str(), " Texture").c_str()))
{
ImGuiFileDialog::Instance()->OpenDialog(title.c_str(),
"Select Texture",
filters,
"./assets/skybox/",
1,
nullptr,
ImGuiFileDialogFlags_DontShowHiddenFiles | ImGuiFileDialogFlags_DisableCreateDirectoryButton | ImGuiFileDialogFlags_HideColumnType
| ImGuiFileDialogFlags_HideColumnDate);
}
if (ImGuiFileDialog::Instance()->Display(title.c_str()))
{
if (ImGuiFileDialog::Instance()->IsOk())
{
std::string texture_path = ImGuiFileDialog::Instance()->GetFilePathName();
texture_path.append(META_EXTENSION);
YAML::Node texture_node = YAML::LoadFile(texture_path);
Hachiko::UID res = texture_node[RESOURCES][0][RESOURCE_ID].as<Hachiko::UID>();
if (res)
{
ChangeCubeMapSide(res, cube_side);
}
else
{
HE_ERROR("Failed when loading the texture.");
}
}
ImGuiFileDialog::Instance()->Close();
}
}
void Hachiko::Skybox::CreateBuffers()
{
constexpr float vertices[] = {
// positions
// Back
-1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
// Left
-1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
// Right
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
// Front
1.0f, 1.0f, 1.0f,
1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
// Top
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
// Bottom
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
1.0f, -1.0f, 1.0f,
1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f
};
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vbo);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), &vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), static_cast<void*>(nullptr));
}
void Hachiko::Skybox::ChangeCubeMapSide(UID texture_uid, TextureCube::Side cube_side)
{
unsigned side_number = static_cast<unsigned>(cube_side);
ReleaseCubemap();
cube.uids[side_number] = texture_uid;
cube = ModuleTexture::LoadCubeMap(cube);
}
void Hachiko::Skybox::BuildIBL()
{
GenerateDiffuseIBL();
GeneratePrefilteredIBL();
GenerateEnvironmentBRDF();
}
void Hachiko::Skybox::GenerateDiffuseIBL()
{
// Use for optimized version (draw at the end) glDepthFunc(GL_LEQUAL);
OPTICK_CATEGORY("GenerateDiffuseIBL", Optick::Category::Rendering);
if (!cube.loaded)
{
HE_ERROR("There is not a skybox loaded");
return;
}
// Delete last irradiance cubemap
glDeleteTextures(1, &diffuse_ibl_id);
diffuse_ibl_id = 0;
// Initialize variables
const float3 front[6] = {float3::unitX, -float3::unitX, float3::unitY, -float3::unitY, float3::unitZ, -float3::unitZ};
const float3 up[6] = {-float3::unitY, -float3::unitY, float3::unitZ, -float3::unitZ, -float3::unitY, -float3::unitY};
Frustum frustum;
frustum.SetKind(FrustumSpaceGL, FrustumRightHanded);
frustum.SetPerspective(math::pi / 2.0f, math::pi / 2.0f);
frustum.SetViewPlaneDistances(0.1f, 100.0f);
// Activate shader and deactivate the depth mask
glDepthFunc(GL_ALWAYS);
glDepthMask(false);
Program* program = App->program->GetDiffuseIBLProgram();
program->Activate();
glViewport(0, 0, cube.resources[0]->height, cube.resources[0]->width);
unsigned frame_buffer;
glGenFramebuffers(1, &frame_buffer);
glBindFramebuffer(GL_FRAMEBUFFER, frame_buffer);
// Generate irradiance cubemap
glGenTextures(1, &diffuse_ibl_id);
glBindTexture(GL_TEXTURE_CUBE_MAP, diffuse_ibl_id);
for (unsigned i = 0; i < 6; ++i)
{
glTexImage2D(
GL_TEXTURE_CUBE_MAP_POSITIVE_X + i,
0,
GL_RGB32F,
cube.resources[i]->width,
cube.resources[i]->height,
0,
GL_RGB,
GL_UNSIGNED_BYTE,
0
);
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
for (unsigned i = 0; i < 6; ++i)
{
unsigned attachment = GL_COLOR_ATTACHMENT0;
glFramebufferTexture2D(GL_FRAMEBUFFER, attachment, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, diffuse_ibl_id, 0);
glDrawBuffers(1, &attachment);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
HE_LOG("Error creating frame buffer");
}
frustum.SetFrame(float3::zero, front[i], up[i]);
App->program->UpdateCamera(frustum);
// Draw skybox
glBindVertexArray(vao);
program->BindUniformInt("skybox", 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, cube.id);
glDrawArrays(GL_TRIANGLES, 0, 36);
}
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
// Delete and unbind the frame buffer, and unbind the skybox vao
glDeleteFramebuffers(1, &frame_buffer);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindVertexArray(0);
// Deactivate shader and set depth mask to default
Program::Deactivate();
glDepthFunc(GL_LESS);
glDepthMask(true);
float2 fb_size = App->renderer->GetFrameBufferSize();
glViewport(0, 0, fb_size.y, fb_size.x);
}
void Hachiko::Skybox::GeneratePrefilteredIBL()
{
// Use for optimized version (draw at the end) glDepthFunc(GL_LEQUAL);
OPTICK_CATEGORY("GeneratePrefilteredIBL", Optick::Category::Rendering);
if (!cube.loaded)
{
HE_ERROR("There is not a skybox loaded");
return;
}
unsigned width = cube.resources[0]->width;
unsigned height = cube.resources[0]->height;
// Delete last irradiance cubemap
glDeleteTextures(1, &prefiltered_ibl_id);
prefiltered_ibl_id = 0;
// Initialize variables
const float3 front[6] = {float3::unitX, -float3::unitX, float3::unitY, -float3::unitY, float3::unitZ, -float3::unitZ};
const float3 up[6] = {-float3::unitY, -float3::unitY, float3::unitZ, -float3::unitZ, -float3::unitY, -float3::unitY};
Frustum frustum;
frustum.SetKind(FrustumSpaceGL, FrustumRightHanded);
frustum.SetPerspective(math::pi / 2.0f, math::pi / 2.0f);
frustum.SetViewPlaneDistances(0.1f, 100.0f);
// Activate shader and deactivate the depth mask
glDepthFunc(GL_ALWAYS);
glDepthMask(false);
Program* program = App->program->GetPrefilteredIBLProgram();
program->Activate();
unsigned frame_buffer;
glGenFramebuffers(1, &frame_buffer);
glBindFramebuffer(GL_FRAMEBUFFER, frame_buffer);
// Generate irradiance cubemap
glGenTextures(1, &prefiltered_ibl_id);
glBindTexture(GL_TEXTURE_CUBE_MAP, prefiltered_ibl_id);
for (unsigned i = 0; i < 6; ++i)
{
glTexImage2D(
GL_TEXTURE_CUBE_MAP_POSITIVE_X + i,
0,
GL_RGB32F,
cube.resources[i]->width,
cube.resources[i]->height,
0,
GL_RGB,
GL_UNSIGNED_BYTE,
0
);
}
prefiltered_ibl_number_of_levels = int(log(float(cube.resources[0]->width)) / log(2));
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL, prefiltered_ibl_number_of_levels);
glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
for (int roughness = 0; roughness < prefiltered_ibl_number_of_levels; ++roughness)
{
glViewport(0, 0, height, width); // IMPORTANT TODO: MOVE TO ADAPT FOR THE MIPMAP
// Render each cube plane
for (unsigned i = 0; i < 6; ++i)
{
unsigned attachment = GL_COLOR_ATTACHMENT0;
glFramebufferTexture2D(GL_FRAMEBUFFER, attachment, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, prefiltered_ibl_id, roughness);
glDrawBuffers(1, &attachment);
// Draw UnitCube using prefiltered environment map shader and roughness
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
HE_LOG("Error creating frame buffer");
}
frustum.SetFrame(float3::zero, front[i], up[i]);
App->program->UpdateCamera(frustum);
float auxRoughness = float(roughness) / float(prefiltered_ibl_number_of_levels - 1);
program->BindUniformFloat("roughness", &auxRoughness);
// Draw skybox
glBindVertexArray(vao);
program->BindUniformInt("skybox", 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, cube.id);
glDrawArrays(GL_TRIANGLES, 0, 36);
}
width = width >> 1;
height = height >> 1;
}
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
// Delete and unbind the frame buffer, and unbind the skybox vao
glDeleteFramebuffers(1, &frame_buffer);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindVertexArray(0);
// Deactivate shader and set depth mask to default
Program::Deactivate();
glDepthFunc(GL_LESS);
glDepthMask(true);
float2 fb_size = App->renderer->GetFrameBufferSize();
glViewport(0, 0, fb_size.y, fb_size.x);
}
void Hachiko::Skybox::GenerateEnvironmentBRDF()
{
// Use for optimized version (draw at the end) glDepthFunc(GL_LEQUAL);
OPTICK_CATEGORY("GenerateEnvironmentBRDF", Optick::Category::Rendering);
if (!cube.loaded)
{
HE_ERROR("There is not a skybox loaded");
return;
}
const unsigned width = 512;
const unsigned height = 512;
// Delete last enviromentBRDF
glDeleteTextures(1, &environment_brdf_id);
environment_brdf_id = 0;
// Activate shader and deactivate the depth mask
glDepthFunc(GL_ALWAYS);
glDepthMask(false);
Program* program = App->program->GetEnvironmentBRDFProgram();
program->Activate();
glViewport(0, 0, height, width);
unsigned frame_buffer;
glGenFramebuffers(1, &frame_buffer);
glBindFramebuffer(GL_FRAMEBUFFER, frame_buffer);
// Generate irradiance cubemap
glGenTextures(1, &environment_brdf_id);
glBindTexture(GL_TEXTURE_2D, environment_brdf_id);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, width, height, 0, GL_RG, GL_FLOAT, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
unsigned attachment = GL_COLOR_ATTACHMENT0;
glFramebufferTexture2D(GL_FRAMEBUFFER, attachment, GL_TEXTURE_2D, environment_brdf_id, 0);
glDrawBuffers(1, &attachment);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
HE_LOG("Error creating frame buffer");
}
glDrawArrays(GL_TRIANGLES, 0, 3);
glBindTexture(GL_TEXTURE_2D, 0);
// Delete and unbind the frame buffer, and unbind the skybox vao
glDeleteFramebuffers(1, &frame_buffer);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindVertexArray(0);
// Deactivate shader and set depth mask to default
Program::Deactivate();
glDepthFunc(GL_LESS);
glDepthMask(true);
float2 fb_size = App->renderer->GetFrameBufferSize();
glViewport(0, 0, fb_size.y, fb_size.x);
}
| 31.631957 | 178 | 0.632442 | [
"render"
] |
247f7b7d10529bbb886efd89d7d3f468af0862a4 | 6,694 | cpp | C++ | windows/pw6e.official/CPlusPlus/Chapter09/AnimationEaseGrapher/AnimationEaseGrapher/MainPage.xaml.cpp | nnaabbcc/exercise | 255fd32b39473b3d0e7702d4b1a8a97bed2a68f8 | [
"MIT"
] | 1 | 2016-11-23T08:18:08.000Z | 2016-11-23T08:18:08.000Z | windows/pw6e.official/CPlusPlus/Chapter09/AnimationEaseGrapher/AnimationEaseGrapher/MainPage.xaml.cpp | nnaabbcc/exercise | 255fd32b39473b3d0e7702d4b1a8a97bed2a68f8 | [
"MIT"
] | null | null | null | windows/pw6e.official/CPlusPlus/Chapter09/AnimationEaseGrapher/AnimationEaseGrapher/MainPage.xaml.cpp | nnaabbcc/exercise | 255fd32b39473b3d0e7702d4b1a8a97bed2a68f8 | [
"MIT"
] | 1 | 2016-11-23T08:17:34.000Z | 2016-11-23T08:17:34.000Z | //
// MainPage.xaml.cpp
// Implementation of the MainPage class.
//
#include "pch.h"
#include "MainPage.xaml.h"
using namespace AnimationEaseGrapher;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Interop;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Media::Animation;
using namespace Windows::UI::Xaml::Navigation;
// C# assembly
using namespace ReflectionHelper;
MainPage::MainPage()
{
InitializeComponent();
this->Loaded += ref new RoutedEventHandler(this, &MainPage::OnMainPageLoaded);
}
void MainPage::OnMainPageLoaded(Object^ sender, RoutedEventArgs^ args)
{
TypeInformation^ baseTypeInfo = ref new TypeInformation(EasingFunctionBase::typeid);
AssemblyInformation^ assemblyInfo = ref new AssemblyInformation(EasingFunctionBase::typeid);
// Enumerate through all Windows Runtime types
for each (TypeInformation^ typeInfo in assemblyInfo->ExportedTypes)
{
// Create RadioButton for each easing function
if (typeInfo->IsPublic &&
baseTypeInfo->IsAssignableFrom(typeInfo) &&
!baseTypeInfo->Equals(typeInfo))
{
RadioButton^ radioButton = ref new RadioButton();
radioButton->Content = typeInfo->Name;
radioButton->Tag = typeInfo;
radioButton->Margin = ThicknessHelper::FromUniformLength(6);
radioButton->Checked += ref new RoutedEventHandler(this, &MainPage::OnEasingFunctionRadioButtonChecked);
easingFunctionStackPanel->Children->Append(radioButton);
}
// Check the first RadioButton in the StackPanel (the one labeled "None")
dynamic_cast<RadioButton^>(easingFunctionStackPanel->Children->GetAt(0))->IsChecked = true;
}
}
void MainPage::OnEasingFunctionRadioButtonChecked(Object^ sender, RoutedEventArgs^ args)
{
RadioButton^ radioButton = dynamic_cast<RadioButton^>(sender);
TypeInformation^ typeInfo = dynamic_cast<TypeInformation^>(radioButton->Tag);
easingFunction = nullptr;
propertiesStackPanel->Children->Clear();
// typeInfo is only null for "None" buton
if (typeInfo != nullptr)
{
// Find a parameterless constructor and instantiate the easing function
for each (ConstructorInformation^ constructorInfo in typeInfo->DeclaredConstructors)
{
if (constructorInfo->IsPublic && constructorInfo->GetParameters()->Length == 0)
{
this->easingFunction = dynamic_cast<EasingFunctionBase^>(constructorInfo->Invoke(nullptr));
}
}
// Enumerate the easing function properties
for each (PropertyInformation^ property in typeInfo->DeclaredProperties)
{
// We can only deal with properties of type int and double
if (property->PropertyType.Name == "Int32" ||
property->PropertyType.Name == "Double")
{
// Create a TextBlock for the property name
TextBlock^ txtblk = ref new TextBlock();
txtblk->Text = property->Name + ":";
this->propertiesStackPanel->Children->Append(txtblk);
// Create a Slider for the property value
Slider^ slider = ref new Slider();
slider->Width = 144;
slider->Minimum = 0;
slider->Maximum = 10;
slider->Tag = property;
if (property->PropertyType.Name == "Int32")
{
slider->StepFrequency = 1;
slider->Value = (int)property->GetValue(this->easingFunction);
}
else
{
slider->StepFrequency = 0.1;
slider->Value = (double)property->GetValue(this->easingFunction);
}
// Define the Slider event handler right here
slider->ValueChanged += ref new RangeBaseValueChangedEventHandler(
[this](Object^ sliderSender, RangeBaseValueChangedEventArgs^ sliderArgs)
{
Slider^ sliderChanging = dynamic_cast<Slider^>(sliderSender);
PropertyInformation^ property = dynamic_cast<PropertyInformation^>(sliderChanging->Tag);
if (property->PropertyType.Name == "Int32")
property->SetValue(easingFunction, (int)sliderArgs->NewValue);
else
property->SetValue(easingFunction, (double)sliderArgs->NewValue);
DrawNewGraph();
});
propertiesStackPanel->Children->Append(slider);
}
}
}
// Initialize EasingMode radio button
for each (UIElement^ child in easingModeStackPanel->Children)
{
RadioButton^ easingModeRadioButton = dynamic_cast<RadioButton^>(child);
easingModeRadioButton->IsEnabled = this->easingFunction != nullptr;
easingModeRadioButton->IsChecked =
this->easingFunction != nullptr &&
this->easingFunction->EasingMode == (EasingMode)(int)easingModeRadioButton->Tag;
}
DrawNewGraph();
}
void MainPage::OnEasingModeRadioButtonChecked(Object^ sender, RoutedEventArgs^ args)
{
RadioButton^ radioButton = dynamic_cast<RadioButton^>(sender);
easingFunction->EasingMode = (EasingMode)(int)radioButton->Tag;
DrawNewGraph();
}
void MainPage::OnDemoButtonClick(Object^ sender, RoutedEventArgs^ args)
{
// Set the selected easing function and start the animation
Storyboard^ storyboard = dynamic_cast<Storyboard^>(this->Resources->Lookup("storyboard"));
dynamic_cast<DoubleAnimation^>(storyboard->Children->GetAt(1))->EasingFunction = easingFunction;
storyboard->Begin();
}
void MainPage::DrawNewGraph()
{
polyline->Points->Clear();
if (easingFunction == nullptr)
{
polyline->Points->Append(Point(0, 0));
polyline->Points->Append(Point(1000, 500));
return;
}
for (int t = 0; t <= 100; t += 1)
{
float x = 10.0f * t;
float y = (float)(500 * easingFunction->Ease(t / 100.0));
polyline->Points->Append(Point(x, y));
}
}
| 39.146199 | 117 | 0.621153 | [
"object"
] |
2490d641ec0b12ddcc88ea1eb92128167ed8b357 | 1,670 | hpp | C++ | include/codegen/include/GlobalNamespace/EssentialHelpers.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/GlobalNamespace/EssentialHelpers.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/GlobalNamespace/EssentialHelpers.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Object
class Object;
// Forward declaring type: Component
class Component;
// Forward declaring type: GameObject
class GameObject;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Autogenerated type: EssentialHelpers
class EssentialHelpers : public ::Il2CppObject {
public:
// static public System.Double get_CurrentTimeStamp()
// Offset: 0xCB0500
static double get_CurrentTimeStamp();
// static public System.Void SafeDestroy(UnityEngine.Object obj)
// Offset: 0xCB05C4
static void SafeDestroy(UnityEngine::Object* obj);
// static public T GetOrAddComponent(UnityEngine.GameObject go)
// Offset: 0xFFFFFFFF
template<class T>
static T GetOrAddComponent(UnityEngine::GameObject* go) {
static_assert(std::is_convertible_v<T, UnityEngine::Component*>);
return THROW_UNLESS((il2cpp_utils::RunGenericMethod<T>("", "EssentialHelpers", "GetOrAddComponent", {il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}, go)));
}
}; // EssentialHelpers
}
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::EssentialHelpers*, "", "EssentialHelpers");
#pragma pack(pop)
| 37.954545 | 178 | 0.715569 | [
"object"
] |
24920f1d8cbf056fec19e71bdb39067b44208170 | 1,675 | cpp | C++ | src/module/base/Common/src/info/AbstractCondition.cpp | 403712387/abstract | 3c7be3a7866a4a202f9d3d7a69015e84d236fcc9 | [
"MIT"
] | 1 | 2020-04-28T03:04:40.000Z | 2020-04-28T03:04:40.000Z | src/module/base/Common/src/info/AbstractCondition.cpp | 403712387/abstract | 3c7be3a7866a4a202f9d3d7a69015e84d236fcc9 | [
"MIT"
] | null | null | null | src/module/base/Common/src/info/AbstractCondition.cpp | 403712387/abstract | 3c7be3a7866a4a202f9d3d7a69015e84d236fcc9 | [
"MIT"
] | null | null | null | #include <sstream>
#include "AbstractCondition.h"
AbstractCondition::AbstractCondition(std::string url, std::set<AbstractType> type, AbstractModel model, int abstractCount)
{
mStreamUrl = url;
mTypes = type;
mModel = model;
mAbstractCount = abstractCount;
}
// 获取流的url
std::string AbstractCondition::getStreamUrl()
{
return mStreamUrl;
}
// 获取提取的类型(提取人脸还是人体)
std::set<AbstractType> AbstractCondition::getAbstractType()
{
return mTypes;
}
// 更新提取的类型
void AbstractCondition::updateAbstractType(std::set<AbstractType> types)
{
mTypes = types;
}
// 获取提取的模式(质量优先还是实时优先)
AbstractModel AbstractCondition::getAbstractModel()
{
return mModel;
}
// 一个跟踪目标中提取图片的张数
int AbstractCondition::getAbstractCount()
{
return mAbstractCount;
}
std::string AbstractCondition::toString()
{
std::stringstream buf;
buf << "stream url:" << mStreamUrl << ", abstract type:";
for (AbstractType type : mTypes)
{
buf << Common::getAbstraceTypeName(type) << ", ";
}
buf << ", abstract module:" << Common::getAbstraceModelName(mModel) << ", abstract count:" << mAbstractCount << ", birthday:" << mBirthday.toString("yyyy-MM-dd HH:mm:ss.zzz").toStdString();
return buf.str();
}
Json::Value AbstractCondition::toJson()
{
Json::Value result;
result["url"] = mStreamUrl;
int index = 0;
for (AbstractType type : mTypes)
{
result["type"][index++] = Common::getAbstraceTypeName(type);
}
result["module"] = Common::getAbstraceModelName(mModel);
result["abstract_count"] = mAbstractCount;
result["birthday"] = mBirthday.toString("yyyy-MM-dd HH:mm:ss.zzz").toStdString();
return result;
}
| 24.632353 | 193 | 0.681791 | [
"model"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.