blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
146bb0ee5c79ff77dddc8d19fa38cbad3eff9e1c
ba32454aecf658f7cb36813a425c33dccbe1a93c
/inheritance/book.cpp
e49e0cd85a3f2e0ce98ce667a3d905fd36558f53
[]
no_license
dottedr/inheritance
12d05f4302610c09c1661551aa71ee4d807498f4
da9d1e6e4a9c0b3f08751e5dcdfbf5b1599fcbd0
refs/heads/master
2020-04-06T23:09:42.145416
2018-11-16T11:45:25
2018-11-16T11:45:25
157,859,948
0
0
null
null
null
null
UTF-8
C++
false
false
396
cpp
// // book.cpp // inheritance // // Created by Sabina Adamska on 16/11/2018. // Copyright © 2018 Sabina Adamska. All rights reserved. // #include "book.hpp" #include <string> using namespace std; book::book (const string &n, int p, const string &i) : product(n, p), _isbn(i) {} string book::description() const { return "" + product::description() + '"' + ", ISBN " + _isbn; }
[ "sabina@sellmyhome.co.uk" ]
sabina@sellmyhome.co.uk
1cd67020c66cec63eca28092d8ff03b92e025d8d
c5d6bf050a4988e16068fb983f489fe57a7f3de2
/GameProgramming/C_Practice10/02_Refactoring/main.cpp
144acc0d49832126b7536b0f61068ebb7aa32d75
[]
no_license
ha-k-pg-fukunaga/1st_Semester_2021
d9ac04022d192b0ccd7b1ff17b4be24ef02e94d3
68dff83c5201ab435b13ccf40f39783a5538afb1
refs/heads/main
2023-06-14T04:55:29.703910
2021-07-06T08:43:42
2021-07-13T04:20:28
381,267,496
0
0
null
null
null
null
UTF-8
C++
false
false
86
cpp
#include<stdio.h> #include<stdlib.h> int main(void) { system("pause"); return 0; }
[ "Yuk321321@icloud.com" ]
Yuk321321@icloud.com
a617396f29a90d99493d01ea5f0f6ca0fe186002
3b82c429e5cb18be36eadc69615a6aee81d5818d
/DP/01_Nth_Fibonacci_Using_DP/03_nth_Fibonacci_Number_Using_DP.cpp
28dc07fd398a263d6a52b7837ea9764fb6cca70a
[]
no_license
mehra-deepak/CN-DS-ALGO
f165090d4804ca09e71ebb4ce58b782e91796b3d
322052ab2938e1d410f86e41f9fe4386ac04da75
refs/heads/master
2023-01-07T20:53:36.067823
2020-11-06T08:11:00
2020-11-06T08:11:00
284,454,031
1
0
null
null
null
null
UTF-8
C++
false
false
385
cpp
#include<iostream> using namespace std; int nthFibonacciNumberUsingDP(int n) { int *ansArray = new int[n+1]; ansArray[0] = 0; ansArray[1] = 1; for(int i=2;i<=n;i++) { ansArray[i] = ansArray[i-1] + ansArray[i-2]; } return ansArray[n]; } int main() { int n; cin>>n; int ans = nthFibonacciNumberUsingDP(n); cout<<ans; }
[ "mehradeepak0608@gmail.com" ]
mehradeepak0608@gmail.com
621d90ec9a96bc149a2d36c68419f50b506c64cb
ee20d5f0983ce8bc7466090b135519d1114ede9d
/Contests/GEOLIP - 2/k.cpp
9d351f507b896f234b873a30a52e8c84bbb67124
[]
no_license
rodrigoAMF/competitive-programming
a12038dd17144044365c1126fa17f968186479d4
06b38197a042bfbd27b20f707493e0a19fda7234
refs/heads/master
2020-03-31T18:28:11.301068
2019-08-02T21:35:53
2019-08-02T21:35:53
152,459,900
5
0
null
null
null
null
UTF-8
C++
false
false
320
cpp
#include <bits/stdc++.h> using namespace std; int main(){ int n; while(scanf("%d", &n) != EOF){ set<int> vetor; int a; for(int i = 0; i < n; i++){ scanf("%d", &a); vetor.insert(a); } printf("%d\n", vetor.size()-2); } return 0; }
[ "rodrigoamf@outlook.com" ]
rodrigoamf@outlook.com
512e0853938358e0d7f51db1388c0a7d98441dc1
916ef1b31f0b683de4f043626d9df59f37edbbc4
/atcoder/06_AtCoder-Regular-Contest/arc036/B/main.cpp
95c9c6fa3148289580bde1f5ade2f030acdda5ed
[]
no_license
solareenlo/cpp
56cc33673d30dd4a4031e4b81cec16b08b3490e0
f78f8a098849938153e6e3a282737e067dbe2c58
refs/heads/master
2021-03-31T04:31:39.420394
2020-11-29T22:22:25
2020-11-29T22:22:25
248,076,420
0
0
null
null
null
null
UTF-8
C++
false
false
667
cpp
#include <bits/stdc++.h> #define REP(i, n) for (int i = 0; i < (n); i++) using namespace std; int main() { cin.tie(0)->sync_with_stdio(false); int n; cin >> n; vector<int> h(n); REP(i, n) cin >> h[i]; vector<int> l(n, 0); REP(i, n - 1) if (h[i] < h[i + 1]) l[i + 1]++; vector<int> r(n, 0); for (int i = n - 1; i > 0; i--) if (h[i - 1] > h[i]) r[i - 1]++; vector<int> c(n, 0); REP(i, n) if (l[i] + r[i] > 0) c[i]++; int res = 0; int sum = 0; c[0] = c[n - 1] = 0; REP(i, n) { if (c[i] > 0) { sum++; res = max(res, sum); } else sum = 0; } if (n == 1) cout << 1 << '\n'; else cout << res + 2 << '\n'; return 0; }
[ "solareenlo@gmail.com" ]
solareenlo@gmail.com
43bf783bac2f630c24763ee26c8b6f771c717ab7
c2e2ca8922f572ee70415b108e30ac118f5678df
/Plugins/AdiosReader/vtkAdiosPixieReader.cxx
ad365508c90ca1439623a8b08908152865429479
[ "MIT", "LicenseRef-scancode-paraview-1.2", "Apache-2.0", "LicenseRef-scancode-protobuf", "BSD-3-Clause" ]
permissive
niboliang/ParaView
78386708a74621592683155ed72bcacd3e7f9bee
8c5941f9f5f0579e05d4c08220521e1585ce5b13
refs/heads/master
2023-05-01T02:44:25.827048
2021-05-24T03:11:20
2021-05-24T03:11:20
369,718,664
0
0
NOASSERTION
2021-05-24T03:11:21
2021-05-22T04:59:41
null
UTF-8
C++
false
false
6,584
cxx
/*========================================================================= Program: Visualization Toolkit Module: vtkAdiosPixieReader.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkAdiosPixieReader.h" #include "vtkAdiosInternals.h" #include "vtkObjectFactory.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkStreamingDemandDrivenPipeline.h" #include <vtksys/ios/sstream> #include <string> #include <map> #include <sys/stat.h> #include <assert.h> #include <vtkCellData.h> #include <vtkDataArray.h> #include <vtkDataSet.h> #include <vtkExtentTranslator.h> #include <vtkImageData.h> #include <vtkMultiBlockDataSet.h> #include <vtkNew.h> #include <vtkPointData.h> #include <vtkPoints.h> #include <vtkSmartPointer.h> #include <vtkStructuredGrid.h> #include <vtksys/ios/sstream> using vtksys_ios::ostringstream; //***************************************************************************** class vtkAdiosPixieReader::Internals { public: Internals(vtkAdiosPixieReader* owner) { this->Owner = owner; this->MeshFile = NULL; // Manage piece information vtkMultiProcessController *ctrl = vtkMultiProcessController::GetGlobalController(); this->ExtentTranslator->SetPiece(ctrl->GetLocalProcessId()); this->ExtentTranslator->SetNumberOfPieces(ctrl->GetNumberOfProcesses()); this->ExtentTranslator->SetGhostLevel(0); // FIXME ??? } // -------------------------------------------------------------------------- virtual ~Internals() { if(this->MeshFile) { delete this->MeshFile; this->MeshFile = NULL; } } // -------------------------------------------------------------------------- void SetMethod(ADIOS_READ_METHOD method) { this->Method = method; } // -------------------------------------------------------------------------- bool NextStep() { return this->MeshFile->NextStep(); } // -------------------------------------------------------------------------- bool Reset() { this->MeshFile->Close(); return this->MeshFile->Open(); } // -------------------------------------------------------------------------- void FillOutput(vtkDataObject* output) { vtkMultiBlockDataSet* multiBlock = vtkMultiBlockDataSet::SafeDownCast(output); if(multiBlock) { vtkImageData* grid = AdiosPixie::NewPixieImageData( this->ExtentTranslator.GetPointer(), this->MeshFile, true); if(grid) { multiBlock->SetBlock(0, grid); grid->FastDelete(); } } } // -------------------------------------------------------------------------- void UpdateFileName(const char* currentFileName) { if(!currentFileName) return; if(!this->MeshFile) { this->MeshFile = new AdiosStream( currentFileName, this->Method, this->Owner->GetParameters()); // Make sure that file is open and metadata loaded this->MeshFile->Open(); } else // Check if the filename has changed { if(strcmp( currentFileName, this->MeshFile->GetFileName()) != 0) { delete this->MeshFile; // not NULL because we are in the else this->MeshFile = new AdiosStream( currentFileName, this->Method, this->Owner->GetParameters()); // Make sure that file is open and metadata loaded this->MeshFile->Open(); } } } // -------------------------------------------------------------------------- bool Open() { return this->MeshFile->Open(); } private: AdiosStream* MeshFile; ADIOS_READ_METHOD Method; vtkAdiosPixieReader* Owner; vtkNew<vtkExtentTranslator> ExtentTranslator; }; //***************************************************************************** vtkStandardNewMacro(vtkAdiosPixieReader); //---------------------------------------------------------------------------- vtkAdiosPixieReader::vtkAdiosPixieReader() { this->FileName = NULL; this->Parameters = NULL; this->SetParameters(""); this->Internal = new Internals(this); this->SetNumberOfInputPorts(0); this->SetNumberOfOutputPorts(1); } //---------------------------------------------------------------------------- vtkAdiosPixieReader::~vtkAdiosPixieReader() { this->SetFileName(NULL); this->SetParameters(NULL); if(this->Internal) { delete this->Internal; this->Internal = NULL; } } //---------------------------------------------------------------------------- void vtkAdiosPixieReader::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "FileName: " << (this->FileName ? this->FileName : "(none)") << "\n"; os << indent << "Parameters: " << (this->Parameters ? this->Parameters : "(none)") << "\n"; } //---------------------------------------------------------------------------- int vtkAdiosPixieReader::CanReadFile(const char* name) { // First make sure the file exists. This prevents an empty file // from being created on older compilers. struct stat fs; if(stat(name, &fs) != 0) { return 0; } return 1; } //---------------------------------------------------------------------------- int vtkAdiosPixieReader::RequestData(vtkInformation *, vtkInformationVector** vtkNotUsed( inputVector ), vtkInformationVector* outputVector) { vtkInformation *info = outputVector->GetInformationObject(0); vtkDataObject* output = info->Get(vtkDataObject::DATA_OBJECT()); this->Internal->UpdateFileName(this->GetFileName()); this->Internal->FillOutput(output); return 1; } //---------------------------------------------------------------------------- void vtkAdiosPixieReader::SetReadMethod(int methodEnum) { this->Internal->SetMethod((ADIOS_READ_METHOD)methodEnum); } //---------------------------------------------------------------------------- void vtkAdiosPixieReader::NextStep() { if(this->Internal->NextStep()) { this->Modified(); } } //---------------------------------------------------------------------------- void vtkAdiosPixieReader::Reset() { if(this->Internal->Reset()) { this->Modified(); } }
[ "sebastien.jourdain@kitware.com" ]
sebastien.jourdain@kitware.com
f19e7dbbccf76bdfc683ab35d3499fca8c033cfb
07977a7d3d8ebaa2fd5e96c3f1af255074c7ca8a
/code/threads/thread.cc
847ffe711317e566f322fd7c3c4efa6822cde6d4
[]
no_license
Yu-Ching-Chen/os_hw2
825d7daadebc55bcbdb3e7351a21955c8365dddd
367458930eb82f826359c5752f3246588e333829
refs/heads/master
2023-05-19T13:24:43.701296
2021-05-21T07:34:05
2021-05-21T07:34:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,721
cc
// thread.cc // Routines to manage threads. These are the main operations: // // Fork -- create a thread to run a procedure concurrently // with the caller (this is done in two steps -- first // allocate the Thread object, then call Fork on it) // Begin -- called when the forked procedure starts up, to turn // interrupts on and clean up after last thread // Finish -- called when the forked procedure finishes, to clean up // Yield -- relinquish control over the CPU to another ready thread // Sleep -- relinquish control over the CPU, but thread is now blocked. // In other words, it will not run again, until explicitly // put back on the ready queue. // // Copyright (c) 1992-1996 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "thread.h" #include "switch.h" #include "synch.h" #include "sysdep.h" // this is put at the top of the execution stack, for detecting stack overflows const int STACK_FENCEPOST = 0xdedbeef; //---------------------------------------------------------------------- // Thread::Thread // Initialize a thread control block, so that we can then call // Thread::Fork. // // "threadName" is an arbitrary string, useful for debugging. //---------------------------------------------------------------------- Thread::Thread(char* threadName, int threadID) { ID = threadID; name = threadName; stackTop = NULL; stack = NULL; status = JUST_CREATED; for (int i = 0; i < MachineStateSize; i++) { machineState[i] = NULL; // not strictly necessary, since // new thread ignores contents // of machine registers } #ifdef USER_PROGRAM space = NULL; #endif } //---------------------------------------------------------------------- // Thread::~Thread // De-allocate a thread. // // NOTE: the current thread *cannot* delete itself directly, // since it is still running on the stack that we need to delete. // // NOTE: if this is the main thread, we can't delete the stack // because we didn't allocate it -- we got it automatically // as part of starting up Nachos. //---------------------------------------------------------------------- Thread::~Thread() { DEBUG(dbgThread, "Deleting thread: " << name); ASSERT(this != kernel->currentThread); if (stack != NULL) DeallocBoundedArray((char *) stack, StackSize * sizeof(int)); else DEBUG(dbgThread, "Thread ID => " << kernel->currentThread->getID() << " cannot be deallocation !!!"); } //---------------------------------------------------------------------- // Thread::Fork // Invoke (*func)(arg), allowing caller and callee to execute // concurrently. // // NOTE: although our definition allows only a single argument // to be passed to the procedure, it is possible to pass multiple // arguments by making them fields of a structure, and passing a pointer // to the structure as "arg". // // Implemented as the following steps: // 1. Allocate a stack // 2. Initialize the stack so that a call to SWITCH will // cause it to run the procedure // 3. Put the thread on the ready queue // // "func" is the procedure to run concurrently. // "arg" is a single argument to be passed to the procedure. //---------------------------------------------------------------------- void Thread::Fork(VoidFunctionPtr func, void *arg) { Interrupt *interrupt = kernel->interrupt; Scheduler *scheduler = kernel->scheduler; IntStatus oldLevel; DEBUG(dbgThread, "Forking thread: " << name << " f(a): " << (int) func << " " << arg); StackAllocate(func, arg); oldLevel = interrupt->SetLevel(IntOff); scheduler->ReadyToRun(this); // ReadyToRun assumes that interrupts // are disabled! (void) interrupt->SetLevel(oldLevel); } //---------------------------------------------------------------------- // Thread::CheckOverflow // Check a thread's stack to see if it has overrun the space // that has been allocated for it. If we had a smarter compiler, // we wouldn't need to worry about this, but we don't. // // NOTE: Nachos will not catch all stack overflow conditions. // In other words, your program may still crash because of an overflow. // // If you get bizarre results (such as seg faults where there is no code) // then you *may* need to increase the stack size. You can avoid stack // overflows by not putting large data structures on the stack. // Don't do this: void foo() { int bigArray[10000]; ... } //---------------------------------------------------------------------- void Thread::CheckOverflow() { if (stack != NULL) { #ifdef HPUX // Stacks grow upward on the Snakes ASSERT(stack[StackSize - 1] == STACK_FENCEPOST); #else ASSERT(*stack == STACK_FENCEPOST); #endif } } //---------------------------------------------------------------------- // Thread::Begin // Called by ThreadRoot when a thread is about to begin // executing the forked procedure. // // It's main responsibilities are: // 1. deallocate the previously running thread if it finished // (see Thread::Finish()) // 2. enable interrupts (so we can get time-sliced) //---------------------------------------------------------------------- void Thread::Begin () { ASSERT(this == kernel->currentThread); DEBUG(dbgThread, "Beginning thread: " << name << ", ID: " << ID); kernel->scheduler->CheckToBeDestroyed(); kernel->interrupt->Enable(); } //---------------------------------------------------------------------- // Thread::Finish // Called by ThreadRoot when a thread is done executing the // forked procedure. // // NOTE: we can't immediately de-allocate the thread data structure // or the execution stack, because we're still running in the thread // and we're still on the stack! Instead, we tell the scheduler // to call the destructor, once it is running in the context of a different thread. // // NOTE: we disable interrupts, because Sleep() assumes interrupts // are disabled. //---------------------------------------------------------------------- // void Thread::Finish () { (void) kernel->interrupt->SetLevel(IntOff); ASSERT(this == kernel->currentThread); DEBUG(dbgThread, "Finishing thread: " << name << ", ID: " << ID); Sleep(TRUE); // invokes SWITCH // not reached } //---------------------------------------------------------------------- // Thread::Yield // Relinquish the CPU if any other thread is ready to run. // If so, put the thread on the end of the ready list, so that // it will eventually be re-scheduled. // // NOTE: returns immediately if no other thread on the ready queue. // Otherwise returns when the thread eventually works its way // to the front of the ready list and gets re-scheduled. // // NOTE: we disable interrupts, so that looking at the thread // on the front of the ready list, and switching to it, can be done // atomically. On return, we re-set the interrupt level to its // original state, in case we are called with interrupts disabled. // // Similar to Thread::Sleep(), but a little different. //---------------------------------------------------------------------- void Thread::Yield() { Thread *nextThread; IntStatus oldLevel = kernel->interrupt->SetLevel(IntOff); ASSERT(this == kernel->currentThread); DEBUG(dbgThread, "Yielding thread: " << name << ", ID: " << ID); //<TODO> // 1. Put current_thread in running state to ready state // 2. Then, find next thread from ready state to push on running state // 3. After resetting some value of current_thread, then context switch nextThread = kernel->scheduler->FindNextToRun(); if (nextThread != NULL) { this->setStatus(READY); kernel->scheduler->ReadyToRun(this); DEBUG(dbgMLFQ, "[ContextSwitch] Tick " << "[" << kernel->stats->totalTicks << "]: Thread [" << nextThread->getID() << "] is now selected for execution, thread [" << ID << "] is replaced, and it has executed " << "[" << RunTime << "] ticks"); kernel->scheduler->Run(nextThread, false); } //<TODO> (void) kernel->interrupt->SetLevel(oldLevel); } //---------------------------------------------------------------------- // Thread::Sleep // Relinquish the CPU, because the current thread has either // finished or is blocked waiting on a synchronization // variable (Semaphore, Lock, or Condition). In the latter case, // eventually some thread will wake this thread up, and put it // back on the ready queue, so that it can be re-scheduled. // // NOTE: if there are no threads on the ready queue, that means // we have no thread to run. "Interrupt::Idle" is called // to signify that we should idle the CPU until the next I/O interrupt // occurs (the only thing that could cause a thread to become // ready to run). // // NOTE: we assume interrupts are already disabled, because it // is called from the synchronization routines which must // disable interrupts for atomicity. We need interrupts off // so that there can't be a time slice between pulling the first thread // off the ready list, and switching to it. //---------------------------------------------------------------------- void Thread::Sleep (bool finishing) { Thread *nextThread; ASSERT(this == kernel->currentThread); ASSERT(kernel->interrupt->getLevel() == IntOff); DEBUG(dbgThread, "Sleeping thread: " << name << ", ID: " << ID); status = BLOCKED; while ((nextThread = kernel->scheduler->FindNextToRun()) == NULL) kernel->interrupt->Idle(); // no one to run, wait for an interruptd //<TODO> // In Thread::Sleep(finishing), we put the current_thread to waiting or terminated state (depend on finishing) // , and determine finishing on Scheduler::Run(nextThread, finishing), not here. // 1. Update RemainingBurstTime // 2. Reset some value of current_thread, then context switch if (nextThread != this) { DEBUG(dbgMLFQ, "[ContextSwitch] Tick " << "[" << kernel->stats->totalTicks << "]: Thread [" << nextThread->getID() << "] is now selected for execution, thread [" << ID << "] is replaced, and it has executed " << "[" << RunTime << "] ticks"); } if (RunTime != 0) { DEBUG(dbgMLFQ, "[UpdateRemainingBurstTime] Tick [" << kernel->stats->totalTicks << "]: Thread [" << ID << "] udpate remaining burst time, " << "from: " << "[" << RemainingBurstTime << "]-[" << RunTime << "] to [" << RemainingBurstTime - RunTime << "]"); RemainingBurstTime = RemainingBurstTime - RunTime; } RunTime = 0; RRTime = 0; if (nextThread != this) kernel->scheduler->Run(nextThread, finishing); //<TODO> } //---------------------------------------------------------------------- // ThreadBegin, ThreadFinish, ThreadPrint // Dummy functions because C++ does not (easily) allow pointers to member // functions. So we create a dummy C function // (which we can pass a pointer to), that then simply calls the // member function. //---------------------------------------------------------------------- static void ThreadFinish() { kernel->currentThread->Finish(); } static void ThreadBegin() { kernel->currentThread->Begin(); } void ThreadPrint(Thread *t) { t->Print(); } #ifdef PARISC //---------------------------------------------------------------------- // PLabelToAddr // On HPUX, function pointers don't always directly point to code, // so we need to do the conversion. //---------------------------------------------------------------------- static void * PLabelToAddr(void *plabel) { int funcPtr = (int) plabel; if (funcPtr & 0x02) { // L-Field is set. This is a PLT pointer funcPtr -= 2; // Get rid of the L bit return (*(void **)funcPtr); } else { // L-field not set. return plabel; } } #endif //---------------------------------------------------------------------- // Thread::StackAllocate // Allocate and initialize an execution stack. The stack is // initialized with an initial stack frame for ThreadRoot, which: // enables interrupts // calls (*func)(arg) // calls Thread::Finish // // "func" is the procedure to be forked // "arg" is the parameter to be passed to the procedure //---------------------------------------------------------------------- void Thread::StackAllocate (VoidFunctionPtr func, void *arg) { stack = (int *) AllocBoundedArray(StackSize * sizeof(int)); #ifdef PARISC // HP stack works from low addresses to high addresses // everyone else works the other way: from high addresses to low addresses stackTop = stack + 16; // HP requires 64-byte frame marker stack[StackSize - 1] = STACK_FENCEPOST; #endif #ifdef SPARC stackTop = stack + StackSize - 96; // SPARC stack must contains at // least 1 activation record // to start with. *stack = STACK_FENCEPOST; #endif #ifdef PowerPC // RS6000 stackTop = stack + StackSize - 16; // RS6000 requires 64-byte frame marker *stack = STACK_FENCEPOST; #endif #ifdef DECMIPS stackTop = stack + StackSize - 4; // -4 to be on the safe side! *stack = STACK_FENCEPOST; #endif #ifdef ALPHA stackTop = stack + StackSize - 8; // -8 to be on the safe side! *stack = STACK_FENCEPOST; #endif #ifdef x86 // the x86 passes the return address on the stack. In order for SWITCH() // to go to ThreadRoot when we switch to this thread, the return addres // used in SWITCH() must be the starting address of ThreadRoot. stackTop = stack + StackSize - 4; // -4 to be on the safe side! *(--stackTop) = (int) ThreadRoot; *stack = STACK_FENCEPOST; #endif #ifdef PARISC machineState[PCState] = PLabelToAddr(ThreadRoot); machineState[StartupPCState] = PLabelToAddr(ThreadBegin); machineState[InitialPCState] = PLabelToAddr(func); machineState[InitialArgState] = arg; machineState[WhenDonePCState] = PLabelToAddr(ThreadFinish); #else machineState[PCState] =(void *)ThreadRoot; machineState[StartupPCState] = (void *)ThreadBegin; machineState[InitialPCState] = (void *)func; machineState[InitialArgState] = (void *)arg; machineState[WhenDonePCState] = (void *)ThreadFinish; #endif } #ifdef USER_PROGRAM #include "machine.h" //---------------------------------------------------------------------- // Thread::SaveUserState // Save the CPU state of a user program on a context switch. // // Note that a user program thread has *two* sets of CPU registers -- // one for its state while executing user code, one for its state // while executing kernel code. This routine saves the former. //---------------------------------------------------------------------- void Thread::SaveUserState() { for (int i = 0; i < NumTotalRegs; i++) userRegisters[i] = kernel->machine->ReadRegister(i); } //---------------------------------------------------------------------- // Thread::RestoreUserState // Restore the CPU state of a user program on a context switch. // // Note that a user program thread has *two* sets of CPU registers -- // one for its state while executing user code, one for its state // while executing kernel code. This routine restores the former. //---------------------------------------------------------------------- void Thread::RestoreUserState() { for (int i = 0; i < NumTotalRegs; i++) kernel->machine->WriteRegister(i, userRegisters[i]); } #endif //---------------------------------------------------------------------- // SimpleThread // Loop 5 times, yielding the CPU to another ready thread // each iteration. // // "which" is simply a number identifying the thread, for debugging // purposes. //---------------------------------------------------------------------- static void SimpleThread(int which) { int num; for (num = 0; num < 5; num++) { cout << "*** thread " << which << " looped " << num << " times\n"; kernel->currentThread->Yield(); } } //---------------------------------------------------------------------- // Thread::SelfTest // Set up a ping-pong between two threads, by forking a thread // to call SimpleThread, and then calling SimpleThread ourselves. //---------------------------------------------------------------------- void Thread::SelfTest() { DEBUG(dbgThread, "Entering Thread::SelfTest"); Thread *t = new Thread("forked thread", 1); t->Fork((VoidFunctionPtr) SimpleThread, (void *) 1); SimpleThread(0); }
[ "a28725977@gmail.com" ]
a28725977@gmail.com
ef8114ab86c07bab2b86185fc874b2918ea77b01
4b3368a37d174e9d0f046b9b32509b8f80889de2
/SoftwareRepository/CheckInMgr/CheckInMgrTests.h
e2fdf318f533d80113d84ea4972e67d72b420309
[]
no_license
riteshgn/remote-code-repo--cs_cpp
f85b65fa3aa906d890b6765452d8a05d3e675d11
c5cfc115cc84581eaa6909d08a82337ff028c971
refs/heads/master
2020-03-31T22:48:12.441457
2018-10-11T20:28:29
2018-10-11T20:28:29
152,631,930
0
0
null
null
null
null
UTF-8
C++
false
false
1,945
h
#pragma once /////////////////////////////////////////////////////////////////////// // CheckInMgrTests.h - Implements all test cases for CheckInMgr // // ver 1.0 // // Language: C++, Visual Studio 2017 // // Application: SoftwareRepository, CSE687 - Object Oriented Design // // Author: Ritesh Nair (rgnair@syr.edu) // /////////////////////////////////////////////////////////////////////// /* * Package Operations: * ------------------- * This file implements the test functors for testing the CheckInMgr * Required Files: * --------------- * TestCore.h, TestCore.cpp * * Maintenance History: * -------------------- * ver 1.0 : 10 Mar 2018 * - first release */ #ifndef CHECKIN_MGR_TESTS_H #define CHECKIN_MGR_TESTS_H #include "../TestCore/TestCore.h" namespace SoftwareRepositoryTests { ///////////////////////////////////////////////////////////////////// // test functors // - Implements test cases to demonstrate the various requirements // on CheckInMgr module class TestCheckInValidations : public TestCore::AbstractTest { public: TestCheckInValidations(AbstractTest::TestTitle title) : AbstractTest(title) { } virtual bool operator()(); }; class TestCheckIn : public TestCore::AbstractTest { public: TestCheckIn(AbstractTest::TestTitle title) : AbstractTest(title) { } virtual bool operator()(); }; class TestCommitValidations : public TestCore::AbstractTest { public: TestCommitValidations(AbstractTest::TestTitle title) : AbstractTest(title) { } virtual bool operator()(); }; class TestCommit : public TestCore::AbstractTest { public: TestCommit(AbstractTest::TestTitle title) : AbstractTest(title) { } virtual bool operator()(); }; } #endif // !CHECKIN_MGR_TESTS_H
[ "riteshgn@gmail.com" ]
riteshgn@gmail.com
cbbfe423c21848b494f9dc4f68e31635759390e4
41094da368bb7c8a0e5ddcc33b1b13dbec7c5126
/lib/include/crete/exception_propagator.h
e272f602b915723e8968bc19fe274d4fdbd10928
[ "BSD-2-Clause-Views" ]
permissive
svlpsu/crete-release
03dd1dfc888c44071c428bd1b2b291f46760ae52
86f0469f267e6e6c5ca39d669537c46c62f6515a
refs/heads/master
2021-01-18T18:28:37.423241
2016-07-11T23:50:28
2016-07-11T23:50:28
61,248,049
2
2
null
2016-07-11T23:50:28
2016-06-15T23:38:03
C
UTF-8
C++
false
false
1,810
h
/*** * Author: Christopher Havlicek */ #ifndef CRETE_EXCEPTION_PROPAGATOR_H #define CRETE_EXCEPTION_PROPAGATOR_H #include <exception> #include <utility> namespace crete { /** * @brief The ExceptionPropagator class * * For multithreading purposes. * * Execute any function with execute_and_catch() * and automatically catch the exception pointer. * Use is_exception_thrown() and rethrow_exception() to * propagate. * * May inherent from or use as a component. * * Remarks: * * Originally, execute_and_catch(Func f, Args&&... args) returned * decltype(f()). However, there is a problem. If an exception is thrown, * it is caught and the function returns - but what? Undefined behavior; * therefore, I've constrained f to only void returning functions * (the return value is ignored if not). * * TODO: Is a mutex necessary to protect eptr_? If so, it's a little complicated. * std::mutex is not copyable nor movable, and that's problematic for how I use this class. * */ class ExceptionPropagator { public: template <typename Func, typename... Args> auto execute_and_catch(Func f, Args&&... args) -> void; auto is_exception_thrown() -> bool; [[noreturn]] auto rethrow_exception() -> void; private: std::exception_ptr eptr_{nullptr}; }; template <typename Func, typename... Args> auto ExceptionPropagator::execute_and_catch(Func f, Args&&... args) -> void { try { f(std::forward<Args>(args)...); } catch(...) { eptr_ = std::current_exception(); } } inline auto ExceptionPropagator::is_exception_thrown() -> bool { return static_cast<bool>(eptr_); } inline auto ExceptionPropagator::rethrow_exception() -> void { std::rethrow_exception(eptr_); } } // namespace crete #endif // CRETE_EXCEPTION_PROPAGATOR_H
[ "chenbo@pdx.edu" ]
chenbo@pdx.edu
37456b042612014542a4d224a4374be6102e8822
2b60430c2108690e23174f193d806de86658bad4
/ModernPL-master/pscx_emulator/pscx_main.cpp
18d7f35b18f36ceb89210024db6df32cca287082
[]
no_license
BCroco/emulator
236daa9d3664f9bc0d752bd34672da30208bac2b
ad36da8d83fd692f1c4dd13c5638121d66d3a652
refs/heads/master
2020-04-12T08:32:45.501739
2018-12-19T05:52:23
2018-12-19T05:52:23
162,388,108
0
0
null
null
null
null
UTF-8
C++
false
false
3,805
cpp
#include "pscx_bios.h" #include "pscx_cpu.h" #include "pscx_interconnect.h" #include <iostream> #include <fstream> #include <vector> #include <string> struct ArgSetParser { ArgSetParser(int argc, char** argv) { m_args.resize(argc); for (size_t i = 0; i < argc; ++i) m_args[i] = argv[i]; } const std::vector<std::string>& args() { return m_args; } private: std::vector<std::string> m_args; }; static void printUsageAndExit(const char* argv0) { std::cerr << "Usage : " << argv0 << " <Path to BIOS BIN> [options]\n" << "App options:\n" << " -h | --help Print this usage message\n" << " -dump | --dump-instructions-registers Dump instructions and registers to the file\n" << " -rt | --run-testing Compare output results with the golden file\n" << std::endl; exit(1); } static void generateDumpOutputFn(const Cpu& cpu) { std::ofstream dumpLog("dump_output.txt"); const std::vector<uint32_t>& instructionsDump = cpu.getInstructionsDump(); // Dump instructions dumpLog << instructionsDump.size() << " "; for (size_t i = 0; i < instructionsDump.size(); ++i) dumpLog << instructionsDump[i] << " "; const uint32_t* regs = cpu.getRegistersPtr(); // Dump registers for (size_t i = 0; i < 32; ++i) dumpLog << regs[i] << " "; dumpLog.close(); } static bool compareGoldenWithDump(const Cpu& cpu) { std::ifstream goldenInput("golden/golden_result.txt"); if (!goldenInput.good()) { LOG("No golden file found"); return false; } uint32_t instructionsCount = 0; goldenInput >> instructionsCount; const std::vector<uint32_t>& instructionsDump = cpu.getInstructionsDump(); if (instructionsCount != instructionsDump.size()) { LOG("incorrect size"); return false; } // Compare opcodes uint32_t opcode = 0; for (size_t i = 0; i < instructionsCount; ++i) { goldenInput >> opcode; if (opcode != instructionsDump[i]) { LOG("Opcodes dosn't match" + i); return false; } } const uint32_t* regs = cpu.getRegistersPtr(); // Compare registers uint32_t registerValue = 0; for (size_t i = 0; i < 32; ++i) { goldenInput >> registerValue; if (registerValue != regs[i]) return false; } goldenInput.close(); return true; } int main(int argc, char** argv) { //From x64/Debug/ launch pscx_emulator.exe "c:\ModernPL\pscx_emulator\roms\SCPH1001.BIN" ArgSetParser parser(argc, argv); const std::vector<std::string>& args = parser.args(); // Should be two arguments at least if (args.size() < 2) printUsageAndExit(args[0].c_str()); // Path to the BIOS std::string biosPath = args[1]; bool dumpInstructionsAndRegsToFile = true; bool runTesting = true; // Parse command line arguments for (size_t i = 2; i < args.size(); ++i) { if (args[i] == "-h" || args[i] == "--help") printUsageAndExit(args[i].c_str()); if (args[i] == "-dump" || args[i] == "--dump-instructions-registers") dumpInstructionsAndRegsToFile = true; if (args[i] == "-rt" || args[i] == "--run-testing") runTesting = true; } Bios bios; Bios::BiosState state = bios.loadBios(biosPath); switch (state) { case Bios::BIOS_STATE_INCORRECT_FILENAME: std::cout << "Can't find location of the bios " << biosPath << std::endl; return EXIT_FAILURE; case Bios::BIOS_STATE_INVALID_BIOS_SIZE: std::cout << "Invalid BIOS size " << biosPath << std::endl; return EXIT_FAILURE; } Interconnect interconnect(bios); Cpu cpu(interconnect); while (cpu.runNextInstuction() != Cpu::INSTRUCTION_TYPE_UNKNOWN); if (dumpInstructionsAndRegsToFile) generateDumpOutputFn(cpu); if (runTesting) { if (compareGoldenWithDump(cpu)) { LOG("Dump matches golden file"); } else { LOG("Dump doesn't match to golden file"); } } //system("pause"); return EXIT_SUCCESS; }
[ "noreply@github.com" ]
noreply@github.com
ee663dd1a4cac597dc7f37dff187f19eb60ee267
669db6135e2972cb31a7494da88652a3706503fc
/sensor_base_files/thermometer/MLX90614_Serial_Demo.ino
8181a332a5a2bafec9475b08ec20f4922ccaf57b
[]
no_license
rpga95/MedCap
08eee1b8820b21096691255a3b8c2081df057b9d
7ff73777d564010a3d3d3a14a1fd34c50e064846
refs/heads/master
2021-07-13T20:08:43.555691
2017-10-19T16:18:02
2017-10-19T16:18:02
107,565,871
0
0
null
null
null
null
UTF-8
C++
false
false
2,370
ino
/****************************************************************************** MLX90614_Serial_Demo.ino Serial output example for the MLX90614 Infrared Thermometer This example reads from the MLX90614 and prints out ambient and object temperatures every half-second or so. Open the serial monitor and set the baud rate to 9600. Hardware Hookup (if you're not using the eval board): MLX90614 ------------- Arduino VDD ------------------ 3.3V VSS ------------------ GND SDA ------------------ SDA (A4 on older boards) SCL ------------------ SCL (A5 on older boards) An LED can be attached to pin 8 to monitor for any read errors. Jim Lindblom @ SparkFun Electronics October 23, 2015 https://github.com/sparkfun/SparkFun_MLX90614_Arduino_Library Development environment specifics: Arduino 1.6.5 SparkFun IR Thermometer Evaluation Board - MLX90614 ******************************************************************************/ #include <Wire.h> // I2C library, required for MLX90614 #include <SparkFunMLX90614.h> // SparkFunMLX90614 Arduino library IRTherm therm; // Create an IRTherm object to interact with throughout const byte LED_PIN = 8; // Optional LED attached to pin 8 (active low) void setup() { Serial.begin(9600); // Initialize Serial to log output therm.begin(); // Initialize thermal IR sensor therm.setUnit(TEMP_F); // Set the library's units to Farenheit // Alternatively, TEMP_F can be replaced with TEMP_C for Celsius or // TEMP_K for Kelvin. pinMode(LED_PIN, OUTPUT); // LED pin as output setLED(LOW); // LED OFF } void loop() { setLED(HIGH); //LED on // Call therm.read() to read object and ambient temperatures from the sensor. if (therm.read()) // On success, read() will return 1, on fail 0. { // Use the object() and ambient() functions to grab the object and ambient // temperatures. // They'll be floats, calculated out to the unit you set with setUnit(). Serial.print("Object: "); Serial.println(therm.object()); Serial.write('°'); // Degree Symbol Serial.println("F"); Serial.print("Ambient: "); Serial.println(therm.ambient()); Serial.write('°'); // Degree Symbol Serial.println("F"); Serial.println(); } setLED(LOW); delay(500); } void setLED(bool on) { if (on) digitalWrite(LED_PIN, LOW); else digitalWrite(LED_PIN, HIGH); }
[ "raj1995@gmail.com" ]
raj1995@gmail.com
9dcbacf991dffcab41aaf22b2ab8f1ca173ce0b3
803ec81c19a50e68e4f2b7c98a41b70c832e587f
/572!.cpp
30bc2856491314bc576afb92bcb3a48d0de77f22
[]
no_license
JiaYu07/UVA
7f1f2f30b36c1771c86cb990ca9ad5dbe2626bdb
cd0c8eee1e2ef192486e09bbfe0ffb9ad2b26c67
refs/heads/master
2020-12-15T21:34:19.143363
2020-02-05T10:56:37
2020-02-05T10:56:37
235,260,745
0
0
null
null
null
null
UTF-8
C++
false
false
944
cpp
#include<iostream> #include<algorithm> using namespace std; #define MAXN 105; int n,m=0; char msg[105][105]; bool vis[105][105]; int ans=0; void dfs(int x,int y){ if(x<0||x>=n||y<0||y>=m)return ; if(vis[x][y]==true||msg[x][y]!='@')return; vis[x][y]=true; for(int tmp_x=-1;tmp_x<=1;++tmp_x)//這樣就不用一個一個去思考 for(int tmp_y=-1;tmp_y<=1;++tmp_y) if(tmp_x!=0||tmp_y!=0)dfs(x+tmp_x,y+tmp_y);//不會重複dfs原點 } int main(){ while(cin>>n>>m&&n&&m){ ans=0; fill(vis[0],vis[0]+105*105,false); for(int i=0;i<n;++i) for(int j=0;j<m;++j) cin>>msg[i][j]; for(int i=0;i<n;++i) for(int j=0;j<m;++j) if(vis[i][j]==false&&msg[i][j]=='@'){ dfs(i,j); ans++; } cout<<ans<<endl; } return 0; }
[ "a0965178617@gmail.com" ]
a0965178617@gmail.com
b831064e2aa4cd162cd22440d281830327066a41
3f6f46e4d1018c1007271c5fee2e57e820bfcd52
/interviewBit/contiguousSubarray.cpp
40cb15a1f275aa0674428c6c22f6da5d25323fef
[]
no_license
a-ritwik/Competitive-coding
caa40b3d5072ffc3d039aa4c11b12bf1bd5aba1e
f4ced67ef45d766396a44f9821a439118cc3c1fb
refs/heads/master
2021-04-15T11:50:32.543211
2018-03-25T09:13:40
2018-03-25T09:13:40
126,676,252
0
0
null
null
null
null
UTF-8
C++
false
false
680
cpp
#include<iostream> #include<vector> using namespace std; int maxSubArray(const vector<int> &A) { int ans = -9999999; int cumulative = 0; int maxval = -9999999; for(int i=0; i<A.size(); i++){ maxval = max(maxval, A[i]); cumulative += A[i]; ans = max(cumulative, ans); if(cumulative<0){ cumulative =0; } } return max(ans, maxval); } int main(){ vector<int> myvector (9); myvector[0]=-2; myvector[1]=1; myvector[2]=-3; myvector[3]=4; myvector[4]=-1; myvector[5]=2; myvector[6]=1; myvector[7]=-5; myvector[8]=4; cout << maxSubArray(myvector); return 0; }
[ "noreply@github.com" ]
noreply@github.com
6d88c53c4cfdd3c13d309e85f4621262332116c3
75452de12ec9eea346e3b9c7789ac0abf3eb1d73
/src/lib/ui/base_view/math.h
dd2e30fc43c609dd0b7f94ee9093c7458d203720
[ "BSD-3-Clause" ]
permissive
oshunter/fuchsia
c9285cc8c14be067b80246e701434bbef4d606d1
2196fc8c176d01969466b97bba3f31ec55f7767b
refs/heads/master
2022-12-22T11:30:15.486382
2020-08-16T03:41:23
2020-08-16T03:41:23
287,920,017
2
2
BSD-3-Clause
2022-12-16T03:30:27
2020-08-16T10:18:30
C++
UTF-8
C++
false
false
3,113
h
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SRC_LIB_UI_BASE_VIEW_MATH_H_ #define SRC_LIB_UI_BASE_VIEW_MATH_H_ #include <fuchsia/ui/gfx/cpp/fidl.h> #include <lib/fostr/fidl/fuchsia/ui/gfx/formatting.h> namespace scenic { // Return true if |point| is contained by |box|, including when it is on the // box boundary, and false otherwise. inline bool ContainsPoint(const fuchsia::ui::gfx::BoundingBox& box, const fuchsia::ui::gfx::vec3& point) { return point.x >= box.min.x && point.y >= box.min.y && point.z >= box.min.z && point.x <= box.max.x && point.y <= box.max.y && point.z <= box.max.z; } // Similar to fuchsia::ui::gfx::ViewProperties: adds the inset to box.min, and // subtracts it from box.max. inline fuchsia::ui::gfx::BoundingBox InsetBy(const fuchsia::ui::gfx::BoundingBox& box, const fuchsia::ui::gfx::vec3& inset) { return {.min = box.min + inset, .max = box.max - inset}; } // Similar to fuchsia::ui::gfx::ViewProperties: adds the inset to box.min, and // subtracts it from box.max. inline fuchsia::ui::gfx::BoundingBox InsetBy(const fuchsia::ui::gfx::BoundingBox& box, const fuchsia::ui::gfx::vec3& inset_from_min, const fuchsia::ui::gfx::vec3& inset_from_max) { return {.min = box.min + inset_from_min, .max = box.max - inset_from_max}; } // Inset the view properties' outer box by its insets. inline fuchsia::ui::gfx::BoundingBox ViewPropertiesLayoutBox( const fuchsia::ui::gfx::ViewProperties& view_properties) { return InsetBy(view_properties.bounding_box, view_properties.inset_from_min, view_properties.inset_from_max); } // Return a vec3 consisting of the maximum x/y/z from the two arguments. inline fuchsia::ui::gfx::vec3 Max(const fuchsia::ui::gfx::vec3& a, const fuchsia::ui::gfx::vec3& b) { return {.x = std::max(a.x, b.x), .y = std::max(a.y, b.y), .z = std::max(a.z, b.z)}; } // Return a vec3 consisting of the maximum of the x/y/z components of |v|, // compared with |min_val|. inline fuchsia::ui::gfx::vec3 Max(const fuchsia::ui::gfx::vec3& v, float min_val) { return {.x = std::max(v.x, min_val), .y = std::max(v.y, min_val), .z = std::max(v.z, min_val)}; } // Return a vec3 consisting of the minimum x/y/z from the two arguments. inline fuchsia::ui::gfx::vec3 Min(const fuchsia::ui::gfx::vec3& a, const fuchsia::ui::gfx::vec3& b) { return {.x = std::min(a.x, b.x), .y = std::min(a.y, b.y), .z = std::min(a.z, b.z)}; } // Return a vec3 consisting of the minimum of the x/y/z components of |v|, // compared with |max_val|. inline fuchsia::ui::gfx::vec3 Min(const fuchsia::ui::gfx::vec3& v, float max_val) { return {.x = std::min(v.x, max_val), .y = std::min(v.y, max_val), .z = std::min(v.z, max_val)}; } } // namespace scenic #endif // SRC_LIB_UI_BASE_VIEW_MATH_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
e1f60f779836bf29e825f60973ccf73ca94e7be8
5456502f97627278cbd6e16d002d50f1de3da7bb
/net/spdy/spdy_no_op_visitor.h
3e0bea8d4315ad0b5cdc584a97ae0b717e80998f
[ "BSD-3-Clause" ]
permissive
TrellixVulnTeam/Chromium_7C66
72d108a413909eb3bd36c73a6c2f98de1573b6e5
c8649ab2a0f5a747369ed50351209a42f59672ee
refs/heads/master
2023-03-16T12:51:40.231959
2017-12-20T10:38:26
2017-12-20T10:38:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,118
h
// Copyright (c) 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // SpdyNoOpVisitor implements several of the visitor and handler interfaces // to make it easier to write tests that need to provide instances. Other // interfaces can be added as needed. #ifndef NET_SPDY_SPDY_NO_OP_VISITOR_H_ #define NET_SPDY_SPDY_NO_OP_VISITOR_H_ #include "net/spdy/spdy_framer.h" #include "net/spdy/spdy_protocol.h" namespace net { namespace test { class SpdyNoOpVisitor : public SpdyFramerVisitorInterface, public SpdyFramerDebugVisitorInterface, public SpdyHeadersHandlerInterface { public: SpdyNoOpVisitor(); ~SpdyNoOpVisitor() override; // SpdyFramerVisitorInterface methods: void OnError(SpdyFramer* framer) override {} void OnSynStream(SpdyStreamId stream_id, SpdyStreamId associated_stream_id, SpdyPriority priority, bool fin, bool unidirectional) override {} void OnSynReply(SpdyStreamId stream_id, bool fin) override {} net::SpdyHeadersHandlerInterface* OnHeaderFrameStart( SpdyStreamId stream_id) override; void OnHeaderFrameEnd(SpdyStreamId stream_id, bool end_headers) override {} void OnDataFrameHeader(SpdyStreamId stream_id, size_t length, bool fin) override {} void OnStreamFrameData(SpdyStreamId stream_id, const char* data, size_t len) override {} void OnStreamEnd(SpdyStreamId stream_id) override {} void OnStreamPadding(SpdyStreamId stream_id, size_t len) override {} void OnRstStream(SpdyStreamId stream_id, SpdyRstStreamStatus status) override {} void OnSetting(SpdySettingsIds id, uint8_t flags, uint32_t value) override {} void OnPing(SpdyPingId unique_id, bool is_ack) override {} void OnSettingsEnd() override {} void OnSettingsAck() override {} void OnGoAway(SpdyStreamId last_accepted_stream_id, SpdyGoAwayStatus status) override {} void OnHeaders(SpdyStreamId stream_id, bool has_priority, int weight, SpdyStreamId parent_stream_id, bool exclusive, bool fin, bool end) override {} void OnWindowUpdate(SpdyStreamId stream_id, int delta_window_size) override {} void OnPushPromise(SpdyStreamId stream_id, SpdyStreamId promised_stream_id, bool end) override {} void OnContinuation(SpdyStreamId stream_id, bool end) override {} void OnAltSvc(SpdyStreamId stream_id, base::StringPiece origin, const SpdyAltSvcWireFormat::AlternativeServiceVector& altsvc_vector) override {} void OnPriority(SpdyStreamId stream_id, SpdyStreamId parent_stream_id, int weight, bool exclusive) override {} bool OnUnknownFrame(SpdyStreamId stream_id, int frame_type) override; // SpdyFramerDebugVisitorInterface methods: void OnSendCompressedFrame(SpdyStreamId stream_id, SpdyFrameType type, size_t payload_len, size_t frame_len) override {} void OnReceiveCompressedFrame(SpdyStreamId stream_id, SpdyFrameType type, size_t frame_len) override {} // SpdyHeadersHandlerInterface methods: void OnHeaderBlockStart() override {} void OnHeader(base::StringPiece key, base::StringPiece value) override {} void OnHeaderBlockEnd(size_t uncompressed_header_bytes) override {} void OnHeaderBlockEnd(size_t /* uncompressed_header_bytes */, size_t /* compressed_header_bytes */) override {} }; } // namespace test } // namespace net #endif // NET_SPDY_SPDY_NO_OP_VISITOR_H_
[ "lixiaodonglove7@aliyun.com" ]
lixiaodonglove7@aliyun.com
61ee60d84fda3591f8776f8dbd9c4743b56a793c
4a0705c907ac3b28d3859a86e44b0a0edb351fd9
/src/EvolutionCoursI.cpp
7d3a93d135679771d5dd08e953a51e209a9831e8
[]
no_license
sillawned/TD4
1322e21c1d89c31dbdf8c543b7c6046946433f1a
5bebfead051c6705c7543f51bd2dc686bfdf1994
refs/heads/master
2020-05-19T06:16:19.045212
2019-05-02T16:45:30
2019-05-02T16:45:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,545
cpp
// // Created by chenghaowang on 29/03/19. // #include "../include/EvolutionCoursI.h" EvolutionCoursI::EvolutionCoursI(const PaireDevises &paireDevises) : paireDevises(paireDevises) {} EvolutionCoursI::EvolutionCoursI(const EvolutionCoursI &e) : paireDevises(e.getPaireDevises()), nbCours(e.getNbCours()), nbMaxCours(e.getNbMaxCours()), cours(new CoursOHLC[e.getNbCours()]){ for (unsigned int i = 0; i < nbCours; i++) cours[i] = e.getCoursAt(i); } EvolutionCoursI &EvolutionCoursI::operator=(const EvolutionCoursI &p) { if (&p != this) { if (nbMaxCours <getNbCours()) { delete[] cours; cours = new CoursOHLC[p.getNbCours()] ; nbMaxCours = p.getNbMaxCours(); } nbCours = p.getNbCours(); for (unsigned int i = 0; i < nbCours; i++) cours[i] = p.getCoursAt(i); } return *this; } void EvolutionCoursI::addCours(double openPrice, double highPrice, double lowPrice, double closePrice, const QDateTime & dateTime) { if (nbCours == nbMaxCours) { auto * newtab = new CoursOHLC[nbMaxCours + 50]; for (unsigned int i = 0; i < nbCours; i++) newtab[i] = cours[i]; CoursOHLC* old = cours; nbMaxCours += 50; cours = newtab; delete[] old; } cours[nbCours++] = CoursOHLC(openPrice, highPrice, lowPrice, closePrice, dateTime); } EvolutionCoursI::~EvolutionCoursI() { delete[](cours); } const PaireDevises &EvolutionCoursI::getPaireDevises() const { return paireDevises; } CoursOHLC *EvolutionCoursI::getCours() const { return cours; } unsigned int EvolutionCoursI::getNbMaxCours() const { return nbMaxCours; } unsigned int EvolutionCoursI::getNbCours() const { return nbCours; } CoursOHLC& EvolutionCoursI::getCoursAt(int index) const { if(index < 0 || index > nbCours - 1) throw TradingException("out of array!"); return cours[index]; } std::ostream &operator<<(std::ostream &os, EvolutionCoursI &i) { for(EvolutionCoursI::Iterator it= i.getIterator();!it.isDone();it.next()){ os <<it.current()<<"\n"; it.current().setCours(0,0,0,0, QDateTime(QDate(0, 0, 0), QTime(0, 0, 0))); // modification possible } return os; } std::ostream &operator<<(std::ostream &os, const EvolutionCoursI &i) { for(EvolutionCoursI::ConstIterator it= i.getIterator();!it.isDone();it.next()){ os <<it.current()<<"\n"; //it.current().setCours(0,0,0,0); // modification impossible } return os; }
[ "chenghao.wang@hds.utc.fr" ]
chenghao.wang@hds.utc.fr
100ffdd70380e6180fe9243bf5a620d19bd3aa7a
fced25ad3f3656b292a3b9240e7801b1e35e4ce4
/iwave/mps/tests/mps_frac_cal/src/main/test_asg_scal_p.cc
a47816cffd1b2a9dcba9eed68e68a575fa8efa45
[ "ICU" ]
permissive
wwsorcas/trip
77cfbed387cdf202498e5d229dd748b9f48a2035
5324b0d68b74b9419435f52a4d8727c86b564867
refs/heads/master
2023-08-31T13:31:09.606896
2023-08-20T04:17:36
2023-08-20T04:17:36
190,781,137
8
0
null
null
null
null
UTF-8
C++
false
false
2,373
cc
#include "asg_defn.hh" #include "asg.hh" #include "test_kernel.hh" IOKEY IWaveInfo::iwave_iokeys[] = { {BULKMOD, 0, true, 1 }, {BUOYANCY, 1, true, 1 }, {SOURCE_P, 2, true, 2 }, {DATA_P, 2, false, 2 }, {"", 0, false, 0 } }; int xargc; char **xargv; int main(int argc, char ** argv) { try { #ifdef IWAVE_USE_MPI int ts=0; MPI_Init_thread(&argc,&argv,MPI_THREAD_FUNNELED,&ts); #endif string test_exc = "test_asg_scal_p.x"; PARARRAY * pars = NULL; FILE * stream = NULL; TSOpt::IWaveEnvironment(argc, argv, 0, &pars, &stream); #ifdef IWAVE_USE_MPI if( retrieveGlobalRank()==0 ){ #endif cerr << "\n------------------------------------------------------------\n" << "Running "<< test_exc <<"\n" << "------------------------------------------------------------\n"; //ps_printall(*pars,stderr); #ifdef IWAVE_USE_MPI } #endif //consistency check of driver, data, and src type string driver_type = valparse<string>(*pars,"driver"); string data_type = valparse<string>(*pars,"data_type"); string src_type = valparse<string>(*pars,"src_type"); if( driver_type.compare("asg")!=0 || src_type.compare("pressure")!=0 || data_type.compare("pressure")!=0 ){ RVLException e; e << "Driver/src/data type is unexpected!\n" << " driver_type="<< driver_type <<"\n" << " src_type=" << src_type <<"\n" << " data_type=" << data_type <<"\n"; throw e; } string test_info; test_info += " driver:"+driver_type+"\n"; test_info += " src type:"+src_type+"\n"; test_info += " data type:"+data_type+"\n"; //running test kernel test_kernel<Scal_MPS_Space>(*pars,*stream,test_info); //clean up ps_delete(&pars); iwave_fdestroy(); #ifdef IWAVE_USE_MPI if( retrieveGlobalRank()==0 ){ #endif cerr << "------------------------------------------------------------\n" << "Exiting "<< test_exc <<"\n" << "------------------------------------------------------------\n\n"; #ifdef IWAVE_USE_MPI } MPI_Finalize(); #endif } catch(RVLException &e){ e << "Exiting with error!\n"; #ifdef IWAVE_USE_MPI if( retrieveGlobalRank()==0 ){ #endif e.write(cerr); #ifdef IWAVE_USE_MPI } MPI_Abort(MPI_COMM_WORLD,0); #endif exit(1); } }
[ "symes@caam.rice.edu" ]
symes@caam.rice.edu
70c839e86a494af627cfac84b36d7f002ddb678a
ab99f239fc699a697c4ffe16a5b8976c64bb3f81
/Advanced/Les2Opdracht2/Les2Opdracht2/Soldier.cpp
e383b1ace3917c1f2a49c84c2cb084193eebcab4
[]
no_license
BeTheBase/KeuzeModuleOOP
073e1230db2f1f2bffc90849d7c0bbbf717b5efc
49945000a41540b5a606b0684b4a84ec98bb7201
refs/heads/master
2020-07-31T09:10:54.573632
2019-12-15T21:07:18
2019-12-15T21:07:18
210,552,032
0
0
null
null
null
null
UTF-8
C++
false
false
213
cpp
#include "Soldier.h" #include <iostream> Soldier::Soldier(NPC* npc) : Decorator(npc) { } Soldier::~Soldier() { } void Soldier::render() { Decorator::render(); std::cout << "added: soldier" << std::endl; }
[ "Bas.ghosts@gmail.com" ]
Bas.ghosts@gmail.com
e229525d7156c106f2c3ae830fd28730a62fa499
c6534626f28a020a25593ae274d8a49e1bfcdc7a
/mod/base/utils.h
5f929ae323dfd41536f3820df7b10eb8150a7978
[ "MIT" ]
permissive
MeetinaXD/bdlauncher-mods
de28267cf8db11ae0aa9bec7e99e0ab3ee56f94a
b8ba6e9c5aea50f37dc623757ae2864457eb9633
refs/heads/master
2021-01-03T19:21:57.995224
2020-02-14T12:32:29
2020-02-14T12:32:29
240,206,972
0
0
MIT
2020-02-13T08:02:57
2020-02-13T08:02:56
null
UTF-8
C++
false
false
808
h
#pragma once //#include <MC.h> #include <string> #include <bdlexport.h> class ItemStack; class ServerPlayer; struct ActorUniqueID; class BlockSource; class Vec3; BDL_EXPORT ItemStack *createItemStack_static(short id, short aux, unsigned char amo, ItemStack *stk); BDL_EXPORT ItemStack *createItemStack(short id, short aux, unsigned char amo); BDL_EXPORT ItemStack *createItemStack_static(std::string const &name, unsigned char amo, ItemStack *stk); BDL_EXPORT ItemStack *createItemStack(std::string const &name, unsigned char amo); BDL_EXPORT void giveItem(ServerPlayer &sp, ItemStack *is); BDL_EXPORT ActorUniqueID summon(BlockSource &bs, Vec3 const &vc, std::string const &name); BDL_EXPORT bool takeItem_unsafe(ServerPlayer &sp, ItemStack *is); BDL_EXPORT bool takeItem(ServerPlayer &sp, ItemStack *is);
[ "root@localhost.localdomain" ]
root@localhost.localdomain
84a9e9ef0d30a907a4cd11e3813242ef71d67e00
9641a2bf42719d70418f534bc4134a7adcb90c35
/core/src/db/snapshot/EventExecutor.h
da7aa26c8bea56756ed4c2ffed3b59c83522268c
[ "Apache-2.0", "BSD-3-Clause", "MIT", "JSON", "LGPL-2.1-only", "LicenseRef-scancode-unknown-license-reference", "Zlib", "LicenseRef-scancode-public-domain" ]
permissive
MXDA/milvus
8d7a5e5f9bccf74411223f2e4c3dfe0fedeb863c
db17edab04ce518de7164c9f0b1bf8ca0747f285
refs/heads/master
2022-12-14T00:28:33.441178
2020-09-07T15:22:52
2020-09-07T15:22:52
281,584,345
1
0
Apache-2.0
2020-07-22T05:33:49
2020-07-22T05:33:49
null
UTF-8
C++
false
false
3,218
h
// Copyright (C) 2019-2020 Zilliz. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations under the License. #pragma once #include <memory> #include <mutex> #include <thread> #include "db/snapshot/Event.h" #include "utils/BlockingQueue.h" namespace milvus { namespace engine { namespace snapshot { using EventPtr = std::shared_ptr<MetaEvent>; using ThreadPtr = std::shared_ptr<std::thread>; using EventQueue = BlockingQueue<EventPtr>; class EventExecutor { public: ~EventExecutor() { Stop(); } static void Init(StorePtr store) { auto& instance = GetInstanceImpl(); if (instance.initialized_) { return; } instance.store_ = store; instance.initialized_ = true; } static EventExecutor& GetInstance() { auto& instance = GetInstanceImpl(); if (!instance.initialized_) { throw std::runtime_error("OperationExecutor should be init"); } return instance; } Status Submit(const EventPtr& evt) { if (evt == nullptr) { return Status(SS_INVALID_ARGUMENT_ERROR, "Invalid Resource"); } Enqueue(evt); return Status::OK(); } void Start() { if (thread_ptr_ == nullptr) { thread_ptr_ = std::make_shared<std::thread>(&EventExecutor::ThreadMain, this); } } void Stop() { if (thread_ptr_ != nullptr) { Enqueue(nullptr); thread_ptr_->join(); thread_ptr_ = nullptr; std::cout << "EventExecutor Stopped" << std::endl; } } private: static EventExecutor& GetInstanceImpl() { static EventExecutor executor; return executor; } void ThreadMain() { Status status; while (true) { EventPtr evt = queue_.Take(); if (evt == nullptr) { break; } /* std::cout << std::this_thread::get_id() << " Dequeue Event " << std::endl; */ status = evt->Process(store_); if (!status.ok()) { std::cout << "EventExecutor Handle Event Error: " << status.ToString() << std::endl; } } } void Enqueue(const EventPtr& evt) { queue_.Put(evt); if (evt != nullptr) { /* std::cout << std::this_thread::get_id() << " Enqueue Event " << std::endl; */ } } EventExecutor() = default; EventExecutor(const EventExecutor&) = delete; ThreadPtr thread_ptr_ = nullptr; EventQueue queue_; std::atomic_bool initialized_ = false; StorePtr store_; }; } // namespace snapshot } // namespace engine } // namespace milvus
[ "noreply@github.com" ]
noreply@github.com
825caac265674170f513f5a47679645615354ea3
921c8855a4ed0de4e5b7e4ddf39d630e34f3077a
/release/modules/matlab/src/invert.cpp
dd95998dd17216f275a2688265186edaafc12413
[ "BSD-3-Clause" ]
permissive
chicn/opencv
13085095d4a78f9febea450e25ff9c0e7c63b0bf
12279ab00c280a666d47f9bff22db7d066c43088
refs/heads/master
2021-01-21T06:42:21.738005
2017-02-28T09:47:16
2017-02-28T09:47:16
83,271,812
0
0
null
2017-02-27T05:31:20
2017-02-27T05:31:20
null
UTF-8
C++
false
false
1,943
cpp
/* * file: invert.cpp * author: A trusty code generator * date: Tue, 28 Feb 2017 10:45:57 * * This file was autogenerated, do not modify. * See LICENSE for full modification and redistribution details. * Copyright 2017 The OpenCV Foundation */ #include <string> #include <vector> #include <cassert> #include <exception> #include <opencv2/matlab/bridge.hpp> #include <opencv2/core.hpp> using namespace cv; using namespace matlab; using namespace bridge; /* * invert * double invert(Mat src, Mat dst, int flags=DECOMP_LU); * Gateway routine * nlhs - number of return arguments * plhs - pointers to return arguments * nrhs - number of input arguments * prhs - pointers to input arguments */ void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) { // parse the inputs ArgumentParser parser("invert"); parser.addVariant("invert", 1, 1, "flags"); MxArrayVector sorted = parser.parse(MxArrayVector(prhs, prhs+nrhs)); // setup BridgeVector inputs(sorted.begin(), sorted.end()); BridgeVector outputs(2); // unpack the arguments Mat src = inputs[0].toMat(); int flags = inputs[1].empty() ? (int) DECOMP_LU : inputs[1].toInt(); Mat dst; double retval; // call the opencv function // [out =] namespace.fun(src1, ..., srcn, dst1, ..., dstn, opt1, ..., optn); try { retval = cv::invert(src, dst, flags); } catch(cv::Exception& e) { error(std::string("cv::exception caught: ").append(e.what()).c_str()); } catch(std::exception& e) { error(std::string("std::exception caught: ").append(e.what()).c_str()); } catch(...) { error("Uncaught exception occurred in invert"); } // assign the outputs into the bridge outputs[0] = retval; outputs[1] = dst; // push the outputs back to matlab for (size_t n = 0; n < static_cast<size_t>(std::max(nlhs,1)); ++n) { plhs[n] = outputs[n].toMxArray().releaseOwnership(); } }
[ "chihiros92@suou.waseda.jp" ]
chihiros92@suou.waseda.jp
43279eabaa508fdc506fbb89cc4be8cef4552ffa
8729c3776077a2b232d3f70c303ff464b148a54b
/Classes/Maps.h
7bc25581a825113a50175b372137f7915b61003d
[]
no_license
duyvip1611/StarCollector
4a0dccfa2dc8ce2d42d746b09e95a789d066dfef
d39fb450d59f1856f4a7a430b78486fb91c3065c
refs/heads/master
2022-11-10T20:28:33.145128
2020-06-27T19:48:50
2020-06-27T19:48:50
275,432,464
0
0
null
null
null
null
UTF-8
C++
false
false
682
h
#ifndef __MAPS_H__ #define __MAPS_H__ #include "cocos2d.h" #include "BaseSprite.h" class Maps : public BaseSprite { public: static Maps* create(int ID); virtual bool init(int ID); virtual void createPhysicBody(bool dynamic = true, bool rotationEnable = true); virtual void updateGameObject(float deltaTime, int direction = 0) {} cocos2d::TMXTiledMap* thisMap; cocos2d::Vec2 startPoint; cocos2d::Vec2 starPositions[50]; int starCount; virtual void loadPhysic(const char* layerName, int tagName); cocos2d::Vec2* getObjectsPositions(char* layerName); virtual void onCollisionEnter(Maps* other) {} virtual void onCollisionExit(Maps* other) {} }; #endif // __MAPS_H__
[ "hoangduy.math@gmail.com" ]
hoangduy.math@gmail.com
e0822163e829f68e92b09c51e65a27a866ec7c2d
f12bf9db10dd8c3a50385079928232939c0f2081
/Skeleton/Skeleton/Fence/Fence.cpp
b09ea2bd7863ac0faf67444b2f307100460a43ef
[]
no_license
okmonn/Skeleton
dddd7a9011fe8c1994138ceb87206106e1c14d3f
eeaaa1d7bc94cf149d1df398fae990b6c41cf125
refs/heads/master
2020-04-09T04:24:10.963507
2019-03-12T09:15:58
2019-03-12T09:15:58
160,021,516
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,248
cpp
#include "Fence.h" #include "../Queue/Queue.h" #include "../Release.h" // コンストラクタ Fence::Fence(std::weak_ptr<Queue> queue) : queue(queue), fence(nullptr), handle(CreateEventEx(nullptr, false, false, EVENT_ALL_ACCESS)), cnt(0) { CreateFence(); } // デストラクタ Fence::~Fence() { Release(fence); CloseHandle(handle); } // フェンスの生成 long Fence::CreateFence(void) { auto hr = Dev->CreateFence(cnt, D3D12_FENCE_FLAGS::D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)); if (FAILED(hr)) { OutputDebugString(_T("\nフェンスの生成:失敗\n")); return hr; } cnt = 1; return hr; } // 待機 void Fence::Wait(void) { //フェンス値更新 ++cnt; //フェンス値を変更 auto hr = queue.lock()->Get()->Signal(fence, cnt); if (FAILED(hr)) { OutputDebugString(_T("\nフェンス値の更新:失敗\n")); return; } //完了を待機(ポーリング) while (fence->GetCompletedValue() != cnt) { //フェンスイベントのセット hr = fence->SetEventOnCompletion(cnt, handle); if (FAILED(hr)) { OutputDebugString(_T("\nフェンスイベントのセット:失敗\n")); return; } //フェンスイベントの待機 WaitForSingleObject(handle, INFINITE); } }
[ "34708824+okmonn@users.noreply.github.com" ]
34708824+okmonn@users.noreply.github.com
429c8844fddc9ca52b93972a686333ed14135fef
f500ff2480eda78de8f7a8c944cdb9503704ff05
/hphp/runtime/vm/translator/hopt/tracebuilder.h
8ace4a0f5c7534656d1ceba6d330b5deec6a3d10
[ "PHP-3.01", "LicenseRef-scancode-unknown-license-reference", "Zend-2.0" ]
permissive
rajeshvv/hiphop-php
fe30bd4adc39da559ea70ad6965fe0efb4da8cd7
98466ea3fd8aa6f92b1c1032138321c5a9962407
refs/heads/master
2021-01-15T22:52:42.968377
2013-04-16T02:03:16
2013-04-17T17:12:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,002
h
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #ifndef incl_HHVM_HHIR_TRACEBUILDER_H_ #define incl_HHVM_HHIR_TRACEBUILDER_H_ #include <boost/scoped_ptr.hpp> #include "runtime/vm/translator/hopt/ir.h" #include "runtime/vm/translator/hopt/irfactory.h" #include "runtime/vm/translator/hopt/cse.h" #include "runtime/vm/translator/hopt/simplifier.h" #include "folly/ScopeGuard.h" namespace HPHP { namespace VM { namespace JIT { class TraceBuilder { public: TraceBuilder(Offset initialBcOffset, uint32_t initialSpOffsetFromFp, IRFactory&, const Func* func); ~TraceBuilder(); void setEnableCse(bool val) { m_enableCse = val; } void setEnableSimplification(bool val) { m_enableSimplification = val; } Trace* makeExitTrace(uint32_t bcOff) { return m_trace->addExitTrace(makeTrace(m_curFunc->getValFunc(), bcOff)); } bool isThisAvailable() const { return m_thisIsAvailable; } void setThisAvailable() { m_thisIsAvailable = true; } void dropLocalRefsInnerTypes(); // Run one more pass of simplification on this builder's trace. void optimizeTrace(); SSATmp* getFP() { return m_fpValue; } /* * Create an IRInstruction attached to this Trace, and allocate a * destination SSATmp for it. Uses the same argument list format as * IRFactory::gen. */ template<class... Args> SSATmp* gen(Args... args) { return makeInstruction( [this] (IRInstruction* inst) { return optimizeInst(inst); }, args... ); } template<class... Args> IRInstruction* genFor(Trace* t, Args... args) { auto instr = m_irFactory.gen(args...); t->back()->push_back(instr); return instr; } SSATmp* genDefCns(const StringData* cnsName, SSATmp* val); SSATmp* genConcat(SSATmp* tl, SSATmp* tr); void genDefCls(PreClass*, const HPHP::VM::Opcode* after); void genDefFunc(Func*); SSATmp* genLdThis(Trace* trace); SSATmp* genLdCtx(const Func* func); SSATmp* genLdRetAddr(); SSATmp* genLdRaw(SSATmp* base, RawMemSlot::Kind kind, Type type); void genStRaw(SSATmp* base, RawMemSlot::Kind kind, SSATmp* value); SSATmp* genLdLoc(uint32_t id); SSATmp* genLdLocAddr(uint32_t id); void genRaiseUninitLoc(uint32_t id); /* * Returns an SSATmp containing the (inner) value of the given local. * If the local is a boxed value, this returns its inner value. * * Note: For boxed values, this will generate a LdRef instruction which * takes the given exit trace in case the inner type doesn't match * the tracked type for this local. This check may be optimized away * if we can determine that the inner type must match the tracked type. */ SSATmp* genLdLocAsCell(uint32_t id, Trace* exitTrace); /* * Asserts that local 'id' has type 'type' and loads it into the * returned SSATmp. */ SSATmp* genLdAssertedLoc(uint32_t id, Type type); SSATmp* genStLoc(uint32_t id, SSATmp* src, bool doRefCount, bool genStoreType, Trace* exit); SSATmp* genLdMem(SSATmp* addr, Type type, Trace* target); SSATmp* genLdMem(SSATmp* addr, int64_t offset, Type type, Trace* target); void genStMem(SSATmp* addr, SSATmp* src, bool genStoreType); void genStMem(SSATmp* addr, int64_t offset, SSATmp* src, bool stType); SSATmp* genLdProp(SSATmp* obj, SSATmp* prop, Type type, Trace* exit); void genStProp(SSATmp* obj, SSATmp* prop, SSATmp* src, bool genStoreType); void genSetPropCell(SSATmp* base, int64_t offset, SSATmp* value); SSATmp* genBoxLoc(uint32_t id); void genBindLoc(uint32_t id, SSATmp* ref, bool doRefCount = true); void genInitLoc(uint32_t id, SSATmp* t); void genCheckClsCnsDefined(SSATmp* cns, Trace* exitTrace); SSATmp* genLdCurFuncPtr(); SSATmp* genLdARFuncPtr(SSATmp* baseAddr, SSATmp* offset); SSATmp* genLdFuncCls(SSATmp* func); SSATmp* genNewObjNoCtorCached(const StringData* className); SSATmp* genNewObjCached(int32_t numParams, const StringData* clsName); SSATmp* genNewObj(int32_t numParams, SSATmp* cls); SSATmp* genNewArray(int32_t capacity); SSATmp* genNewTuple(int32_t numArgs, SSATmp* sp); SSATmp* genDefActRec(SSATmp* func, SSATmp* objOrClass, int32_t numArgs, const StringData* invName); SSATmp* genFreeActRec(); void genGuardLoc(uint32_t id, Type type, Trace* exitTrace); void genGuardStk(uint32_t id, Type type, Trace* exitTrace); void genAssertStk(uint32_t id, Type type); SSATmp* genGuardType(SSATmp* src, Type type, Trace* nextTrace); void genGuardRefs(SSATmp* funcPtr, SSATmp* nParams, SSATmp* bitsPtr, SSATmp* firstBitNum, SSATmp* mask64, SSATmp* vals64, Trace* exitTrace); void genAssertLoc(uint32_t id, Type type, bool override = false); // ignores conflict w/ prev type SSATmp* genUnboxPtr(SSATmp* ptr); SSATmp* genLdRef(SSATmp* ref, Type type, Trace* exit); SSATmp* genAdd(SSATmp* src1, SSATmp* src2); SSATmp* genLdAddr(SSATmp* base, int64_t offset); SSATmp* genSub(SSATmp* src1, SSATmp* src2); SSATmp* genMul(SSATmp* src1, SSATmp* src2); SSATmp* genAnd(SSATmp* src1, SSATmp* src2); SSATmp* genOr(SSATmp* src1, SSATmp* src2); SSATmp* genXor(SSATmp* src1, SSATmp* src2); SSATmp* genNot(SSATmp* src); SSATmp* genDefUninit(); SSATmp* genDefInitNull(); SSATmp* genDefNull(); SSATmp* genPtrToInitNull(); SSATmp* genPtrToUninit(); SSATmp* genDefNone(); SSATmp* genJmp(Trace* target); SSATmp* genJmpCond(SSATmp* src, Trace* target, bool negate); void genJmp(Block* target, SSATmp* src); void genExitWhenSurprised(Trace* target); void genExitOnVarEnv(Trace* target); void genCheckInit(SSATmp* src, Trace* target) { gen(CheckInit, getFirstBlock(target), src); } SSATmp* genCmp(Opcode opc, SSATmp* src1, SSATmp* src2); SSATmp* genCastStk(uint32_t id, Type type); SSATmp* genConvToBool(SSATmp* src); SSATmp* genConvToDbl(SSATmp* src); SSATmp* genConvToStr(SSATmp* src); SSATmp* genConvToArr(SSATmp* src); SSATmp* genConvToObj(SSATmp* src); SSATmp* genLdPropAddr(SSATmp* obj, SSATmp* prop); SSATmp* genLdClsMethod(SSATmp* cls, uint32_t methodSlot); SSATmp* genLdClsMethodCache(SSATmp* className, SSATmp* methodName, SSATmp* baseClass, Trace* slowPathExit); SSATmp* genCall(SSATmp* actRec, uint32_t returnBcOffset, SSATmp* func, uint32_t numParams, SSATmp** params); SSATmp* genCallBuiltin(SSATmp* func, Type type, uint32_t numArgs, SSATmp** args); void genReleaseVVOrExit(Trace* exit); SSATmp* genGenericRetDecRefs(SSATmp* retVal, int numLocals); void genRetVal(SSATmp* val); SSATmp* genRetAdjustStack(); void genRetCtrl(SSATmp* sp, SSATmp* fp, SSATmp* retAddr); void genDecRef(SSATmp* tmp); void genDecRefMem(SSATmp* base, int64_t offset, Type type); void genDecRefStack(Type type, uint32_t stackOff); void genDecRefLoc(int id); void genDecRefThis(); void genIncStat(int32_t counter, int32_t value, bool force = false); SSATmp* genIncRef(SSATmp* src); SSATmp* genSpillStack(uint32_t stackAdjustment, uint32_t numOpnds, SSATmp** opnds); SSATmp* genLdStack(int32_t stackOff, Type type); SSATmp* genDefFP(); SSATmp* genDefSP(int32_t spOffset); SSATmp* genLdStackAddr(SSATmp* sp, int64_t offset); SSATmp* genLdStackAddr(int64_t offset) { return genLdStackAddr(m_spValue, offset); } void genNativeImpl(); void genUnlinkContVarEnv(); void genLinkContVarEnv(); Trace* genContRaiseCheck(SSATmp* cont, Trace* target); Trace* genContPreNext(SSATmp* cont, Trace* target); Trace* genContStartedCheck(SSATmp* cont, Trace* target); SSATmp* genIterInit(SSATmp* src, uint32_t iterId, uint32_t valLocalId); SSATmp* genIterInitK(SSATmp* src, uint32_t iterId, uint32_t valLocalId, uint32_t keyLocalId); SSATmp* genIterNext(uint32_t iterId, uint32_t valLocalId); SSATmp* genIterNextK(uint32_t iterId, uint32_t valLocalId, uint32_t keyLocalId); SSATmp* genIterFree(uint32_t iterId); SSATmp* genInterpOne(uint32_t pcOff, uint32_t stackAdjustment, Type resultType); Trace* getExitSlowTrace(uint32_t bcOff, int32_t stackDeficit, uint32_t numOpnds, SSATmp** opnds); /* * Generates a trace exit that can be the target of a conditional * or unconditional control flow instruction from the main trace. * * Lifetime of the returned pointer is managed by the trace this * TraceBuilder is generating. */ typedef std::function<void(IRFactory*, Trace*)> ExitTraceCallback; Trace* genExitTrace(uint32_t bcOff, int32_t stackDeficit, uint32_t numOpnds, SSATmp* const* opnds, TraceExitType::ExitType, uint32_t notTakenBcOff = 0, ExitTraceCallback beforeExit = ExitTraceCallback()); /* * Generates a target exit trace for GuardFailure exits. * * Lifetime of the returned pointer is managed by the trace this * TraceBuilder is generating. */ Trace* genExitGuardFailure(uint32_t off); // generates the ExitTrace instruction at the end of a trace void genTraceEnd(uint32_t nextPc, TraceExitType::ExitType exitType = TraceExitType::Normal); template<typename T> SSATmp* genDefConst(T val) { ConstData cdata(val); return gen(DefConst, typeForConst(val), &cdata); } template<typename T> SSATmp* genDefConst(T val, Type type) { ConstData cdata(val); return gen(DefConst, type, &cdata); } template<typename T> SSATmp* genLdConst(T val) { ConstData cdata(val); return gen(LdConst, typeForConst(val), &cdata); } Trace* getTrace() const { return m_trace.get(); } IRFactory* getIrFactory() { return &m_irFactory; } int32_t getSpOffset() { return m_spOffset; } SSATmp* getSp() const { return m_spValue; } SSATmp* getFp() const { return m_fpValue; } Type getLocalType(unsigned id) const; Block* getFirstBlock(Trace* trace) { return trace ? trace->front() : nullptr; } // hint the execution frequency of the current block void hint(Block::Hint h) const { m_trace->back()->setHint(h); } struct DisableCseGuard { DisableCseGuard(TraceBuilder& tb) : m_tb(tb) , m_oldEnable(tb.m_enableCse) { m_tb.m_enableCse = false; } ~DisableCseGuard() { m_tb.m_enableCse = m_oldEnable; } private: TraceBuilder& m_tb; bool m_oldEnable; }; /* * cond() generates if-then-else blocks within a trace. The caller * supplies lambdas to create the branch, next-body, and taken-body. * The next and taken lambdas must return one SSATmp* value; cond() returns * the SSATmp for the merged value. */ template <class Branch, class Next, class Taken> SSATmp* cond(const Func* func, Branch branch, Next next, Taken taken) { Block* taken_block = m_irFactory.defBlock(func); Block* done_block = m_irFactory.defBlock(func, 1); DisableCseGuard guard(*this); branch(taken_block); SSATmp* v1 = next(); genJmp(done_block, v1); appendBlock(taken_block); SSATmp* v2 = taken(); genJmp(done_block, v2); appendBlock(done_block); SSATmp* result = done_block->getLabel()->getDst(0); result->setType(Type::unionOf(v1->getType(), v2->getType())); return result; } /* * ifThen generates if-then blocks within a trace that do not * produce values. Code emitted in the taken lambda will be executed * iff the branch emitted in the branch lambda is taken. */ template <class Branch, class Taken> void ifThen(const Func* func, Branch branch, Taken taken) { Block* taken_block = m_irFactory.defBlock(func); Block* done_block = m_irFactory.defBlock(func); DisableCseGuard guard(*this); branch(taken_block); assert(!m_trace->back()->getNext()); m_trace->back()->setNext(done_block); appendBlock(taken_block); taken(); taken_block->setNext(done_block); appendBlock(done_block); } /* * ifThenExit produces a conditional exit with user-supplied logic * if the exit is taken. */ Trace* ifThenExit(const Func* func, int stackDeficit, const std::vector<SSATmp*> &stackValues, ExitTraceCallback exit, Offset exitBcOff, Offset bcOff) { return genExitTrace(exitBcOff, stackDeficit, stackValues.size(), stackValues.size() ? &stackValues[0] : nullptr, TraceExitType::NormalCc, bcOff /* notTakenOff */, exit); } /* * ifElse generates if-then-else blocks with an empty 'then' block * that do not produce values. Code emitted in the next lambda will * be executed iff the branch emitted in the branch lambda is not * taken. */ template <class Branch, class Next> void ifElse(const Func* func, Branch branch, Next next) { Block* done_block = m_irFactory.defBlock(func); DisableCseGuard guard(*this); branch(done_block); next(); m_trace->back()->setNext(done_block); appendBlock(done_block); } private: static void appendInstruction(IRInstruction* inst, Block* block); void appendInstruction(IRInstruction* inst); void appendBlock(Block* block); enum CloneInstMode { kCloneInst, kUseInst }; SSATmp* optimizeWork(IRInstruction* inst); SSATmp* optimizeInst(IRInstruction* inst); SSATmp* cseLookup(IRInstruction* inst); void cseInsert(IRInstruction* inst); void cseKill(SSATmp* src); CSEHash* getCSEHashTable(IRInstruction* inst); void killCse(); void killLocals(); void killLocalValue(uint32_t id); void setLocalValue(unsigned id, SSATmp* value); void setLocalType(uint32_t id, Type type); SSATmp* getLocalValue(unsigned id) const; bool isValueAvailable(SSATmp* tmp) const; bool anyLocalHasValue(SSATmp* tmp) const; void updateLocalRefValues(SSATmp* oldRef, SSATmp* newRef); void updateTrackedState(IRInstruction* inst); void clearTrackedState(); Trace* makeTrace(const Func* func, uint32_t bcOff) { return new Trace(m_irFactory.defBlock(func), bcOff); } void genStLocAux(uint32_t id, SSATmp* t0, bool genStoreType); // saved state information associated with the start of a block struct State { SSATmp *spValue, *fpValue; int32_t spOffset; bool thisAvailable; std::vector<SSATmp*> localValues; std::vector<Type> localTypes; SSATmp* refCountedMemValue; }; void saveState(Block*); void mergeState(State* s1); void useState(Block*); /* * Fields */ IRFactory& m_irFactory; Simplifier m_simplifier; Offset const m_initialBcOff; // offset of initial bytecode in trace boost::scoped_ptr<Trace> const m_trace; // generated trace // Flags that enable optimizations bool m_enableCse; bool m_enableSimplification; // Snapshots of state at the beginning of blocks we haven't reached yet. StateVector<Block,State*> m_snapshots; /* * While building a trace one instruction at a time, a TraceBuilder * tracks various state for generating code and for optimization: * * (1) m_fpValue & m_spValue track which SSATmp holds the current VM * frame and stack pointer values. * * (2) m_spOffset tracks the offset of the m_spValue from m_fpValue. * * (3) m_curFunc tracks the current function containing the * generated code; currently, this remains constant during * tracebuilding but once we implement inlining it'll have to * be updated to track the context of inlined functions. * * (4) m_cseHash is for common sub-expression elimination of non-constants. * constants are globally available and managed by IRFactory. * * (5) m_thisIsAvailable tracks whether the current ActRec has a * non-null this pointer. * * (6) m_localValues & m_localTypes track the current values and * types held in locals. These vectors are indexed by the * local's id. * * The function updateTrackedState(IRInstruction* inst) updates this * state (called after an instruction is appended to the trace), and * the function clearTrackedState() clears it. * * After branch instructions, updateTrackedState() creates an instance * of State holding snapshots of these fields (except m_curFunc and * m_constTable), optionally merges with the State already saved at * the branch target, and saves it. Then, before generating code for * the branch target, useState() restores the saved (and merged) state. */ SSATmp* m_spValue; // current physical sp SSATmp* m_fpValue; // current physical fp int32_t m_spOffset; // offset of physical sp from physical fp SSATmp* m_curFunc; // current function context CSEHash m_cseHash; bool m_thisIsAvailable; // true only if current ActRec has non-null this // state of values in memory SSATmp* m_refCountedMemValue; // vectors that track local values & types std::vector<SSATmp*> m_localValues; std::vector<Type> m_localTypes; }; template<> inline SSATmp* TraceBuilder::genDefConst(Type t) { ConstData cdata(0); return gen(DefConst, t, &cdata); } }}} #endif
[ "sgolemon@fb.com" ]
sgolemon@fb.com
f16c54bf0067b9b79a6b37cab95b1b4b87300a65
7634551875312f26ce2fa08701f798bd299aade7
/tests/whitebox/dns/wb_nresolver.cc
7aafd44b6259d022fada6cd1ce734b1bc6c2d572
[ "Apache-2.0" ]
permissive
dev0z/is2
ed6d3338f597f940ea90e5c679a6ad6d1309793e
401501b930d349ddde5c32a33f9620f16514cb9d
refs/heads/master
2020-04-23T18:18:03.413189
2019-02-18T21:55:05
2019-02-18T21:55:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,396
cc
//: ---------------------------------------------------------------------------- //: Copyright (C) 2018 Verizon. All Rights Reserved. //: All Rights Reserved //: //: \file: wb_nresolver.cc //: \details: TODO //: \author: Reed P. Morrison //: \date: 09/30/2015 //: //: 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. //: //: ---------------------------------------------------------------------------- //: ---------------------------------------------------------------------------- //: Includes //: ---------------------------------------------------------------------------- #include "hurl/nconn/host_info.h" #include "hurl/dns/nresolver.h" #include "hurl/dns/ai_cache.h" #include "hurl/support/time_util.h" #include "catch/catch.hpp" #include <unistd.h> #include <sys/poll.h> //: ---------------------------------------------------------------------------- //: Constants //: ---------------------------------------------------------------------------- #define GOOD_DATA_VALUE_1 0xDEADBEEFDEADBEEFUL #define GOOD_DATA_VALUE_2 0xDEADBEEFDEADBEEEUL #define BAD_DATA_VALUE_1 0xDEADBEEFDEADF154UL #define BAD_DATA_VALUE_2 0xDEADBEEFDEADF155UL //: ---------------------------------------------------------------------------- //: Globals //: ---------------------------------------------------------------------------- static uint32_t g_dns_reqs_qd = 0; static uint32_t g_lkp_sucess = 0; static uint32_t g_lkp_fail = 0; static uint32_t g_lkp_err = 0; //: ---------------------------------------------------------------------------- //: Test helpers //: ---------------------------------------------------------------------------- int32_t test_resolved_cb(const ns_hurl::host_info *a_host_info, void *a_data) { --g_dns_reqs_qd; //printf("DEBUG: test_resolved_cb: a_host_info: %p a_data: %p g_dns_reqs_qd: %d\n", a_host_info, a_data, g_dns_reqs_qd); if(a_host_info && ((a_data == (void *)(GOOD_DATA_VALUE_1)) || (a_data == (void *)(GOOD_DATA_VALUE_2)))) { ++g_lkp_sucess; } else if(!a_host_info && ((a_data == (void *)(BAD_DATA_VALUE_1)) || (a_data == (void *)(BAD_DATA_VALUE_2)))) { ++g_lkp_fail; } else { ++g_lkp_err; } return 0; } //: ---------------------------------------------------------------------------- //: Get cache key //: ---------------------------------------------------------------------------- TEST_CASE( "get cache key", "[get_cache_key]" ) { SECTION("Verify get cache key") { std::string l_host = "google.com"; uint16_t l_port = 7868; std::string l_label = ns_hurl::get_cache_key(l_host, l_port); REQUIRE((l_label == "google.com:7868")); } } //: ---------------------------------------------------------------------------- //: nresolver //: ---------------------------------------------------------------------------- TEST_CASE( "nresolver test", "[nresolver]" ) { SECTION("Validate No cache") { ns_hurl::nresolver *l_nresolver = new ns_hurl::nresolver(); l_nresolver->init(false, ""); ns_hurl::host_info l_host_info; int32_t l_status; l_status = l_nresolver->lookup_tryfast("google.com", 80, l_host_info); REQUIRE(( l_status == -1 )); l_status = l_nresolver->lookup_sync("google.com", 80, l_host_info); REQUIRE(( l_status == 0 )); l_status = l_nresolver->lookup_tryfast("google.com", 80, l_host_info); REQUIRE(( l_status == -1 )); bool l_use_cache = l_nresolver->get_use_cache(); ns_hurl::ai_cache *l_ai_cache = l_nresolver->get_ai_cache(); REQUIRE(( l_use_cache == false )); REQUIRE(( l_ai_cache == NULL )); delete l_nresolver; } SECTION("Validate cache") { ns_hurl::nresolver *l_nresolver = new ns_hurl::nresolver(); l_nresolver->init(true); ns_hurl::host_info l_host_info; int32_t l_status; l_status = l_nresolver->lookup_sync("google.com", 80, l_host_info); REQUIRE(( l_status == 0 )); l_status = l_nresolver->lookup_sync("yahoo.com", 80, l_host_info); REQUIRE(( l_status == 0 )); l_status = l_nresolver->lookup_tryfast("yahoo.com", 80, l_host_info); REQUIRE(( l_status == 0 )); l_status = l_nresolver->lookup_tryfast("google.com", 80, l_host_info); REQUIRE(( l_status == 0 )); bool l_use_cache = l_nresolver->get_use_cache(); ns_hurl::ai_cache *l_ai_cache = l_nresolver->get_ai_cache(); REQUIRE(( l_use_cache == true )); REQUIRE(( l_ai_cache != NULL )); delete l_nresolver; } #ifdef ASYNC_DNS_SUPPORT // --------------------------------------------------------------------- // TODO: Quarantining flaky test... // --------------------------------------------------------------------- #if 0 SECTION("Validate async") { ns_hurl::nresolver *l_nresolver = new ns_hurl::nresolver(); l_nresolver->add_resolver_host("8.8.8.8"); l_nresolver->set_retries(1); l_nresolver->set_timeout_s(1); // Set up poller // TODO ns_hurl::nresolver::adns_ctx *l_adns_ctx = NULL; l_adns_ctx = l_nresolver->get_new_adns_ctx(NULL, test_resolved_cb); REQUIRE((l_adns_ctx != NULL)); uint64_t l_active; ns_hurl::nresolver::lookup_job_q_t l_lookup_job_q; ns_hurl::nresolver::lookup_job_pq_t l_lookup_job_pq; int32_t l_status = 0; void *l_job_handle = NULL; // Set globals g_lkp_sucess = 0; g_lkp_fail = 0; g_lkp_err = 0; // Good ++g_dns_reqs_qd; l_status = l_nresolver->lookup_async(l_adns_ctx, "google.com", 80, (void *)(GOOD_DATA_VALUE_1), l_active, &l_job_handle); REQUIRE((l_status == 0)); // Good ++g_dns_reqs_qd; l_status = l_nresolver->lookup_async(l_adns_ctx, "yahoo.com", 80, (void *)(GOOD_DATA_VALUE_2), l_active, &l_job_handle); REQUIRE((l_status == 0)); // Bad ++g_dns_reqs_qd; l_status = l_nresolver->lookup_async(l_adns_ctx, "arfarhfarfbloop", 9874, test_resolved_cb, (void *)(BAD_DATA_VALUE_1), l_active, l_lookup_job_q, l_lookup_job_pq, &l_job_handle); REQUIRE((l_status == 0)); // Bad ++g_dns_reqs_qd; l_status = l_nresolver->lookup_async(l_adns_ctx, "wonbaombaboiuiuiuoad.com", 80, (void *)(BAD_DATA_VALUE_2), l_active, &l_job_handle); REQUIRE((l_status == 0)); uint32_t l_timeout_s = 5; uint64_t l_start_s = ns_hurl::get_time_s(); while(g_dns_reqs_qd && ((ns_hurl::get_time_s()) < (l_start_s + l_timeout_s))) { int l_count; l_count = poll(&l_pfd, 1, 1*1000); (void) l_count; l_status = l_nresolver->handle_io(l_ctx); std::string l_unused; l_status = l_nresolver->lookup_async(l_ctx, l_unused, 0, test_resolved_cb, NULL, l_active, l_lookup_job_q, l_lookup_job_pq, &l_job_handle); REQUIRE((l_status == 0)); if(g_dns_reqs_qd == 0) { break; } } uint64_t l_end_s = ns_hurl::get_time_s(); INFO("l_end_s: " << l_end_s) INFO("l_start_s: " << l_start_s) INFO("l_timeout_s: " << l_timeout_s) INFO("g_dns_reqs_qd: " << g_dns_reqs_qd) //REQUIRE((l_end_s >= (l_start_s + l_timeout_s))); if((l_end_s >= (l_start_s + l_timeout_s))) { // Handle timeouts } //printf("DEBUG: outtie\n"); INFO("g_lkp_sucess: " << g_lkp_sucess) REQUIRE((g_lkp_sucess == 2)); INFO("g_lkp_fail: " << g_lkp_fail) REQUIRE((g_lkp_fail == 2)); INFO("g_lkp_err: " << g_lkp_err) REQUIRE((g_lkp_err == 0)); l_nresolver->destroy_async(l_adns_ctx); delete l_nresolver; } #endif // --------------------------------------------------------------------- // TODO: Quarantining flaky test... // --------------------------------------------------------------------- #if 0 SECTION("Validate async -bad resolver") { ns_hurl::nresolver *l_nresolver = new ns_hurl::nresolver(); // --------------------------------------------------- // Set resolver to something far and slow hopefully? // grabbed hong kong one from: // http://public-dns.tk/nameserver/hk.html // --------------------------------------------------- l_nresolver->add_resolver_host("210.0.128.242"); l_nresolver->set_port(6969); l_nresolver->set_retries(1); l_nresolver->set_timeout_s(1); // Set up poller // TODO ns_hurl::nresolver::adns_ctx *l_adns_ctx = NULL; l_adns_ctx = l_nresolver->get_new_adns_ctx(NULL, test_resolved_cb); REQUIRE((l_adns_ctx != NULL)); uint64_t l_active; int32_t l_status = 0; void *l_job_handle = NULL; // Set globals g_lkp_sucess = 0; g_lkp_fail = 0; g_lkp_err = 0; // Good ++g_dns_reqs_qd; l_status = l_nresolver->lookup_async(l_adns_ctx, "google.com", 80, (void *)(BAD_DATA_VALUE_1), l_active, &l_job_handle); REQUIRE((l_status == 0)); // Good ++g_dns_reqs_qd; l_status = l_nresolver->lookup_async(l_adns_ctx, "yahoo.com", 80, (void *)(BAD_DATA_VALUE_2), l_active, &l_job_handle); REQUIRE((l_status == 0)); // Bad ++g_dns_reqs_qd; l_status = l_nresolver->lookup_async(l_adns_ctx, "arfarhfarfbloop", 9874, (void *)(BAD_DATA_VALUE_1), l_active, &l_job_handle); REQUIRE((l_status == 0)); // Bad ++g_dns_reqs_qd; l_status = l_nresolver->lookup_async(l_adns_ctx, "wonbaombaboiuiuiuoad.com", 80, (void *)(BAD_DATA_VALUE_2), l_active, &l_job_handle); REQUIRE((l_status == 0)); uint32_t l_timeout_s = 5; uint64_t l_start_s = ns_hurl::get_time_s(); while(g_dns_reqs_qd && ((ns_hurl::get_time_s()) < (l_start_s + l_timeout_s))) { int l_count; l_count = poll(&l_pfd, 1, 1*1000); (void) l_count; //printf("DEBUG: poll: %d\n", l_count); l_status = l_nresolver->handle_io(l_ctx); std::string l_unused; l_status = l_nresolver->lookup_async(l_adns_ctx, l_unused, 0, NULL, l_active, &l_job_handle); REQUIRE((l_status == 0)); if(g_dns_reqs_qd == 0) { break; } } uint64_t l_end_s = ns_hurl::get_time_s(); INFO("l_end_s: " << l_end_s) INFO("l_start_s: " << l_start_s) INFO("l_timeout_s: " << l_timeout_s) INFO("g_dns_reqs_qd: " << g_dns_reqs_qd) //REQUIRE((l_end_s >= (l_start_s + l_timeout_s))); if((l_end_s >= (l_start_s + l_timeout_s))) { // Handle timeouts } //printf("DEBUG: outtie\n"); INFO("g_lkp_sucess: " << g_lkp_sucess) REQUIRE((g_lkp_sucess == 0)); INFO("g_lkp_fail: " << g_lkp_fail) REQUIRE((g_lkp_fail == 4)); INFO("g_lkp_err: " << g_lkp_err) REQUIRE((g_lkp_err == 0)); l_nresolver->destroy_async(l_adns_ctx); delete l_nresolver; } #endif #endif }
[ "reed.morrison@verizondigitalmedia.com" ]
reed.morrison@verizondigitalmedia.com
d59e507c85e7985caefa58e2f4b00c7d44af016d
c2122daa243688a497dbc87dfc9f489f09d11677
/quadcopter/application_code/drone_altitude_controller.hpp
8af71830634407b137527ea96cce4555656d0de2
[]
no_license
capslockqq/quadcopter_esp32
90f960e16c2a1c74ac218b85593c0260003061ee
70b2d100ecabfe8436322958af11614c2fca00a6
refs/heads/master
2020-12-01T15:35:54.575230
2020-01-06T22:20:23
2020-01-06T22:20:23
230,683,656
1
0
null
null
null
null
UTF-8
C++
false
false
411
hpp
#pragma once #include "../../component_framework/components/Component.hpp" #include "../../component_framework/components/Input.hpp" #include "../../component_framework/components/Output.hpp" class Drone_Altitude_Controller : public Component { public: Drone_Altitude_Controller(Component *parent, const char* name, const char* id); virtual ~Drone_Altitude_Controller(); void Update(); };
[ "emil@LAPTOP-HMHI1QGV.localdomain" ]
emil@LAPTOP-HMHI1QGV.localdomain
ce747c2d3c6d5ae0c480c697d5a66840a6859721
8eca20d5f941200ea2a42368fec81d2bcf5e6663
/lab1/Zad3/main.cpp
f43804e808fbc3febb2a671960930561c9e4b07c
[ "MIT" ]
permissive
fgulan/ooup-fer
47f9be0f88db2b38eec3ece86919164989d33982
f5df4ba2ab55e52c7475089b4f71c0e244e88162
refs/heads/master
2021-04-28T18:48:36.600209
2018-02-17T18:42:38
2018-02-17T18:42:38
121,881,913
0
0
null
null
null
null
UTF-8
C++
false
false
572
cpp
// // main.cpp // Zad3 // // Created by Filip Gulan on 27/03/16. // Copyright © 2016 FIlip Gulan. All rights reserved. // #include <iostream> class CoolClass { public: virtual void set(int x) { x_=x; }; virtual int get() { return x_; }; private: int x_; }; class PlainOldClass { public: void set(int x){x_=x;}; int get(){return x_;}; private: int x_; }; int main(int argc, const char * argv[]) { printf("CoolClas : %ld\nPlainOldClass : %ld\n", sizeof(CoolClass), sizeof(PlainOldClass)); return 0; }
[ "filip.gulan@infinum.hr" ]
filip.gulan@infinum.hr
db9a384e40a9a22561c6b2012586d5204e91c482
f0556fbb206661c333277cfaacbd14418dbb29d8
/MyList/moc_mylist.cpp
79100265cfe930678524c2c2656273420c01ebf9
[]
no_license
Usman-Sheik/MY14
878699b031bc40f24212fb7c6a883ea321d5a8fa
ed344b0bb233719f82d32a6d60705e24337c2d43
refs/heads/master
2021-05-26T12:33:31.231103
2012-01-04T13:47:32
2012-01-04T13:47:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,464
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'mylist.h' ** ** Created: Mon Dec 26 19:18:41 2011 ** by: The Qt Meta Object Compiler version 62 (Qt 4.7.4) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "mylist.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'mylist.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.7.4. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_MyLIst[] = { // content: 5, // revision 0, // classname 0, 0, // classinfo 3, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: signature, parameters, type, tag, flags 8, 7, 7, 7, 0x0a, 24, 7, 7, 7, 0x0a, 33, 7, 7, 7, 0x0a, 0 // eod }; static const char qt_meta_stringdata_MyLIst[] = { "MyLIst\0\0addElement(int)\0remove()\0" "displayList()\0" }; const QMetaObject MyLIst::staticMetaObject = { { &QObject::staticMetaObject, qt_meta_stringdata_MyLIst, qt_meta_data_MyLIst, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &MyLIst::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *MyLIst::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *MyLIst::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_MyLIst)) return static_cast<void*>(const_cast< MyLIst*>(this)); return QObject::qt_metacast(_clname); } int MyLIst::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: addElement((*reinterpret_cast< int(*)>(_a[1]))); break; case 1: remove(); break; case 2: displayList(); break; default: ; } _id -= 3; } return _id; } QT_END_MOC_NAMESPACE
[ "usmanabu314@gmail.com" ]
usmanabu314@gmail.com
716591feb213ddd4bd13cc78f4ea2f7797c581ed
ac5af4b30a50073c825bc966009bef147c930fa0
/AtCoder/abc052_b.cpp
eaf1ed0f5ab0c16e4d66644fc2ebfa7fa67ab9ec
[]
no_license
ism-k/compro
65e1acb842b742edc5cea75c67ea5eb01859192c
32e1661b7b739ed449b21d0ad7e99bce8e2e0d0b
refs/heads/master
2020-03-15T07:49:12.652173
2019-12-15T10:30:19
2019-12-15T10:30:19
132,037,711
0
0
null
null
null
null
UTF-8
C++
false
false
579
cpp
#include <iostream> #include <bitset> #include <string> #include <algorithm> #include <cmath> #include <vector> using namespace std; #define REP(i,n) for(int i=0;i<n;i++) int main() { int N; cin >> N; string S; cin >> S; int x = 0; int max_x = 0;; for(int i = 0; i < S.size(); i++) { if (S[i] == 'I') { x++; if (max_x < x) { max_x = x; } } else if (S[i] == 'D') { x--; } } cout << max_x << endl; }
[ "kusunoki.iz@dsp.cse.kyutech.ac.jp" ]
kusunoki.iz@dsp.cse.kyutech.ac.jp
fd5b97c02b000744b2a5e007f1e6410dec88ae02
8741a8e1fa4c910f47c1246fd11411fa36029578
/MySolution/Project/DataSet/Source/NBlobField.cpp
4b2f34830740b5d770d47b86fb019b02205dca72
[]
no_license
liwenlang/MyMFC
36b38198908c712fa366b24baeefa0f70825d874
2fb1ccddbdd57de8585f55adc486859e240532a5
refs/heads/master
2023-02-26T01:08:09.172756
2021-01-27T09:19:22
2021-01-27T09:19:22
268,955,339
0
0
null
null
null
null
GB18030
C++
false
false
6,792
cpp
// NBlobField.cpp: implementation of the NBlobField class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "NBlobField.h" #include "NDataModelDataSet.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// NBlobField::NBlobField(void *pOwner): NDataField(pOwner) { SetDataType(ftBlob); SetSize(sizeof(void*) + sizeof(long)); //m_isBlobFiled = TRUE; } NBlobField::~NBlobField() { } long NBlobField::GetBlob(const void *pRowbufferOffset,void *&pBlob) { //void *ptr; long iSize; CopyMemory(&iSize,(char*)(pRowbufferOffset)+sizeof(void*),sizeof(long)); CopyMemory(&pBlob,pRowbufferOffset,sizeof(void*)); return iSize; } BOOL NBlobField::SetBlob(void *pRowbufferOffset,void *pBlob,long iBlockSize,BOOL alloOrigValueBuff) { void *ptr = NULL; if(iBlockSize >0 ) { ptr = new char[iBlockSize]; memcpy(ptr,pBlob,(UINT)iBlockSize); } return SetBolbData(pRowbufferOffset, ptr, iBlockSize,alloOrigValueBuff); } /*void NBlobField::FreeBolbData(void *pRowbufferOffset) { void *ptr; //long iSize; //CopyMemory(&iSize,(char*)(pRowbufferOffset)+sizeof(void*),sizeof(long)); CopyMemory(&ptr,pRowbufferOffset,sizeof(void*)); if (ptr != NULL) { delete [](char*)ptr; } //将指针清空 memset(pRowbufferOffset,0,GetSize()); }*/ BOOL NBlobField::SetAsString(const CString & val,void *buffer) { // return SetBlob(buffer,val.GetBuffer(0),val.GetLength()*sizeof(_TCHAR) /*+ 1*/); return SetBlob(buffer,(LPVOID)(LPCTSTR)val,val.GetLength()*sizeof(_TCHAR) /*+ 1*/); //考虑了GetAsString 时的采用GetBufferSetLength函数,大字段中不在保存结束字符窜 \0 } CString NBlobField::GetAsString(const void *buffer) { if(IsUpdateAsBlobFiled()) { CString strErrMsg; strErrMsg.Format(_T("NBlobField::GetAsString 取值错误,大字段不能使用GetAsString %s"),this->GetFieldName()); CDataSetErrorInfo::Instance()->PrintInfo(strErrMsg,CDataSetErrorInfo::DataSetError); return _T(""); } void *pBlob; UINT iSize = GetBlob(buffer,pBlob); CString sResult; if (iSize >0) { LPTSTR pTembuffer = sResult.GetBufferSetLength(iSize/sizeof(_TCHAR)); //memset(buffer,iSize + 1,0); memcpy(pTembuffer,pBlob,iSize); //int test = sResult.GetLength(); } //sResult = (char*)pBlob; return sResult; } int NBlobField::CompareValue(const void * pData1,const int iData1Size,const void * pData2,const int iData2Size) { TCHAR * pCValue1 = (TCHAR*)pData1; UINT iCValue1Size = iData1Size/sizeof(TCHAR); TCHAR * pCValue2 = (TCHAR*)pData2; UINT iCValue2Size = iData2Size/sizeof(TCHAR); UINT iMinSize = min(iCValue1Size,iCValue2Size); int ret = 0 ; UINT iCurPos = 0; while(iCurPos < iMinSize) { ret = (int)(*pCValue1 - *pCValue2); if(ret != 0) break; ++pCValue1, ++pCValue2; iCurPos++; } if(0 == ret) { if(iCValue1Size > iCValue2Size) ret = 1; else if(iCValue1Size < iCValue2Size) ret = -1; } if ( ret < 0 ) ret = -1 ; else if ( ret > 0 ) ret = 1 ; return( ret ); //long minsize = min(iData2Size,iData1Size); //int compresult = memcmp(pData1,pData2,minsize); //if (compresult == 0) //当返回值有大小,或者没有大小,但是但是内存大小相等 //{ // if (iData1Size > minsize) // { // return 1;//pData1 > pData2 // } // else if(iData1Size == iData2Size) // { // return 0; // } // else // return -1; //} // //return compresult; } int NBlobField::Compare(const void * pData1,const void * pData2) { // void *pBlob1,*pBlob2; // long size = GetBlob(pData1,pBlob1); // size = min(GetBlob(pData2,pBlob2),size); // // //return 0; // //进行内存比较 // return memcmp(pBlob1,pBlob2,size); void *pBlob1,*pBlob2; long size1 = GetBlob(pData1,pBlob1); long size2 = GetBlob(pData2,pBlob2); return CompareValue(pBlob1,size1,pBlob2,size2); //long minsize = min(size2,size1); /////[2010年2月6日] // ///int compresult = memcmp(pBlob1,pBlob2,size); //int compresult = memcmp(pBlob1,pBlob2,minsize); //if (compresult == 0) //当返回值有大小,或者没有大小,但是但是内存大小相等 //{ // if (size1 > minsize) // { // return 1;//pData1 > pData2 // } // else if(size1 == size2) // { // return 0; // } // else // return -1; //} //return compresult; } BOOL NBlobField::FilterCompare(const void * pData1) { if (m_pFilterValue == NULL) { return TRUE; } if(TRUE == m_isUpdateAsBlobFiled) return TRUE; CString strTemValue = GetAsString(pData1); return (this->*m_pFuncompare)(strTemValue.GetBuffer(0),m_pFilterValue); //return FALSE; } BOOL NBlobField::FilterCompareValue(const void * pData1,const int iSize) { if (m_pFilterValue == NULL) { return TRUE; } if(TRUE == m_isUpdateAsBlobFiled) return TRUE; return (this->*m_pFuncompare)(pData1,m_pFilterValue); } BOOL NBlobField::FilterCompareEqual(const void * pData1,const void * pData2) { return _tcscmp((LPTSTR)pData2,(LPTSTR)pData1) == 0; } BOOL NBlobField::FilterCompareLike(const void * pData1,const void * pData2) { return _tcscspn((LPTSTR )pData1,(LPTSTR )pData2) >= 0; } BOOL NBlobField::FilterCompareGreater(const void * pData1,const void * pData2) { //BOOL test = strcmp((char *)pData1,(char *)pData2) > 0; return _tcscmp((LPTSTR )pData1,(LPTSTR )pData2) > 0; } BOOL NBlobField::FilterCompareLess(const void * pData1,const void * pData2) { return _tcscmp((LPTSTR )pData1,(LPTSTR )pData2) < 0; } BOOL NBlobField::SetFilter(LPTSTR sOperator ,LPTSTR sValue) { FreeFilterValue(); //NDataField::SetFilter(sOperator,sValue); CString sop = sOperator; if (sop == _T("<")) { m_pFuncompare = (BOOL (NDataField::*) ( const void * ,const void * ))(&NBlobField::FilterCompareLess); } else if (sop == _T(">")) { m_pFuncompare = (BOOL (NDataField::*) ( const void * ,const void * ))(&NBlobField::FilterCompareGreater); } else if (sop == _T("=")) { m_pFuncompare = (BOOL (NDataField::*) ( const void * ,const void * ))(&NBlobField::FilterCompareEqual); } else if (sop.CompareNoCase(_T("like"))) { m_pFuncompare = (BOOL (NDataField::*) ( const void * ,const void * ))(&NBlobField::FilterCompareLike); } m_pFilterValue = new BYTE [(_tcslen(sValue) + 1)*sizeof(_TCHAR)] ; memset(m_pFilterValue,0,(_tcslen(sValue) + 1)*sizeof(_TCHAR)); _tcscpy_s((LPTSTR)m_pFilterValue, strlen((char*)m_pFilterValue), sValue); m_FilterOperator = sOperator; return TRUE; //return TRUE; } BOOL NBlobField::FreeFilterValue() { if (m_pFilterValue != NULL) { delete [] m_pFilterValue; m_pFilterValue = NULL; } return TRUE; }
[ "1156881120@qq.com" ]
1156881120@qq.com
f1e438037aac97d2641a49324af7699dfe5bc1b6
4b0550dbbcb2b49fa2bad6480fa7fa04993a13ff
/build-tcpclientGui-Desktop_Qt_5_8_0_MSVC2015_32bit-Debug/ui_paradlg.h
ca4c261221763baa438f8ada6727306715da0eed
[]
no_license
wfwgghb/devclientQt
ab76be1629b70fa3c1ee0fde5dbf50b8bca60ca2
8218d4351d6d3adfdd81522a3a453ffba9d33db6
refs/heads/master
2020-03-10T12:01:25.262989
2018-04-13T08:07:49
2018-04-13T08:07:49
129,368,243
0
0
null
null
null
null
UTF-8
C++
false
false
11,468
h
/******************************************************************************** ** Form generated from reading UI file 'paradlg.ui' ** ** Created by: Qt User Interface Compiler version 5.8.0 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_PARADLG_H #define UI_PARADLG_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QDialog> #include <QtWidgets/QDialogButtonBox> #include <QtWidgets/QGroupBox> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QPushButton> #include <QtWidgets/QTableView> #include <QtWidgets/QToolButton> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_ParaDlg { public: QDialogButtonBox *buttonBox; QGroupBox *groupBox; QLabel *label; QLabel *label_2; QLineEdit *lineEdit; QLineEdit *lineEdit_2; QLabel *label_3; QLineEdit *lineEdit_3; QLabel *label_6; QLineEdit *lineEdit_6; QLabel *label_8; QLabel *label_9; QGroupBox *groupBox_2; QWidget *horizontalLayoutWidget; QHBoxLayout *horizontalLayout; QLabel *label_4; QLineEdit *lineEdit_4; QToolButton *toolButton; QWidget *horizontalLayoutWidget_2; QHBoxLayout *horizontalLayout_2; QLabel *label_5; QLineEdit *lineEdit_5; QPushButton *pushButton_3; QGroupBox *groupBox_3; QTableView *tableView; QPushButton *pushButton; QWidget *horizontalLayoutWidget_3; QHBoxLayout *horizontalLayout_3; QPushButton *pushButton_4; QLineEdit *lineEdit_7; QLabel *label_10; QLabel *label_11; QLabel *label_12; QPushButton *pushButton_5; QPushButton *pushButton_6; QLabel *label_13; void setupUi(QDialog *ParaDlg) { if (ParaDlg->objectName().isEmpty()) ParaDlg->setObjectName(QStringLiteral("ParaDlg")); ParaDlg->resize(1006, 481); buttonBox = new QDialogButtonBox(ParaDlg); buttonBox->setObjectName(QStringLiteral("buttonBox")); buttonBox->setGeometry(QRect(650, 430, 341, 32)); buttonBox->setOrientation(Qt::Horizontal); buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok); groupBox = new QGroupBox(ParaDlg); groupBox->setObjectName(QStringLiteral("groupBox")); groupBox->setGeometry(QRect(30, 20, 231, 141)); label = new QLabel(groupBox); label->setObjectName(QStringLiteral("label")); label->setGeometry(QRect(10, 20, 71, 20)); label_2 = new QLabel(groupBox); label_2->setObjectName(QStringLiteral("label_2")); label_2->setGeometry(QRect(10, 50, 71, 20)); lineEdit = new QLineEdit(groupBox); lineEdit->setObjectName(QStringLiteral("lineEdit")); lineEdit->setGeometry(QRect(80, 20, 113, 20)); lineEdit_2 = new QLineEdit(groupBox); lineEdit_2->setObjectName(QStringLiteral("lineEdit_2")); lineEdit_2->setGeometry(QRect(80, 50, 113, 20)); label_3 = new QLabel(groupBox); label_3->setObjectName(QStringLiteral("label_3")); label_3->setGeometry(QRect(10, 80, 71, 20)); lineEdit_3 = new QLineEdit(groupBox); lineEdit_3->setObjectName(QStringLiteral("lineEdit_3")); lineEdit_3->setGeometry(QRect(80, 80, 113, 20)); label_6 = new QLabel(groupBox); label_6->setObjectName(QStringLiteral("label_6")); label_6->setGeometry(QRect(10, 110, 71, 20)); lineEdit_6 = new QLineEdit(groupBox); lineEdit_6->setObjectName(QStringLiteral("lineEdit_6")); lineEdit_6->setGeometry(QRect(80, 110, 113, 20)); label_8 = new QLabel(groupBox); label_8->setObjectName(QStringLiteral("label_8")); label_8->setGeometry(QRect(200, 50, 21, 20)); label_9 = new QLabel(groupBox); label_9->setObjectName(QStringLiteral("label_9")); label_9->setGeometry(QRect(200, 80, 21, 20)); groupBox_2 = new QGroupBox(ParaDlg); groupBox_2->setObjectName(QStringLiteral("groupBox_2")); groupBox_2->setGeometry(QRect(20, 280, 231, 151)); horizontalLayoutWidget = new QWidget(groupBox_2); horizontalLayoutWidget->setObjectName(QStringLiteral("horizontalLayoutWidget")); horizontalLayoutWidget->setGeometry(QRect(10, 40, 211, 31)); horizontalLayout = new QHBoxLayout(horizontalLayoutWidget); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); horizontalLayout->setContentsMargins(0, 0, 0, 0); label_4 = new QLabel(horizontalLayoutWidget); label_4->setObjectName(QStringLiteral("label_4")); horizontalLayout->addWidget(label_4); lineEdit_4 = new QLineEdit(horizontalLayoutWidget); lineEdit_4->setObjectName(QStringLiteral("lineEdit_4")); horizontalLayout->addWidget(lineEdit_4); toolButton = new QToolButton(horizontalLayoutWidget); toolButton->setObjectName(QStringLiteral("toolButton")); horizontalLayout->addWidget(toolButton); horizontalLayoutWidget_2 = new QWidget(groupBox_2); horizontalLayoutWidget_2->setObjectName(QStringLiteral("horizontalLayoutWidget_2")); horizontalLayoutWidget_2->setGeometry(QRect(10, 100, 211, 31)); horizontalLayout_2 = new QHBoxLayout(horizontalLayoutWidget_2); horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2")); horizontalLayout_2->setContentsMargins(0, 0, 0, 0); label_5 = new QLabel(horizontalLayoutWidget_2); label_5->setObjectName(QStringLiteral("label_5")); horizontalLayout_2->addWidget(label_5); lineEdit_5 = new QLineEdit(horizontalLayoutWidget_2); lineEdit_5->setObjectName(QStringLiteral("lineEdit_5")); horizontalLayout_2->addWidget(lineEdit_5); pushButton_3 = new QPushButton(ParaDlg); pushButton_3->setObjectName(QStringLiteral("pushButton_3")); pushButton_3->setGeometry(QRect(170, 160, 75, 23)); groupBox_3 = new QGroupBox(ParaDlg); groupBox_3->setObjectName(QStringLiteral("groupBox_3")); groupBox_3->setGeometry(QRect(260, 20, 731, 411)); tableView = new QTableView(groupBox_3); tableView->setObjectName(QStringLiteral("tableView")); tableView->setGeometry(QRect(20, 30, 701, 341)); pushButton = new QPushButton(groupBox_3); pushButton->setObjectName(QStringLiteral("pushButton")); pushButton->setGeometry(QRect(30, 380, 75, 23)); horizontalLayoutWidget_3 = new QWidget(groupBox_3); horizontalLayoutWidget_3->setObjectName(QStringLiteral("horizontalLayoutWidget_3")); horizontalLayoutWidget_3->setGeometry(QRect(159, 380, 140, 25)); horizontalLayout_3 = new QHBoxLayout(horizontalLayoutWidget_3); horizontalLayout_3->setObjectName(QStringLiteral("horizontalLayout_3")); horizontalLayout_3->setContentsMargins(0, 0, 0, 0); pushButton_4 = new QPushButton(horizontalLayoutWidget_3); pushButton_4->setObjectName(QStringLiteral("pushButton_4")); horizontalLayout_3->addWidget(pushButton_4); lineEdit_7 = new QLineEdit(horizontalLayoutWidget_3); lineEdit_7->setObjectName(QStringLiteral("lineEdit_7")); horizontalLayout_3->addWidget(lineEdit_7); label_10 = new QLabel(horizontalLayoutWidget_3); label_10->setObjectName(QStringLiteral("label_10")); horizontalLayout_3->addWidget(label_10); label_11 = new QLabel(groupBox_3); label_11->setObjectName(QStringLiteral("label_11")); label_11->setGeometry(QRect(513, 380, 71, 20)); label_12 = new QLabel(groupBox_3); label_12->setObjectName(QStringLiteral("label_12")); label_12->setGeometry(QRect(420, 380, 71, 20)); pushButton_5 = new QPushButton(groupBox_3); pushButton_5->setObjectName(QStringLiteral("pushButton_5")); pushButton_5->setGeometry(QRect(664, 380, 51, 23)); pushButton_6 = new QPushButton(groupBox_3); pushButton_6->setObjectName(QStringLiteral("pushButton_6")); pushButton_6->setGeometry(QRect(600, 380, 51, 23)); label_13 = new QLabel(ParaDlg); label_13->setObjectName(QStringLiteral("label_13")); label_13->setGeometry(QRect(270, 440, 54, 12)); retranslateUi(ParaDlg); QObject::connect(buttonBox, SIGNAL(accepted()), ParaDlg, SLOT(accept())); QObject::connect(buttonBox, SIGNAL(rejected()), ParaDlg, SLOT(reject())); QMetaObject::connectSlotsByName(ParaDlg); } // setupUi void retranslateUi(QDialog *ParaDlg) { ParaDlg->setWindowTitle(QApplication::translate("ParaDlg", "Dialog", Q_NULLPTR)); groupBox->setTitle(QApplication::translate("ParaDlg", "\350\256\276\345\244\207\345\256\232\344\275\215", Q_NULLPTR)); label->setText(QApplication::translate("ParaDlg", "\350\256\276\345\244\207\345\217\267\357\274\232", Q_NULLPTR)); label_2->setText(QApplication::translate("ParaDlg", "\345\201\234\350\275\246\345\234\272\357\274\232", Q_NULLPTR)); lineEdit_2->setText(QApplication::translate("ParaDlg", "0001", Q_NULLPTR)); label_3->setText(QApplication::translate("ParaDlg", "\345\214\272\345\237\237\345\217\267\357\274\232", Q_NULLPTR)); lineEdit_3->setText(QApplication::translate("ParaDlg", "01010", Q_NULLPTR)); label_6->setText(QApplication::translate("ParaDlg", "\346\263\212\344\275\215\345\217\267\357\274\232", Q_NULLPTR)); label_8->setText(QApplication::translate("ParaDlg", "*", Q_NULLPTR)); label_9->setText(QApplication::translate("ParaDlg", "*", Q_NULLPTR)); groupBox_2->setTitle(QApplication::translate("ParaDlg", "\344\270\213\350\275\275\346\226\207\344\273\266\350\256\276\347\275\256", Q_NULLPTR)); label_4->setText(QApplication::translate("ParaDlg", "\346\226\207\344\273\266\350\267\257\345\276\204\357\274\232", Q_NULLPTR)); toolButton->setText(QApplication::translate("ParaDlg", "...", Q_NULLPTR)); label_5->setText(QApplication::translate("ParaDlg", "\350\275\257\344\273\266\347\211\210\346\234\254\357\274\232", Q_NULLPTR)); pushButton_3->setText(QApplication::translate("ParaDlg", "\346\220\234\347\264\242", Q_NULLPTR)); groupBox_3->setTitle(QApplication::translate("ParaDlg", "\345\234\260\347\243\201\350\256\276\345\244\207\345\217\202\346\225\260\350\256\276\347\275\256", Q_NULLPTR)); pushButton->setText(QApplication::translate("ParaDlg", "\346\217\220\344\272\244", Q_NULLPTR)); pushButton_4->setText(QApplication::translate("ParaDlg", "\350\275\254\345\210\260", Q_NULLPTR)); label_10->setText(QApplication::translate("ParaDlg", "\351\241\265", Q_NULLPTR)); label_11->setText(QString()); label_12->setText(QString()); pushButton_5->setText(QApplication::translate("ParaDlg", "\344\270\213\344\270\200\351\241\265", Q_NULLPTR)); pushButton_6->setText(QApplication::translate("ParaDlg", "\344\270\212\344\270\200\351\241\265", Q_NULLPTR)); label_13->setText(QString()); } // retranslateUi }; namespace Ui { class ParaDlg: public Ui_ParaDlg {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_PARADLG_H
[ "425180220@qq.com" ]
425180220@qq.com
f328d075d2b6e7b14005b09ea8c327c94ae9759f
943dd54918355e8028fdd759bae6d9dd837e11e0
/third-party/adafruit-arduino-samd/libraries/SPI/SPI.h
d4ab2d64aff7a5b3043fb77d6494e882f729c7ed
[ "BSD-3-Clause", "LGPL-2.1-or-later" ]
permissive
fieldkit/firmware
06e920ad01c2f48142413d3a3447188bc9753004
45c51ce8dc51df886875e97de17980c839882adf
refs/heads/main
2023-08-23T22:29:02.022772
2023-07-24T22:18:01
2023-07-24T22:18:01
183,808,180
11
1
BSD-3-Clause
2023-04-04T20:42:38
2019-04-27T18:27:51
C++
UTF-8
C++
false
false
4,755
h
/* * SPI Master library for Arduino Zero. * Copyright (c) 2015 Arduino LLC * * 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; either * version 2.1 of the License, or (at your option) any later version. * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _SPI_H_INCLUDED #define _SPI_H_INCLUDED #include <Arduino.h> // SPI_HAS_TRANSACTION means SPI has // - beginTransaction() // - endTransaction() // - usingInterrupt() // - SPISetting(clock, bitOrder, dataMode) #define SPI_HAS_TRANSACTION 1 // SPI_HAS_NOTUSINGINTERRUPT means that SPI has notUsingInterrupt() method #define SPI_HAS_NOTUSINGINTERRUPT 1 #define SPI_MODE0 0x02 #define SPI_MODE1 0x00 #define SPI_MODE2 0x03 #define SPI_MODE3 0x01 #if defined(ARDUINO_ARCH_SAMD) // The datasheet specifies a typical SPI SCK period (tSCK) of 42 ns, // see "Table 36-48. SPI Timing Characteristics and Requirements", // which translates into a maximum SPI clock of 23.8 MHz. // Conservatively, the divider is set for a 12 MHz maximum SPI clock. #define SPI_MIN_CLOCK_DIVIDER (uint8_t)(1 + ((F_CPU - 1) / 12000000)) #endif class SPISettings { public: SPISettings(uint32_t clock, BitOrder bitOrder, uint8_t dataMode) { if (__builtin_constant_p(clock)) { init_AlwaysInline(clock, bitOrder, dataMode); } else { init_MightInline(clock, bitOrder, dataMode); } } // Default speed set to 4MHz, SPI mode set to MODE 0 and Bit order set to MSB first. SPISettings() { init_AlwaysInline(4000000, MSBFIRST, SPI_MODE0); } private: void init_MightInline(uint32_t clock, BitOrder bitOrder, uint8_t dataMode) { init_AlwaysInline(clock, bitOrder, dataMode); } void init_AlwaysInline(uint32_t clock, BitOrder bitOrder, uint8_t dataMode) __attribute__((__always_inline__)) { this->clockFreq = (clock >= (F_CPU / SPI_MIN_CLOCK_DIVIDER) ? F_CPU / SPI_MIN_CLOCK_DIVIDER : clock); this->bitOrder = (bitOrder == MSBFIRST ? MSB_FIRST : LSB_FIRST); switch (dataMode) { case SPI_MODE0: this->dataMode = SERCOM_SPI_MODE_0; break; case SPI_MODE1: this->dataMode = SERCOM_SPI_MODE_1; break; case SPI_MODE2: this->dataMode = SERCOM_SPI_MODE_2; break; case SPI_MODE3: this->dataMode = SERCOM_SPI_MODE_3; break; default: this->dataMode = SERCOM_SPI_MODE_0; break; } } uint32_t clockFreq; SercomSpiClockMode dataMode; SercomDataOrder bitOrder; friend class SPIClass; }; class SPIClass { public: SPIClass(SERCOM *p_sercom, uint8_t uc_pinMISO, uint8_t uc_pinSCK, uint8_t uc_pinMOSI, SercomSpiTXPad, SercomRXPad); byte transfer(uint8_t data); uint16_t transfer16(uint16_t data); void transfer(void *buf, size_t count); // Transaction Functions void usingInterrupt(int interruptNumber); void notUsingInterrupt(int interruptNumber); void beginTransaction(SPISettings settings); void endTransaction(void); // SPI Configuration methods void attachInterrupt(); void detachInterrupt(); void begin(); void end(); void setBitOrder(BitOrder order); void setDataMode(uint8_t uc_mode); void setClockDivider(uint8_t uc_div); private: void init(); void config(SPISettings settings); SERCOM *_p_sercom; uint8_t _uc_pinMiso; uint8_t _uc_pinMosi; uint8_t _uc_pinSCK; SercomSpiTXPad _padTx; SercomRXPad _padRx; bool initialized; uint8_t interruptMode; char interruptSave; uint32_t interruptMask; }; #if SPI_INTERFACES_COUNT > 0 extern SPIClass SPI; #endif #if SPI_INTERFACES_COUNT > 1 extern SPIClass SPI1; #endif #if SPI_INTERFACES_COUNT > 2 extern SPIClass SPI2; #endif #if SPI_INTERFACES_COUNT > 3 extern SPIClass SPI3; #endif #if SPI_INTERFACES_COUNT > 4 extern SPIClass SPI4; #endif #if SPI_INTERFACES_COUNT > 5 extern SPIClass SPI5; #endif // For compatibility with sketches designed for AVR @ 16 MHz // New programs should use SPI.beginTransaction to set the SPI clock #if F_CPU == 48000000 #define SPI_CLOCK_DIV2 6 #define SPI_CLOCK_DIV4 12 #define SPI_CLOCK_DIV8 24 #define SPI_CLOCK_DIV16 48 #define SPI_CLOCK_DIV32 96 #define SPI_CLOCK_DIV64 192 #define SPI_CLOCK_DIV128 255 #endif #endif
[ "jlewalle@gmail.com" ]
jlewalle@gmail.com
d6562533c31f176a5e59f668cc6450245523f50a
92ed12aef7e5d1d6e5b0574bc6d70549b1b345e5
/Problems Implementations/C++ Implementation/Rounds Participations/LeetCode/September-30-Day LeetCoding Challenge_2020/Week 1/Image Overlap.cpp
d746ea67c8f7bc7be138c5b11a1e1acc0c397bca
[]
no_license
AmEr-Tinsley/Competitive-programming
0d9adc3ef7b0a0d7a2aefc74ac3376ca3e97d74c
0892a75e6f2a0d489d9edd53e37d4787c3452aa4
refs/heads/master
2023-03-16T23:58:07.349218
2023-03-11T17:50:27
2023-03-11T17:50:27
159,981,161
5
1
null
2022-09-03T07:46:03
2018-12-01T19:47:10
C++
UTF-8
C++
false
false
842
cpp
class Solution { public: int largestOverlap(vector<vector<int>>& A, vector<vector<int>>& B) { int n = (int)A.size(); std::vector<int> v(n); for(int i = 0;i<n;i++)A.push_back(v),A.insert(A.begin(),v); for(int i = 0;i<3*n;i++) for(int j =0;j<n;j++)A[i].insert(A[i].begin(),0),A[i].push_back(0); int ret = 0; for(int i = 0;i<=A.size()-n;i++){ for(int j =0;j<=A[i].size()-n;j++){ ret = max(ret,count(A,B,i,j,n)); } } return ret; } int count(vector<vector<int>>& A,vector<vector<int>>& B,int x,int y,int n){ int ret = 0; for(int i1=0,i2=x;i1<n && i2<x+n;i1++,i2++){ for(int j1=0,j2=y;j1<n && j2<y+n;j1++,j2++){ ret+= (int)((A[i2][j2] == B[i1][j1]) & A[i2][j2]) ; } } return ret; } };
[ "amerhosni07@gmail.com" ]
amerhosni07@gmail.com
2993bb06157ed37805394209ffc3dbb44add97a6
a5a99f646e371b45974a6fb6ccc06b0a674818f2
/L1Trigger/L1THGCal/interface/concentrator/HGCalConcentratorThresholdImpl.h
f259a2b01511b16e2d70df794e63e6a5bb509ab2
[ "Apache-2.0" ]
permissive
cms-sw/cmssw
4ecd2c1105d59c66d385551230542c6615b9ab58
19c178740257eb48367778593da55dcad08b7a4f
refs/heads/master
2023-08-23T21:57:42.491143
2023-08-22T20:22:40
2023-08-22T20:22:40
10,969,551
1,006
3,696
Apache-2.0
2023-09-14T19:14:28
2013-06-26T14:09:07
C++
UTF-8
C++
false
false
877
h
#ifndef __L1Trigger_L1THGCal_HGCalConcentratorThresholdImpl_h__ #define __L1Trigger_L1THGCal_HGCalConcentratorThresholdImpl_h__ #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "DataFormats/L1THGCal/interface/HGCalTriggerCell.h" #include "L1Trigger/L1THGCal/interface/HGCalTriggerTools.h" #include <vector> class HGCalConcentratorThresholdImpl { public: HGCalConcentratorThresholdImpl(const edm::ParameterSet& conf); void select(const std::vector<l1t::HGCalTriggerCell>& trigCellVecInput, std::vector<l1t::HGCalTriggerCell>& trigCellVecOutput, std::vector<l1t::HGCalTriggerCell>& trigCellVecNotSelected); void setGeometry(const HGCalTriggerGeometryBase* const geom) { triggerTools_.setGeometry(geom); } private: double threshold_silicon_; double threshold_scintillator_; HGCalTriggerTools triggerTools_; }; #endif
[ "jean-baptiste.sauvan@cern.ch" ]
jean-baptiste.sauvan@cern.ch
6650c5e76a560e174f281ccd5b6f274967ef95a6
c2135a1cefebc0b230bed71595f5b2b1cec6e304
/~2017/2864.cpp
1c141aa5c4ce23b2100ea3c1a300ff7bbc89c475
[]
no_license
pbysu/BOJ
d9df7a4b1a4aa440282f607a428e290f0e284e20
7c24608b4636f9203b2be14429850817ec6ea427
refs/heads/master
2020-03-07T17:23:29.706432
2018-06-01T10:48:46
2018-06-01T10:48:46
127,609,935
1
0
null
null
null
null
UTF-8
C++
false
false
794
cpp
#include<iostream> #include<math.h> #include<string> using namespace std; string ns; string nf; string ms; string mf; int main() { cin >> ns>> ms; int nSize = ns.length(); nf = ns; mf = ms; for (int i = 0; i < nSize; i++) { if (ns[i] == '5' || ns[i] == '6') { ns[i] = '6'; nf[i] = '5'; } } int mSize = ms.length(); for (int i = 0; i < mSize; i++) { if (ms[i] == '5' || ms[i] == '6') { ms[i] = '6'; mf[i] = '5'; } } int nma=0; int nmi = 0; int mma = 0; int mmi = 0; int ten = 1; for (int i = nSize-1; i >= 0; i--) { nma+=(ns[i] - '0')*ten; nmi += (nf[i] - '0')*ten; ten *= 10; } ten = 1; for (int i = mSize - 1; i >= 0; i--) { mma += (ms[i] - '0')*ten; mmi += (mf[i] - '0')*ten; ten *= 10; } printf("%d %d", mmi + nmi, mma + nma); return 0; }
[ "park.bysu@gmail.com" ]
park.bysu@gmail.com
d9bf424e3efe5a2711d546f1ad14da0b707e6e06
ad822f849322c5dcad78d609f28259031a96c98e
/SDK/SedimentFilter_Large_classes.h
43faf86cac0c3dbd249681ce124410a172a54dcd
[]
no_license
zH4x-SDK/zAstroneer-SDK
1cdc9c51b60be619202c0258a0dd66bf96898ac4
35047f506eaef251a161792fcd2ddd24fe446050
refs/heads/main
2023-07-24T08:20:55.346698
2021-08-27T13:33:33
2021-08-27T13:33:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,548
h
#pragma once // Name: Astroneer-SDK, Version: 1.0.0 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass SedimentFilter_Large.SedimentFilter_Large_C // 0x0048 (0x06A8 - 0x0660) class ASedimentFilter_Large_C : public APhysicalItem { public: struct FPointerToUberGraphFrame UberGraphFrame; // 0x0660(0x0008) (Transient, DuplicateTransient) class USceneComponent* TooltipAnchor; // 0x0668(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData) class USkeletalMeshComponent* ModuleBody; // 0x0670(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData) class UChildActorComponent* SelectorUI; // 0x0678(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData) class UResourceInfoComponent* ResourceInfo; // 0x0680(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData) class UChildSlotComponent* Body_Slot; // 0x0688(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData) class UDeformEventReceiver* DeformEventReceiver; // 0x0690(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData) class UPowerComponent* Power; // 0x0698(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData) class UPrimitiveComponent* Placeholder_Mesh; // 0x06A0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass SedimentFilter_Large.SedimentFilter_Large_C"); return ptr; } void UpgradeModule(); class UChildSlotComponent* GetBodySlotLegacy(); void UserConstructionScript(); void ReceiveBeginPlay(); void ReceiveEndPlay(TEnumAsByte<EEndPlayReason> EndPlayReason); void ExecuteUbergraph_SedimentFilter_Large(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
87f9e1d82c6fe4f28da0ea5872776850435151d5
c40887c484748c663153ee7bffe474a87bdee768
/src_for_harc_journal/lru.cpp
61cf39c6b045ac7e5f8e7aa4eb0bd73fc71674d2
[]
no_license
weRginger/imba-sim
565a07aa069d89e17313840e1e3b913183685502
ef982b6b4590b48d84acc13225546ce9e7727eb0
refs/heads/master
2021-06-14T00:20:43.486849
2017-01-26T20:46:59
2017-01-26T20:46:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
230
cpp
// // C++ Implementation: lru_ziqi // // Description: // // // Author: ziqi fan, UMN // // Copyright: See COPYING file that comes with this distribution // Copyright (c) 2010, Tim Day <timday@timday.com> // // #include "lru.h"
[ "ziqifan16@gmail.com" ]
ziqifan16@gmail.com
024c2efb2cb67224a7ef84fbe538638e7390e756
f7a8476e7eff4c3807f1d66931290105b132bd7b
/Block1.h
e8f14e0ec607672bfa4ad55ab808cf3f55163af3
[]
no_license
jasiekmg/Projekt4
11b09796c779b4fff2e2e45b62442a3ceedf362b
55ed330aa43dc62539326242be78fbff84ffae08
refs/heads/master
2020-06-03T11:48:26.847676
2019-06-28T06:27:50
2019-06-28T06:27:50
191,556,486
0
0
null
null
null
null
UTF-8
C++
false
false
610
h
#pragma once #include <SFML/Graphics.hpp> using namespace sf; class Block1 : public sf::Drawable { public: Block1(float t_X, float t_Y); Block1() = delete; ~Block1() = default; void update(); void grawitacja(); void rysuj(); float right(); float left(); float top(); float bottom(); int masa =100; private: void draw(RenderTarget& target, RenderStates state) const override; RectangleShape shape; const float block1Width{ 40.0f }; const float block1Height{ 40.0f }; const float block1Velocity{ 4.0f }; Vector2f velocity{ block1Velocity, block1Velocity }; };
[ "noreply@github.com" ]
noreply@github.com
5c6e569196850e9dc0b857d527f7939af9c7502a
8c8820fb84dea70d31c1e31dd57d295bd08dd644
/Engine/Public/Subsystems/GameInstanceSubsystem.h
14a638abc8beaa3b36d197cd15ec588277040bfc
[]
no_license
redisread/UE-Runtime
e1a56df95a4591e12c0fd0e884ac6e54f69d0a57
48b9e72b1ad04458039c6ddeb7578e4fc68a7bac
refs/heads/master
2022-11-15T08:30:24.570998
2020-06-20T06:37:55
2020-06-20T06:37:55
274,085,558
3
0
null
null
null
null
UTF-8
C++
false
false
507
h
// Copyright Epic Games, Inc. All Rights Reserved. #pragma once #include "Subsystems/Subsystem.h" #include "GameInstanceSubsystem.generated.h" class UGameInstance; /** * UGameInstanceSubsystem * Base class for auto instanced and initialized systems that share the lifetime of the game instance */ UCLASS(Abstract, Within = GameInstance) class ENGINE_API UGameInstanceSubsystem : public USubsystem { GENERATED_BODY() public: UGameInstanceSubsystem(); UGameInstance* GetGameInstance() const; };
[ "wujiahong19981022@outlook.com" ]
wujiahong19981022@outlook.com
0d6398ca883bb8510834633d09b8a021b2625dbb
4a19b7f0352f3f79ff2759e0d6808e159133819c
/src/histogram.cpp
a446c1fd810c970825034c7a861d07ded2a3a813
[]
no_license
thierry3000/green_function_method
853084b67b04371fc20dd92466a7ba1991b8d60f
392af9b2e2f92a4c67614a97bcd66c62dcfc780b
refs/heads/master
2020-04-03T11:37:46.788845
2018-12-05T08:36:31
2018-12-05T08:36:31
155,227,479
0
0
null
null
null
null
UTF-8
C++
false
false
1,916
cpp
/***************************************************** Evaluate histograms of solute levels. TWS December 07. Version 2.0, May 1, 2010. Version 3.0, Ma7 17,2011. ******************************************************/ #define _CRT_SECURE_NO_DEPRECATE #include <math.h> #include "nrutil.h" #include <stdio.h> void histogram(void) { extern int mxx,myy,mzz,nnt,nnv,nseg,nnod,nsp; extern float *pmin,*pmax,*pmean,*pref; extern float **pt; int i,j,itp,isp,nctop,ncbot,nstat,nstatm=101; float step,dev; float *po2samp,*stat,*cumu,*mstat; FILE *ofp; po2samp = vector(1,nstatm); stat = vector(1,nstatm); cumu = vector(1,nstatm); mstat = vector(1,nstatm); ofp = fopen("output/Histogram.out", "w"); for(isp=1; isp<=nsp; isp++){ step = pref[isp]/100; nctop = pmax[isp]/step + 1.; if(nctop > 100) nctop = 100; ncbot = pmin[isp]/step; if(ncbot <= 2) ncbot = 0; nstat = nctop - ncbot + 1; dev = 0.; if(nstat > nstatm) printf("*** nstatm too small in histogram\n"); for(i=1; i<=nstat; i++){ po2samp[i] = step*(i - 1 + ncbot); mstat[i] = 0; } for(itp=1; itp<=nnt; itp++){ dev = dev + SQR(pmean[isp] - pt[itp][isp]); for(j=1; j<=nstat; j++) if(pt[itp][isp] <= po2samp[j]){ mstat[j] = mstat[j] + 1; goto binned; } binned:; } dev = sqrt(dev/nnt); for(i=1; i<=nstat; i++) stat[i] = mstat[i]*100./nnt; cumu[1] = stat[1]; for(i=2; i<=nstat; i++) cumu[i] = cumu[i-1] + stat[i]; fprintf(ofp,"Histogram data for solute %i\n", isp); fprintf(ofp,"value %% cumul. %%\n"); for(i=1; i<=nstat; i++) fprintf(ofp,"%g %7.2f %7.2f\n", po2samp[i],stat[i],cumu[i]); fprintf(ofp,"Mean = %f deviation = %f min = %f max = %f\n", pmean[isp],dev,pmin[isp],pmax[isp]); } fclose(ofp); free_vector(po2samp,1,nstatm); free_vector(stat,1,nstatm); free_vector(cumu,1,nstatm); free_vector(mstat,1,nstatm); }
[ "thierry@lusi.uni-sb.de" ]
thierry@lusi.uni-sb.de
d3000279016aad080dc5803a2379d1df8a76f777
a11b50cf2c3c0ab1600ddd144a57c53a0a6d61dd
/libgdal_1110/alg/gdalwarpkernel.cpp
8b0f7e999cc6951b84de959b3836461aea3294a6
[ "LicenseRef-scancode-info-zip-2005-02", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-warranty-disclaimer", "MIT", "SunPro" ]
permissive
dlubom/walls
78f549e5a2e678d101f9e953daa04b5505d4fca7
e34363945b4c422a327380e20a6414e4298cfa58
refs/heads/master
2021-06-01T11:02:38.562704
2020-03-22T14:34:29
2020-03-22T14:34:56
87,931,918
1
0
null
2017-04-11T12:34:06
2017-04-11T12:34:06
null
UTF-8
C++
false
false
208,016
cpp
/****************************************************************************** * $Id: gdalwarpkernel.cpp 27159 2014-04-12 15:49:25Z rouault $ * * Project: High Performance Image Reprojector * Purpose: Implementation of the GDALWarpKernel class. Implements the actual * image warping for a "chunk" of input and output imagery already * loaded into memory. * Author: Frank Warmerdam, warmerdam@pobox.com * ****************************************************************************** * Copyright (c) 2003, Frank Warmerdam <warmerdam@pobox.com> * Copyright (c) 2008-2013, Even Rouault <even dot rouault at mines-paris dot 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 "gdalwarper.h" #include "gdal_alg_priv.h" #include "cpl_string.h" #include "gdalwarpkernel_opencl.h" #include "cpl_atomic_ops.h" #include "cpl_multiproc.h" CPL_CVSID("$Id: gdalwarpkernel.cpp 27159 2014-04-12 15:49:25Z rouault $"); static const int anGWKFilterRadius[] = { 0, // Nearest neighbour 1, // Bilinear 2, // Cubic Convolution 2, // Cubic B-Spline 3, // Lanczos windowed sinc 0, // Average 0, // Mode }; /* Used in gdalwarpoperation.cpp */ int GWKGetFilterRadius(GDALResampleAlg eResampleAlg) { return anGWKFilterRadius[eResampleAlg]; } #ifdef HAVE_OPENCL static CPLErr GWKOpenCLCase( GDALWarpKernel * ); #endif static CPLErr GWKGeneralCase( GDALWarpKernel * ); static CPLErr GWKNearestNoMasksByte( GDALWarpKernel *poWK ); static CPLErr GWKBilinearNoMasksByte( GDALWarpKernel *poWK ); static CPLErr GWKCubicNoMasksByte( GDALWarpKernel *poWK ); static CPLErr GWKCubicSplineNoMasksByte( GDALWarpKernel *poWK ); static CPLErr GWKNearestByte( GDALWarpKernel *poWK ); static CPLErr GWKNearestNoMasksShort( GDALWarpKernel *poWK ); static CPLErr GWKBilinearNoMasksShort( GDALWarpKernel *poWK ); static CPLErr GWKCubicNoMasksShort( GDALWarpKernel *poWK ); static CPLErr GWKCubicSplineNoMasksShort( GDALWarpKernel *poWK ); static CPLErr GWKNearestShort( GDALWarpKernel *poWK ); static CPLErr GWKNearestNoMasksFloat( GDALWarpKernel *poWK ); static CPLErr GWKNearestFloat( GDALWarpKernel *poWK ); static CPLErr GWKAverageOrMode( GDALWarpKernel * ); /************************************************************************/ /* GWKJobStruct */ /************************************************************************/ typedef struct _GWKJobStruct GWKJobStruct; struct _GWKJobStruct { void *hThread; GDALWarpKernel *poWK; int iYMin; int iYMax; volatile int *pnCounter; volatile int *pbStop; void *hCond; void *hCondMutex; int (*pfnProgress)(GWKJobStruct* psJob); void *pTransformerArg; } ; /************************************************************************/ /* GWKProgressThread() */ /************************************************************************/ /* Return TRUE if the computation must be interrupted */ static int GWKProgressThread(GWKJobStruct* psJob) { CPLAcquireMutex(psJob->hCondMutex, 1.0); (*(psJob->pnCounter)) ++; CPLCondSignal(psJob->hCond); int bStop = *(psJob->pbStop); CPLReleaseMutex(psJob->hCondMutex); return bStop; } /************************************************************************/ /* GWKProgressMonoThread() */ /************************************************************************/ /* Return TRUE if the computation must be interrupted */ static int GWKProgressMonoThread(GWKJobStruct* psJob) { GDALWarpKernel *poWK = psJob->poWK; int nCounter = ++(*(psJob->pnCounter)); if( !poWK->pfnProgress( poWK->dfProgressBase + poWK->dfProgressScale * (nCounter / (double) psJob->iYMax), "", poWK->pProgress ) ) { CPLError( CE_Failure, CPLE_UserInterrupt, "User terminated" ); *(psJob->pbStop) = TRUE; return TRUE; } return FALSE; } /************************************************************************/ /* GWKGenericMonoThread() */ /************************************************************************/ static CPLErr GWKGenericMonoThread( GDALWarpKernel *poWK, void (*pfnFunc) (void *pUserData) ) { volatile int bStop = FALSE; volatile int nCounter = 0; GWKJobStruct sThreadJob; sThreadJob.poWK = poWK; sThreadJob.pnCounter = &nCounter; sThreadJob.iYMin = 0; sThreadJob.iYMax = poWK->nDstYSize; sThreadJob.pbStop = &bStop; sThreadJob.hCond = NULL; sThreadJob.hCondMutex = NULL; sThreadJob.hThread = NULL; sThreadJob.pfnProgress = GWKProgressMonoThread; sThreadJob.pTransformerArg = poWK->pTransformerArg; pfnFunc(&sThreadJob); return !bStop ? CE_None : CE_Failure; } /************************************************************************/ /* GWKRun() */ /************************************************************************/ static CPLErr GWKRun( GDALWarpKernel *poWK, const char* pszFuncName, void (*pfnFunc) (void *pUserData) ) { int nDstYSize = poWK->nDstYSize; CPLDebug( "GDAL", "GDALWarpKernel()::%s()\n" "Src=%d,%d,%dx%d Dst=%d,%d,%dx%d", pszFuncName, poWK->nSrcXOff, poWK->nSrcYOff, poWK->nSrcXSize, poWK->nSrcYSize, poWK->nDstXOff, poWK->nDstYOff, poWK->nDstXSize, poWK->nDstYSize ); if( !poWK->pfnProgress( poWK->dfProgressBase, "", poWK->pProgress ) ) { CPLError( CE_Failure, CPLE_UserInterrupt, "User terminated" ); return CE_Failure; } const char* pszWarpThreads = CSLFetchNameValue(poWK->papszWarpOptions, "NUM_THREADS"); int nThreads; if (pszWarpThreads == NULL) pszWarpThreads = CPLGetConfigOption("GDAL_NUM_THREADS", "1"); if (EQUAL(pszWarpThreads, "ALL_CPUS")) nThreads = CPLGetNumCPUs(); else nThreads = atoi(pszWarpThreads); if (nThreads > 128) nThreads = 128; if (nThreads >= nDstYSize / 2) nThreads = nDstYSize / 2; if (nThreads <= 1) { return GWKGenericMonoThread(poWK, pfnFunc); } else { GWKJobStruct* pasThreadJob = (GWKJobStruct*)CPLCalloc(sizeof(GWKJobStruct), nThreads); /* -------------------------------------------------------------------- */ /* Duplicate pTransformerArg per thread. */ /* -------------------------------------------------------------------- */ int i; int bTransformerCloningSuccess = TRUE; for(i=0;i<nThreads;i++) { pasThreadJob[i].pTransformerArg = GDALCloneTransformer(poWK->pTransformerArg); if( pasThreadJob[i].pTransformerArg == NULL ) { CPLDebug("WARP", "Cannot deserialize transformer"); bTransformerCloningSuccess = FALSE; break; } } if (!bTransformerCloningSuccess) { for(i=0;i<nThreads;i++) { if( pasThreadJob[i].pTransformerArg ) GDALDestroyTransformer(pasThreadJob[i].pTransformerArg); } CPLFree(pasThreadJob); CPLDebug("WARP", "Cannot duplicate transformer function. " "Falling back to mono-thread computation"); return GWKGenericMonoThread(poWK, pfnFunc); } void* hCond = CPLCreateCond(); if (hCond == NULL) { for(i=0;i<nThreads;i++) { if( pasThreadJob[i].pTransformerArg ) GDALDestroyTransformer(pasThreadJob[i].pTransformerArg); } CPLFree(pasThreadJob); CPLDebug("WARP", "Multithreading disabled. " "Falling back to mono-thread computation"); return GWKGenericMonoThread(poWK, pfnFunc); } CPLDebug("WARP", "Using %d threads", nThreads); void* hCondMutex = CPLCreateMutex(); /* and take implicitely the mutex */ volatile int bStop = FALSE; volatile int nCounter = 0; /* -------------------------------------------------------------------- */ /* Lannch worker threads */ /* -------------------------------------------------------------------- */ for(i=0;i<nThreads;i++) { pasThreadJob[i].poWK = poWK; pasThreadJob[i].pnCounter = &nCounter; pasThreadJob[i].iYMin = (int)(((GIntBig)i) * nDstYSize / nThreads); pasThreadJob[i].iYMax = (int)(((GIntBig)(i + 1)) * nDstYSize / nThreads); pasThreadJob[i].pbStop = &bStop; pasThreadJob[i].hCond = hCond; pasThreadJob[i].hCondMutex = hCondMutex; pasThreadJob[i].pfnProgress = GWKProgressThread; pasThreadJob[i].hThread = CPLCreateJoinableThread( pfnFunc, (void*) &pasThreadJob[i] ); } /* -------------------------------------------------------------------- */ /* Report progress. */ /* -------------------------------------------------------------------- */ while(nCounter < nDstYSize) { CPLCondWait(hCond, hCondMutex); if( !poWK->pfnProgress( poWK->dfProgressBase + poWK->dfProgressScale * (nCounter / (double) nDstYSize), "", poWK->pProgress ) ) { CPLError( CE_Failure, CPLE_UserInterrupt, "User terminated" ); bStop = TRUE; break; } } /* Release mutex before joining threads, otherwise they will dead-lock */ /* forever in GWKProgressThread() */ CPLReleaseMutex(hCondMutex); /* -------------------------------------------------------------------- */ /* Wait for all threads to complete and finish. */ /* -------------------------------------------------------------------- */ for(i=0;i<nThreads;i++) { CPLJoinThread(pasThreadJob[i].hThread); GDALDestroyTransformer(pasThreadJob[i].pTransformerArg); } CPLFree(pasThreadJob); CPLDestroyCond(hCond); CPLDestroyMutex(hCondMutex); return !bStop ? CE_None : CE_Failure; } } /************************************************************************/ /* ==================================================================== */ /* GDALWarpKernel */ /* ==================================================================== */ /************************************************************************/ /** * \class GDALWarpKernel "gdalwarper.h" * * Low level image warping class. * * This class is responsible for low level image warping for one * "chunk" of imagery. The class is essentially a structure with all * data members public - primarily so that new special-case functions * can be added without changing the class declaration. * * Applications are normally intended to interactive with warping facilities * through the GDALWarpOperation class, though the GDALWarpKernel can in * theory be used directly if great care is taken in setting up the * control data. * * <h3>Design Issues</h3> * * My intention is that PerformWarp() would analyse the setup in terms * of the datatype, resampling type, and validity/density mask usage and * pick one of many specific implementations of the warping algorithm over * a continuim of optimization vs. generality. At one end there will be a * reference general purpose implementation of the algorithm that supports * any data type (working internally in double precision complex), all three * resampling types, and any or all of the validity/density masks. At the * other end would be highly optimized algorithms for common cases like * nearest neighbour resampling on GDT_Byte data with no masks. * * The full set of optimized versions have not been decided but we should * expect to have at least: * - One for each resampling algorithm for 8bit data with no masks. * - One for each resampling algorithm for float data with no masks. * - One for each resampling algorithm for float data with any/all masks * (essentially the generic case for just float data). * - One for each resampling algorithm for 8bit data with support for * input validity masks (per band or per pixel). This handles the common * case of nodata masking. * - One for each resampling algorithm for float data with support for * input validity masks (per band or per pixel). This handles the common * case of nodata masking. * * Some of the specializations would operate on all bands in one pass * (especially the ones without masking would do this), while others might * process each band individually to reduce code complexity. * * <h3>Masking Semantics</h3> * * A detailed explanation of the semantics of the validity and density masks, * and their effects on resampling kernels is needed here. */ /************************************************************************/ /* GDALWarpKernel Data Members */ /************************************************************************/ /** * \var GDALResampleAlg GDALWarpKernel::eResample; * * Resampling algorithm. * * The resampling algorithm to use. One of GRA_NearestNeighbour, GRA_Bilinear, * GRA_Cubic, GRA_CubicSpline, GRA_Lanczos, GRA_Average, or GRA_Mode. * * This field is required. GDT_NearestNeighbour may be used as a default * value. */ /** * \var GDALDataType GDALWarpKernel::eWorkingDataType; * * Working pixel data type. * * The datatype of pixels in the source image (papabySrcimage) and * destination image (papabyDstImage) buffers. Note that operations on * some data types (such as GDT_Byte) may be much better optimized than other * less common cases. * * This field is required. It may not be GDT_Unknown. */ /** * \var int GDALWarpKernel::nBands; * * Number of bands. * * The number of bands (layers) of imagery being warped. Determines the * number of entries in the papabySrcImage, papanBandSrcValid, * and papabyDstImage arrays. * * This field is required. */ /** * \var int GDALWarpKernel::nSrcXSize; * * Source image width in pixels. * * This field is required. */ /** * \var int GDALWarpKernel::nSrcYSize; * * Source image height in pixels. * * This field is required. */ /** * \var int GDALWarpKernel::papabySrcImage; * * Array of source image band data. * * This is an array of pointers (of size GDALWarpKernel::nBands) pointers * to image data. Each individual band of image data is organized as a single * block of image data in left to right, then bottom to top order. The actual * type of the image data is determined by GDALWarpKernel::eWorkingDataType. * * To access the the pixel value for the (x=3,y=4) pixel (zero based) of * the second band with eWorkingDataType set to GDT_Float32 use code like * this: * * \code * float dfPixelValue; * int nBand = 1; // band indexes are zero based. * int nPixel = 3; // zero based * int nLine = 4; // zero based * * assert( nPixel >= 0 && nPixel < poKern->nSrcXSize ); * assert( nLine >= 0 && nLine < poKern->nSrcYSize ); * assert( nBand >= 0 && nBand < poKern->nBands ); * dfPixelValue = ((float *) poKern->papabySrcImage[nBand-1]) * [nPixel + nLine * poKern->nSrcXSize]; * \endcode * * This field is required. */ /** * \var GUInt32 **GDALWarpKernel::papanBandSrcValid; * * Per band validity mask for source pixels. * * Array of pixel validity mask layers for each source band. Each of * the mask layers is the same size (in pixels) as the source image with * one bit per pixel. Note that it is legal (and common) for this to be * NULL indicating that none of the pixels are invalidated, or for some * band validity masks to be NULL in which case all pixels of the band are * valid. The following code can be used to test the validity of a particular * pixel. * * \code * int bIsValid = TRUE; * int nBand = 1; // band indexes are zero based. * int nPixel = 3; // zero based * int nLine = 4; // zero based * * assert( nPixel >= 0 && nPixel < poKern->nSrcXSize ); * assert( nLine >= 0 && nLine < poKern->nSrcYSize ); * assert( nBand >= 0 && nBand < poKern->nBands ); * * if( poKern->papanBandSrcValid != NULL * && poKern->papanBandSrcValid[nBand] != NULL ) * { * GUInt32 *panBandMask = poKern->papanBandSrcValid[nBand]; * int iPixelOffset = nPixel + nLine * poKern->nSrcXSize; * * bIsValid = panBandMask[iPixelOffset>>5] * & (0x01 << (iPixelOffset & 0x1f)); * } * \endcode */ /** * \var GUInt32 *GDALWarpKernel::panUnifiedSrcValid; * * Per pixel validity mask for source pixels. * * A single validity mask layer that applies to the pixels of all source * bands. It is accessed similarly to papanBandSrcValid, but without the * extra level of band indirection. * * This pointer may be NULL indicating that all pixels are valid. * * Note that if both panUnifiedSrcValid, and papanBandSrcValid are available, * the pixel isn't considered to be valid unless both arrays indicate it is * valid. */ /** * \var float *GDALWarpKernel::pafUnifiedSrcDensity; * * Per pixel density mask for source pixels. * * A single density mask layer that applies to the pixels of all source * bands. It contains values between 0.0 and 1.0 indicating the degree to * which this pixel should be allowed to contribute to the output result. * * This pointer may be NULL indicating that all pixels have a density of 1.0. * * The density for a pixel may be accessed like this: * * \code * float fDensity = 1.0; * int nPixel = 3; // zero based * int nLine = 4; // zero based * * assert( nPixel >= 0 && nPixel < poKern->nSrcXSize ); * assert( nLine >= 0 && nLine < poKern->nSrcYSize ); * if( poKern->pafUnifiedSrcDensity != NULL ) * fDensity = poKern->pafUnifiedSrcDensity * [nPixel + nLine * poKern->nSrcXSize]; * \endcode */ /** * \var int GDALWarpKernel::nDstXSize; * * Width of destination image in pixels. * * This field is required. */ /** * \var int GDALWarpKernel::nDstYSize; * * Height of destination image in pixels. * * This field is required. */ /** * \var GByte **GDALWarpKernel::papabyDstImage; * * Array of destination image band data. * * This is an array of pointers (of size GDALWarpKernel::nBands) pointers * to image data. Each individual band of image data is organized as a single * block of image data in left to right, then bottom to top order. The actual * type of the image data is determined by GDALWarpKernel::eWorkingDataType. * * To access the the pixel value for the (x=3,y=4) pixel (zero based) of * the second band with eWorkingDataType set to GDT_Float32 use code like * this: * * \code * float dfPixelValue; * int nBand = 1; // band indexes are zero based. * int nPixel = 3; // zero based * int nLine = 4; // zero based * * assert( nPixel >= 0 && nPixel < poKern->nDstXSize ); * assert( nLine >= 0 && nLine < poKern->nDstYSize ); * assert( nBand >= 0 && nBand < poKern->nBands ); * dfPixelValue = ((float *) poKern->papabyDstImage[nBand-1]) * [nPixel + nLine * poKern->nSrcYSize]; * \endcode * * This field is required. */ /** * \var GUInt32 *GDALWarpKernel::panDstValid; * * Per pixel validity mask for destination pixels. * * A single validity mask layer that applies to the pixels of all destination * bands. It is accessed similarly to papanUnitifiedSrcValid, but based * on the size of the destination image. * * This pointer may be NULL indicating that all pixels are valid. */ /** * \var float *GDALWarpKernel::pafDstDensity; * * Per pixel density mask for destination pixels. * * A single density mask layer that applies to the pixels of all destination * bands. It contains values between 0.0 and 1.0. * * This pointer may be NULL indicating that all pixels have a density of 1.0. * * The density for a pixel may be accessed like this: * * \code * float fDensity = 1.0; * int nPixel = 3; // zero based * int nLine = 4; // zero based * * assert( nPixel >= 0 && nPixel < poKern->nDstXSize ); * assert( nLine >= 0 && nLine < poKern->nDstYSize ); * if( poKern->pafDstDensity != NULL ) * fDensity = poKern->pafDstDensity[nPixel + nLine * poKern->nDstXSize]; * \endcode */ /** * \var int GDALWarpKernel::nSrcXOff; * * X offset to source pixel coordinates for transformation. * * See pfnTransformer. * * This field is required. */ /** * \var int GDALWarpKernel::nSrcYOff; * * Y offset to source pixel coordinates for transformation. * * See pfnTransformer. * * This field is required. */ /** * \var int GDALWarpKernel::nDstXOff; * * X offset to destination pixel coordinates for transformation. * * See pfnTransformer. * * This field is required. */ /** * \var int GDALWarpKernel::nDstYOff; * * Y offset to destination pixel coordinates for transformation. * * See pfnTransformer. * * This field is required. */ /** * \var GDALTransformerFunc GDALWarpKernel::pfnTransformer; * * Source/destination location transformer. * * The function to call to transform coordinates between source image * pixel/line coordinates and destination image pixel/line coordinates. * See GDALTransformerFunc() for details of the semantics of this function. * * The GDALWarpKern algorithm will only ever use this transformer in * "destination to source" mode (bDstToSrc=TRUE), and will always pass * partial or complete scanlines of points in the destination image as * input. This means, amoung other things, that it is safe to the the * approximating transform GDALApproxTransform() as the transformation * function. * * Source and destination images may be subsets of a larger overall image. * The transformation algorithms will expect and return pixel/line coordinates * in terms of this larger image, so coordinates need to be offset by * the offsets specified in nSrcXOff, nSrcYOff, nDstXOff, and nDstYOff before * passing to pfnTransformer, and after return from it. * * The GDALWarpKernel::pfnTransformerArg value will be passed as the callback * data to this function when it is called. * * This field is required. */ /** * \var void *GDALWarpKernel::pTransformerArg; * * Callback data for pfnTransformer. * * This field may be NULL if not required for the pfnTransformer being used. */ /** * \var GDALProgressFunc GDALWarpKernel::pfnProgress; * * The function to call to report progress of the algorithm, and to check * for a requested termination of the operation. It operates according to * GDALProgressFunc() semantics. * * Generally speaking the progress function will be invoked for each * scanline of the destination buffer that has been processed. * * This field may be NULL (internally set to GDALDummyProgress()). */ /** * \var void *GDALWarpKernel::pProgress; * * Callback data for pfnProgress. * * This field may be NULL if not required for the pfnProgress being used. */ /************************************************************************/ /* GDALWarpKernel() */ /************************************************************************/ GDALWarpKernel::GDALWarpKernel() { eResample = GRA_NearestNeighbour; eWorkingDataType = GDT_Unknown; nBands = 0; nDstXOff = 0; nDstYOff = 0; nDstXSize = 0; nDstYSize = 0; nSrcXOff = 0; nSrcYOff = 0; nSrcXSize = 0; nSrcYSize = 0; dfXScale = 1.0; dfYScale = 1.0; dfXFilter = 0.0; dfYFilter = 0.0; nXRadius = 0; nYRadius = 0; nFiltInitX = 0; nFiltInitY = 0; pafDstDensity = NULL; pafUnifiedSrcDensity = NULL; panDstValid = NULL; panUnifiedSrcValid = NULL; papabyDstImage = NULL; papabySrcImage = NULL; papanBandSrcValid = NULL; pfnProgress = GDALDummyProgress; pProgress = NULL; dfProgressBase = 0.0; dfProgressScale = 1.0; pfnTransformer = NULL; pTransformerArg = NULL; papszWarpOptions = NULL; } /************************************************************************/ /* ~GDALWarpKernel() */ /************************************************************************/ GDALWarpKernel::~GDALWarpKernel() { } /************************************************************************/ /* PerformWarp() */ /************************************************************************/ /** * \fn CPLErr GDALWarpKernel::PerformWarp(); * * This method performs the warp described in the GDALWarpKernel. * * @return CE_None on success or CE_Failure if an error occurs. */ CPLErr GDALWarpKernel::PerformWarp() { CPLErr eErr; if( (eErr = Validate()) != CE_None ) return eErr; // See #2445 and #3079 if (nSrcXSize <= 0 || nSrcYSize <= 0) { if ( !pfnProgress( dfProgressBase + dfProgressScale, "", pProgress ) ) { CPLError( CE_Failure, CPLE_UserInterrupt, "User terminated" ); return CE_Failure; } return CE_None; } /* -------------------------------------------------------------------- */ /* Pre-calculate resampling scales and window sizes for filtering. */ /* -------------------------------------------------------------------- */ dfXScale = (double)nDstXSize / nSrcXSize; dfYScale = (double)nDstYSize / nSrcYSize; if( nSrcXSize >= nDstXSize && nSrcXSize <= nDstXSize + 1 + 2 * anGWKFilterRadius[eResample] ) dfXScale = 1; if( nSrcYSize >= nDstYSize && nSrcYSize <= nDstYSize + 1 + 2 * anGWKFilterRadius[eResample] ) dfYScale = 1; dfXFilter = anGWKFilterRadius[eResample]; dfYFilter = anGWKFilterRadius[eResample]; nXRadius = ( dfXScale < 1.0 ) ? (int)ceil( dfXFilter / dfXScale ) :(int)dfXFilter; nYRadius = ( dfYScale < 1.0 ) ? (int)ceil( dfYFilter / dfYScale ) : (int)dfYFilter; // Filter window offset depends on the parity of the kernel radius nFiltInitX = ((anGWKFilterRadius[eResample] + 1) % 2) - nXRadius; nFiltInitY = ((anGWKFilterRadius[eResample] + 1) % 2) - nYRadius; /* -------------------------------------------------------------------- */ /* Set up resampling functions. */ /* -------------------------------------------------------------------- */ if( CSLFetchBoolean( papszWarpOptions, "USE_GENERAL_CASE", FALSE ) ) return GWKGeneralCase( this ); #if defined(HAVE_OPENCL) if((eWorkingDataType == GDT_Byte || eWorkingDataType == GDT_CInt16 || eWorkingDataType == GDT_UInt16 || eWorkingDataType == GDT_Int16 || eWorkingDataType == GDT_CFloat32 || eWorkingDataType == GDT_Float32) && (eResample == GRA_Bilinear || eResample == GRA_Cubic || eResample == GRA_CubicSpline || eResample == GRA_Lanczos) && CSLFetchBoolean( papszWarpOptions, "USE_OPENCL", TRUE )) { CPLErr eResult = GWKOpenCLCase( this ); // CE_Warning tells us a suitable OpenCL environment was not available // so we fall through to other CPU based methods. if( eResult != CE_Warning ) return eResult; } #endif /* defined HAVE_OPENCL */ if( eWorkingDataType == GDT_Byte && eResample == GRA_NearestNeighbour && papanBandSrcValid == NULL && panUnifiedSrcValid == NULL && pafUnifiedSrcDensity == NULL && panDstValid == NULL && pafDstDensity == NULL ) return GWKNearestNoMasksByte( this ); if( eWorkingDataType == GDT_Byte && eResample == GRA_Bilinear && papanBandSrcValid == NULL && panUnifiedSrcValid == NULL && pafUnifiedSrcDensity == NULL && panDstValid == NULL && pafDstDensity == NULL ) return GWKBilinearNoMasksByte( this ); if( eWorkingDataType == GDT_Byte && eResample == GRA_Cubic && papanBandSrcValid == NULL && panUnifiedSrcValid == NULL && pafUnifiedSrcDensity == NULL && panDstValid == NULL && pafDstDensity == NULL ) return GWKCubicNoMasksByte( this ); if( eWorkingDataType == GDT_Byte && eResample == GRA_CubicSpline && papanBandSrcValid == NULL && panUnifiedSrcValid == NULL && pafUnifiedSrcDensity == NULL && panDstValid == NULL && pafDstDensity == NULL ) return GWKCubicSplineNoMasksByte( this ); if( eWorkingDataType == GDT_Byte && eResample == GRA_NearestNeighbour ) return GWKNearestByte( this ); if( (eWorkingDataType == GDT_Int16 || eWorkingDataType == GDT_UInt16) && eResample == GRA_NearestNeighbour && papanBandSrcValid == NULL && panUnifiedSrcValid == NULL && pafUnifiedSrcDensity == NULL && panDstValid == NULL && pafDstDensity == NULL ) return GWKNearestNoMasksShort( this ); if( (eWorkingDataType == GDT_Int16 ) && eResample == GRA_Cubic && papanBandSrcValid == NULL && panUnifiedSrcValid == NULL && pafUnifiedSrcDensity == NULL && panDstValid == NULL && pafDstDensity == NULL ) return GWKCubicNoMasksShort( this ); if( (eWorkingDataType == GDT_Int16 ) && eResample == GRA_CubicSpline && papanBandSrcValid == NULL && panUnifiedSrcValid == NULL && pafUnifiedSrcDensity == NULL && panDstValid == NULL && pafDstDensity == NULL ) return GWKCubicSplineNoMasksShort( this ); if( (eWorkingDataType == GDT_Int16 ) && eResample == GRA_Bilinear && papanBandSrcValid == NULL && panUnifiedSrcValid == NULL && pafUnifiedSrcDensity == NULL && panDstValid == NULL && pafDstDensity == NULL ) return GWKBilinearNoMasksShort( this ); if( (eWorkingDataType == GDT_Int16 || eWorkingDataType == GDT_UInt16) && eResample == GRA_NearestNeighbour ) return GWKNearestShort( this ); if( eWorkingDataType == GDT_Float32 && eResample == GRA_NearestNeighbour && papanBandSrcValid == NULL && panUnifiedSrcValid == NULL && pafUnifiedSrcDensity == NULL && panDstValid == NULL && pafDstDensity == NULL ) return GWKNearestNoMasksFloat( this ); if( eWorkingDataType == GDT_Float32 && eResample == GRA_NearestNeighbour ) return GWKNearestFloat( this ); if( eResample == GRA_Average ) return GWKAverageOrMode( this ); if( eResample == GRA_Mode ) return GWKAverageOrMode( this ); return GWKGeneralCase( this ); } /************************************************************************/ /* Validate() */ /************************************************************************/ /** * \fn CPLErr GDALWarpKernel::Validate() * * Check the settings in the GDALWarpKernel, and issue a CPLError() * (and return CE_Failure) if the configuration is considered to be * invalid for some reason. * * This method will also do some standard defaulting such as setting * pfnProgress to GDALDummyProgress() if it is NULL. * * @return CE_None on success or CE_Failure if an error is detected. */ CPLErr GDALWarpKernel::Validate() { if ( (size_t)eResample >= (sizeof(anGWKFilterRadius) / sizeof(anGWKFilterRadius[0])) ) { CPLError( CE_Failure, CPLE_AppDefined, "Unsupported resampling method %d.", (int) eResample ); return CE_Failure; } // Safety check for callers that would use GDALWarpKernel without using // GDALWarpOperation. if( (eResample == GRA_CubicSpline || eResample == GRA_Lanczos) && atoi(CSLFetchNameValueDef(papszWarpOptions, "EXTRA_ELTS", "0") ) != WARP_EXTRA_ELTS ) { CPLError( CE_Failure, CPLE_AppDefined, "Source arrays must have WARP_EXTRA_ELTS extra elements at their end. " "See GDALWarpKernel class definition. If this condition is fulfilled, " "define a EXTRA_ELTS=%d warp options", WARP_EXTRA_ELTS); return CE_Failure; } return CE_None; } /************************************************************************/ /* GWKOverlayDensity() */ /* */ /* Compute the final density for the destination pixel. This */ /* is a function of the overlay density (passed in) and the */ /* original density. */ /************************************************************************/ static void GWKOverlayDensity( GDALWarpKernel *poWK, int iDstOffset, double dfDensity ) { if( dfDensity < 0.0001 || poWK->pafDstDensity == NULL ) return; poWK->pafDstDensity[iDstOffset] = (float) ( 1.0 - (1.0 - dfDensity) * (1.0 - poWK->pafDstDensity[iDstOffset]) ); } /************************************************************************/ /* GWKSetPixelValue() */ /************************************************************************/ static int GWKSetPixelValue( GDALWarpKernel *poWK, int iBand, int iDstOffset, double dfDensity, double dfReal, double dfImag ) { GByte *pabyDst = poWK->papabyDstImage[iBand]; /* -------------------------------------------------------------------- */ /* If the source density is less than 100% we need to fetch the */ /* existing destination value, and mix it with the source to */ /* get the new "to apply" value. Also compute composite */ /* density. */ /* */ /* We avoid mixing if density is very near one or risk mixing */ /* in very extreme nodata values and causing odd results (#1610) */ /* -------------------------------------------------------------------- */ if( dfDensity < 0.9999 ) { double dfDstReal, dfDstImag, dfDstDensity = 1.0; if( dfDensity < 0.0001 ) return TRUE; if( poWK->pafDstDensity != NULL ) dfDstDensity = poWK->pafDstDensity[iDstOffset]; else if( poWK->panDstValid != NULL && !((poWK->panDstValid[iDstOffset>>5] & (0x01 << (iDstOffset & 0x1f))) ) ) dfDstDensity = 0.0; // It seems like we also ought to be testing panDstValid[] here! switch( poWK->eWorkingDataType ) { case GDT_Byte: dfDstReal = pabyDst[iDstOffset]; dfDstImag = 0.0; break; case GDT_Int16: dfDstReal = ((GInt16 *) pabyDst)[iDstOffset]; dfDstImag = 0.0; break; case GDT_UInt16: dfDstReal = ((GUInt16 *) pabyDst)[iDstOffset]; dfDstImag = 0.0; break; case GDT_Int32: dfDstReal = ((GInt32 *) pabyDst)[iDstOffset]; dfDstImag = 0.0; break; case GDT_UInt32: dfDstReal = ((GUInt32 *) pabyDst)[iDstOffset]; dfDstImag = 0.0; break; case GDT_Float32: dfDstReal = ((float *) pabyDst)[iDstOffset]; dfDstImag = 0.0; break; case GDT_Float64: dfDstReal = ((double *) pabyDst)[iDstOffset]; dfDstImag = 0.0; break; case GDT_CInt16: dfDstReal = ((GInt16 *) pabyDst)[iDstOffset*2]; dfDstImag = ((GInt16 *) pabyDst)[iDstOffset*2+1]; break; case GDT_CInt32: dfDstReal = ((GInt32 *) pabyDst)[iDstOffset*2]; dfDstImag = ((GInt32 *) pabyDst)[iDstOffset*2+1]; break; case GDT_CFloat32: dfDstReal = ((float *) pabyDst)[iDstOffset*2]; dfDstImag = ((float *) pabyDst)[iDstOffset*2+1]; break; case GDT_CFloat64: dfDstReal = ((double *) pabyDst)[iDstOffset*2]; dfDstImag = ((double *) pabyDst)[iDstOffset*2+1]; break; default: CPLAssert( FALSE ); dfDstDensity = 0.0; return FALSE; } // the destination density is really only relative to the portion // not occluded by the overlay. double dfDstInfluence = (1.0 - dfDensity) * dfDstDensity; dfReal = (dfReal * dfDensity + dfDstReal * dfDstInfluence) / (dfDensity + dfDstInfluence); dfImag = (dfImag * dfDensity + dfDstImag * dfDstInfluence) / (dfDensity + dfDstInfluence); } /* -------------------------------------------------------------------- */ /* Actually apply the destination value. */ /* */ /* Avoid using the destination nodata value for integer datatypes */ /* if by chance it is equal to the computed pixel value. */ /* -------------------------------------------------------------------- */ #define CLAMP(type,minval,maxval) \ do { \ if (dfReal < minval) ((type *) pabyDst)[iDstOffset] = (type)minval; \ else if (dfReal > maxval) ((type *) pabyDst)[iDstOffset] = (type)maxval; \ else ((type *) pabyDst)[iDstOffset] = (minval < 0) ? (type)floor(dfReal + 0.5) : (type)(dfReal + 0.5); \ if (poWK->padfDstNoDataReal != NULL && \ poWK->padfDstNoDataReal[iBand] == (double)((type *) pabyDst)[iDstOffset]) \ { \ if (((type *) pabyDst)[iDstOffset] == minval) \ ((type *) pabyDst)[iDstOffset] = (type)(minval + 1); \ else \ ((type *) pabyDst)[iDstOffset] --; \ } } while(0) switch( poWK->eWorkingDataType ) { case GDT_Byte: CLAMP(GByte, 0.0, 255.0); break; case GDT_Int16: CLAMP(GInt16, -32768.0, 32767.0); break; case GDT_UInt16: CLAMP(GUInt16, 0.0, 65535.0); break; case GDT_UInt32: CLAMP(GUInt32, 0.0, 4294967295.0); break; case GDT_Int32: CLAMP(GInt32, -2147483648.0, 2147483647.0); break; case GDT_Float32: ((float *) pabyDst)[iDstOffset] = (float) dfReal; break; case GDT_Float64: ((double *) pabyDst)[iDstOffset] = dfReal; break; case GDT_CInt16: if( dfReal < -32768 ) ((GInt16 *) pabyDst)[iDstOffset*2] = -32768; else if( dfReal > 32767 ) ((GInt16 *) pabyDst)[iDstOffset*2] = 32767; else ((GInt16 *) pabyDst)[iDstOffset*2] = (GInt16) floor(dfReal+0.5); if( dfImag < -32768 ) ((GInt16 *) pabyDst)[iDstOffset*2+1] = -32768; else if( dfImag > 32767 ) ((GInt16 *) pabyDst)[iDstOffset*2+1] = 32767; else ((GInt16 *) pabyDst)[iDstOffset*2+1] = (GInt16) floor(dfImag+0.5); break; case GDT_CInt32: if( dfReal < -2147483648.0 ) ((GInt32 *) pabyDst)[iDstOffset*2] = (GInt32) -2147483648.0; else if( dfReal > 2147483647.0 ) ((GInt32 *) pabyDst)[iDstOffset*2] = (GInt32) 2147483647.0; else ((GInt32 *) pabyDst)[iDstOffset*2] = (GInt32) floor(dfReal+0.5); if( dfImag < -2147483648.0 ) ((GInt32 *) pabyDst)[iDstOffset*2+1] = (GInt32) -2147483648.0; else if( dfImag > 2147483647.0 ) ((GInt32 *) pabyDst)[iDstOffset*2+1] = (GInt32) 2147483647.0; else ((GInt32 *) pabyDst)[iDstOffset*2+1] = (GInt32) floor(dfImag+0.5); break; case GDT_CFloat32: ((float *) pabyDst)[iDstOffset*2] = (float) dfReal; ((float *) pabyDst)[iDstOffset*2+1] = (float) dfImag; break; case GDT_CFloat64: ((double *) pabyDst)[iDstOffset*2] = (double) dfReal; ((double *) pabyDst)[iDstOffset*2+1] = (double) dfImag; break; default: return FALSE; } return TRUE; } /************************************************************************/ /* GWKGetPixelValue() */ /************************************************************************/ static int GWKGetPixelValue( GDALWarpKernel *poWK, int iBand, int iSrcOffset, double *pdfDensity, double *pdfReal, double *pdfImag ) { GByte *pabySrc = poWK->papabySrcImage[iBand]; if( poWK->panUnifiedSrcValid != NULL && !((poWK->panUnifiedSrcValid[iSrcOffset>>5] & (0x01 << (iSrcOffset & 0x1f))) ) ) { *pdfDensity = 0.0; return FALSE; } if( poWK->papanBandSrcValid != NULL && poWK->papanBandSrcValid[iBand] != NULL && !((poWK->papanBandSrcValid[iBand][iSrcOffset>>5] & (0x01 << (iSrcOffset & 0x1f)))) ) { *pdfDensity = 0.0; return FALSE; } switch( poWK->eWorkingDataType ) { case GDT_Byte: *pdfReal = pabySrc[iSrcOffset]; *pdfImag = 0.0; break; case GDT_Int16: *pdfReal = ((GInt16 *) pabySrc)[iSrcOffset]; *pdfImag = 0.0; break; case GDT_UInt16: *pdfReal = ((GUInt16 *) pabySrc)[iSrcOffset]; *pdfImag = 0.0; break; case GDT_Int32: *pdfReal = ((GInt32 *) pabySrc)[iSrcOffset]; *pdfImag = 0.0; break; case GDT_UInt32: *pdfReal = ((GUInt32 *) pabySrc)[iSrcOffset]; *pdfImag = 0.0; break; case GDT_Float32: *pdfReal = ((float *) pabySrc)[iSrcOffset]; *pdfImag = 0.0; break; case GDT_Float64: *pdfReal = ((double *) pabySrc)[iSrcOffset]; *pdfImag = 0.0; break; case GDT_CInt16: *pdfReal = ((GInt16 *) pabySrc)[iSrcOffset*2]; *pdfImag = ((GInt16 *) pabySrc)[iSrcOffset*2+1]; break; case GDT_CInt32: *pdfReal = ((GInt32 *) pabySrc)[iSrcOffset*2]; *pdfImag = ((GInt32 *) pabySrc)[iSrcOffset*2+1]; break; case GDT_CFloat32: *pdfReal = ((float *) pabySrc)[iSrcOffset*2]; *pdfImag = ((float *) pabySrc)[iSrcOffset*2+1]; break; case GDT_CFloat64: *pdfReal = ((double *) pabySrc)[iSrcOffset*2]; *pdfImag = ((double *) pabySrc)[iSrcOffset*2+1]; break; default: *pdfDensity = 0.0; return FALSE; } if( poWK->pafUnifiedSrcDensity != NULL ) *pdfDensity = poWK->pafUnifiedSrcDensity[iSrcOffset]; else *pdfDensity = 1.0; return *pdfDensity != 0.0; } /************************************************************************/ /* GWKGetPixelRow() */ /************************************************************************/ /* It is assumed that adfImag[] is set to 0 by caller code for non-complex */ /* data-types. */ static int GWKGetPixelRow( GDALWarpKernel *poWK, int iBand, int iSrcOffset, int nHalfSrcLen, double* padfDensity, double adfReal[], double* padfImag ) { // We know that nSrcLen is even, so we can *always* unroll loops 2x int nSrcLen = nHalfSrcLen * 2; int bHasValid = FALSE; int i; if( padfDensity != NULL ) { // Init the density for ( i = 0; i < nSrcLen; i += 2 ) { padfDensity[i] = 1.0; padfDensity[i+1] = 1.0; } if ( poWK->panUnifiedSrcValid != NULL ) { for ( i = 0; i < nSrcLen; i += 2 ) { if(poWK->panUnifiedSrcValid[(iSrcOffset+i)>>5] & (0x01 << ((iSrcOffset+i) & 0x1f))) bHasValid = TRUE; else padfDensity[i] = 0.0; if(poWK->panUnifiedSrcValid[(iSrcOffset+i+1)>>5] & (0x01 << ((iSrcOffset+i+1) & 0x1f))) bHasValid = TRUE; else padfDensity[i+1] = 0.0; } // Reset or fail as needed if ( bHasValid ) bHasValid = FALSE; else return FALSE; } if ( poWK->papanBandSrcValid != NULL && poWK->papanBandSrcValid[iBand] != NULL) { for ( i = 0; i < nSrcLen; i += 2 ) { if(poWK->papanBandSrcValid[iBand][(iSrcOffset+i)>>5] & (0x01 << ((iSrcOffset+i) & 0x1f))) bHasValid = TRUE; else padfDensity[i] = 0.0; if(poWK->papanBandSrcValid[iBand][(iSrcOffset+i+1)>>5] & (0x01 << ((iSrcOffset+i+1) & 0x1f))) bHasValid = TRUE; else padfDensity[i+1] = 0.0; } // Reset or fail as needed if ( bHasValid ) bHasValid = FALSE; else return FALSE; } } // Fetch data switch( poWK->eWorkingDataType ) { case GDT_Byte: { GByte* pSrc = (GByte*) poWK->papabySrcImage[iBand]; pSrc += iSrcOffset; for ( i = 0; i < nSrcLen; i += 2 ) { adfReal[i] = pSrc[i]; adfReal[i+1] = pSrc[i+1]; } break; } case GDT_Int16: { GInt16* pSrc = (GInt16*) poWK->papabySrcImage[iBand]; pSrc += iSrcOffset; for ( i = 0; i < nSrcLen; i += 2 ) { adfReal[i] = pSrc[i]; adfReal[i+1] = pSrc[i+1]; } break; } case GDT_UInt16: { GUInt16* pSrc = (GUInt16*) poWK->papabySrcImage[iBand]; pSrc += iSrcOffset; for ( i = 0; i < nSrcLen; i += 2 ) { adfReal[i] = pSrc[i]; adfReal[i+1] = pSrc[i+1]; } break; } case GDT_Int32: { GInt32* pSrc = (GInt32*) poWK->papabySrcImage[iBand]; pSrc += iSrcOffset; for ( i = 0; i < nSrcLen; i += 2 ) { adfReal[i] = pSrc[i]; adfReal[i+1] = pSrc[i+1]; } break; } case GDT_UInt32: { GUInt32* pSrc = (GUInt32*) poWK->papabySrcImage[iBand]; pSrc += iSrcOffset; for ( i = 0; i < nSrcLen; i += 2 ) { adfReal[i] = pSrc[i]; adfReal[i+1] = pSrc[i+1]; } break; } case GDT_Float32: { float* pSrc = (float*) poWK->papabySrcImage[iBand]; pSrc += iSrcOffset; for ( i = 0; i < nSrcLen; i += 2 ) { adfReal[i] = pSrc[i]; adfReal[i+1] = pSrc[i+1]; } break; } case GDT_Float64: { double* pSrc = (double*) poWK->papabySrcImage[iBand]; pSrc += iSrcOffset; for ( i = 0; i < nSrcLen; i += 2 ) { adfReal[i] = pSrc[i]; adfReal[i+1] = pSrc[i+1]; } break; } case GDT_CInt16: { GInt16* pSrc = (GInt16*) poWK->papabySrcImage[iBand]; pSrc += 2 * iSrcOffset; for ( i = 0; i < nSrcLen; i += 2 ) { adfReal[i] = pSrc[2*i]; padfImag[i] = pSrc[2*i+1]; adfReal[i+1] = pSrc[2*i+2]; padfImag[i+1] = pSrc[2*i+3]; } break; } case GDT_CInt32: { GInt32* pSrc = (GInt32*) poWK->papabySrcImage[iBand]; pSrc += 2 * iSrcOffset; for ( i = 0; i < nSrcLen; i += 2 ) { adfReal[i] = pSrc[2*i]; padfImag[i] = pSrc[2*i+1]; adfReal[i+1] = pSrc[2*i+2]; padfImag[i+1] = pSrc[2*i+3]; } break; } case GDT_CFloat32: { float* pSrc = (float*) poWK->papabySrcImage[iBand]; pSrc += 2 * iSrcOffset; for ( i = 0; i < nSrcLen; i += 2 ) { adfReal[i] = pSrc[2*i]; padfImag[i] = pSrc[2*i+1]; adfReal[i+1] = pSrc[2*i+2]; padfImag[i+1] = pSrc[2*i+3]; } break; } case GDT_CFloat64: { double* pSrc = (double*) poWK->papabySrcImage[iBand]; pSrc += 2 * iSrcOffset; for ( i = 0; i < nSrcLen; i += 2 ) { adfReal[i] = pSrc[2*i]; padfImag[i] = pSrc[2*i+1]; adfReal[i+1] = pSrc[2*i+2]; padfImag[i+1] = pSrc[2*i+3]; } break; } default: CPLAssert(FALSE); if( padfDensity ) memset( padfDensity, 0, nSrcLen * sizeof(double) ); return FALSE; } if( padfDensity == NULL ) return TRUE; if( poWK->pafUnifiedSrcDensity == NULL ) { for ( i = 0; i < nSrcLen; i += 2 ) { // Take into account earlier calcs if(padfDensity[i] > 0.000000001) { padfDensity[i] = 1.0; bHasValid = TRUE; } if(padfDensity[i+1] > 0.000000001) { padfDensity[i+1] = 1.0; bHasValid = TRUE; } } } else { for ( i = 0; i < nSrcLen; i += 2 ) { if(padfDensity[i] > 0.000000001) padfDensity[i] = poWK->pafUnifiedSrcDensity[iSrcOffset+i]; if(padfDensity[i] > 0.000000001) bHasValid = TRUE; if(padfDensity[i+1] > 0.000000001) padfDensity[i+1] = poWK->pafUnifiedSrcDensity[iSrcOffset+i+1]; if(padfDensity[i+1] > 0.000000001) bHasValid = TRUE; } } return bHasValid; } /************************************************************************/ /* GWKGetPixelByte() */ /************************************************************************/ static int GWKGetPixelByte( GDALWarpKernel *poWK, int iBand, int iSrcOffset, double *pdfDensity, GByte *pbValue ) { GByte *pabySrc = poWK->papabySrcImage[iBand]; if ( ( poWK->panUnifiedSrcValid != NULL && !((poWK->panUnifiedSrcValid[iSrcOffset>>5] & (0x01 << (iSrcOffset & 0x1f))) ) ) || ( poWK->papanBandSrcValid != NULL && poWK->papanBandSrcValid[iBand] != NULL && !((poWK->papanBandSrcValid[iBand][iSrcOffset>>5] & (0x01 << (iSrcOffset & 0x1f)))) ) ) { *pdfDensity = 0.0; return FALSE; } *pbValue = pabySrc[iSrcOffset]; if ( poWK->pafUnifiedSrcDensity == NULL ) *pdfDensity = 1.0; else *pdfDensity = poWK->pafUnifiedSrcDensity[iSrcOffset]; return *pdfDensity != 0.0; } /************************************************************************/ /* GWKGetPixelShort() */ /************************************************************************/ static int GWKGetPixelShort( GDALWarpKernel *poWK, int iBand, int iSrcOffset, double *pdfDensity, GInt16 *piValue ) { GInt16 *pabySrc = (GInt16 *)poWK->papabySrcImage[iBand]; if ( ( poWK->panUnifiedSrcValid != NULL && !((poWK->panUnifiedSrcValid[iSrcOffset>>5] & (0x01 << (iSrcOffset & 0x1f))) ) ) || ( poWK->papanBandSrcValid != NULL && poWK->papanBandSrcValid[iBand] != NULL && !((poWK->papanBandSrcValid[iBand][iSrcOffset>>5] & (0x01 << (iSrcOffset & 0x1f)))) ) ) { *pdfDensity = 0.0; return FALSE; } *piValue = pabySrc[iSrcOffset]; if ( poWK->pafUnifiedSrcDensity == NULL ) *pdfDensity = 1.0; else *pdfDensity = poWK->pafUnifiedSrcDensity[iSrcOffset]; return *pdfDensity != 0.0; } /************************************************************************/ /* GWKGetPixelFloat() */ /************************************************************************/ static int GWKGetPixelFloat( GDALWarpKernel *poWK, int iBand, int iSrcOffset, double *pdfDensity, float *pfValue ) { float *pabySrc = (float *)poWK->papabySrcImage[iBand]; if ( ( poWK->panUnifiedSrcValid != NULL && !((poWK->panUnifiedSrcValid[iSrcOffset>>5] & (0x01 << (iSrcOffset & 0x1f))) ) ) || ( poWK->papanBandSrcValid != NULL && poWK->papanBandSrcValid[iBand] != NULL && !((poWK->papanBandSrcValid[iBand][iSrcOffset>>5] & (0x01 << (iSrcOffset & 0x1f)))) ) ) { *pdfDensity = 0.0; return FALSE; } *pfValue = pabySrc[iSrcOffset]; if ( poWK->pafUnifiedSrcDensity == NULL ) *pdfDensity = 1.0; else *pdfDensity = poWK->pafUnifiedSrcDensity[iSrcOffset]; return *pdfDensity != 0.0; } /************************************************************************/ /* GWKBilinearResample() */ /* Set of bilinear interpolators */ /************************************************************************/ static int GWKBilinearResample( GDALWarpKernel *poWK, int iBand, double dfSrcX, double dfSrcY, double *pdfDensity, double *pdfReal, double *pdfImag ) { // Save as local variables to avoid following pointers int nSrcXSize = poWK->nSrcXSize; int nSrcYSize = poWK->nSrcYSize; int iSrcX = (int) floor(dfSrcX - 0.5); int iSrcY = (int) floor(dfSrcY - 0.5); int iSrcOffset; double dfRatioX = 1.5 - (dfSrcX - iSrcX); double dfRatioY = 1.5 - (dfSrcY - iSrcY); double adfDensity[2], adfReal[2], adfImag[2] = {0, 0}; double dfAccumulatorReal = 0.0, dfAccumulatorImag = 0.0; double dfAccumulatorDensity = 0.0; double dfAccumulatorDivisor = 0.0; int bShifted = FALSE; if (iSrcX == -1) { iSrcX = 0; dfRatioX = 1; } if (iSrcY == -1) { iSrcY = 0; dfRatioY = 1; } iSrcOffset = iSrcX + iSrcY * nSrcXSize; // Shift so we don't overrun the array if( nSrcXSize * nSrcYSize == iSrcOffset + 1 || nSrcXSize * nSrcYSize == iSrcOffset + nSrcXSize + 1 ) { bShifted = TRUE; --iSrcOffset; } // Get pixel row if ( iSrcY >= 0 && iSrcY < nSrcYSize && iSrcOffset >= 0 && iSrcOffset < nSrcXSize * nSrcYSize && GWKGetPixelRow( poWK, iBand, iSrcOffset, 1, adfDensity, adfReal, adfImag ) ) { double dfMult1 = dfRatioX * dfRatioY; double dfMult2 = (1.0-dfRatioX) * dfRatioY; // Shifting corrected if ( bShifted ) { adfReal[0] = adfReal[1]; adfImag[0] = adfImag[1]; adfDensity[0] = adfDensity[1]; } // Upper Left Pixel if ( iSrcX >= 0 && iSrcX < nSrcXSize && adfDensity[0] > 0.000000001 ) { dfAccumulatorDivisor += dfMult1; dfAccumulatorReal += adfReal[0] * dfMult1; dfAccumulatorImag += adfImag[0] * dfMult1; dfAccumulatorDensity += adfDensity[0] * dfMult1; } // Upper Right Pixel if ( iSrcX+1 >= 0 && iSrcX+1 < nSrcXSize && adfDensity[1] > 0.000000001 ) { dfAccumulatorDivisor += dfMult2; dfAccumulatorReal += adfReal[1] * dfMult2; dfAccumulatorImag += adfImag[1] * dfMult2; dfAccumulatorDensity += adfDensity[1] * dfMult2; } } // Get pixel row if ( iSrcY+1 >= 0 && iSrcY+1 < nSrcYSize && iSrcOffset+nSrcXSize >= 0 && iSrcOffset+nSrcXSize < nSrcXSize * nSrcYSize && GWKGetPixelRow( poWK, iBand, iSrcOffset+nSrcXSize, 1, adfDensity, adfReal, adfImag ) ) { double dfMult1 = dfRatioX * (1.0-dfRatioY); double dfMult2 = (1.0-dfRatioX) * (1.0-dfRatioY); // Shifting corrected if ( bShifted ) { adfReal[0] = adfReal[1]; adfImag[0] = adfImag[1]; adfDensity[0] = adfDensity[1]; } // Lower Left Pixel if ( iSrcX >= 0 && iSrcX < nSrcXSize && adfDensity[0] > 0.000000001 ) { dfAccumulatorDivisor += dfMult1; dfAccumulatorReal += adfReal[0] * dfMult1; dfAccumulatorImag += adfImag[0] * dfMult1; dfAccumulatorDensity += adfDensity[0] * dfMult1; } // Lower Right Pixel if ( iSrcX+1 >= 0 && iSrcX+1 < nSrcXSize && adfDensity[1] > 0.000000001 ) { dfAccumulatorDivisor += dfMult2; dfAccumulatorReal += adfReal[1] * dfMult2; dfAccumulatorImag += adfImag[1] * dfMult2; dfAccumulatorDensity += adfDensity[1] * dfMult2; } } /* -------------------------------------------------------------------- */ /* Return result. */ /* -------------------------------------------------------------------- */ if ( dfAccumulatorDivisor == 1.0 ) { *pdfReal = dfAccumulatorReal; *pdfImag = dfAccumulatorImag; *pdfDensity = dfAccumulatorDensity; return TRUE; } else if ( dfAccumulatorDivisor < 0.00001 ) { *pdfReal = 0.0; *pdfImag = 0.0; *pdfDensity = 0.0; return FALSE; } else { *pdfReal = dfAccumulatorReal / dfAccumulatorDivisor; *pdfImag = dfAccumulatorImag / dfAccumulatorDivisor; *pdfDensity = dfAccumulatorDensity / dfAccumulatorDivisor; return TRUE; } } static int GWKBilinearResampleNoMasksByte( GDALWarpKernel *poWK, int iBand, double dfSrcX, double dfSrcY, GByte *pbValue ) { double dfAccumulator = 0.0; double dfAccumulatorDivisor = 0.0; int iSrcX = (int) floor(dfSrcX - 0.5); int iSrcY = (int) floor(dfSrcY - 0.5); int iSrcOffset = iSrcX + iSrcY * poWK->nSrcXSize; double dfRatioX = 1.5 - (dfSrcX - iSrcX); double dfRatioY = 1.5 - (dfSrcY - iSrcY); // Upper Left Pixel if( iSrcX >= 0 && iSrcX < poWK->nSrcXSize && iSrcY >= 0 && iSrcY < poWK->nSrcYSize ) { double dfMult = dfRatioX * dfRatioY; dfAccumulatorDivisor += dfMult; dfAccumulator += (double)poWK->papabySrcImage[iBand][iSrcOffset] * dfMult; } // Upper Right Pixel if( iSrcX+1 >= 0 && iSrcX+1 < poWK->nSrcXSize && iSrcY >= 0 && iSrcY < poWK->nSrcYSize ) { double dfMult = (1.0-dfRatioX) * dfRatioY; dfAccumulatorDivisor += dfMult; dfAccumulator += (double)poWK->papabySrcImage[iBand][iSrcOffset+1] * dfMult; } // Lower Right Pixel if( iSrcX+1 >= 0 && iSrcX+1 < poWK->nSrcXSize && iSrcY+1 >= 0 && iSrcY+1 < poWK->nSrcYSize ) { double dfMult = (1.0-dfRatioX) * (1.0-dfRatioY); dfAccumulatorDivisor += dfMult; dfAccumulator += (double)poWK->papabySrcImage[iBand][iSrcOffset+1+poWK->nSrcXSize] * dfMult; } // Lower Left Pixel if( iSrcX >= 0 && iSrcX < poWK->nSrcXSize && iSrcY+1 >= 0 && iSrcY+1 < poWK->nSrcYSize ) { double dfMult = dfRatioX * (1.0-dfRatioY); dfAccumulatorDivisor += dfMult; dfAccumulator += (double)poWK->papabySrcImage[iBand][iSrcOffset+poWK->nSrcXSize] * dfMult; } /* -------------------------------------------------------------------- */ /* Return result. */ /* -------------------------------------------------------------------- */ double dfValue; if( dfAccumulatorDivisor < 0.00001 ) { *pbValue = 0; return FALSE; } else if( dfAccumulatorDivisor == 1.0 ) { dfValue = dfAccumulator; } else { dfValue = dfAccumulator / dfAccumulatorDivisor; } if ( dfValue < 0.0 ) *pbValue = 0; else if ( dfValue > 255.0 ) *pbValue = 255; else *pbValue = (GByte)(0.5 + dfValue); return TRUE; } static int GWKBilinearResampleNoMasksShort( GDALWarpKernel *poWK, int iBand, double dfSrcX, double dfSrcY, GInt16 *piValue ) { double dfAccumulator = 0.0; double dfAccumulatorDivisor = 0.0; int iSrcX = (int) floor(dfSrcX - 0.5); int iSrcY = (int) floor(dfSrcY - 0.5); int iSrcOffset = iSrcX + iSrcY * poWK->nSrcXSize; double dfRatioX = 1.5 - (dfSrcX - iSrcX); double dfRatioY = 1.5 - (dfSrcY - iSrcY); // Upper Left Pixel if( iSrcX >= 0 && iSrcX < poWK->nSrcXSize && iSrcY >= 0 && iSrcY < poWK->nSrcYSize ) { double dfMult = dfRatioX * dfRatioY; dfAccumulatorDivisor += dfMult; dfAccumulator += (double)((GInt16 *)poWK->papabySrcImage[iBand])[iSrcOffset] * dfMult; } // Upper Right Pixel if( iSrcX+1 >= 0 && iSrcX+1 < poWK->nSrcXSize && iSrcY >= 0 && iSrcY < poWK->nSrcYSize ) { double dfMult = (1.0-dfRatioX) * dfRatioY; dfAccumulatorDivisor += dfMult; dfAccumulator += (double)((GInt16 *)poWK->papabySrcImage[iBand])[iSrcOffset+1] * dfMult; } // Lower Right Pixel if( iSrcX+1 >= 0 && iSrcX+1 < poWK->nSrcXSize && iSrcY+1 >= 0 && iSrcY+1 < poWK->nSrcYSize ) { double dfMult = (1.0-dfRatioX) * (1.0-dfRatioY); dfAccumulatorDivisor += dfMult; dfAccumulator += (double)((GInt16 *)poWK->papabySrcImage[iBand])[iSrcOffset+1+poWK->nSrcXSize] * dfMult; } // Lower Left Pixel if( iSrcX >= 0 && iSrcX < poWK->nSrcXSize && iSrcY+1 >= 0 && iSrcY+1 < poWK->nSrcYSize ) { double dfMult = dfRatioX * (1.0-dfRatioY); dfAccumulatorDivisor += dfMult; dfAccumulator += (double)((GInt16 *)poWK->papabySrcImage[iBand])[iSrcOffset+poWK->nSrcXSize] * dfMult; } /* -------------------------------------------------------------------- */ /* Return result. */ /* -------------------------------------------------------------------- */ if( dfAccumulatorDivisor == 1.0 ) { *piValue = (GInt16)(0.5 + dfAccumulator); return TRUE; } else if( dfAccumulatorDivisor < 0.00001 ) { *piValue = 0; return FALSE; } else { *piValue = (GInt16)(0.5 + dfAccumulator / dfAccumulatorDivisor); return TRUE; } } /************************************************************************/ /* GWKCubicResample() */ /* Set of bicubic interpolators using cubic convolution. */ /************************************************************************/ #define CubicConvolution(distance1,distance2,distance3,f0,f1,f2,f3) \ ( f1 \ + distance1*0.5*(f2 - f0) \ + distance2*0.5*(2.0*f0 - 5.0*f1 + 4.0*f2 - f3) \ + distance3*0.5*(3.0*(f1 - f2) + f3 - f0)) static int GWKCubicResample( GDALWarpKernel *poWK, int iBand, double dfSrcX, double dfSrcY, double *pdfDensity, double *pdfReal, double *pdfImag ) { int iSrcX = (int) (dfSrcX - 0.5); int iSrcY = (int) (dfSrcY - 0.5); int iSrcOffset = iSrcX + iSrcY * poWK->nSrcXSize; double dfDeltaX = dfSrcX - 0.5 - iSrcX; double dfDeltaY = dfSrcY - 0.5 - iSrcY; double dfDeltaX2 = dfDeltaX * dfDeltaX; double dfDeltaY2 = dfDeltaY * dfDeltaY; double dfDeltaX3 = dfDeltaX2 * dfDeltaX; double dfDeltaY3 = dfDeltaY2 * dfDeltaY; double adfValueDens[4], adfValueReal[4], adfValueImag[4]; double adfDensity[4], adfReal[4], adfImag[4] = {0, 0, 0, 0}; int i; // Get the bilinear interpolation at the image borders if ( iSrcX - 1 < 0 || iSrcX + 2 >= poWK->nSrcXSize || iSrcY - 1 < 0 || iSrcY + 2 >= poWK->nSrcYSize ) return GWKBilinearResample( poWK, iBand, dfSrcX, dfSrcY, pdfDensity, pdfReal, pdfImag ); for ( i = -1; i < 3; i++ ) { if ( !GWKGetPixelRow(poWK, iBand, iSrcOffset + i * poWK->nSrcXSize - 1, 2, adfDensity, adfReal, adfImag) || adfDensity[0] < 0.000000001 || adfDensity[1] < 0.000000001 || adfDensity[2] < 0.000000001 || adfDensity[3] < 0.000000001 ) { return GWKBilinearResample( poWK, iBand, dfSrcX, dfSrcY, pdfDensity, pdfReal, pdfImag ); } adfValueDens[i + 1] = CubicConvolution(dfDeltaX, dfDeltaX2, dfDeltaX3, adfDensity[0], adfDensity[1], adfDensity[2], adfDensity[3]); adfValueReal[i + 1] = CubicConvolution(dfDeltaX, dfDeltaX2, dfDeltaX3, adfReal[0], adfReal[1], adfReal[2], adfReal[3]); adfValueImag[i + 1] = CubicConvolution(dfDeltaX, dfDeltaX2, dfDeltaX3, adfImag[0], adfImag[1], adfImag[2], adfImag[3]); } /* -------------------------------------------------------------------- */ /* For now, if we have any pixels missing in the kernel area, */ /* we fallback on using bilinear interpolation. Ideally we */ /* should do "weight adjustment" of our results similarly to */ /* what is done for the cubic spline and lanc. interpolators. */ /* -------------------------------------------------------------------- */ *pdfDensity = CubicConvolution(dfDeltaY, dfDeltaY2, dfDeltaY3, adfValueDens[0], adfValueDens[1], adfValueDens[2], adfValueDens[3]); *pdfReal = CubicConvolution(dfDeltaY, dfDeltaY2, dfDeltaY3, adfValueReal[0], adfValueReal[1], adfValueReal[2], adfValueReal[3]); *pdfImag = CubicConvolution(dfDeltaY, dfDeltaY2, dfDeltaY3, adfValueImag[0], adfValueImag[1], adfValueImag[2], adfValueImag[3]); return TRUE; } static int GWKCubicResampleNoMasksByte( GDALWarpKernel *poWK, int iBand, double dfSrcX, double dfSrcY, GByte *pbValue ) { int iSrcX = (int) (dfSrcX - 0.5); int iSrcY = (int) (dfSrcY - 0.5); int iSrcOffset = iSrcX + iSrcY * poWK->nSrcXSize; double dfDeltaX = dfSrcX - 0.5 - iSrcX; double dfDeltaY = dfSrcY - 0.5 - iSrcY; double dfDeltaX2 = dfDeltaX * dfDeltaX; double dfDeltaY2 = dfDeltaY * dfDeltaY; double dfDeltaX3 = dfDeltaX2 * dfDeltaX; double dfDeltaY3 = dfDeltaY2 * dfDeltaY; double adfValue[4]; int i; // Get the bilinear interpolation at the image borders if ( iSrcX - 1 < 0 || iSrcX + 2 >= poWK->nSrcXSize || iSrcY - 1 < 0 || iSrcY + 2 >= poWK->nSrcYSize ) return GWKBilinearResampleNoMasksByte( poWK, iBand, dfSrcX, dfSrcY, pbValue); for ( i = -1; i < 3; i++ ) { int iOffset = iSrcOffset + i * poWK->nSrcXSize; adfValue[i + 1] = CubicConvolution(dfDeltaX, dfDeltaX2, dfDeltaX3, (double)poWK->papabySrcImage[iBand][iOffset - 1], (double)poWK->papabySrcImage[iBand][iOffset], (double)poWK->papabySrcImage[iBand][iOffset + 1], (double)poWK->papabySrcImage[iBand][iOffset + 2]); } double dfValue = CubicConvolution(dfDeltaY, dfDeltaY2, dfDeltaY3, adfValue[0], adfValue[1], adfValue[2], adfValue[3]); if ( dfValue < 0.0 ) *pbValue = 0; else if ( dfValue > 255.0 ) *pbValue = 255; else *pbValue = (GByte)(0.5 + dfValue); return TRUE; } static int GWKCubicResampleNoMasksShort( GDALWarpKernel *poWK, int iBand, double dfSrcX, double dfSrcY, GInt16 *piValue ) { int iSrcX = (int) (dfSrcX - 0.5); int iSrcY = (int) (dfSrcY - 0.5); int iSrcOffset = iSrcX + iSrcY * poWK->nSrcXSize; double dfDeltaX = dfSrcX - 0.5 - iSrcX; double dfDeltaY = dfSrcY - 0.5 - iSrcY; double dfDeltaX2 = dfDeltaX * dfDeltaX; double dfDeltaY2 = dfDeltaY * dfDeltaY; double dfDeltaX3 = dfDeltaX2 * dfDeltaX; double dfDeltaY3 = dfDeltaY2 * dfDeltaY; double adfValue[4]; int i; // Get the bilinear interpolation at the image borders if ( iSrcX - 1 < 0 || iSrcX + 2 >= poWK->nSrcXSize || iSrcY - 1 < 0 || iSrcY + 2 >= poWK->nSrcYSize ) return GWKBilinearResampleNoMasksShort( poWK, iBand, dfSrcX, dfSrcY, piValue); for ( i = -1; i < 3; i++ ) { int iOffset = iSrcOffset + i * poWK->nSrcXSize; adfValue[i + 1] =CubicConvolution(dfDeltaX, dfDeltaX2, dfDeltaX3, (double)((GInt16 *)poWK->papabySrcImage[iBand])[iOffset - 1], (double)((GInt16 *)poWK->papabySrcImage[iBand])[iOffset], (double)((GInt16 *)poWK->papabySrcImage[iBand])[iOffset + 1], (double)((GInt16 *)poWK->papabySrcImage[iBand])[iOffset + 2]); } double dfValue = CubicConvolution( dfDeltaY, dfDeltaY2, dfDeltaY3, adfValue[0], adfValue[1], adfValue[2], adfValue[3]); if ( dfValue < -32768.0 ) *piValue = -32768; else if ( dfValue > 32767.0 ) *piValue = 32767; else *piValue = (GInt16)floor(0.5 + dfValue); return TRUE; } /************************************************************************/ /* GWKLanczosSinc() */ /************************************************************************/ /* * Lanczos windowed sinc interpolation kernel with radius r. * / * | sinc(x) * sinc(x/r), if |x| < r * L(x) = | 1, if x = 0 , * | 0, otherwise * \ * * where sinc(x) = sin(PI * x) / (PI * x). */ #define GWK_PI 3.14159265358979323846 static double GWKLanczosSinc( double dfX, double dfR ) { if ( dfX == 0.0 ) return 1.0; const double dfPIX = GWK_PI * dfX; const double dfPIXoverR = dfPIX / dfR; const double dfPIX2overR = dfPIX * dfPIXoverR; return sin(dfPIX) * sin(dfPIXoverR) / dfPIX2overR; } //#undef GWK_PI /************************************************************************/ /* GWKBSpline() */ /************************************************************************/ static double GWKBSpline( double x ) { double xp2 = x + 2.0; double xp1 = x + 1.0; double xm1 = x - 1.0; // This will most likely be used, so we'll compute it ahead of time to // avoid stalling the processor double xp2c = xp2 * xp2 * xp2; // Note that the test is computed only if it is needed return (((xp2 > 0.0)?((xp1 > 0.0)?((x > 0.0)?((xm1 > 0.0)? -4.0 * xm1*xm1*xm1:0.0) + 6.0 * x*x*x:0.0) + -4.0 * xp1*xp1*xp1:0.0) + xp2c:0.0) ) * 0.166666666666666666666; } /************************************************************************/ /* GWKResampleWrkStruct */ /************************************************************************/ typedef struct _GWKResampleWrkStruct GWKResampleWrkStruct; typedef int (*pfnGWKResampleType) ( GDALWarpKernel *poWK, int iBand, double dfSrcX, double dfSrcY, double *pdfDensity, double *pdfReal, double *pdfImag, GWKResampleWrkStruct* psWrkStruct ); struct _GWKResampleWrkStruct { pfnGWKResampleType pfnGWKResample; // Space for saved X weights double *padfWeightsX; char *panCalcX; double *padfWeightsY; // only used by GWKResampleOptimizedLanczos int iLastSrcX; // only used by GWKResampleOptimizedLanczos int iLastSrcY; // only used by GWKResampleOptimizedLanczos double dfLastDeltaX; // only used by GWKResampleOptimizedLanczos double dfLastDeltaY; // only used by GWKResampleOptimizedLanczos // Space for saving a row of pixels double *padfRowDensity; double *padfRowReal; double *padfRowImag; }; /************************************************************************/ /* GWKResampleCreateWrkStruct() */ /************************************************************************/ static int GWKResample( GDALWarpKernel *poWK, int iBand, double dfSrcX, double dfSrcY, double *pdfDensity, double *pdfReal, double *pdfImag, GWKResampleWrkStruct* psWrkStruct ); static int GWKResampleOptimizedLanczos( GDALWarpKernel *poWK, int iBand, double dfSrcX, double dfSrcY, double *pdfDensity, double *pdfReal, double *pdfImag, GWKResampleWrkStruct* psWrkStruct ); static GWKResampleWrkStruct* GWKResampleCreateWrkStruct(GDALWarpKernel *poWK) { int nXDist = ( poWK->nXRadius + 1 ) * 2; int nYDist = ( poWK->nYRadius + 1 ) * 2; GWKResampleWrkStruct* psWrkStruct = (GWKResampleWrkStruct*)CPLMalloc(sizeof(GWKResampleWrkStruct)); // Alloc space for saved X weights psWrkStruct->padfWeightsX = (double *)CPLCalloc( nXDist, sizeof(double) ); psWrkStruct->panCalcX = (char *)CPLMalloc( nXDist * sizeof(char) ); psWrkStruct->padfWeightsY = (double *)CPLCalloc( nYDist, sizeof(double) ); psWrkStruct->iLastSrcX = -10; psWrkStruct->iLastSrcY = -10; psWrkStruct->dfLastDeltaX = -10; psWrkStruct->dfLastDeltaY = -10; // Alloc space for saving a row of pixels if( poWK->pafUnifiedSrcDensity == NULL && poWK->panUnifiedSrcValid == NULL && poWK->papanBandSrcValid == NULL ) { psWrkStruct->padfRowDensity = NULL; } else { psWrkStruct->padfRowDensity = (double *)CPLCalloc( nXDist, sizeof(double) ); } psWrkStruct->padfRowReal = (double *)CPLCalloc( nXDist, sizeof(double) ); psWrkStruct->padfRowImag = (double *)CPLCalloc( nXDist, sizeof(double) ); if( poWK->eResample == GRA_Lanczos && poWK->dfXFilter == 3.0 && poWK->dfYFilter == 3.0 ) { psWrkStruct->pfnGWKResample = GWKResampleOptimizedLanczos; const double dfXScale = poWK->dfXScale; if( dfXScale < 1.0 ) { int iMin = poWK->nFiltInitX, iMax = poWK->nXRadius; while( iMin * dfXScale < -3.0 ) iMin ++; while( iMax * dfXScale > 3.0 ) iMax --; for(int i = iMin; i <= iMax; ++i) { psWrkStruct->padfWeightsX[i-poWK->nFiltInitX] = GWKLanczosSinc(i * dfXScale, poWK->dfXFilter) * dfXScale; } } const double dfYScale = poWK->dfYScale; if( dfYScale < 1.0 ) { int jMin = poWK->nFiltInitY, jMax = poWK->nYRadius; while( jMin * dfYScale < -3.0 ) jMin ++; while( jMax * dfYScale > 3.0 ) jMax --; for(int j = jMin; j <= jMax; ++j) { psWrkStruct->padfWeightsY[j-poWK->nFiltInitY] = GWKLanczosSinc(j * dfYScale, poWK->dfYFilter) * dfYScale; } } } else psWrkStruct->pfnGWKResample = GWKResample; return psWrkStruct; } /************************************************************************/ /* GWKResampleDeleteWrkStruct() */ /************************************************************************/ static void GWKResampleDeleteWrkStruct(GWKResampleWrkStruct* psWrkStruct) { CPLFree( psWrkStruct->padfWeightsX ); CPLFree( psWrkStruct->padfWeightsY ); CPLFree( psWrkStruct->panCalcX ); CPLFree( psWrkStruct->padfRowDensity ); CPLFree( psWrkStruct->padfRowReal ); CPLFree( psWrkStruct->padfRowImag ); CPLFree( psWrkStruct ); } /************************************************************************/ /* GWKResample() */ /************************************************************************/ static int GWKResample( GDALWarpKernel *poWK, int iBand, double dfSrcX, double dfSrcY, double *pdfDensity, double *pdfReal, double *pdfImag, GWKResampleWrkStruct* psWrkStruct ) { // Save as local variables to avoid following pointers in loops const int nSrcXSize = poWK->nSrcXSize; const int nSrcYSize = poWK->nSrcYSize; double dfAccumulatorReal = 0.0, dfAccumulatorImag = 0.0; double dfAccumulatorDensity = 0.0; double dfAccumulatorWeight = 0.0; const int iSrcX = (int) floor( dfSrcX - 0.5 ); const int iSrcY = (int) floor( dfSrcY - 0.5 ); const int iSrcOffset = iSrcX + iSrcY * nSrcXSize; const double dfDeltaX = dfSrcX - 0.5 - iSrcX; const double dfDeltaY = dfSrcY - 0.5 - iSrcY; const int eResample = poWK->eResample; const double dfXScale = poWK->dfXScale, dfYScale = poWK->dfYScale; const double dfXFilter = poWK->dfXFilter, dfYFilter = poWK->dfYFilter; int i, j; const int nXDist = ( poWK->nXRadius + 1 ) * 2; // Space for saved X weights double *padfWeightsX = psWrkStruct->padfWeightsX; char *panCalcX = psWrkStruct->panCalcX; // Space for saving a row of pixels double *padfRowDensity = psWrkStruct->padfRowDensity; double *padfRowReal = psWrkStruct->padfRowReal; double *padfRowImag = psWrkStruct->padfRowImag; // Mark as needing calculation (don't calculate the weights yet, // because a mask may render it unnecessary) memset( panCalcX, FALSE, nXDist * sizeof(char) ); CPLAssert( eResample == GRA_CubicSpline || eResample == GRA_Lanczos ); // Skip sampling over edge of image j = poWK->nFiltInitY; int jMax= poWK->nYRadius; if( iSrcY + j < 0 ) j = -iSrcY; if( iSrcY + jMax >= nSrcYSize ) jMax = nSrcYSize - iSrcY - 1; int iMin = poWK->nFiltInitX, iMax = poWK->nXRadius; if( iSrcX + iMin < 0 ) iMin = -iSrcX; if( iSrcX + iMax >= nSrcXSize ) iMax = nSrcXSize - iSrcX - 1; const int bXScaleBelow1 = ( dfXScale < 1.0 ); const int bYScaleBelow1 = ( dfYScale < 1.0 ); int iRowOffset = iSrcOffset + (j - 1) * nSrcXSize + iMin; // Loop over pixel rows in the kernel for ( ; j <= jMax; ++j ) { double dfWeight1; iRowOffset += nSrcXSize; // Get pixel values // We can potentially read extra elements after the "normal" end of the source arrays, // but the contract of papabySrcImage[iBand], papanBandSrcValid[iBand], // panUnifiedSrcValid and pafUnifiedSrcDensity is to have WARP_EXTRA_ELTS // reserved at their end. if ( !GWKGetPixelRow( poWK, iBand, iRowOffset, (iMax-iMin+2)/2, padfRowDensity, padfRowReal, padfRowImag ) ) continue; // Select the resampling algorithm if ( eResample == GRA_CubicSpline ) // Calculate the Y weight dfWeight1 = ( bYScaleBelow1 ) ? GWKBSpline(((double)j) * dfYScale) * dfYScale : GWKBSpline(((double)j) - dfDeltaY); else /*if ( eResample == GRA_Lanczos )*/ { if( bYScaleBelow1 ) dfWeight1 = GWKLanczosSinc(j * dfYScale, dfYFilter) * dfYScale; else dfWeight1 = GWKLanczosSinc(j - dfDeltaY, dfYFilter); } // Iterate over pixels in row for (i = iMin; i <= iMax; ++i ) { double dfWeight2; // Skip sampling if pixel has zero density if ( padfRowDensity != NULL && padfRowDensity[i-iMin] < 0.000000001 ) continue; // Make or use a cached set of weights for this row if ( panCalcX[i-iMin] ) // Use saved weight value instead of recomputing it dfWeight2 = dfWeight1 * padfWeightsX[i-iMin]; else { // Choose among possible algorithms if ( eResample == GRA_CubicSpline ) // Calculate & save the X weight padfWeightsX[i-iMin] = dfWeight2 = ( bXScaleBelow1 ) ? GWKBSpline((double)i * dfXScale) * dfXScale : GWKBSpline(dfDeltaX - (double)i); else /*if ( eResample == GRA_Lanczos )*/ { // Calculate & save the X weight if( bXScaleBelow1 ) padfWeightsX[i-iMin] = dfWeight2 = GWKLanczosSinc(i * dfXScale, dfXFilter) * dfXScale; else padfWeightsX[i-iMin] = dfWeight2 = GWKLanczosSinc(i - dfDeltaX, dfXFilter); } dfWeight2 *= dfWeight1; panCalcX[i-iMin] = TRUE; } // Accumulate! dfAccumulatorReal += padfRowReal[i-iMin] * dfWeight2; dfAccumulatorImag += padfRowImag[i-iMin] * dfWeight2; if( padfRowDensity != NULL ) dfAccumulatorDensity += padfRowDensity[i-iMin] * dfWeight2; dfAccumulatorWeight += dfWeight2; } } if ( dfAccumulatorWeight < 0.000001 || (padfRowDensity != NULL && dfAccumulatorDensity < 0.000001) ) { *pdfDensity = 0.0; return FALSE; } // Calculate the output taking into account weighting if ( dfAccumulatorWeight < 0.99999 || dfAccumulatorWeight > 1.00001 ) { *pdfReal = dfAccumulatorReal / dfAccumulatorWeight; *pdfImag = dfAccumulatorImag / dfAccumulatorWeight; if( padfRowDensity != NULL ) *pdfDensity = dfAccumulatorDensity / dfAccumulatorWeight; else *pdfDensity = 1.0; } else { *pdfReal = dfAccumulatorReal; *pdfImag = dfAccumulatorImag; if( padfRowDensity != NULL ) *pdfDensity = dfAccumulatorDensity; else *pdfDensity = 1.0; } return TRUE; } /************************************************************************/ /* GWKResampleOptimizedLanczos() */ /************************************************************************/ static int GWKResampleOptimizedLanczos( GDALWarpKernel *poWK, int iBand, double dfSrcX, double dfSrcY, double *pdfDensity, double *pdfReal, double *pdfImag, GWKResampleWrkStruct* psWrkStruct ) { // Save as local variables to avoid following pointers in loops const int nSrcXSize = poWK->nSrcXSize; const int nSrcYSize = poWK->nSrcYSize; double dfAccumulatorReal = 0.0, dfAccumulatorImag = 0.0; double dfAccumulatorDensity = 0.0; double dfAccumulatorWeight = 0.0; const int iSrcX = (int) floor( dfSrcX - 0.5 ); const int iSrcY = (int) floor( dfSrcY - 0.5 ); const int iSrcOffset = iSrcX + iSrcY * nSrcXSize; const double dfDeltaX = dfSrcX - 0.5 - iSrcX; const double dfDeltaY = dfSrcY - 0.5 - iSrcY; const double dfXScale = poWK->dfXScale, dfYScale = poWK->dfYScale; // Space for saved X weights double *padfWeightsX = psWrkStruct->padfWeightsX; double *padfWeightsY = psWrkStruct->padfWeightsY; // Space for saving a row of pixels double *padfRowDensity = psWrkStruct->padfRowDensity; double *padfRowReal = psWrkStruct->padfRowReal; double *padfRowImag = psWrkStruct->padfRowImag; // Skip sampling over edge of image int jMin = poWK->nFiltInitY, jMax= poWK->nYRadius; if( iSrcY + jMin < 0 ) jMin = -iSrcY; if( iSrcY + jMax >= nSrcYSize ) jMax = nSrcYSize - iSrcY - 1; int iMin = poWK->nFiltInitX, iMax = poWK->nXRadius; if( iSrcX + iMin < 0 ) iMin = -iSrcX; if( iSrcX + iMax >= nSrcXSize ) iMax = nSrcXSize - iSrcX - 1; if( dfXScale < 1.0 ) { while( iMin * dfXScale < -3.0 ) iMin ++; while( iMax * dfXScale > 3.0 ) iMax --; // padfWeightsX computed in GWKResampleCreateWrkStruct } else { while( iMin - dfDeltaX < -3.0 ) iMin ++; while( iMax - dfDeltaX > 3.0 ) iMax --; if( iSrcX != psWrkStruct->iLastSrcX || dfDeltaX != psWrkStruct->dfLastDeltaX ) { // Optimisation of GWKLanczosSinc(i - dfDeltaX) based on the following // trigonometric formulas. //sin(GWK_PI * (dfBase + k)) = sin(GWK_PI * dfBase) * cos(GWK_PI * k) + cos(GWK_PI * dfBase) * sin(GWK_PI * k) //sin(GWK_PI * (dfBase + k)) = dfSinPIBase * cos(GWK_PI * k) + dfCosPIBase * sin(GWK_PI * k) //sin(GWK_PI * (dfBase + k)) = dfSinPIBase * cos(GWK_PI * k) //sin(GWK_PI * (dfBase + k)) = dfSinPIBase * (((k % 2) == 0) ? 1 : -1) //sin(GWK_PI / dfR * (dfBase + k)) = sin(GWK_PI / dfR * dfBase) * cos(GWK_PI / dfR * k) + cos(GWK_PI / dfR * dfBase) * sin(GWK_PI / dfR * k) //sin(GWK_PI / dfR * (dfBase + k)) = dfSinPIBaseOverR * cos(GWK_PI / dfR * k) + dfCosPIBaseOverR * sin(GWK_PI / dfR * k) double dfSinPIDeltaXOver3 = sin((-GWK_PI / 3) * dfDeltaX); double dfSin2PIDeltaXOver3 = dfSinPIDeltaXOver3 * dfSinPIDeltaXOver3; /* ok to use sqrt(1-sin^2) since GWK_PI / 3 * dfDeltaX < PI/2 */ double dfCosPIDeltaXOver3 = sqrt(1 - dfSin2PIDeltaXOver3); double dfSinPIDeltaX = (3-4*dfSin2PIDeltaXOver3)*dfSinPIDeltaXOver3; const double dfInvPI2Over3 = 3.0 / (GWK_PI * GWK_PI); double dfInvPI2Over3xSinPIDeltaX = dfInvPI2Over3 * dfSinPIDeltaX; double dfInvPI2Over3xSinPIDeltaXxm0d5SinPIDeltaXOver3 = -0.5 * dfInvPI2Over3xSinPIDeltaX * dfSinPIDeltaXOver3; const double dfSinPIOver3 = 0.8660254037844386; double dfInvPI2Over3xSinPIDeltaXxSinPIOver3xCosPIDeltaXOver3 = dfSinPIOver3 * dfInvPI2Over3xSinPIDeltaX * dfCosPIDeltaXOver3; double padfCst[] = { dfInvPI2Over3xSinPIDeltaX * dfSinPIDeltaXOver3, dfInvPI2Over3xSinPIDeltaXxm0d5SinPIDeltaXOver3 - dfInvPI2Over3xSinPIDeltaXxSinPIOver3xCosPIDeltaXOver3, dfInvPI2Over3xSinPIDeltaXxm0d5SinPIDeltaXOver3 + dfInvPI2Over3xSinPIDeltaXxSinPIOver3xCosPIDeltaXOver3 }; for (int i = iMin; i <= iMax; ++i ) { const double dfX = i - dfDeltaX; if (dfX == 0.0) padfWeightsX[i-poWK->nFiltInitX] = 1.0; else padfWeightsX[i-poWK->nFiltInitX] = padfCst[(i + 3) % 3] / (dfX * dfX); //CPLAssert(fabs(padfWeightsX[i-poWK->nFiltInitX] - GWKLanczosSinc(dfX, 3.0)) < 1e-10); } psWrkStruct->iLastSrcX = iSrcX; psWrkStruct->dfLastDeltaX = dfDeltaX; } } if( dfYScale < 1.0 ) { while( jMin * dfYScale < -3.0 ) jMin ++; while( jMax * dfYScale > 3.0 ) jMax --; // padfWeightsY computed in GWKResampleCreateWrkStruct } else { while( jMin - dfDeltaY < -3.0 ) jMin ++; while( jMax - dfDeltaY > 3.0 ) jMax --; if( iSrcY != psWrkStruct->iLastSrcY || dfDeltaY != psWrkStruct->dfLastDeltaY ) { double dfSinPIDeltaYOver3 = sin((-GWK_PI / 3) * dfDeltaY); double dfSin2PIDeltaYOver3 = dfSinPIDeltaYOver3 * dfSinPIDeltaYOver3; /* ok to use sqrt(1-sin^2) since GWK_PI / 3 * dfDeltaY < PI/2 */ double dfCosPIDeltaYOver3 = sqrt(1 - dfSin2PIDeltaYOver3); double dfSinPIDeltaY = (3-4*dfSin2PIDeltaYOver3)*dfSinPIDeltaYOver3; const double dfInvPI2Over3 = 3.0 / (GWK_PI * GWK_PI); double dfInvPI2Over3xSinPIDeltaY = dfInvPI2Over3 * dfSinPIDeltaY; double dfInvPI2Over3xSinPIDeltaYxm0d5SinPIDeltaYOver3 = -0.5 * dfInvPI2Over3xSinPIDeltaY * dfSinPIDeltaYOver3; const double dfSinPIOver3 = 0.8660254037844386; double dfInvPI2Over3xSinPIDeltaYxSinPIOver3xCosPIDeltaYOver3 = dfSinPIOver3 * dfInvPI2Over3xSinPIDeltaY * dfCosPIDeltaYOver3; double padfCst[] = { dfInvPI2Over3xSinPIDeltaY * dfSinPIDeltaYOver3, dfInvPI2Over3xSinPIDeltaYxm0d5SinPIDeltaYOver3 - dfInvPI2Over3xSinPIDeltaYxSinPIOver3xCosPIDeltaYOver3, dfInvPI2Over3xSinPIDeltaYxm0d5SinPIDeltaYOver3 + dfInvPI2Over3xSinPIDeltaYxSinPIOver3xCosPIDeltaYOver3 }; for ( int j = jMin; j <= jMax; ++j ) { const double dfY = j - dfDeltaY; if (dfY == 0.0) padfWeightsY[j-poWK->nFiltInitY] = 1.0; else padfWeightsY[j-poWK->nFiltInitY] = padfCst[(j + 3) % 3] / (dfY * dfY); //CPLAssert(fabs(padfWeightsY[j-poWK->nFiltInitY] - GWKLanczosSinc(dfY, 3.0)) < 1e-10); } psWrkStruct->iLastSrcY = iSrcY; psWrkStruct->dfLastDeltaY = dfDeltaY; } } int iRowOffset = iSrcOffset + (jMin - 1) * nSrcXSize + iMin; // If we have no density information, we can simply compute the // accumulated weight. if( padfRowDensity == NULL ) { double dfRowAccWeight = 0.0; for (int i = iMin; i <= iMax; ++i ) { dfRowAccWeight += padfWeightsX[i-poWK->nFiltInitX]; } double dfColAccWeight = 0.0; for ( int j = jMin; j <= jMax; ++j ) { dfColAccWeight += padfWeightsY[j-poWK->nFiltInitY]; } dfAccumulatorWeight = dfRowAccWeight * dfColAccWeight; if( !GDALDataTypeIsComplex(poWK->eWorkingDataType) ) padfRowImag = NULL; } // Loop over pixel rows in the kernel for ( int j = jMin; j <= jMax; ++j ) { double dfWeight1; iRowOffset += nSrcXSize; // Get pixel values // We can potentially read extra elements after the "normal" end of the source arrays, // but the contract of papabySrcImage[iBand], papanBandSrcValid[iBand], // panUnifiedSrcValid and pafUnifiedSrcDensity is to have WARP_EXTRA_ELTS // reserved at their end. if ( !GWKGetPixelRow( poWK, iBand, iRowOffset, (iMax-iMin+2)/2, padfRowDensity, padfRowReal, padfRowImag ) ) continue; dfWeight1 = padfWeightsY[j-poWK->nFiltInitY]; // Iterate over pixels in row if ( padfRowDensity != NULL ) { for (int i = iMin; i <= iMax; ++i ) { double dfWeight2; // Skip sampling if pixel has zero density if ( padfRowDensity[i - iMin] < 0.000000001 ) continue; // Use a cached set of weights for this row dfWeight2 = dfWeight1 * padfWeightsX[i- poWK->nFiltInitX]; // Accumulate! dfAccumulatorReal += padfRowReal[i - iMin] * dfWeight2; dfAccumulatorImag += padfRowImag[i - iMin] * dfWeight2; dfAccumulatorDensity += padfRowDensity[i - iMin] * dfWeight2; dfAccumulatorWeight += dfWeight2; } } else if( padfRowImag == NULL ) { double dfRowAccReal = 0.0; for (int i = iMin; i <= iMax; ++i ) { double dfWeight2 = padfWeightsX[i- poWK->nFiltInitX]; // Accumulate! dfRowAccReal += padfRowReal[i - iMin] * dfWeight2; } dfAccumulatorReal += dfRowAccReal * dfWeight1; } else { double dfRowAccReal = 0.0; double dfRowAccImag = 0.0; for (int i = iMin; i <= iMax; ++i ) { double dfWeight2 = padfWeightsX[i- poWK->nFiltInitX]; // Accumulate! dfRowAccReal += padfRowReal[i - iMin] * dfWeight2; dfRowAccImag += padfRowImag[i - iMin] * dfWeight2; } dfAccumulatorReal += dfRowAccReal * dfWeight1; dfAccumulatorImag += dfRowAccImag * dfWeight1; } } if ( dfAccumulatorWeight < 0.000001 || (padfRowDensity != NULL && dfAccumulatorDensity < 0.000001) ) { *pdfDensity = 0.0; return FALSE; } // Calculate the output taking into account weighting if ( dfAccumulatorWeight < 0.99999 || dfAccumulatorWeight > 1.00001 ) { const double dfInvAcc = 1.0 / dfAccumulatorWeight; *pdfReal = dfAccumulatorReal * dfInvAcc; *pdfImag = dfAccumulatorImag * dfInvAcc; if( padfRowDensity != NULL ) *pdfDensity = dfAccumulatorDensity * dfInvAcc; else *pdfDensity = 1.0; } else { *pdfReal = dfAccumulatorReal; *pdfImag = dfAccumulatorImag; if( padfRowDensity != NULL ) *pdfDensity = dfAccumulatorDensity; else *pdfDensity = 1.0; } return TRUE; } static int GWKCubicSplineResampleNoMasksByte( GDALWarpKernel *poWK, int iBand, double dfSrcX, double dfSrcY, GByte *pbValue, double *padfBSpline ) { // Commonly used; save locally int nSrcXSize = poWK->nSrcXSize; int nSrcYSize = poWK->nSrcYSize; double dfAccumulator = 0.0; int iSrcX = (int) floor( dfSrcX - 0.5 ); int iSrcY = (int) floor( dfSrcY - 0.5 ); int iSrcOffset = iSrcX + iSrcY * nSrcXSize; double dfDeltaX = dfSrcX - 0.5 - iSrcX; double dfDeltaY = dfSrcY - 0.5 - iSrcY; double dfXScale = poWK->dfXScale; double dfYScale = poWK->dfYScale; int nXRadius = poWK->nXRadius; int nYRadius = poWK->nYRadius; GByte* pabySrcBand = poWK->papabySrcImage[iBand]; // Politely refusing to process invalid coordinates or obscenely small image if ( iSrcX >= nSrcXSize || iSrcY >= nSrcYSize || nXRadius > nSrcXSize || nYRadius > nSrcYSize ) return GWKBilinearResampleNoMasksByte( poWK, iBand, dfSrcX, dfSrcY, pbValue); // Loop over all rows in the kernel int j, jC; for ( jC = 0, j = 1 - nYRadius; j <= nYRadius; ++j, ++jC ) { int iSampJ; // Calculate the Y weight double dfWeight1 = ( dfYScale < 1.0 ) ? GWKBSpline((double)j * dfYScale) * dfYScale : GWKBSpline((double)j - dfDeltaY); // Flip sampling over edge of image if ( iSrcY + j < 0 ) iSampJ = iSrcOffset - (iSrcY + j) * nSrcXSize; else if ( iSrcY + j >= nSrcYSize ) iSampJ = iSrcOffset + (2*nSrcYSize - 2*iSrcY - j - 1) * nSrcXSize; else iSampJ = iSrcOffset + j * nSrcXSize; // Loop over all pixels in the row int i, iC; for ( iC = 0, i = 1 - nXRadius; i <= nXRadius; ++i, ++iC ) { int iSampI; double dfWeight2; // Flip sampling over edge of image if ( iSrcX + i < 0 ) iSampI = -iSrcX - i; else if ( iSrcX + i >= nSrcXSize ) iSampI = 2*nSrcXSize - 2*iSrcX - i - 1; else iSampI = i; // Make a cached set of GWKBSpline values if( jC == 0 ) { // Calculate & save the X weight dfWeight2 = padfBSpline[iC] = ((dfXScale < 1.0 ) ? GWKBSpline((double)i * dfXScale) * dfXScale : GWKBSpline(dfDeltaX - (double)i)); dfWeight2 *= dfWeight1; } else dfWeight2 = dfWeight1 * padfBSpline[iC]; // Retrieve the pixel & accumulate dfAccumulator += (double)pabySrcBand[iSampI+iSampJ] * dfWeight2; } } if ( dfAccumulator < 0.0 ) *pbValue = 0; else if ( dfAccumulator > 255.0 ) *pbValue = 255; else *pbValue = (GByte)(0.5 + dfAccumulator); return TRUE; } static int GWKCubicSplineResampleNoMasksShort( GDALWarpKernel *poWK, int iBand, double dfSrcX, double dfSrcY, GInt16 *piValue, double *padfBSpline ) { //Save src size to local var int nSrcXSize = poWK->nSrcXSize; int nSrcYSize = poWK->nSrcYSize; double dfAccumulator = 0.0; int iSrcX = (int) floor( dfSrcX - 0.5 ); int iSrcY = (int) floor( dfSrcY - 0.5 ); int iSrcOffset = iSrcX + iSrcY * nSrcXSize; double dfDeltaX = dfSrcX - 0.5 - iSrcX; double dfDeltaY = dfSrcY - 0.5 - iSrcY; double dfXScale = poWK->dfXScale; double dfYScale = poWK->dfYScale; int nXRadius = poWK->nXRadius; int nYRadius = poWK->nYRadius; // Save band array pointer to local var; cast here instead of later GInt16* pabySrcBand = ((GInt16 *)poWK->papabySrcImage[iBand]); // Politely refusing to process invalid coordinates or obscenely small image if ( iSrcX >= nSrcXSize || iSrcY >= nSrcYSize || nXRadius > nSrcXSize || nYRadius > nSrcYSize ) return GWKBilinearResampleNoMasksShort( poWK, iBand, dfSrcX, dfSrcY, piValue); // Loop over all pixels in the kernel int j, jC; for ( jC = 0, j = 1 - nYRadius; j <= nYRadius; ++j, ++jC ) { int iSampJ; // Calculate the Y weight double dfWeight1 = ( dfYScale < 1.0 ) ? GWKBSpline((double)j * dfYScale) * dfYScale : GWKBSpline((double)j - dfDeltaY); // Flip sampling over edge of image if ( iSrcY + j < 0 ) iSampJ = iSrcOffset - (iSrcY + j) * nSrcXSize; else if ( iSrcY + j >= nSrcYSize ) iSampJ = iSrcOffset + (2*nSrcYSize - 2*iSrcY - j - 1) * nSrcXSize; else iSampJ = iSrcOffset + j * nSrcXSize; // Loop over all pixels in row int i, iC; for ( iC = 0, i = 1 - nXRadius; i <= nXRadius; ++i, ++iC ) { int iSampI; double dfWeight2; // Flip sampling over edge of image if ( iSrcX + i < 0 ) iSampI = -iSrcX - i; else if(iSrcX + i >= nSrcXSize) iSampI = 2*nSrcXSize - 2*iSrcX - i - 1; else iSampI = i; // Make a cached set of GWKBSpline values if ( jC == 0 ) { // Calculate & save the X weight dfWeight2 = padfBSpline[iC] = ((dfXScale < 1.0 ) ? GWKBSpline((double)i * dfXScale) * dfXScale : GWKBSpline(dfDeltaX - (double)i)); dfWeight2 *= dfWeight1; } else dfWeight2 = dfWeight1 * padfBSpline[iC]; dfAccumulator += (double)pabySrcBand[iSampI + iSampJ] * dfWeight2; } } *piValue = (GInt16)(0.5 + dfAccumulator); return TRUE; } /************************************************************************/ /* GWKOpenCLCase() */ /* */ /* This is identical to GWKGeneralCase(), but functions via */ /* OpenCL. This means we have vector optimization (SSE) and/or */ /* GPU optimization depending on our prefs. The code itsef is */ /* general and not optimized, but by defining constants we can */ /* make some pretty darn good code on the fly. */ /************************************************************************/ #if defined(HAVE_OPENCL) static CPLErr GWKOpenCLCase( GDALWarpKernel *poWK ) { int iDstY, iBand; int nDstXSize = poWK->nDstXSize, nDstYSize = poWK->nDstYSize; int nSrcXSize = poWK->nSrcXSize, nSrcYSize = poWK->nSrcYSize; int nDstXOff = poWK->nDstXOff , nDstYOff = poWK->nDstYOff; int nSrcXOff = poWK->nSrcXOff , nSrcYOff = poWK->nSrcYOff; CPLErr eErr = CE_None; struct oclWarper *warper; cl_channel_type imageFormat; int useImag = FALSE; OCLResampAlg resampAlg; cl_int err; switch ( poWK->eWorkingDataType ) { case GDT_Byte: imageFormat = CL_UNORM_INT8; break; case GDT_UInt16: imageFormat = CL_UNORM_INT16; break; case GDT_CInt16: useImag = TRUE; case GDT_Int16: imageFormat = CL_SNORM_INT16; break; case GDT_CFloat32: useImag = TRUE; case GDT_Float32: imageFormat = CL_FLOAT; break; default: // We don't support higher precision formats CPLDebug( "OpenCL", "Unsupported resampling OpenCL data type %d.", (int) poWK->eWorkingDataType ); return CE_Warning; } switch (poWK->eResample) { case GRA_Bilinear: resampAlg = OCL_Bilinear; break; case GRA_Cubic: resampAlg = OCL_Cubic; break; case GRA_CubicSpline: resampAlg = OCL_CubicSpline; break; case GRA_Lanczos: resampAlg = OCL_Lanczos; break; default: // We don't support higher precision formats CPLDebug( "OpenCL", "Unsupported resampling OpenCL resampling alg %d.", (int) poWK->eResample ); return CE_Warning; } // Using a factor of 2 or 4 seems to have much less rounding error than 3 on the GPU. // Then the rounding error can cause strange artifacting under the right conditions. warper = GDALWarpKernelOpenCL_createEnv(nSrcXSize, nSrcYSize, nDstXSize, nDstYSize, imageFormat, poWK->nBands, 4, useImag, poWK->papanBandSrcValid != NULL, poWK->pafDstDensity, poWK->padfDstNoDataReal, resampAlg, &err ); if(err != CL_SUCCESS || warper == NULL) { eErr = CE_Warning; if (warper != NULL) goto free_warper; return eErr; } CPLDebug( "GDAL", "GDALWarpKernel()::GWKOpenCLCase()\n" "Src=%d,%d,%dx%d Dst=%d,%d,%dx%d", nSrcXOff, nSrcYOff, nSrcXSize, nSrcYSize, nDstXOff, nDstYOff, nDstXSize, nDstYSize ); if( !poWK->pfnProgress( poWK->dfProgressBase, "", poWK->pProgress ) ) { CPLError( CE_Failure, CPLE_UserInterrupt, "User terminated" ); eErr = CE_Failure; goto free_warper; } /* ==================================================================== */ /* Loop over bands. */ /* ==================================================================== */ for( iBand = 0; iBand < poWK->nBands; iBand++ ) { if( poWK->papanBandSrcValid != NULL && poWK->papanBandSrcValid[iBand] != NULL) { GDALWarpKernelOpenCL_setSrcValid(warper, (int *)poWK->papanBandSrcValid[iBand], iBand); if(err != CL_SUCCESS) { CPLError( CE_Failure, CPLE_AppDefined, "OpenCL routines reported failure (%d) on line %d.", (int) err, __LINE__ ); eErr = CE_Failure; goto free_warper; } } err = GDALWarpKernelOpenCL_setSrcImg(warper, poWK->papabySrcImage[iBand], iBand); if(err != CL_SUCCESS) { CPLError( CE_Failure, CPLE_AppDefined, "OpenCL routines reported failure (%d) on line %d.", (int) err, __LINE__ ); eErr = CE_Failure; goto free_warper; } err = GDALWarpKernelOpenCL_setDstImg(warper, poWK->papabyDstImage[iBand], iBand); if(err != CL_SUCCESS) { CPLError( CE_Failure, CPLE_AppDefined, "OpenCL routines reported failure (%d) on line %d.", (int) err, __LINE__ ); eErr = CE_Failure; goto free_warper; } } /* -------------------------------------------------------------------- */ /* Allocate x,y,z coordinate arrays for transformation ... one */ /* scanlines worth of positions. */ /* -------------------------------------------------------------------- */ double *padfX, *padfY, *padfZ; int *pabSuccess; padfX = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfY = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfZ = (double *) CPLMalloc(sizeof(double) * nDstXSize); pabSuccess = (int *) CPLMalloc(sizeof(int) * nDstXSize); /* ==================================================================== */ /* Loop over output lines. */ /* ==================================================================== */ for( iDstY = 0; iDstY < nDstYSize && eErr == CE_None; ++iDstY ) { int iDstX; /* ---------------------------------------------------------------- */ /* Setup points to transform to source image space. */ /* ---------------------------------------------------------------- */ for( iDstX = 0; iDstX < nDstXSize; ++iDstX ) { padfX[iDstX] = iDstX + 0.5 + nDstXOff; padfY[iDstX] = iDstY + 0.5 + nDstYOff; padfZ[iDstX] = 0.0; } /* ---------------------------------------------------------------- */ /* Transform the points from destination pixel/line coordinates*/ /* to source pixel/line coordinates. */ /* ---------------------------------------------------------------- */ poWK->pfnTransformer( poWK->pTransformerArg, TRUE, nDstXSize, padfX, padfY, padfZ, pabSuccess ); err = GDALWarpKernelOpenCL_setCoordRow(warper, padfX, padfY, nSrcXOff, nSrcYOff, pabSuccess, iDstY); if(err != CL_SUCCESS) { CPLError( CE_Failure, CPLE_AppDefined, "OpenCL routines reported failure (%d) on line %d.", (int) err, __LINE__ ); return CE_Failure; } //Update the valid & density masks because we don't do so in the kernel for( iDstX = 0; iDstX < nDstXSize && eErr == CE_None; iDstX++ ) { double dfX = padfX[iDstX]; double dfY = padfY[iDstX]; int iDstOffset = iDstX + iDstY * nDstXSize; //See GWKGeneralCase() for appropriate commenting if( !pabSuccess[iDstX] || dfX < nSrcXOff || dfY < nSrcYOff ) continue; int iSrcX = ((int) dfX) - nSrcXOff; int iSrcY = ((int) dfY) - nSrcYOff; if( iSrcX < 0 || iSrcX >= nSrcXSize || iSrcY < 0 || iSrcY >= nSrcYSize ) continue; int iSrcOffset = iSrcX + iSrcY * nSrcXSize; double dfDensity = 1.0; if( poWK->pafUnifiedSrcDensity != NULL && iSrcX >= 0 && iSrcY >= 0 && iSrcX < nSrcXSize && iSrcY < nSrcYSize ) dfDensity = poWK->pafUnifiedSrcDensity[iSrcOffset]; GWKOverlayDensity( poWK, iDstOffset, dfDensity ); //Because this is on the bit-wise level, it can't be done well in OpenCL if( poWK->panDstValid != NULL ) poWK->panDstValid[iDstOffset>>5] |= 0x01 << (iDstOffset & 0x1f); } } CPLFree( padfX ); CPLFree( padfY ); CPLFree( padfZ ); CPLFree( pabSuccess ); err = GDALWarpKernelOpenCL_runResamp(warper, poWK->pafUnifiedSrcDensity, poWK->panUnifiedSrcValid, poWK->pafDstDensity, poWK->panDstValid, poWK->dfXScale, poWK->dfYScale, poWK->dfXFilter, poWK->dfYFilter, poWK->nXRadius, poWK->nYRadius, poWK->nFiltInitX, poWK->nFiltInitY); if(err != CL_SUCCESS) { CPLError( CE_Failure, CPLE_AppDefined, "OpenCL routines reported failure (%d) on line %d.", (int) err, __LINE__ ); eErr = CE_Failure; goto free_warper; } /* ==================================================================== */ /* Loop over output lines. */ /* ==================================================================== */ for( iDstY = 0; iDstY < nDstYSize && eErr == CE_None; iDstY++ ) { for( iBand = 0; iBand < poWK->nBands; iBand++ ) { int iDstX; void *rowReal, *rowImag; GByte *pabyDst = poWK->papabyDstImage[iBand]; err = GDALWarpKernelOpenCL_getRow(warper, &rowReal, &rowImag, iDstY, iBand); if(err != CL_SUCCESS) { CPLError( CE_Failure, CPLE_AppDefined, "OpenCL routines reported failure (%d) on line %d.", (int) err, __LINE__ ); eErr = CE_Failure; goto free_warper; } //Copy the data from the warper to GDAL's memory switch ( poWK->eWorkingDataType ) { case GDT_Byte: memcpy((void **)&(((GByte *)pabyDst)[iDstY*nDstXSize]), rowReal, sizeof(GByte)*nDstXSize); break; case GDT_Int16: memcpy((void **)&(((GInt16 *)pabyDst)[iDstY*nDstXSize]), rowReal, sizeof(GInt16)*nDstXSize); break; case GDT_UInt16: memcpy((void **)&(((GUInt16 *)pabyDst)[iDstY*nDstXSize]), rowReal, sizeof(GUInt16)*nDstXSize); break; case GDT_Float32: memcpy((void **)&(((float *)pabyDst)[iDstY*nDstXSize]), rowReal, sizeof(float)*nDstXSize); break; case GDT_CInt16: { GInt16 *pabyDstI16 = &(((GInt16 *)pabyDst)[iDstY*nDstXSize]); for (iDstX = 0; iDstX < nDstXSize; iDstX++) { pabyDstI16[iDstX*2 ] = ((GInt16 *)rowReal)[iDstX]; pabyDstI16[iDstX*2+1] = ((GInt16 *)rowImag)[iDstX]; } } break; case GDT_CFloat32: { float *pabyDstF32 = &(((float *)pabyDst)[iDstY*nDstXSize]); for (iDstX = 0; iDstX < nDstXSize; iDstX++) { pabyDstF32[iDstX*2 ] = ((float *)rowReal)[iDstX]; pabyDstF32[iDstX*2+1] = ((float *)rowImag)[iDstX]; } } break; default: // We don't support higher precision formats CPLError( CE_Failure, CPLE_AppDefined, "Unsupported resampling OpenCL data type %d.", (int) poWK->eWorkingDataType ); eErr = CE_Failure; goto free_warper; } } } free_warper: if((err = GDALWarpKernelOpenCL_deleteEnv(warper)) != CL_SUCCESS) { CPLError( CE_Failure, CPLE_AppDefined, "OpenCL routines reported failure (%d) on line %d.", (int) err, __LINE__ ); return CE_Failure; } return eErr; } #endif /* defined(HAVE_OPENCL) */ #define COMPUTE_iSrcOffset(_pabSuccess, _iDstX, _padfX, _padfY, _poWK, _nSrcXSize, _nSrcYSize) \ if( !_pabSuccess[_iDstX] ) \ continue; \ \ /* -------------------------------------------------------------------- */ \ /* Figure out what pixel we want in our source raster, and skip */ \ /* further processing if it is well off the source image. */ \ /* -------------------------------------------------------------------- */ \ /* We test against the value before casting to avoid the */ \ /* problem of asymmetric truncation effects around zero. That is */ \ /* -0.5 will be 0 when cast to an int. */ \ if( _padfX[_iDstX] < _poWK->nSrcXOff \ || _padfY[_iDstX] < _poWK->nSrcYOff ) \ continue; \ \ int iSrcX, iSrcY, iSrcOffset;\ \ iSrcX = ((int) (_padfX[_iDstX] + 1e-10)) - _poWK->nSrcXOff;\ iSrcY = ((int) (_padfY[_iDstX] + 1e-10)) - _poWK->nSrcYOff;\ \ /* If operating outside natural projection area, padfX/Y can be */ \ /* a very huge positive number, that becomes -2147483648 in the */ \ /* int trucation. So it is necessary to test now for non negativeness. */ \ if( iSrcX < 0 || iSrcX >= _nSrcXSize || iSrcY < 0 || iSrcY >= _nSrcYSize )\ continue;\ \ iSrcOffset = iSrcX + iSrcY * _nSrcXSize; /************************************************************************/ /* GWKGeneralCase() */ /* */ /* This is the most general case. It attempts to handle all */ /* possible features with relatively little concern for */ /* efficiency. */ /************************************************************************/ static void GWKGeneralCaseThread(void* pData); static CPLErr GWKGeneralCase( GDALWarpKernel *poWK ) { return GWKRun( poWK, "GWKGeneralCase", GWKGeneralCaseThread ); } static void GWKGeneralCaseThread( void* pData) { GWKJobStruct* psJob = (GWKJobStruct*) pData; GDALWarpKernel *poWK = psJob->poWK; int iYMin = psJob->iYMin; int iYMax = psJob->iYMax; int iDstY; int nDstXSize = poWK->nDstXSize; int nSrcXSize = poWK->nSrcXSize, nSrcYSize = poWK->nSrcYSize; /* -------------------------------------------------------------------- */ /* Allocate x,y,z coordinate arrays for transformation ... one */ /* scanlines worth of positions. */ /* -------------------------------------------------------------------- */ double *padfX, *padfY, *padfZ; int *pabSuccess; padfX = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfY = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfZ = (double *) CPLMalloc(sizeof(double) * nDstXSize); pabSuccess = (int *) CPLMalloc(sizeof(int) * nDstXSize); GWKResampleWrkStruct* psWrkStruct = NULL; if (poWK->eResample == GRA_CubicSpline || poWK->eResample == GRA_Lanczos ) { psWrkStruct = GWKResampleCreateWrkStruct(poWK); } /* ==================================================================== */ /* Loop over output lines. */ /* ==================================================================== */ for( iDstY = iYMin; iDstY < iYMax; iDstY++ ) { int iDstX; /* -------------------------------------------------------------------- */ /* Setup points to transform to source image space. */ /* -------------------------------------------------------------------- */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { padfX[iDstX] = iDstX + 0.5 + poWK->nDstXOff; padfY[iDstX] = iDstY + 0.5 + poWK->nDstYOff; padfZ[iDstX] = 0.0; } /* -------------------------------------------------------------------- */ /* Transform the points from destination pixel/line coordinates */ /* to source pixel/line coordinates. */ /* -------------------------------------------------------------------- */ poWK->pfnTransformer( psJob->pTransformerArg, TRUE, nDstXSize, padfX, padfY, padfZ, pabSuccess ); /* ==================================================================== */ /* Loop over pixels in output scanline. */ /* ==================================================================== */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { int iDstOffset; COMPUTE_iSrcOffset(pabSuccess, iDstX, padfX, padfY, poWK, nSrcXSize, nSrcYSize); /* -------------------------------------------------------------------- */ /* Do not try to apply transparent/invalid source pixels to the */ /* destination. This currently ignores the multi-pixel input */ /* of bilinear and cubic resamples. */ /* -------------------------------------------------------------------- */ double dfDensity = 1.0; if( poWK->pafUnifiedSrcDensity != NULL ) { dfDensity = poWK->pafUnifiedSrcDensity[iSrcOffset]; if( dfDensity < 0.00001 ) continue; } if( poWK->panUnifiedSrcValid != NULL && !(poWK->panUnifiedSrcValid[iSrcOffset>>5] & (0x01 << (iSrcOffset & 0x1f))) ) continue; /* ==================================================================== */ /* Loop processing each band. */ /* ==================================================================== */ int iBand; int bHasFoundDensity = FALSE; iDstOffset = iDstX + iDstY * nDstXSize; for( iBand = 0; iBand < poWK->nBands; iBand++ ) { double dfBandDensity = 0.0; double dfValueReal = 0.0; double dfValueImag = 0.0; /* -------------------------------------------------------------------- */ /* Collect the source value. */ /* -------------------------------------------------------------------- */ if ( poWK->eResample == GRA_NearestNeighbour || nSrcXSize == 1 || nSrcYSize == 1) { GWKGetPixelValue( poWK, iBand, iSrcOffset, &dfBandDensity, &dfValueReal, &dfValueImag ); } else if ( poWK->eResample == GRA_Bilinear ) { GWKBilinearResample( poWK, iBand, padfX[iDstX]-poWK->nSrcXOff, padfY[iDstX]-poWK->nSrcYOff, &dfBandDensity, &dfValueReal, &dfValueImag ); } else if ( poWK->eResample == GRA_Cubic ) { GWKCubicResample( poWK, iBand, padfX[iDstX]-poWK->nSrcXOff, padfY[iDstX]-poWK->nSrcYOff, &dfBandDensity, &dfValueReal, &dfValueImag ); } else if ( poWK->eResample == GRA_CubicSpline || poWK->eResample == GRA_Lanczos ) { psWrkStruct->pfnGWKResample( poWK, iBand, padfX[iDstX]-poWK->nSrcXOff, padfY[iDstX]-poWK->nSrcYOff, &dfBandDensity, &dfValueReal, &dfValueImag, psWrkStruct ); } // If we didn't find any valid inputs skip to next band. if ( dfBandDensity < 0.0000000001 ) continue; bHasFoundDensity = TRUE; /* -------------------------------------------------------------------- */ /* We have a computed value from the source. Now apply it to */ /* the destination pixel. */ /* -------------------------------------------------------------------- */ GWKSetPixelValue( poWK, iBand, iDstOffset, dfBandDensity, dfValueReal, dfValueImag ); } if (!bHasFoundDensity) continue; /* -------------------------------------------------------------------- */ /* Update destination density/validity masks. */ /* -------------------------------------------------------------------- */ GWKOverlayDensity( poWK, iDstOffset, dfDensity ); if( poWK->panDstValid != NULL ) { poWK->panDstValid[iDstOffset>>5] |= 0x01 << (iDstOffset & 0x1f); } } /* Next iDstX */ /* -------------------------------------------------------------------- */ /* Report progress to the user, and optionally cancel out. */ /* -------------------------------------------------------------------- */ if (psJob->pfnProgress(psJob)) break; } /* -------------------------------------------------------------------- */ /* Cleanup and return. */ /* -------------------------------------------------------------------- */ CPLFree( padfX ); CPLFree( padfY ); CPLFree( padfZ ); CPLFree( pabSuccess ); if (psWrkStruct) GWKResampleDeleteWrkStruct(psWrkStruct); } /************************************************************************/ /* GWKNearestNoMasksByte() */ /* */ /* Case for 8bit input data with nearest neighbour resampling */ /* without concerning about masking. Should be as fast as */ /* possible for this particular transformation type. */ /************************************************************************/ static void GWKNearestNoMasksByteThread(void* pData); static CPLErr GWKNearestNoMasksByte( GDALWarpKernel *poWK ) { return GWKRun( poWK, "GWKNearestNoMasksByte", GWKNearestNoMasksByteThread ); } static void GWKNearestNoMasksByteThread(void* pData) { GWKJobStruct* psJob = (GWKJobStruct*) pData; GDALWarpKernel *poWK = psJob->poWK; int iYMin = psJob->iYMin; int iYMax = psJob->iYMax; int iDstY; int nDstXSize = poWK->nDstXSize; int nSrcXSize = poWK->nSrcXSize, nSrcYSize = poWK->nSrcYSize; /* -------------------------------------------------------------------- */ /* Allocate x,y,z coordinate arrays for transformation ... one */ /* scanlines worth of positions. */ /* -------------------------------------------------------------------- */ double *padfX, *padfY, *padfZ; int *pabSuccess; padfX = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfY = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfZ = (double *) CPLMalloc(sizeof(double) * nDstXSize); pabSuccess = (int *) CPLMalloc(sizeof(int) * nDstXSize); /* ==================================================================== */ /* Loop over output lines. */ /* ==================================================================== */ for( iDstY = iYMin; iDstY < iYMax; iDstY++ ) { int iDstX; /* -------------------------------------------------------------------- */ /* Setup points to transform to source image space. */ /* -------------------------------------------------------------------- */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { padfX[iDstX] = iDstX + 0.5 + poWK->nDstXOff; padfY[iDstX] = iDstY + 0.5 + poWK->nDstYOff; padfZ[iDstX] = 0.0; } /* -------------------------------------------------------------------- */ /* Transform the points from destination pixel/line coordinates */ /* to source pixel/line coordinates. */ /* -------------------------------------------------------------------- */ poWK->pfnTransformer( psJob->pTransformerArg, TRUE, nDstXSize, padfX, padfY, padfZ, pabSuccess ); /* ==================================================================== */ /* Loop over pixels in output scanline. */ /* ==================================================================== */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { COMPUTE_iSrcOffset(pabSuccess, iDstX, padfX, padfY, poWK, nSrcXSize, nSrcYSize); /* ==================================================================== */ /* Loop processing each band. */ /* ==================================================================== */ int iBand; int iDstOffset; iDstOffset = iDstX + iDstY * nDstXSize; for( iBand = 0; iBand < poWK->nBands; iBand++ ) { poWK->papabyDstImage[iBand][iDstOffset] = poWK->papabySrcImage[iBand][iSrcOffset]; } } /* -------------------------------------------------------------------- */ /* Report progress to the user, and optionally cancel out. */ /* -------------------------------------------------------------------- */ if (psJob->pfnProgress(psJob)) break; } /* -------------------------------------------------------------------- */ /* Cleanup and return. */ /* -------------------------------------------------------------------- */ CPLFree( padfX ); CPLFree( padfY ); CPLFree( padfZ ); CPLFree( pabSuccess ); } /************************************************************************/ /* GWKBilinearNoMasksByte() */ /* */ /* Case for 8bit input data with bilinear resampling without */ /* concerning about masking. Should be as fast as possible */ /* for this particular transformation type. */ /************************************************************************/ static void GWKBilinearNoMasksByteThread(void* pData); static CPLErr GWKBilinearNoMasksByte( GDALWarpKernel *poWK ) { return GWKRun( poWK, "GWKBilinearNoMasksByte", GWKBilinearNoMasksByteThread ); } static void GWKBilinearNoMasksByteThread(void* pData) { GWKJobStruct* psJob = (GWKJobStruct*) pData; GDALWarpKernel *poWK = psJob->poWK; int iYMin = psJob->iYMin; int iYMax = psJob->iYMax; int iDstY; int nDstXSize = poWK->nDstXSize; int nSrcXSize = poWK->nSrcXSize, nSrcYSize = poWK->nSrcYSize; /* -------------------------------------------------------------------- */ /* Allocate x,y,z coordinate arrays for transformation ... one */ /* scanlines worth of positions. */ /* -------------------------------------------------------------------- */ double *padfX, *padfY, *padfZ; int *pabSuccess; padfX = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfY = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfZ = (double *) CPLMalloc(sizeof(double) * nDstXSize); pabSuccess = (int *) CPLMalloc(sizeof(int) * nDstXSize); /* ==================================================================== */ /* Loop over output lines. */ /* ==================================================================== */ for( iDstY = iYMin; iDstY < iYMax; iDstY++ ) { int iDstX; /* -------------------------------------------------------------------- */ /* Setup points to transform to source image space. */ /* -------------------------------------------------------------------- */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { padfX[iDstX] = iDstX + 0.5 + poWK->nDstXOff; padfY[iDstX] = iDstY + 0.5 + poWK->nDstYOff; padfZ[iDstX] = 0.0; } /* -------------------------------------------------------------------- */ /* Transform the points from destination pixel/line coordinates */ /* to source pixel/line coordinates. */ /* -------------------------------------------------------------------- */ poWK->pfnTransformer( psJob->pTransformerArg, TRUE, nDstXSize, padfX, padfY, padfZ, pabSuccess ); /* ==================================================================== */ /* Loop over pixels in output scanline. */ /* ==================================================================== */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { COMPUTE_iSrcOffset(pabSuccess, iDstX, padfX, padfY, poWK, nSrcXSize, nSrcYSize); /* ==================================================================== */ /* Loop processing each band. */ /* ==================================================================== */ int iBand; int iDstOffset; iDstOffset = iDstX + iDstY * nDstXSize; for( iBand = 0; iBand < poWK->nBands; iBand++ ) { GWKBilinearResampleNoMasksByte( poWK, iBand, padfX[iDstX]-poWK->nSrcXOff, padfY[iDstX]-poWK->nSrcYOff, &poWK->papabyDstImage[iBand][iDstOffset] ); } } /* -------------------------------------------------------------------- */ /* Report progress to the user, and optionally cancel out. */ /* -------------------------------------------------------------------- */ if (psJob->pfnProgress(psJob)) break; } /* -------------------------------------------------------------------- */ /* Cleanup and return. */ /* -------------------------------------------------------------------- */ CPLFree( padfX ); CPLFree( padfY ); CPLFree( padfZ ); CPLFree( pabSuccess ); } /************************************************************************/ /* GWKCubicNoMasksByte() */ /* */ /* Case for 8bit input data with cubic resampling without */ /* concerning about masking. Should be as fast as possible */ /* for this particular transformation type. */ /************************************************************************/ static void GWKCubicNoMasksByteThread(void* pData); static CPLErr GWKCubicNoMasksByte( GDALWarpKernel *poWK ) { return GWKRun( poWK, "GWKCubicNoMasksByte", GWKCubicNoMasksByteThread ); } static void GWKCubicNoMasksByteThread( void* pData ) { GWKJobStruct* psJob = (GWKJobStruct*) pData; GDALWarpKernel *poWK = psJob->poWK; int iYMin = psJob->iYMin; int iYMax = psJob->iYMax; int iDstY; int nDstXSize = poWK->nDstXSize; int nSrcXSize = poWK->nSrcXSize, nSrcYSize = poWK->nSrcYSize; /* -------------------------------------------------------------------- */ /* Allocate x,y,z coordinate arrays for transformation ... one */ /* scanlines worth of positions. */ /* -------------------------------------------------------------------- */ double *padfX, *padfY, *padfZ; int *pabSuccess; padfX = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfY = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfZ = (double *) CPLMalloc(sizeof(double) * nDstXSize); pabSuccess = (int *) CPLMalloc(sizeof(int) * nDstXSize); /* ==================================================================== */ /* Loop over output lines. */ /* ==================================================================== */ for( iDstY = iYMin; iDstY < iYMax; iDstY++ ) { int iDstX; /* -------------------------------------------------------------------- */ /* Setup points to transform to source image space. */ /* -------------------------------------------------------------------- */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { padfX[iDstX] = iDstX + 0.5 + poWK->nDstXOff; padfY[iDstX] = iDstY + 0.5 + poWK->nDstYOff; padfZ[iDstX] = 0.0; } /* -------------------------------------------------------------------- */ /* Transform the points from destination pixel/line coordinates */ /* to source pixel/line coordinates. */ /* -------------------------------------------------------------------- */ poWK->pfnTransformer( psJob->pTransformerArg, TRUE, nDstXSize, padfX, padfY, padfZ, pabSuccess ); /* ==================================================================== */ /* Loop over pixels in output scanline. */ /* ==================================================================== */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { COMPUTE_iSrcOffset(pabSuccess, iDstX, padfX, padfY, poWK, nSrcXSize, nSrcYSize); /* ==================================================================== */ /* Loop processing each band. */ /* ==================================================================== */ int iBand; int iDstOffset; iDstOffset = iDstX + iDstY * nDstXSize; for( iBand = 0; iBand < poWK->nBands; iBand++ ) { GWKCubicResampleNoMasksByte( poWK, iBand, padfX[iDstX]-poWK->nSrcXOff, padfY[iDstX]-poWK->nSrcYOff, &poWK->papabyDstImage[iBand][iDstOffset] ); } } /* -------------------------------------------------------------------- */ /* Report progress to the user, and optionally cancel out. */ /* -------------------------------------------------------------------- */ if (psJob->pfnProgress(psJob)) break; } /* -------------------------------------------------------------------- */ /* Cleanup and return. */ /* -------------------------------------------------------------------- */ CPLFree( padfX ); CPLFree( padfY ); CPLFree( padfZ ); CPLFree( pabSuccess ); } /************************************************************************/ /* GWKCubicSplineNoMasksByte() */ /* */ /* Case for 8bit input data with cubic spline resampling without */ /* concerning about masking. Should be as fast as possible */ /* for this particular transformation type. */ /************************************************************************/ static void GWKCubicSplineNoMasksByteThread(void* pData); static CPLErr GWKCubicSplineNoMasksByte( GDALWarpKernel *poWK ) { return GWKRun( poWK, "GWKCubicSplineNoMasksByte", GWKCubicSplineNoMasksByteThread ); } static void GWKCubicSplineNoMasksByteThread( void* pData ) { GWKJobStruct* psJob = (GWKJobStruct*) pData; GDALWarpKernel *poWK = psJob->poWK; int iYMin = psJob->iYMin; int iYMax = psJob->iYMax; int iDstY; int nDstXSize = poWK->nDstXSize; int nSrcXSize = poWK->nSrcXSize, nSrcYSize = poWK->nSrcYSize; /* -------------------------------------------------------------------- */ /* Allocate x,y,z coordinate arrays for transformation ... one */ /* scanlines worth of positions. */ /* -------------------------------------------------------------------- */ double *padfX, *padfY, *padfZ; int *pabSuccess; padfX = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfY = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfZ = (double *) CPLMalloc(sizeof(double) * nDstXSize); pabSuccess = (int *) CPLMalloc(sizeof(int) * nDstXSize); int nXRadius = poWK->nXRadius; double *padfBSpline = (double *)CPLCalloc( nXRadius * 2, sizeof(double) ); /* ==================================================================== */ /* Loop over output lines. */ /* ==================================================================== */ for( iDstY = iYMin; iDstY < iYMax; iDstY++ ) { int iDstX; /* -------------------------------------------------------------------- */ /* Setup points to transform to source image space. */ /* -------------------------------------------------------------------- */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { padfX[iDstX] = iDstX + 0.5 + poWK->nDstXOff; padfY[iDstX] = iDstY + 0.5 + poWK->nDstYOff; padfZ[iDstX] = 0.0; } /* -------------------------------------------------------------------- */ /* Transform the points from destination pixel/line coordinates */ /* to source pixel/line coordinates. */ /* -------------------------------------------------------------------- */ poWK->pfnTransformer( psJob->pTransformerArg, TRUE, nDstXSize, padfX, padfY, padfZ, pabSuccess ); /* ==================================================================== */ /* Loop over pixels in output scanline. */ /* ==================================================================== */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { COMPUTE_iSrcOffset(pabSuccess, iDstX, padfX, padfY, poWK, nSrcXSize, nSrcYSize); /* ==================================================================== */ /* Loop processing each band. */ /* ==================================================================== */ int iBand; int iDstOffset; iDstOffset = iDstX + iDstY * nDstXSize; for( iBand = 0; iBand < poWK->nBands; iBand++ ) { GWKCubicSplineResampleNoMasksByte( poWK, iBand, padfX[iDstX]-poWK->nSrcXOff, padfY[iDstX]-poWK->nSrcYOff, &poWK->papabyDstImage[iBand][iDstOffset], padfBSpline); } } /* -------------------------------------------------------------------- */ /* Report progress to the user, and optionally cancel out. */ /* -------------------------------------------------------------------- */ if (psJob->pfnProgress(psJob)) break; } /* -------------------------------------------------------------------- */ /* Cleanup and return. */ /* -------------------------------------------------------------------- */ CPLFree( padfX ); CPLFree( padfY ); CPLFree( padfZ ); CPLFree( pabSuccess ); CPLFree( padfBSpline ); } /************************************************************************/ /* GWKNearestByte() */ /* */ /* Case for 8bit input data with nearest neighbour resampling */ /* using valid flags. Should be as fast as possible for this */ /* particular transformation type. */ /************************************************************************/ static void GWKNearestByteThread(void* pData); static CPLErr GWKNearestByte( GDALWarpKernel *poWK ) { return GWKRun( poWK, "GWKNearestByte", GWKNearestByteThread ); } static void GWKNearestByteThread( void* pData ) { GWKJobStruct* psJob = (GWKJobStruct*) pData; GDALWarpKernel *poWK = psJob->poWK; int iYMin = psJob->iYMin; int iYMax = psJob->iYMax; int iDstY; int nDstXSize = poWK->nDstXSize; int nSrcXSize = poWK->nSrcXSize, nSrcYSize = poWK->nSrcYSize; /* -------------------------------------------------------------------- */ /* Allocate x,y,z coordinate arrays for transformation ... one */ /* scanlines worth of positions. */ /* -------------------------------------------------------------------- */ double *padfX, *padfY, *padfZ; int *pabSuccess; padfX = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfY = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfZ = (double *) CPLMalloc(sizeof(double) * nDstXSize); pabSuccess = (int *) CPLMalloc(sizeof(int) * nDstXSize); /* ==================================================================== */ /* Loop over output lines. */ /* ==================================================================== */ for( iDstY = iYMin; iDstY < iYMax; iDstY++ ) { int iDstX; /* -------------------------------------------------------------------- */ /* Setup points to transform to source image space. */ /* -------------------------------------------------------------------- */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { padfX[iDstX] = iDstX + 0.5 + poWK->nDstXOff; padfY[iDstX] = iDstY + 0.5 + poWK->nDstYOff; padfZ[iDstX] = 0.0; } /* -------------------------------------------------------------------- */ /* Transform the points from destination pixel/line coordinates */ /* to source pixel/line coordinates. */ /* -------------------------------------------------------------------- */ poWK->pfnTransformer( psJob->pTransformerArg, TRUE, nDstXSize, padfX, padfY, padfZ, pabSuccess ); /* ==================================================================== */ /* Loop over pixels in output scanline. */ /* ==================================================================== */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { int iDstOffset; COMPUTE_iSrcOffset(pabSuccess, iDstX, padfX, padfY, poWK, nSrcXSize, nSrcYSize); /* -------------------------------------------------------------------- */ /* Do not try to apply invalid source pixels to the dest. */ /* -------------------------------------------------------------------- */ if( poWK->panUnifiedSrcValid != NULL && !(poWK->panUnifiedSrcValid[iSrcOffset>>5] & (0x01 << (iSrcOffset & 0x1f))) ) continue; /* -------------------------------------------------------------------- */ /* Do not try to apply transparent source pixels to the destination.*/ /* -------------------------------------------------------------------- */ double dfDensity = 1.0; if( poWK->pafUnifiedSrcDensity != NULL ) { dfDensity = poWK->pafUnifiedSrcDensity[iSrcOffset]; if( dfDensity < 0.00001 ) continue; } /* ==================================================================== */ /* Loop processing each band. */ /* ==================================================================== */ int iBand; iDstOffset = iDstX + iDstY * nDstXSize; for( iBand = 0; iBand < poWK->nBands; iBand++ ) { GByte bValue = 0; double dfBandDensity = 0.0; /* -------------------------------------------------------------------- */ /* Collect the source value. */ /* -------------------------------------------------------------------- */ if ( GWKGetPixelByte( poWK, iBand, iSrcOffset, &dfBandDensity, &bValue ) ) { if( dfBandDensity < 1.0 ) { if( dfBandDensity == 0.0 ) /* do nothing */; else { /* let the general code take care of mixing */ GWKSetPixelValue( poWK, iBand, iDstOffset, dfBandDensity, (double) bValue, 0.0 ); } } else { poWK->papabyDstImage[iBand][iDstOffset] = bValue; } } } /* -------------------------------------------------------------------- */ /* Mark this pixel valid/opaque in the output. */ /* -------------------------------------------------------------------- */ GWKOverlayDensity( poWK, iDstOffset, dfDensity ); if( poWK->panDstValid != NULL ) { poWK->panDstValid[iDstOffset>>5] |= 0x01 << (iDstOffset & 0x1f); } } /* Next iDstX */ /* -------------------------------------------------------------------- */ /* Report progress to the user, and optionally cancel out. */ /* -------------------------------------------------------------------- */ if (psJob->pfnProgress(psJob)) break; } /* Next iDstY */ /* -------------------------------------------------------------------- */ /* Cleanup and return. */ /* -------------------------------------------------------------------- */ CPLFree( padfX ); CPLFree( padfY ); CPLFree( padfZ ); CPLFree( pabSuccess ); } /************************************************************************/ /* GWKNearestNoMasksShort() */ /* */ /* Case for 16bit signed and unsigned integer input data with */ /* nearest neighbour resampling without concerning about masking. */ /* Should be as fast as possible for this particular */ /* transformation type. */ /************************************************************************/ static void GWKNearestNoMasksShortThread(void* pData); static CPLErr GWKNearestNoMasksShort( GDALWarpKernel *poWK ) { return GWKRun( poWK, "GWKNearestNoMasksShort", GWKNearestNoMasksShortThread ); } static void GWKNearestNoMasksShortThread( void* pData ) { GWKJobStruct* psJob = (GWKJobStruct*) pData; GDALWarpKernel *poWK = psJob->poWK; int iYMin = psJob->iYMin; int iYMax = psJob->iYMax; int iDstY; int nDstXSize = poWK->nDstXSize; int nSrcXSize = poWK->nSrcXSize, nSrcYSize = poWK->nSrcYSize; /* -------------------------------------------------------------------- */ /* Allocate x,y,z coordinate arrays for transformation ... one */ /* scanlines worth of positions. */ /* -------------------------------------------------------------------- */ double *padfX, *padfY, *padfZ; int *pabSuccess; padfX = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfY = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfZ = (double *) CPLMalloc(sizeof(double) * nDstXSize); pabSuccess = (int *) CPLMalloc(sizeof(int) * nDstXSize); /* ==================================================================== */ /* Loop over output lines. */ /* ==================================================================== */ for( iDstY = iYMin; iDstY < iYMax; iDstY++ ) { int iDstX; /* -------------------------------------------------------------------- */ /* Setup points to transform to source image space. */ /* -------------------------------------------------------------------- */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { padfX[iDstX] = iDstX + 0.5 + poWK->nDstXOff; padfY[iDstX] = iDstY + 0.5 + poWK->nDstYOff; padfZ[iDstX] = 0.0; } /* -------------------------------------------------------------------- */ /* Transform the points from destination pixel/line coordinates */ /* to source pixel/line coordinates. */ /* -------------------------------------------------------------------- */ poWK->pfnTransformer( psJob->pTransformerArg, TRUE, nDstXSize, padfX, padfY, padfZ, pabSuccess ); /* ==================================================================== */ /* Loop over pixels in output scanline. */ /* ==================================================================== */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { int iDstOffset; COMPUTE_iSrcOffset(pabSuccess, iDstX, padfX, padfY, poWK, nSrcXSize, nSrcYSize); /* ==================================================================== */ /* Loop processing each band. */ /* ==================================================================== */ int iBand; iDstOffset = iDstX + iDstY * nDstXSize; for( iBand = 0; iBand < poWK->nBands; iBand++ ) { ((GInt16 *)poWK->papabyDstImage[iBand])[iDstOffset] = ((GInt16 *)poWK->papabySrcImage[iBand])[iSrcOffset]; } } /* -------------------------------------------------------------------- */ /* Report progress to the user, and optionally cancel out. */ /* -------------------------------------------------------------------- */ if (psJob->pfnProgress(psJob)) break; } /* -------------------------------------------------------------------- */ /* Cleanup and return. */ /* -------------------------------------------------------------------- */ CPLFree( padfX ); CPLFree( padfY ); CPLFree( padfZ ); CPLFree( pabSuccess ); } /************************************************************************/ /* GWKBilinearNoMasksShort() */ /* */ /* Case for 16bit input data with cubic resampling without */ /* concerning about masking. Should be as fast as possible */ /* for this particular transformation type. */ /************************************************************************/ static void GWKBilinearNoMasksShortThread(void* pData); static CPLErr GWKBilinearNoMasksShort( GDALWarpKernel *poWK ) { return GWKRun( poWK, "GWKBilinearNoMasksShort", GWKBilinearNoMasksShortThread ); } static void GWKBilinearNoMasksShortThread( void* pData ) { GWKJobStruct* psJob = (GWKJobStruct*) pData; GDALWarpKernel *poWK = psJob->poWK; int iYMin = psJob->iYMin; int iYMax = psJob->iYMax; int iDstY; int nDstXSize = poWK->nDstXSize; int nSrcXSize = poWK->nSrcXSize, nSrcYSize = poWK->nSrcYSize; /* -------------------------------------------------------------------- */ /* Allocate x,y,z coordinate arrays for transformation ... one */ /* scanlines worth of positions. */ /* -------------------------------------------------------------------- */ double *padfX, *padfY, *padfZ; int *pabSuccess; padfX = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfY = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfZ = (double *) CPLMalloc(sizeof(double) * nDstXSize); pabSuccess = (int *) CPLMalloc(sizeof(int) * nDstXSize); /* ==================================================================== */ /* Loop over output lines. */ /* ==================================================================== */ for( iDstY = iYMin; iDstY < iYMax; iDstY++ ) { int iDstX; /* -------------------------------------------------------------------- */ /* Setup points to transform to source image space. */ /* -------------------------------------------------------------------- */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { padfX[iDstX] = iDstX + 0.5 + poWK->nDstXOff; padfY[iDstX] = iDstY + 0.5 + poWK->nDstYOff; padfZ[iDstX] = 0.0; } /* -------------------------------------------------------------------- */ /* Transform the points from destination pixel/line coordinates */ /* to source pixel/line coordinates. */ /* -------------------------------------------------------------------- */ poWK->pfnTransformer( psJob->pTransformerArg, TRUE, nDstXSize, padfX, padfY, padfZ, pabSuccess ); /* ==================================================================== */ /* Loop over pixels in output scanline. */ /* ==================================================================== */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { COMPUTE_iSrcOffset(pabSuccess, iDstX, padfX, padfY, poWK, nSrcXSize, nSrcYSize); /* ==================================================================== */ /* Loop processing each band. */ /* ==================================================================== */ int iBand; int iDstOffset; iDstOffset = iDstX + iDstY * nDstXSize; for( iBand = 0; iBand < poWK->nBands; iBand++ ) { GInt16 iValue = 0; GWKBilinearResampleNoMasksShort( poWK, iBand, padfX[iDstX]-poWK->nSrcXOff, padfY[iDstX]-poWK->nSrcYOff, &iValue ); ((GInt16 *)poWK->papabyDstImage[iBand])[iDstOffset] = iValue; } } /* -------------------------------------------------------------------- */ /* Report progress to the user, and optionally cancel out. */ /* -------------------------------------------------------------------- */ if (psJob->pfnProgress(psJob)) break; } /* -------------------------------------------------------------------- */ /* Cleanup and return. */ /* -------------------------------------------------------------------- */ CPLFree( padfX ); CPLFree( padfY ); CPLFree( padfZ ); CPLFree( pabSuccess ); } /************************************************************************/ /* GWKCubicNoMasksShort() */ /* */ /* Case for 16bit input data with cubic resampling without */ /* concerning about masking. Should be as fast as possible */ /* for this particular transformation type. */ /************************************************************************/ static void GWKCubicNoMasksShortThread(void* pData); static CPLErr GWKCubicNoMasksShort( GDALWarpKernel *poWK ) { return GWKRun( poWK, "GWKCubicNoMasksShort", GWKCubicNoMasksShortThread ); } static void GWKCubicNoMasksShortThread( void* pData ) { GWKJobStruct* psJob = (GWKJobStruct*) pData; GDALWarpKernel *poWK = psJob->poWK; int iYMin = psJob->iYMin; int iYMax = psJob->iYMax; int iDstY; int nDstXSize = poWK->nDstXSize; int nSrcXSize = poWK->nSrcXSize, nSrcYSize = poWK->nSrcYSize; /* -------------------------------------------------------------------- */ /* Allocate x,y,z coordinate arrays for transformation ... one */ /* scanlines worth of positions. */ /* -------------------------------------------------------------------- */ double *padfX, *padfY, *padfZ; int *pabSuccess; padfX = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfY = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfZ = (double *) CPLMalloc(sizeof(double) * nDstXSize); pabSuccess = (int *) CPLMalloc(sizeof(int) * nDstXSize); /* ==================================================================== */ /* Loop over output lines. */ /* ==================================================================== */ for( iDstY = iYMin; iDstY < iYMax; iDstY++ ) { int iDstX; /* -------------------------------------------------------------------- */ /* Setup points to transform to source image space. */ /* -------------------------------------------------------------------- */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { padfX[iDstX] = iDstX + 0.5 + poWK->nDstXOff; padfY[iDstX] = iDstY + 0.5 + poWK->nDstYOff; padfZ[iDstX] = 0.0; } /* -------------------------------------------------------------------- */ /* Transform the points from destination pixel/line coordinates */ /* to source pixel/line coordinates. */ /* -------------------------------------------------------------------- */ poWK->pfnTransformer( psJob->pTransformerArg, TRUE, nDstXSize, padfX, padfY, padfZ, pabSuccess ); /* ==================================================================== */ /* Loop over pixels in output scanline. */ /* ==================================================================== */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { COMPUTE_iSrcOffset(pabSuccess, iDstX, padfX, padfY, poWK, nSrcXSize, nSrcYSize); /* ==================================================================== */ /* Loop processing each band. */ /* ==================================================================== */ int iBand; int iDstOffset; iDstOffset = iDstX + iDstY * nDstXSize; for( iBand = 0; iBand < poWK->nBands; iBand++ ) { GInt16 iValue = 0; GWKCubicResampleNoMasksShort( poWK, iBand, padfX[iDstX]-poWK->nSrcXOff, padfY[iDstX]-poWK->nSrcYOff, &iValue ); ((GInt16 *)poWK->papabyDstImage[iBand])[iDstOffset] = iValue; } } /* -------------------------------------------------------------------- */ /* Report progress to the user, and optionally cancel out. */ /* -------------------------------------------------------------------- */ if (psJob->pfnProgress(psJob)) break; } /* -------------------------------------------------------------------- */ /* Cleanup and return. */ /* -------------------------------------------------------------------- */ CPLFree( padfX ); CPLFree( padfY ); CPLFree( padfZ ); CPLFree( pabSuccess ); } /************************************************************************/ /* GWKCubicSplineNoMasksShort() */ /* */ /* Case for 16bit input data with cubic resampling without */ /* concerning about masking. Should be as fast as possible */ /* for this particular transformation type. */ /************************************************************************/ static void GWKCubicSplineNoMasksShortThread(void* pData); static CPLErr GWKCubicSplineNoMasksShort( GDALWarpKernel *poWK ) { return GWKRun( poWK, "GWKCubicSplineNoMasksShort", GWKCubicSplineNoMasksShortThread ); } static void GWKCubicSplineNoMasksShortThread( void* pData ) { GWKJobStruct* psJob = (GWKJobStruct*) pData; GDALWarpKernel *poWK = psJob->poWK; int iYMin = psJob->iYMin; int iYMax = psJob->iYMax; int iDstY; int nDstXSize = poWK->nDstXSize; int nSrcXSize = poWK->nSrcXSize, nSrcYSize = poWK->nSrcYSize; /* -------------------------------------------------------------------- */ /* Allocate x,y,z coordinate arrays for transformation ... one */ /* scanlines worth of positions. */ /* -------------------------------------------------------------------- */ double *padfX, *padfY, *padfZ; int *pabSuccess; padfX = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfY = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfZ = (double *) CPLMalloc(sizeof(double) * nDstXSize); pabSuccess = (int *) CPLMalloc(sizeof(int) * nDstXSize); int nXRadius = poWK->nXRadius; // Make space to save weights double *padfBSpline = (double *)CPLCalloc( nXRadius * 2, sizeof(double) ); /* ==================================================================== */ /* Loop over output lines. */ /* ==================================================================== */ for( iDstY = iYMin; iDstY < iYMax; iDstY++ ) { int iDstX; /* -------------------------------------------------------------------- */ /* Setup points to transform to source image space. */ /* -------------------------------------------------------------------- */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { padfX[iDstX] = iDstX + 0.5 + poWK->nDstXOff; padfY[iDstX] = iDstY + 0.5 + poWK->nDstYOff; padfZ[iDstX] = 0.0; } /* -------------------------------------------------------------------- */ /* Transform the points from destination pixel/line coordinates */ /* to source pixel/line coordinates. */ /* -------------------------------------------------------------------- */ poWK->pfnTransformer( psJob->pTransformerArg, TRUE, nDstXSize, padfX, padfY, padfZ, pabSuccess ); /* ==================================================================== */ /* Loop over pixels in output scanline. */ /* ==================================================================== */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { COMPUTE_iSrcOffset(pabSuccess, iDstX, padfX, padfY, poWK, nSrcXSize, nSrcYSize); /* ==================================================================== */ /* Loop processing each band. */ /* ==================================================================== */ int iBand; int iDstOffset; iDstOffset = iDstX + iDstY * nDstXSize; for( iBand = 0; iBand < poWK->nBands; iBand++ ) { GInt16 iValue = 0; GWKCubicSplineResampleNoMasksShort( poWK, iBand, padfX[iDstX]-poWK->nSrcXOff, padfY[iDstX]-poWK->nSrcYOff, &iValue, padfBSpline); ((GInt16 *)poWK->papabyDstImage[iBand])[iDstOffset] = iValue; } } /* -------------------------------------------------------------------- */ /* Report progress to the user, and optionally cancel out. */ /* -------------------------------------------------------------------- */ if (psJob->pfnProgress(psJob)) break; } /* -------------------------------------------------------------------- */ /* Cleanup and return. */ /* -------------------------------------------------------------------- */ CPLFree( padfX ); CPLFree( padfY ); CPLFree( padfZ ); CPLFree( pabSuccess ); CPLFree( padfBSpline ); } /************************************************************************/ /* GWKNearestShort() */ /* */ /* Case for 32bit float input data with nearest neighbour */ /* resampling using valid flags. Should be as fast as possible */ /* for this particular transformation type. */ /************************************************************************/ static void GWKNearestShortThread(void* pData); static CPLErr GWKNearestShort( GDALWarpKernel *poWK ) { return GWKRun( poWK, "GWKNearestShort", GWKNearestShortThread ); } static void GWKNearestShortThread(void* pData) { GWKJobStruct* psJob = (GWKJobStruct*) pData; GDALWarpKernel *poWK = psJob->poWK; int iYMin = psJob->iYMin; int iYMax = psJob->iYMax; int iDstY; int nDstXSize = poWK->nDstXSize; int nSrcXSize = poWK->nSrcXSize, nSrcYSize = poWK->nSrcYSize; /* -------------------------------------------------------------------- */ /* Allocate x,y,z coordinate arrays for transformation ... one */ /* scanlines worth of positions. */ /* -------------------------------------------------------------------- */ double *padfX, *padfY, *padfZ; int *pabSuccess; padfX = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfY = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfZ = (double *) CPLMalloc(sizeof(double) * nDstXSize); pabSuccess = (int *) CPLMalloc(sizeof(int) * nDstXSize); /* ==================================================================== */ /* Loop over output lines. */ /* ==================================================================== */ for( iDstY = iYMin; iDstY < iYMax; iDstY++ ) { int iDstX; /* -------------------------------------------------------------------- */ /* Setup points to transform to source image space. */ /* -------------------------------------------------------------------- */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { padfX[iDstX] = iDstX + 0.5 + poWK->nDstXOff; padfY[iDstX] = iDstY + 0.5 + poWK->nDstYOff; padfZ[iDstX] = 0.0; } /* -------------------------------------------------------------------- */ /* Transform the points from destination pixel/line coordinates */ /* to source pixel/line coordinates. */ /* -------------------------------------------------------------------- */ poWK->pfnTransformer( psJob->pTransformerArg, TRUE, nDstXSize, padfX, padfY, padfZ, pabSuccess ); /* ==================================================================== */ /* Loop over pixels in output scanline. */ /* ==================================================================== */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { int iDstOffset; COMPUTE_iSrcOffset(pabSuccess, iDstX, padfX, padfY, poWK, nSrcXSize, nSrcYSize); /* -------------------------------------------------------------------- */ /* Don't generate output pixels for which the source valid */ /* mask exists and is invalid. */ /* -------------------------------------------------------------------- */ if( poWK->panUnifiedSrcValid != NULL && !(poWK->panUnifiedSrcValid[iSrcOffset>>5] & (0x01 << (iSrcOffset & 0x1f))) ) continue; /* -------------------------------------------------------------------- */ /* Do not try to apply transparent source pixels to the destination.*/ /* -------------------------------------------------------------------- */ double dfDensity = 1.0; if( poWK->pafUnifiedSrcDensity != NULL ) { dfDensity = poWK->pafUnifiedSrcDensity[iSrcOffset]; if( dfDensity < 0.00001 ) continue; } /* ==================================================================== */ /* Loop processing each band. */ /* ==================================================================== */ int iBand; iDstOffset = iDstX + iDstY * nDstXSize; for( iBand = 0; iBand < poWK->nBands; iBand++ ) { GInt16 iValue = 0; double dfBandDensity = 0.0; /* -------------------------------------------------------------------- */ /* Collect the source value. */ /* -------------------------------------------------------------------- */ if ( GWKGetPixelShort( poWK, iBand, iSrcOffset, &dfBandDensity, &iValue ) ) { if( dfBandDensity < 1.0 ) { if( dfBandDensity == 0.0 ) /* do nothing */; else { /* let the general code take care of mixing */ GWKSetPixelValue( poWK, iBand, iDstOffset, dfBandDensity, (double) iValue, 0.0 ); } } else { ((GInt16 *)poWK->papabyDstImage[iBand])[iDstOffset] = iValue; } } } /* -------------------------------------------------------------------- */ /* Mark this pixel valid/opaque in the output. */ /* -------------------------------------------------------------------- */ GWKOverlayDensity( poWK, iDstOffset, dfDensity ); if( poWK->panDstValid != NULL ) { poWK->panDstValid[iDstOffset>>5] |= 0x01 << (iDstOffset & 0x1f); } } /* Next iDstX */ /* -------------------------------------------------------------------- */ /* Report progress to the user, and optionally cancel out. */ /* -------------------------------------------------------------------- */ if (psJob->pfnProgress(psJob)) break; } /* Next iDstY */ /* -------------------------------------------------------------------- */ /* Cleanup and return. */ /* -------------------------------------------------------------------- */ CPLFree( padfX ); CPLFree( padfY ); CPLFree( padfZ ); CPLFree( pabSuccess ); } /************************************************************************/ /* GWKNearestNoMasksFloat() */ /* */ /* Case for 32bit float input data with nearest neighbour */ /* resampling without concerning about masking. Should be as fast */ /* as possible for this particular transformation type. */ /************************************************************************/ static void GWKNearestNoMasksFloatThread(void* pData); static CPLErr GWKNearestNoMasksFloat( GDALWarpKernel *poWK ) { return GWKRun( poWK, "GWKNearestNoMasksFloat", GWKNearestNoMasksFloatThread ); } static void GWKNearestNoMasksFloatThread( void* pData ) { GWKJobStruct* psJob = (GWKJobStruct*) pData; GDALWarpKernel *poWK = psJob->poWK; int iYMin = psJob->iYMin; int iYMax = psJob->iYMax; int iDstY; int nDstXSize = poWK->nDstXSize; int nSrcXSize = poWK->nSrcXSize, nSrcYSize = poWK->nSrcYSize; /* -------------------------------------------------------------------- */ /* Allocate x,y,z coordinate arrays for transformation ... one */ /* scanlines worth of positions. */ /* -------------------------------------------------------------------- */ double *padfX, *padfY, *padfZ; int *pabSuccess; padfX = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfY = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfZ = (double *) CPLMalloc(sizeof(double) * nDstXSize); pabSuccess = (int *) CPLMalloc(sizeof(int) * nDstXSize); /* ==================================================================== */ /* Loop over output lines. */ /* ==================================================================== */ for( iDstY = iYMin; iDstY < iYMax; iDstY++ ) { int iDstX; /* -------------------------------------------------------------------- */ /* Setup points to transform to source image space. */ /* -------------------------------------------------------------------- */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { padfX[iDstX] = iDstX + 0.5 + poWK->nDstXOff; padfY[iDstX] = iDstY + 0.5 + poWK->nDstYOff; padfZ[iDstX] = 0.0; } /* -------------------------------------------------------------------- */ /* Transform the points from destination pixel/line coordinates */ /* to source pixel/line coordinates. */ /* -------------------------------------------------------------------- */ poWK->pfnTransformer( psJob->pTransformerArg, TRUE, nDstXSize, padfX, padfY, padfZ, pabSuccess ); /* ==================================================================== */ /* Loop over pixels in output scanline. */ /* ==================================================================== */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { int iDstOffset; COMPUTE_iSrcOffset(pabSuccess, iDstX, padfX, padfY, poWK, nSrcXSize, nSrcYSize); /* ==================================================================== */ /* Loop processing each band. */ /* ==================================================================== */ int iBand; iDstOffset = iDstX + iDstY * nDstXSize; for( iBand = 0; iBand < poWK->nBands; iBand++ ) { ((float *)poWK->papabyDstImage[iBand])[iDstOffset] = ((float *)poWK->papabySrcImage[iBand])[iSrcOffset]; } } /* -------------------------------------------------------------------- */ /* Report progress to the user, and optionally cancel out. */ /* -------------------------------------------------------------------- */ if (psJob->pfnProgress(psJob)) break; } /* -------------------------------------------------------------------- */ /* Cleanup and return. */ /* -------------------------------------------------------------------- */ CPLFree( padfX ); CPLFree( padfY ); CPLFree( padfZ ); CPLFree( pabSuccess ); } /************************************************************************/ /* GWKNearestFloat() */ /* */ /* Case for 32bit float input data with nearest neighbour */ /* resampling using valid flags. Should be as fast as possible */ /* for this particular transformation type. */ /************************************************************************/ static void GWKNearestFloatThread(void* pData); static CPLErr GWKNearestFloat( GDALWarpKernel *poWK ) { return GWKRun( poWK, "GWKNearestFloat", GWKNearestFloatThread ); } static void GWKNearestFloatThread( void* pData ) { GWKJobStruct* psJob = (GWKJobStruct*) pData; GDALWarpKernel *poWK = psJob->poWK; int iYMin = psJob->iYMin; int iYMax = psJob->iYMax; int iDstY; int nDstXSize = poWK->nDstXSize; int nSrcXSize = poWK->nSrcXSize, nSrcYSize = poWK->nSrcYSize; /* -------------------------------------------------------------------- */ /* Allocate x,y,z coordinate arrays for transformation ... one */ /* scanlines worth of positions. */ /* -------------------------------------------------------------------- */ double *padfX, *padfY, *padfZ; int *pabSuccess; padfX = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfY = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfZ = (double *) CPLMalloc(sizeof(double) * nDstXSize); pabSuccess = (int *) CPLMalloc(sizeof(int) * nDstXSize); /* ==================================================================== */ /* Loop over output lines. */ /* ==================================================================== */ for( iDstY = iYMin; iDstY < iYMax; iDstY++ ) { int iDstX; /* -------------------------------------------------------------------- */ /* Setup points to transform to source image space. */ /* -------------------------------------------------------------------- */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { padfX[iDstX] = iDstX + 0.5 + poWK->nDstXOff; padfY[iDstX] = iDstY + 0.5 + poWK->nDstYOff; padfZ[iDstX] = 0.0; } /* -------------------------------------------------------------------- */ /* Transform the points from destination pixel/line coordinates */ /* to source pixel/line coordinates. */ /* -------------------------------------------------------------------- */ poWK->pfnTransformer( psJob->pTransformerArg, TRUE, nDstXSize, padfX, padfY, padfZ, pabSuccess ); /* ==================================================================== */ /* Loop over pixels in output scanline. */ /* ==================================================================== */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { int iDstOffset; COMPUTE_iSrcOffset(pabSuccess, iDstX, padfX, padfY, poWK, nSrcXSize, nSrcYSize); /* -------------------------------------------------------------------- */ /* Do not try to apply invalid source pixels to the dest. */ /* -------------------------------------------------------------------- */ if( poWK->panUnifiedSrcValid != NULL && !(poWK->panUnifiedSrcValid[iSrcOffset>>5] & (0x01 << (iSrcOffset & 0x1f))) ) continue; /* -------------------------------------------------------------------- */ /* Do not try to apply transparent source pixels to the destination.*/ /* -------------------------------------------------------------------- */ double dfDensity = 1.0; if( poWK->pafUnifiedSrcDensity != NULL ) { dfDensity = poWK->pafUnifiedSrcDensity[iSrcOffset]; if( dfDensity < 0.00001 ) continue; } /* ==================================================================== */ /* Loop processing each band. */ /* ==================================================================== */ int iBand; iDstOffset = iDstX + iDstY * nDstXSize; for( iBand = 0; iBand < poWK->nBands; iBand++ ) { float fValue = 0; double dfBandDensity = 0.0; /* -------------------------------------------------------------------- */ /* Collect the source value. */ /* -------------------------------------------------------------------- */ if ( GWKGetPixelFloat( poWK, iBand, iSrcOffset, &dfBandDensity, &fValue ) ) { if( dfBandDensity < 1.0 ) { if( dfBandDensity == 0.0 ) /* do nothing */; else { /* let the general code take care of mixing */ GWKSetPixelValue( poWK, iBand, iDstOffset, dfBandDensity, (double) fValue, 0.0 ); } } else { ((float *)poWK->papabyDstImage[iBand])[iDstOffset] = fValue; } } } /* -------------------------------------------------------------------- */ /* Mark this pixel valid/opaque in the output. */ /* -------------------------------------------------------------------- */ GWKOverlayDensity( poWK, iDstOffset, dfDensity ); if( poWK->panDstValid != NULL ) { poWK->panDstValid[iDstOffset>>5] |= 0x01 << (iDstOffset & 0x1f); } } /* -------------------------------------------------------------------- */ /* Report progress to the user, and optionally cancel out. */ /* -------------------------------------------------------------------- */ if (psJob->pfnProgress(psJob)) break; } /* -------------------------------------------------------------------- */ /* Cleanup and return. */ /* -------------------------------------------------------------------- */ CPLFree( padfX ); CPLFree( padfY ); CPLFree( padfZ ); CPLFree( pabSuccess ); } /************************************************************************/ /* GWKAverageOrMode() */ /* */ /************************************************************************/ static void GWKAverageOrModeThread(void* pData); static CPLErr GWKAverageOrMode( GDALWarpKernel *poWK ) { return GWKRun( poWK, "GWKAverageOrMode", GWKAverageOrModeThread ); } // overall logic based on GWKGeneralCaseThread() static void GWKAverageOrModeThread( void* pData) { GWKJobStruct* psJob = (GWKJobStruct*) pData; GDALWarpKernel *poWK = psJob->poWK; int iYMin = psJob->iYMin; int iYMax = psJob->iYMax; int iDstY, iDstX, iSrcX, iSrcY, iDstOffset; int nDstXSize = poWK->nDstXSize; int nSrcXSize = poWK->nSrcXSize, nSrcYSize = poWK->nSrcYSize; /* -------------------------------------------------------------------- */ /* Find out which algorithm to use (small optim.) */ /* -------------------------------------------------------------------- */ int nAlgo = 0; // these vars only used with nAlgo == 3 int *panVals = NULL; int nBins = 0, nBinsOffset = 0; // only used with nAlgo = 2 float* pafVals = NULL; int* panSums = NULL; if ( poWK->eResample == GRA_Average ) { nAlgo = 1; } else if( poWK->eResample == GRA_Mode ) { // TODO check color table count > 256 if ( poWK->eWorkingDataType == GDT_Byte || poWK->eWorkingDataType == GDT_UInt16 || poWK->eWorkingDataType == GDT_Int16 ) { nAlgo = 3; /* In the case of a paletted or non-paletted byte band, */ /* input values are between 0 and 255 */ if ( poWK->eWorkingDataType == GDT_Byte ) { nBins = 256; } /* In the case of Int16, input values are between -32768 and 32767 */ else if ( poWK->eWorkingDataType == GDT_Int16 ) { nBins = 65536; nBinsOffset = 32768; } /* In the case of UInt16, input values are between 0 and 65537 */ else if ( poWK->eWorkingDataType == GDT_UInt16 ) { nBins = 65536; } panVals = (int*) VSIMalloc(nBins * sizeof(int)); if( panVals == NULL ) return; } else { nAlgo = 2; if ( nSrcXSize > 0 && nSrcYSize > 0 ) { pafVals = (float*) VSIMalloc3(nSrcXSize, nSrcYSize, sizeof(float)); panSums = (int*) VSIMalloc3(nSrcXSize, nSrcYSize, sizeof(int)); if( pafVals == NULL || panSums == NULL ) { VSIFree(pafVals); VSIFree(panSums); return; } } } } else { // other resample algorithms not permitted here CPLDebug( "GDAL", "GDALWarpKernel():GWKAverageOrModeThread() ERROR, illegal resample" ); return; } CPLDebug( "GDAL", "GDALWarpKernel():GWKAverageOrModeThread() using algo %d", nAlgo ); /* -------------------------------------------------------------------- */ /* Allocate x,y,z coordinate arrays for transformation ... two */ /* scanlines worth of positions. */ /* -------------------------------------------------------------------- */ double *padfX, *padfY, *padfZ; double *padfX2, *padfY2, *padfZ2; int *pabSuccess, *pabSuccess2; padfX = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfY = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfZ = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfX2 = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfY2 = (double *) CPLMalloc(sizeof(double) * nDstXSize); padfZ2 = (double *) CPLMalloc(sizeof(double) * nDstXSize); pabSuccess = (int *) CPLMalloc(sizeof(int) * nDstXSize); pabSuccess2 = (int *) CPLMalloc(sizeof(int) * nDstXSize); /* ==================================================================== */ /* Loop over output lines. */ /* ==================================================================== */ for( iDstY = iYMin; iDstY < iYMax; iDstY++ ) { /* -------------------------------------------------------------------- */ /* Setup points to transform to source image space. */ /* -------------------------------------------------------------------- */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { padfX[iDstX] = iDstX + poWK->nDstXOff; padfY[iDstX] = iDstY + poWK->nDstYOff; padfZ[iDstX] = 0.0; padfX2[iDstX] = iDstX + 1.0 + poWK->nDstXOff; padfY2[iDstX] = iDstY + 1.0 + poWK->nDstYOff; padfZ2[iDstX] = 0.0; } /* -------------------------------------------------------------------- */ /* Transform the points from destination pixel/line coordinates */ /* to source pixel/line coordinates. */ /* -------------------------------------------------------------------- */ poWK->pfnTransformer( psJob->pTransformerArg, TRUE, nDstXSize, padfX, padfY, padfZ, pabSuccess ); poWK->pfnTransformer( psJob->pTransformerArg, TRUE, nDstXSize, padfX2, padfY2, padfZ2, pabSuccess2 ); /* ==================================================================== */ /* Loop over pixels in output scanline. */ /* ==================================================================== */ for( iDstX = 0; iDstX < nDstXSize; iDstX++ ) { int iSrcOffset = 0; double dfDensity = 1.0; int bHasFoundDensity = FALSE; if( !pabSuccess[iDstX] || !pabSuccess2[iDstX] ) continue; iDstOffset = iDstX + iDstY * nDstXSize; /* ==================================================================== */ /* Loop processing each band. */ /* ==================================================================== */ for( int iBand = 0; iBand < poWK->nBands; iBand++ ) { double dfBandDensity = 0.0; double dfValueReal = 0.0; double dfValueImag = 0.0; double dfValueRealTmp = 0.0; double dfValueImagTmp = 0.0; /* -------------------------------------------------------------------- */ /* Collect the source value. */ /* -------------------------------------------------------------------- */ double dfTotal = 0; int nCount = 0; // count of pixels used to compute average/mode int nCount2 = 0; // count of all pixels sampled, including nodata int iSrcXMin, iSrcXMax,iSrcYMin,iSrcYMax; // compute corners in source crs iSrcXMin = MAX( ((int) floor((padfX[iDstX] + 1e-10))) - poWK->nSrcXOff, 0 ); iSrcXMax = MIN( ((int) ceil((padfX2[iDstX] - 1e-10))) - poWK->nSrcXOff, nSrcXSize ); iSrcYMin = MAX( ((int) floor((padfY[iDstX] + 1e-10))) - poWK->nSrcYOff, 0 ); iSrcYMax = MIN( ((int) ceil((padfY2[iDstX] - 1e-10))) - poWK->nSrcYOff, nSrcYSize ); // The transformation might not have preserved ordering of coordinates // so do the necessary swapping (#5433) // NOTE: this is really an approximative fix. To do something more precise // we would for example need to compute the transformation of coordinates // in the [iDstX,iDstY]x[iDstX+1,iDstY+1] square back to source coordinates, // and take the bounding box of the got source coordinates. if( iSrcXMax < iSrcXMin ) { iSrcXMin = MAX( ((int) floor((padfX2[iDstX] + 1e-10))) - poWK->nSrcXOff, 0 ); iSrcXMax = MIN( ((int) ceil((padfX[iDstX] - 1e-10))) - poWK->nSrcXOff, nSrcXSize ); } if( iSrcYMax < iSrcYMin ) { iSrcYMin = MAX( ((int) floor((padfY2[iDstX] + 1e-10))) - poWK->nSrcYOff, 0 ); iSrcYMax = MIN( ((int) ceil((padfY[iDstX] - 1e-10))) - poWK->nSrcYOff, nSrcYSize ); } if( iSrcXMin == iSrcXMax && iSrcXMax < nSrcXSize ) iSrcXMax ++; if( iSrcYMin == iSrcYMax && iSrcYMax < nSrcYSize ) iSrcYMax ++; // loop over source lines and pixels - 3 possible algorithms if ( nAlgo == 1 ) // poWK->eResample == GRA_Average { // this code adapted from GDALDownsampleChunk32R_AverageT() in gcore/overview.cpp for( iSrcY = iSrcYMin; iSrcY < iSrcYMax; iSrcY++ ) { for( iSrcX = iSrcXMin; iSrcX < iSrcXMax; iSrcX++ ) { iSrcOffset = iSrcX + iSrcY * nSrcXSize; if( poWK->panUnifiedSrcValid != NULL && !(poWK->panUnifiedSrcValid[iSrcOffset>>5] & (0x01 << (iSrcOffset & 0x1f))) ) { continue; } nCount2++; if ( GWKGetPixelValue( poWK, iBand, iSrcOffset, &dfBandDensity, &dfValueRealTmp, &dfValueImagTmp ) && dfBandDensity > 0.0000000001 ) { nCount++; dfTotal += dfValueRealTmp; } } } if ( nCount > 0 ) { dfValueReal = dfTotal / nCount; dfBandDensity = 1; bHasFoundDensity = TRUE; } } // GRA_Average else if ( nAlgo == 2 || nAlgo == 3 ) // poWK->eResample == GRA_Mode { // this code adapted from GDALDownsampleChunk32R_Mode() in gcore/overview.cpp if ( nAlgo == 2 ) // int32 or float { /* I'm not sure how much sense it makes to run a majority filter on floating point data, but here it is for the sake of compatability. It won't look right on RGB images by the nature of the filter. */ int iMaxInd = 0, iMaxVal = -1, i = 0; for( iSrcY = iSrcYMin; iSrcY < iSrcYMax; iSrcY++ ) { for( iSrcX = iSrcXMin; iSrcX < iSrcXMax; iSrcX++ ) { iSrcOffset = iSrcX + iSrcY * nSrcXSize; if( poWK->panUnifiedSrcValid != NULL && !(poWK->panUnifiedSrcValid[iSrcOffset>>5] & (0x01 << (iSrcOffset & 0x1f))) ) continue; nCount2++; if ( GWKGetPixelValue( poWK, iBand, iSrcOffset, &dfBandDensity, &dfValueRealTmp, &dfValueImagTmp ) && dfBandDensity > 0.0000000001 ) { nCount++; float fVal = dfValueRealTmp; //Check array for existing entry for( i = 0; i < iMaxInd; ++i ) if( pafVals[i] == fVal && ++panSums[i] > panSums[iMaxVal] ) { iMaxVal = i; break; } //Add to arr if entry not already there if( i == iMaxInd ) { pafVals[iMaxInd] = fVal; panSums[iMaxInd] = 1; if( iMaxVal < 0 ) iMaxVal = iMaxInd; ++iMaxInd; } } } } if( iMaxVal != -1 ) { dfValueReal = pafVals[iMaxVal]; dfBandDensity = 1; bHasFoundDensity = TRUE; } } else // byte or int16 { int nMaxVal = 0, iMaxInd = -1; memset(panVals, 0, nBins*sizeof(int)); for( iSrcY = iSrcYMin; iSrcY < iSrcYMax; iSrcY++ ) { for( iSrcX = iSrcXMin; iSrcX < iSrcXMax; iSrcX++ ) { iSrcOffset = iSrcX + iSrcY * nSrcXSize; if( poWK->panUnifiedSrcValid != NULL && !(poWK->panUnifiedSrcValid[iSrcOffset>>5] & (0x01 << (iSrcOffset & 0x1f))) ) continue; nCount2++; if ( GWKGetPixelValue( poWK, iBand, iSrcOffset, &dfBandDensity, &dfValueRealTmp, &dfValueImagTmp ) && dfBandDensity > 0.0000000001 ) { nCount++; int nVal = (int) dfValueRealTmp; if ( ++panVals[nVal+nBinsOffset] > nMaxVal) { //Sum the density //Is it the most common value so far? iMaxInd = nVal; nMaxVal = panVals[nVal+nBinsOffset]; } } } } if( iMaxInd != -1 ) { dfValueReal = (float)iMaxInd; dfBandDensity = 1; bHasFoundDensity = TRUE; } } } // GRA_Mode /* -------------------------------------------------------------------- */ /* We have a computed value from the source. Now apply it to */ /* the destination pixel. */ /* -------------------------------------------------------------------- */ if ( bHasFoundDensity ) { // TODO should we compute dfBandDensity in fct of nCount/nCount2 , // or use as a threshold to set the dest value? // dfBandDensity = (float) nCount / nCount2; // if ( (float) nCount / nCount2 > 0.1 ) // or fix gdalwarp crop_to_cutline to crop partially overlapping pixels GWKSetPixelValue( poWK, iBand, iDstOffset, dfBandDensity, dfValueReal, dfValueImag ); } } if (!bHasFoundDensity) continue; /* -------------------------------------------------------------------- */ /* Update destination density/validity masks. */ /* -------------------------------------------------------------------- */ GWKOverlayDensity( poWK, iDstOffset, dfDensity ); if( poWK->panDstValid != NULL ) { poWK->panDstValid[iDstOffset>>5] |= 0x01 << (iDstOffset & 0x1f); } } /* Next iDstX */ /* -------------------------------------------------------------------- */ /* Report progress to the user, and optionally cancel out. */ /* -------------------------------------------------------------------- */ if (psJob->pfnProgress(psJob)) break; } /* -------------------------------------------------------------------- */ /* Cleanup and return. */ /* -------------------------------------------------------------------- */ CPLFree( padfX ); CPLFree( padfY ); CPLFree( padfZ ); CPLFree( padfX2 ); CPLFree( padfY2 ); CPLFree( padfZ2 ); CPLFree( pabSuccess ); CPLFree( pabSuccess2 ); VSIFree( panVals ); VSIFree(pafVals); VSIFree(panSums); }
[ "jedwards@fastmail.com" ]
jedwards@fastmail.com
24fdebf5b97232500ed73b9188ed9d7b575eaf00
ad237097e8400fd5d7bd5c3f3c2785edb1806863
/InputPortElement.hpp
24289d498529d11af93367607d0ef61e6e22c002
[]
no_license
kirillPshenychnyi/combinational_logic
2006a9a505580fac7bcd47d0444a356b2c95fa40
24bc190d138f80baf585a01b2a653bfc6891c2b1
refs/heads/master
2021-01-10T08:26:31.027451
2016-03-27T18:34:38
2016-03-27T18:34:38
54,841,885
0
0
null
null
null
null
UTF-8
C++
false
false
531
hpp
#ifndef _INPUT_PORT_ELEMENT_HPP #define _INPUT_PORT_ELEMENT_HPP #include "Element.hpp" #include "InputPort.hpp" class InputPortElement : public Element { const InputPort & m_inputPort; public: InputPortElement(const InputPort & _input) :m_inputPort(_input) {} InputPortElement(const InputPortElement &) = delete; InputPortElement & operator = (const InputPortElement & ) = delete; bool evaluate() const ; }; inline bool InputPortElement::evaluate() const { return m_inputPort.getValue(); } #endif
[ "pshenychnyi96@gmail.com" ]
pshenychnyi96@gmail.com
0ee1ffcba9a925fc868ef7cf0d27bba76738e18a
d4291c13f4ebf3610f8c4adc75eede4baee0b2c1
/CommonTools/RecoAlgos/interface/PrimaryVertexAssignment.h
3efbbf6a06cb35d669ff6e01c07cefd97b680850
[ "Apache-2.0" ]
permissive
pasmuss/cmssw
22efced0a4a43ef8bc8066b2a6bddece0023a66e
566f40c323beef46134485a45ea53349f59ae534
refs/heads/master
2021-07-07T08:37:50.928560
2017-08-28T08:54:23
2017-08-28T08:54:23
237,956,377
0
0
Apache-2.0
2020-02-03T12:08:41
2020-02-03T12:08:41
null
UTF-8
C++
false
false
4,238
h
#ifndef CommonTools_PFCandProducer_PrimaryVertexAssignment_ #define CommonTools_PFCandProducer_PrimaryVertexAssignment_ #include "DataFormats/RecoCandidate/interface/RecoChargedRefCandidate.h" #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDProducer.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Framework/interface/Event.h" #include "DataFormats/Candidate/interface/Candidate.h" #include "DataFormats/ParticleFlowCandidate/interface/PFCandidateFwd.h" #include "DataFormats/ParticleFlowCandidate/interface/PFCandidate.h" #include "DataFormats/VertexReco/interface/VertexFwd.h" #include "TrackingTools/TransientTrack/interface/TransientTrackBuilder.h" class PrimaryVertexAssignment { public: enum Quality {UsedInFit=7,PrimaryDz=6,PrimaryV0=5,BTrack=4,Unused=3,OtherDz=2,NotReconstructedPrimary=1,Unassigned=0}; PrimaryVertexAssignment(const edm::ParameterSet& iConfig): maxDzSigForPrimaryAssignment_(iConfig.getParameter<double>("maxDzSigForPrimaryAssignment")), maxDzForPrimaryAssignment_(iConfig.getParameter<double>("maxDzForPrimaryAssignment")), maxDzErrorForPrimaryAssignment_(iConfig.getParameter<double>("maxDzErrorForPrimaryAssignment")), maxJetDeltaR_(iConfig.getParameter<double>("maxJetDeltaR")), minJetPt_(iConfig.getParameter<double>("minJetPt")), maxDistanceToJetAxis_(iConfig.getParameter<double>("maxDistanceToJetAxis")), maxDzForJetAxisAssigment_(iConfig.getParameter<double>("maxDzForJetAxisAssigment")), maxDxyForJetAxisAssigment_(iConfig.getParameter<double>("maxDxyForJetAxisAssigment")), maxDxySigForNotReconstructedPrimary_(iConfig.getParameter<double>("maxDxySigForNotReconstructedPrimary")), maxDxyForNotReconstructedPrimary_(iConfig.getParameter<double>("maxDxyForNotReconstructedPrimary")) {} ~PrimaryVertexAssignment(){} std::pair<int,PrimaryVertexAssignment::Quality> chargedHadronVertex(const reco::VertexCollection& vertices, const reco::TrackRef& trackRef, const reco::Track * track, const edm::View<reco::Candidate> & jets, const TransientTrackBuilder & builder) const; std::pair<int,PrimaryVertexAssignment::Quality> chargedHadronVertex(const reco::VertexCollection& vertices, const reco::TrackRef& trackRef, const edm::View<reco::Candidate> & jets, const TransientTrackBuilder & builder) const { return chargedHadronVertex(vertices,trackRef,&(*trackRef),jets,builder); } std::pair<int,PrimaryVertexAssignment::Quality> chargedHadronVertex( const reco::VertexCollection& vertices, const reco::PFCandidate& pfcand, const edm::View<reco::Candidate>& jets, const TransientTrackBuilder& builder) const { if(pfcand.gsfTrackRef().isNull()) { if(pfcand.trackRef().isNull()) return std::pair<int,PrimaryVertexAssignment::Quality>(-1,PrimaryVertexAssignment::Unassigned); else return chargedHadronVertex(vertices,pfcand.trackRef(),jets,builder); } return chargedHadronVertex(vertices,reco::TrackRef(),&(*pfcand.gsfTrackRef()),jets,builder); } std::pair<int,PrimaryVertexAssignment::Quality> chargedHadronVertex( const reco::VertexCollection& vertices, const reco::RecoChargedRefCandidate& chcand, const edm::View<reco::Candidate>& jets, const TransientTrackBuilder& builder) const { if(chcand.track().isNull()) return std::pair<int,PrimaryVertexAssignment::Quality>(-1,PrimaryVertexAssignment::Unassigned); return chargedHadronVertex(vertices,chcand.track(),jets,builder); } private : double maxDzSigForPrimaryAssignment_; double maxDzForPrimaryAssignment_; double maxDzErrorForPrimaryAssignment_; double maxJetDeltaR_; double minJetPt_; double maxDistanceToJetAxis_; double maxDzForJetAxisAssigment_; double maxDxyForJetAxisAssigment_; double maxDxySigForNotReconstructedPrimary_; double maxDxyForNotReconstructedPrimary_; }; #endif
[ "andrea.rizzi@cern.ch" ]
andrea.rizzi@cern.ch
f0a8bfae7ce1f576390e7398af2a3c966f874b80
184107c757476e25d455e8614cdc048a91d3fbb7
/src/test/addrman_tests.cpp
14ccd9f10a7c7e4c26e235026a0092dcb4420e4e
[ "MIT" ]
permissive
estamat/cryptotest
ed653787bdbababec590978ec892ecd7de595d49
24bce31b81e33e5eec259096b5a40322812c40cf
refs/heads/master
2020-05-02T11:41:08.003651
2019-03-27T06:59:00
2019-03-27T06:59:00
177,936,451
0
0
null
null
null
null
UTF-8
C++
false
false
18,341
cpp
// Copyright (c) 2012-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "addrman.h" #include "test/test_wiki.h" #include <string> #include <boost/test/unit_test.hpp> #include "hash.h" #include "netbase.h" #include "random.h" using namespace std; class CAddrManTest : public CAddrMan { uint64_t state; public: CAddrManTest() { state = 1; } //! Ensure that bucket placement is always the same for testing purposes. void MakeDeterministic() { nKey.SetNull(); seed_insecure_rand(true); } int RandomInt(int nMax) { state = (CHashWriter(SER_GETHASH, 0) << state).GetHash().GetCheapHash(); return (unsigned int)(state % nMax); } CAddrInfo* Find(const CNetAddr& addr, int* pnId = NULL) { return CAddrMan::Find(addr, pnId); } CAddrInfo* Create(const CAddress& addr, const CNetAddr& addrSource, int* pnId = NULL) { return CAddrMan::Create(addr, addrSource, pnId); } void Delete(int nId) { CAddrMan::Delete(nId); } }; static CNetAddr ResolveIP(const char* ip) { CNetAddr addr; BOOST_CHECK_MESSAGE(LookupHost(ip, addr, false), strprintf("failed to resolve: %s", ip)); return addr; } static CNetAddr ResolveIP(std::string ip) { return ResolveIP(ip.c_str()); } static CService ResolveService(const char* ip, int port = 0) { CService serv; BOOST_CHECK_MESSAGE(Lookup(ip, serv, port, false), strprintf("failed to resolve: %s:%i", ip, port)); return serv; } static CService ResolveService(std::string ip, int port = 0) { return ResolveService(ip.c_str(), port); } BOOST_FIXTURE_TEST_SUITE(addrman_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(addrman_simple) { CAddrManTest addrman; // Set addrman addr placement to be deterministic. addrman.MakeDeterministic(); CNetAddr source = ResolveIP("252.2.2.2"); // Test 1: Does Addrman respond correctly when empty. BOOST_CHECK(addrman.size() == 0); CAddrInfo addr_null = addrman.Select(); BOOST_CHECK(addr_null.ToString() == "[::]:0"); // Test 2: Does Addrman::Add work as expected. CService addr1 = ResolveService("250.1.1.1", 8333); addrman.Add(CAddress(addr1, NODE_NONE), source); BOOST_CHECK(addrman.size() == 1); CAddrInfo addr_ret1 = addrman.Select(); BOOST_CHECK(addr_ret1.ToString() == "250.1.1.1:8333"); // Test 3: Does IP address deduplication work correctly. // Expected dup IP should not be added. CService addr1_dup = ResolveService("250.1.1.1", 8333); addrman.Add(CAddress(addr1_dup, NODE_NONE), source); BOOST_CHECK(addrman.size() == 1); // Test 5: New table has one addr and we add a diff addr we should // have two addrs. CService addr2 = ResolveService("250.1.1.2", 8333); addrman.Add(CAddress(addr2, NODE_NONE), source); BOOST_CHECK(addrman.size() == 2); // Test 6: AddrMan::Clear() should empty the new table. addrman.Clear(); BOOST_CHECK(addrman.size() == 0); CAddrInfo addr_null2 = addrman.Select(); BOOST_CHECK(addr_null2.ToString() == "[::]:0"); } BOOST_AUTO_TEST_CASE(addrman_ports) { CAddrManTest addrman; // Set addrman addr placement to be deterministic. addrman.MakeDeterministic(); CNetAddr source = ResolveIP("252.2.2.2"); BOOST_CHECK(addrman.size() == 0); // Test 7; Addr with same IP but diff port does not replace existing addr. CService addr1 = ResolveService("250.1.1.1", 8333); addrman.Add(CAddress(addr1, NODE_NONE), source); BOOST_CHECK(addrman.size() == 1); CService addr1_port = ResolveService("250.1.1.1", 8334); addrman.Add(CAddress(addr1_port, NODE_NONE), source); BOOST_CHECK(addrman.size() == 1); CAddrInfo addr_ret2 = addrman.Select(); BOOST_CHECK(addr_ret2.ToString() == "250.1.1.1:8333"); // Test 8: Add same IP but diff port to tried table, it doesn't get added. // Perhaps this is not ideal behavior but it is the current behavior. addrman.Good(CAddress(addr1_port, NODE_NONE)); BOOST_CHECK(addrman.size() == 1); bool newOnly = true; CAddrInfo addr_ret3 = addrman.Select(newOnly); BOOST_CHECK(addr_ret3.ToString() == "250.1.1.1:8333"); } BOOST_AUTO_TEST_CASE(addrman_select) { CAddrManTest addrman; // Set addrman addr placement to be deterministic. addrman.MakeDeterministic(); CNetAddr source = ResolveIP("252.2.2.2"); // Test 9: Select from new with 1 addr in new. CService addr1 = ResolveService("250.1.1.1", 8333); addrman.Add(CAddress(addr1, NODE_NONE), source); BOOST_CHECK(addrman.size() == 1); bool newOnly = true; CAddrInfo addr_ret1 = addrman.Select(newOnly); BOOST_CHECK(addr_ret1.ToString() == "250.1.1.1:8333"); // Test 10: move addr to tried, select from new expected nothing returned. addrman.Good(CAddress(addr1, NODE_NONE)); BOOST_CHECK(addrman.size() == 1); CAddrInfo addr_ret2 = addrman.Select(newOnly); BOOST_CHECK(addr_ret2.ToString() == "[::]:0"); CAddrInfo addr_ret3 = addrman.Select(); BOOST_CHECK(addr_ret3.ToString() == "250.1.1.1:8333"); BOOST_CHECK(addrman.size() == 1); // Add three addresses to new table. CService addr2 = ResolveService("250.3.1.1", 8333); CService addr3 = ResolveService("250.3.2.2", 9999); CService addr4 = ResolveService("250.3.3.3", 9999); addrman.Add(CAddress(addr2, NODE_NONE), ResolveService("250.3.1.1", 8333)); addrman.Add(CAddress(addr3, NODE_NONE), ResolveService("250.3.1.1", 8333)); addrman.Add(CAddress(addr4, NODE_NONE), ResolveService("250.4.1.1", 8333)); // Add three addresses to tried table. CService addr5 = ResolveService("250.4.4.4", 8333); CService addr6 = ResolveService("250.4.5.5", 7777); CService addr7 = ResolveService("250.4.6.6", 8333); addrman.Add(CAddress(addr5, NODE_NONE), ResolveService("250.3.1.1", 8333)); addrman.Good(CAddress(addr5, NODE_NONE)); addrman.Add(CAddress(addr6, NODE_NONE), ResolveService("250.3.1.1", 8333)); addrman.Good(CAddress(addr6, NODE_NONE)); addrman.Add(CAddress(addr7, NODE_NONE), ResolveService("250.1.1.3", 8333)); addrman.Good(CAddress(addr7, NODE_NONE)); // Test 11: 6 addrs + 1 addr from last test = 7. BOOST_CHECK(addrman.size() == 7); // Test 12: Select pulls from new and tried regardless of port number. BOOST_CHECK(addrman.Select().ToString() == "250.4.6.6:8333"); BOOST_CHECK(addrman.Select().ToString() == "250.3.2.2:9999"); BOOST_CHECK(addrman.Select().ToString() == "250.3.3.3:9999"); BOOST_CHECK(addrman.Select().ToString() == "250.4.4.4:8333"); } BOOST_AUTO_TEST_CASE(addrman_new_collisions) { CAddrManTest addrman; // Set addrman addr placement to be deterministic. addrman.MakeDeterministic(); CNetAddr source = ResolveIP("252.2.2.2"); BOOST_CHECK(addrman.size() == 0); for (unsigned int i = 1; i < 18; i++) { CService addr = ResolveService("250.1.1." + boost::to_string(i)); addrman.Add(CAddress(addr, NODE_NONE), source); //Test 13: No collision in new table yet. BOOST_CHECK(addrman.size() == i); } //Test 14: new table collision! CService addr1 = ResolveService("250.1.1.18"); addrman.Add(CAddress(addr1, NODE_NONE), source); BOOST_CHECK(addrman.size() == 17); CService addr2 = ResolveService("250.1.1.19"); addrman.Add(CAddress(addr2, NODE_NONE), source); BOOST_CHECK(addrman.size() == 18); } BOOST_AUTO_TEST_CASE(addrman_tried_collisions) { CAddrManTest addrman; // Set addrman addr placement to be deterministic. addrman.MakeDeterministic(); CNetAddr source = ResolveIP("252.2.2.2"); BOOST_CHECK(addrman.size() == 0); for (unsigned int i = 1; i < 80; i++) { CService addr = ResolveService("250.1.1." + boost::to_string(i)); addrman.Add(CAddress(addr, NODE_NONE), source); addrman.Good(CAddress(addr, NODE_NONE)); //Test 15: No collision in tried table yet. BOOST_TEST_MESSAGE(addrman.size()); BOOST_CHECK(addrman.size() == i); } //Test 16: tried table collision! CService addr1 = ResolveService("250.1.1.80"); addrman.Add(CAddress(addr1, NODE_NONE), source); BOOST_CHECK(addrman.size() == 79); CService addr2 = ResolveService("250.1.1.81"); addrman.Add(CAddress(addr2, NODE_NONE), source); BOOST_CHECK(addrman.size() == 80); } BOOST_AUTO_TEST_CASE(addrman_find) { CAddrManTest addrman; // Set addrman addr placement to be deterministic. addrman.MakeDeterministic(); BOOST_CHECK(addrman.size() == 0); CAddress addr1 = CAddress(ResolveService("250.1.2.1", 8333), NODE_NONE); CAddress addr2 = CAddress(ResolveService("250.1.2.1", 9999), NODE_NONE); CAddress addr3 = CAddress(ResolveService("251.255.2.1", 8333), NODE_NONE); CNetAddr source1 = ResolveIP("250.1.2.1"); CNetAddr source2 = ResolveIP("250.1.2.2"); addrman.Add(addr1, source1); addrman.Add(addr2, source2); addrman.Add(addr3, source1); // Test 17: ensure Find returns an IP matching what we searched on. CAddrInfo* info1 = addrman.Find(addr1); BOOST_CHECK(info1); if (info1) BOOST_CHECK(info1->ToString() == "250.1.2.1:8333"); // Test 18; Find does not discriminate by port number. CAddrInfo* info2 = addrman.Find(addr2); BOOST_CHECK(info2); if (info2) BOOST_CHECK(info2->ToString() == info1->ToString()); // Test 19: Find returns another IP matching what we searched on. CAddrInfo* info3 = addrman.Find(addr3); BOOST_CHECK(info3); if (info3) BOOST_CHECK(info3->ToString() == "251.255.2.1:8333"); } BOOST_AUTO_TEST_CASE(addrman_create) { CAddrManTest addrman; // Set addrman addr placement to be deterministic. addrman.MakeDeterministic(); BOOST_CHECK(addrman.size() == 0); CAddress addr1 = CAddress(ResolveService("250.1.2.1", 8333), NODE_NONE); CNetAddr source1 = ResolveIP("250.1.2.1"); int nId; CAddrInfo* pinfo = addrman.Create(addr1, source1, &nId); // Test 20: The result should be the same as the input addr. BOOST_CHECK(pinfo->ToString() == "250.1.2.1:8333"); CAddrInfo* info2 = addrman.Find(addr1); BOOST_CHECK(info2->ToString() == "250.1.2.1:8333"); } BOOST_AUTO_TEST_CASE(addrman_delete) { CAddrManTest addrman; // Set addrman addr placement to be deterministic. addrman.MakeDeterministic(); BOOST_CHECK(addrman.size() == 0); CAddress addr1 = CAddress(ResolveService("250.1.2.1", 8333), NODE_NONE); CNetAddr source1 = ResolveIP("250.1.2.1"); int nId; addrman.Create(addr1, source1, &nId); // Test 21: Delete should actually delete the addr. BOOST_CHECK(addrman.size() == 1); addrman.Delete(nId); BOOST_CHECK(addrman.size() == 0); CAddrInfo* info2 = addrman.Find(addr1); BOOST_CHECK(info2 == NULL); } BOOST_AUTO_TEST_CASE(addrman_getaddr) { CAddrManTest addrman; // Set addrman addr placement to be deterministic. addrman.MakeDeterministic(); // Test 22: Sanity check, GetAddr should never return anything if addrman // is empty. BOOST_CHECK(addrman.size() == 0); vector<CAddress> vAddr1 = addrman.GetAddr(); BOOST_CHECK(vAddr1.size() == 0); CAddress addr1 = CAddress(ResolveService("250.250.2.1", 8333), NODE_NONE); addr1.nTime = GetAdjustedTime(); // Set time so isTerrible = false CAddress addr2 = CAddress(ResolveService("250.251.2.2", 9999), NODE_NONE); addr2.nTime = GetAdjustedTime(); CAddress addr3 = CAddress(ResolveService("251.252.2.3", 8333), NODE_NONE); addr3.nTime = GetAdjustedTime(); CAddress addr4 = CAddress(ResolveService("252.253.3.4", 8333), NODE_NONE); addr4.nTime = GetAdjustedTime(); CAddress addr5 = CAddress(ResolveService("252.254.4.5", 8333), NODE_NONE); addr5.nTime = GetAdjustedTime(); CNetAddr source1 = ResolveIP("250.1.2.1"); CNetAddr source2 = ResolveIP("250.2.3.3"); // Test 23: Ensure GetAddr works with new addresses. addrman.Add(addr1, source1); addrman.Add(addr2, source2); addrman.Add(addr3, source1); addrman.Add(addr4, source2); addrman.Add(addr5, source1); // GetAddr returns 23% of addresses, 23% of 5 is 1 rounded down. BOOST_CHECK(addrman.GetAddr().size() == 1); // Test 24: Ensure GetAddr works with new and tried addresses. addrman.Good(CAddress(addr1, NODE_NONE)); addrman.Good(CAddress(addr2, NODE_NONE)); BOOST_CHECK(addrman.GetAddr().size() == 1); // Test 25: Ensure GetAddr still returns 23% when addrman has many addrs. for (unsigned int i = 1; i < (8 * 256); i++) { int octet1 = i % 256; int octet2 = (i / 256) % 256; int octet3 = (i / (256 * 2)) % 256; string strAddr = boost::to_string(octet1) + "." + boost::to_string(octet2) + "." + boost::to_string(octet3) + ".23"; CAddress addr = CAddress(ResolveService(strAddr), NODE_NONE); // Ensure that for all addrs in addrman, isTerrible == false. addr.nTime = GetAdjustedTime(); addrman.Add(addr, ResolveIP(strAddr)); if (i % 8 == 0) addrman.Good(addr); } vector<CAddress> vAddr = addrman.GetAddr(); size_t percent23 = (addrman.size() * 23) / 100; BOOST_CHECK(vAddr.size() == percent23); BOOST_CHECK(vAddr.size() == 461); // (Addrman.size() < number of addresses added) due to address collisons. BOOST_CHECK(addrman.size() == 2007); } BOOST_AUTO_TEST_CASE(caddrinfo_get_tried_bucket) { CAddrManTest addrman; // Set addrman addr placement to be deterministic. addrman.MakeDeterministic(); CAddress addr1 = CAddress(ResolveService("250.1.1.1", 8333), NODE_NONE); CAddress addr2 = CAddress(ResolveService("250.1.1.1", 9999), NODE_NONE); CNetAddr source1 = ResolveIP("250.1.1.1"); CAddrInfo info1 = CAddrInfo(addr1, source1); uint256 nKey1 = (uint256)(CHashWriter(SER_GETHASH, 0) << 1).GetHash(); uint256 nKey2 = (uint256)(CHashWriter(SER_GETHASH, 0) << 2).GetHash(); BOOST_CHECK(info1.GetTriedBucket(nKey1) == 40); // Test 26: Make sure key actually randomizes bucket placement. A fail on // this test could be a security issue. BOOST_CHECK(info1.GetTriedBucket(nKey1) != info1.GetTriedBucket(nKey2)); // Test 27: Two addresses with same IP but different ports can map to // different buckets because they have different keys. CAddrInfo info2 = CAddrInfo(addr2, source1); BOOST_CHECK(info1.GetKey() != info2.GetKey()); BOOST_CHECK(info1.GetTriedBucket(nKey1) != info2.GetTriedBucket(nKey1)); set<int> buckets; for (int i = 0; i < 255; i++) { CAddrInfo infoi = CAddrInfo( CAddress(ResolveService("250.1.1." + boost::to_string(i)), NODE_NONE), ResolveIP("250.1.1." + boost::to_string(i))); int bucket = infoi.GetTriedBucket(nKey1); buckets.insert(bucket); } // Test 28: IP addresses in the same group (\16 prefix for IPv4) should // never get more than 8 buckets BOOST_CHECK(buckets.size() == 8); buckets.clear(); for (int j = 0; j < 255; j++) { CAddrInfo infoj = CAddrInfo( CAddress(ResolveService("250." + boost::to_string(j) + ".1.1"), NODE_NONE), ResolveIP("250." + boost::to_string(j) + ".1.1")); int bucket = infoj.GetTriedBucket(nKey1); buckets.insert(bucket); } // Test 29: IP addresses in the different groups should map to more than // 8 buckets. BOOST_CHECK(buckets.size() == 160); } BOOST_AUTO_TEST_CASE(caddrinfo_get_new_bucket) { CAddrManTest addrman; // Set addrman addr placement to be deterministic. addrman.MakeDeterministic(); CAddress addr1 = CAddress(ResolveService("250.1.2.1", 8333), NODE_NONE); CAddress addr2 = CAddress(ResolveService("250.1.2.1", 9999), NODE_NONE); CNetAddr source1 = ResolveIP("250.1.2.1"); CAddrInfo info1 = CAddrInfo(addr1, source1); uint256 nKey1 = (uint256)(CHashWriter(SER_GETHASH, 0) << 1).GetHash(); uint256 nKey2 = (uint256)(CHashWriter(SER_GETHASH, 0) << 2).GetHash(); BOOST_CHECK(info1.GetNewBucket(nKey1) == 786); // Test 30: Make sure key actually randomizes bucket placement. A fail on // this test could be a security issue. BOOST_CHECK(info1.GetNewBucket(nKey1) != info1.GetNewBucket(nKey2)); // Test 31: Ports should not effect bucket placement in the addr CAddrInfo info2 = CAddrInfo(addr2, source1); BOOST_CHECK(info1.GetKey() != info2.GetKey()); BOOST_CHECK(info1.GetNewBucket(nKey1) == info2.GetNewBucket(nKey1)); set<int> buckets; for (int i = 0; i < 255; i++) { CAddrInfo infoi = CAddrInfo( CAddress(ResolveService("250.1.1." + boost::to_string(i)), NODE_NONE), ResolveIP("250.1.1." + boost::to_string(i))); int bucket = infoi.GetNewBucket(nKey1); buckets.insert(bucket); } // Test 32: IP addresses in the same group (\16 prefix for IPv4) should // always map to the same bucket. BOOST_CHECK(buckets.size() == 1); buckets.clear(); for (int j = 0; j < 4 * 255; j++) { CAddrInfo infoj = CAddrInfo(CAddress( ResolveService( boost::to_string(250 + (j / 255)) + "." + boost::to_string(j % 256) + ".1.1"), NODE_NONE), ResolveIP("251.4.1.1")); int bucket = infoj.GetNewBucket(nKey1); buckets.insert(bucket); } // Test 33: IP addresses in the same source groups should map to no more // than 64 buckets. BOOST_CHECK(buckets.size() <= 64); buckets.clear(); for (int p = 0; p < 255; p++) { CAddrInfo infoj = CAddrInfo( CAddress(ResolveService("250.1.1.1"), NODE_NONE), ResolveIP("250." + boost::to_string(p) + ".1.1")); int bucket = infoj.GetNewBucket(nKey1); buckets.insert(bucket); } // Test 34: IP addresses in the different source groups should map to more // than 64 buckets. BOOST_CHECK(buckets.size() > 64); } BOOST_AUTO_TEST_SUITE_END()
[ "44753202+Altcoinwiki@users.noreply.github.com" ]
44753202+Altcoinwiki@users.noreply.github.com
c2acbbe9bc0598166d5fcb9b4fb833d4a45e96c2
ada620944bd6323abecd2a0c85b5facf69c8b288
/GaiaEngine/src/graphics/shaders/ShaderUniform.cpp
4732dc2467898dfbdb4b0e76d1b655cd2f46e9ce
[]
no_license
JacobHensley/Gaia
4bf53bd58d5e1773d29bad087a86072b294fbe71
e84e4c58d05781fc3f91d8b07ce2c3c4e53ab043
refs/heads/master
2021-10-26T00:28:18.047047
2019-04-08T21:19:00
2019-04-08T21:19:00
69,699,867
5
0
null
null
null
null
UTF-8
C++
false
false
1,071
cpp
#include "GaPCH.h" #include "ShaderUniform.h" ShaderUniform::ShaderUniform(const String& name, const String& type, uint count) : m_Name(name), m_Count(count), m_Offset(0) { m_Type = StringToType(type); m_Size = SizeFromType(m_Type) * m_Count; } ShaderUniform::~ShaderUniform() { } uint ShaderUniform::SizeFromType(Type type) { if (type == Type::SHADER_INT) return 4; if (type == Type::SHADER_FLOAT) return 4; if (type == Type::SHADER_SAMPLER2D) return 4; if (type == Type::SHADER_MAT4) return 4 * 4 * 4; return NULL; } Type ShaderUniform::StringToType(const String& name) { if (name == "int") return Type::SHADER_INT; if (name == "float") return Type::SHADER_FLOAT; if (name == "sampler2D") return Type::SHADER_SAMPLER2D; if (name == "mat4") return Type::SHADER_MAT4; return Type::NONE; } String ShaderUniform::StringFromType(Type type) { if (type == Type::SHADER_INT) return "int"; if (type == Type::SHADER_FLOAT) return "float"; if (type == Type::SHADER_SAMPLER2D) return "sampler2D"; if (type == Type::SHADER_MAT4) return "mat4"; return ""; }
[ "j@cobhensley.com" ]
j@cobhensley.com
0459832930a559832a8d6b4638f4537c3058f84c
a0ff445e18410e03ed017e40ad86822ee5d2b337
/King.cpp
774fdc7cb75bee6031b485824f80aea2251174cb
[]
no_license
juancarlosfarah/chess
5e3b55421d85ea0ef2d57a5ffa2870ad969ea746
d22ff27dbca526b466704360ec34ba7e7f9c002a
refs/heads/master
2021-01-03T03:15:05.001039
2020-02-12T01:04:30
2020-02-12T01:04:30
239,898,367
0
0
null
null
null
null
UTF-8
C++
false
false
2,545
cpp
// ========================================== // File: King.cpp // Author: Juan Carlos Farah // Email: juancarlos.farah14@imperial.ac.uk // ========================================== #include <iostream> using namespace std; #include "King.hpp" #include "Settings.hpp" // Constructor: Default // ==================== King::King() : ChessPiece() {} // Constructor: // ============ // This constructor takes a Color and creates a King of that Color. King::King(Color color) : ChessPiece(color) { this->name = KING_NAME; this->initSymbol(color); } // Constructor: // ============ // This constructor takes a Color and a ChessSquare and // constructs a King of that Color, setting its square // property to point to the given ChessSquare. King::King(Color c, const ChessSquare& cs) : ChessPiece(c, cs) { this->name = KING_NAME; this->initSymbol(c); } // Destructor: // =========== King::~King() {} // Private Method: initSymbol // ========================== // This method initialises the symbol // property of the King given its Color. void King::initSymbol(Color color) { this->symbol = (color == White) ? WHITE_KING : BLACK_KING; } // Public Method: isPossibleMove // ============================= // This method takes a ChessSquare and a pointer to the ChessPiece // in that ChessSquare (or nullptr if its empty), and returns a // pair of booleans. The first bool indicates if the move is // possible given the rules of movement of the King. The second // bool is true if the move requires the King to go through one // or more squares. This indicates if the move needs to be checked // further by the ChessBoard for any potential obstructions. // This method is inherited from the ChessPiece superclass. pair<bool, bool> King::isPossibleMove(ChessSquare& square, ChessPiece* piece) const { // Initialise return value. pair<bool, bool> rvalue(false, false); // Ensure validity at the ChessPiece level. if (!ChessPiece::isPossibleMove(square, piece).first) return rvalue; // A King can only move to any adjacent square and so does not // require the extra validation for potential blocks in the way, // thus leaving the second bool in rvalue as false. if (this->square->isAdjacent(square)) { rvalue.first = true; } return rvalue; } // Friend Operator: << // =================== // Outputs the symbol property of the King operand. ostream& operator<<(ostream& os, King king) { os << king.symbol; return os; }
[ "farah.juancarlos@gmail.com" ]
farah.juancarlos@gmail.com
d908a96b82d6e9045dfc3cf00733a2a403bc1e25
b1e9283abbb5201ad400fc4d064945a27eaec920
/codeforces-round-695-div-2/A-wizard-of-orz/main.cpp
1d84b644212a525371275856e2e3d160622e0d2d
[]
no_license
arunjain9988/CP
011696edb87009d50a12a6effc1b103cae07ba2f
e32f601f46218ee9871a06b66050dcbbede480a6
refs/heads/main
2023-05-07T20:38:46.801070
2021-05-10T08:45:16
2021-05-10T08:45:16
356,560,643
0
0
null
null
null
null
UTF-8
C++
false
false
1,625
cpp
#include <bits/stdc++.h> // This will work only for g++ compiler. #define loop(i, l, r) for (int i = (int)(l); i < (int)(r); ++i) #define floop(i, l, r) for (int i = (int)(l); i <= (int)(r); ++i) #define rloop(i, l, r) for (int i = (int)(l); i >= (int)(r); --i) //short hand for usual tokens #define pb push_back // to be used with algorithms that processes a container Eg: find(all(c),42) #define all(x) (x).begin(), (x).end() //Forward traversal #define rall(x) (x).rbegin, (x).rend() //reverse traversal // traversal function to avoid long template definition. Now with C++11 auto alleviates the pain. #define tr(c,i) for(__typeof__((c)).begin() i = (c).begin(); i != (c).end(); i++) using namespace std; // Shorthand for commonly used types typedef vector<int> vi; typedef vector<vi> vvi; typedef pair<int, int> ii; typedef vector<ii> vii; typedef long long ll; typedef vector<ll> vll; typedef vector<vll> vvll; typedef double ld; int n; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.precision(10); cout << fixed; int t; cin>>t; string f = "0123456789"; // string b = "" while(t--) { cin>>n; if (n==1) { cout<<"9\n"; continue; } if (n==2) { cout<<"98\n"; continue; } if (n==3) { cout<<"989\n"; continue; } cout<<"989"; n-=3; int cp = n/f.size(); int remain = n%f.size(); loop(i,0,cp) { cout<<f; } cout<<f.substr(0,remain); cout<<'\n'; } return 0; }
[ "arunjain9988@gmail.com" ]
arunjain9988@gmail.com
2a5f8f10420b91d06dc44578df309ab2e638a6e3
7dd8a20b3a4f00890cdaf10b5d46312104e01e7d
/infra/includes/ClientServerDefines.hpp
c4c372bd4821807c834725dac67e8ea80b188ba7
[]
no_license
ikulyeshov/pctask
865f09c52e19fdffc888c8e915e03104290b2bb0
6c7a9c73323aec6f7151dcbc981b403e89ad5afc
refs/heads/master
2021-01-01T05:20:07.899301
2016-04-16T18:36:42
2016-04-16T18:36:42
56,241,786
0
0
null
null
null
null
UTF-8
C++
false
false
571
hpp
/* * ClientServerDefines.hpp * * Created on: Apr 16, 2016 * Author: ihor */ #ifndef INCLUDES_CLIENTSERVERDEFINES_HPP_ #define INCLUDES_CLIENTSERVERDEFINES_HPP_ namespace infra { const char MSG_START[] = "Start %i"; const char MSG_STOP[] = "Stop %i"; const char MSG_QOS[] = "Qos %i"; //bitrate as argument const char MSG_CAPS[] = "Caps %i(%i) %ix%i"; //<camera> <row num> <resx x resy> const char MSG_CAPS_REQ[] = "Capsreq"; const char MSG_OVERHEAT[] = "Overheat %i"; //camera } //namespace infra #endif /* INCLUDES_CLIENTSERVERDEFINES_HPP_ */
[ "igorek03@yahoo.com" ]
igorek03@yahoo.com
82660c4871946d97455fe8129697f5e62e32c87a
4adb7fbe4a5da738ae7a1299576d4630fb6146b0
/2021-05-05/test/1_11000.cpp
cd3a823d0fa713f8aedb8486231c477a0b902458
[]
no_license
catch4/changmoo
b299859520cf272b72768e42c6514c6798f52c41
979ac337065c4b1fba89ee58a82afa2b4a93331f
refs/heads/main
2023-06-29T06:53:59.237820
2021-07-21T12:32:44
2021-07-21T12:32:44
350,213,168
0
0
null
null
null
null
UTF-8
C++
false
false
931
cpp
#include <algorithm> #include <iostream> #include <queue> #include <vector> #define pii pair<int, int> using namespace std; int n, ans; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cin >> n; vector<pii> range(n); for (int i = 0; i < n; ++i) { int from, to; cin >> from >> to; range[i] = {from, to}; } sort(range.begin(), range.end()); // 강의 빨리 끝나는 순 priority_queue<int, vector<int>, greater<int>> room; // 강의 끝나는 시간 오름차순 room.push(range[0].second); for (int i = 1; i < n; ++i) { const auto& [from, to] = range[i]; int now = room.top(); // 제일 빨리 끝나는 강의실 if (now <= from) room.pop(); // 강의 끝나는 시간 <= 강의 시작 시간이면 그 강의실 이용 room.push(to); } cout << room.size(); return 0; }
[ "public.stevemoon@gmail.com" ]
public.stevemoon@gmail.com
4d03700f644534718ebf756fa0629f3da3cb68da
bb3ab1d635a1696bb8cb81c672d06747d9a521a6
/src/crypto/chacha20.h
06873244b01d69611767930fd1509389e2c0c344
[ "MIT" ]
permissive
dogxteam/dogxwallet-master
55ab22aa37c7ce131a06151958743acb1f3e12af
346189354bdec9a80c20bdc429ddec15c3b17b73
refs/heads/master
2020-04-28T23:42:38.257585
2019-03-14T17:19:07
2019-03-14T17:19:07
175,666,685
5
0
null
null
null
null
UTF-8
C++
false
false
678
h
// Copyright (c) 2017 The dogxcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef dogxCOIN_CRYPTO_CHACHA20_H #define dogxCOIN_CRYPTO_CHACHA20_H #include <stdint.h> #include <stdlib.h> /** A PRNG class for ChaCha20. */ class ChaCha20 { private: uint32_t input[16]; public: ChaCha20(); ChaCha20(const unsigned char* key, size_t keylen); void SetKey(const unsigned char* key, size_t keylen); void SetIV(uint64_t iv); void Seek(uint64_t pos); void Output(unsigned char* output, size_t bytes); }; #endif // dogxCOIN_CRYPTO_CHACHA20_H
[ "alizha@tom.com" ]
alizha@tom.com
6f8e815a64958707f8c5252c72fe0b1b89071f7f
59418b5794f251391650d8593704190606fa2b41
/plugin_api/em5/em5/fire/FireHelper.h
dbadae1fb43ae4356ed2750cfe822a4a8aeec65d
[]
no_license
JeveruBerry/emergency5_sdk
8e5726f28123962541f7e9e4d70b2d8d5cc76cff
e5b23d905c356aab6f8b26432c72d18e5838ccf6
refs/heads/master
2023-08-25T12:25:19.117165
2018-12-18T16:55:16
2018-12-18T17:09:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,084
h
// Copyright (C) 2012-2018 Promotion Software GmbH //[-------------------------------------------------------] //[ Header guard ] //[-------------------------------------------------------] #pragma once //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include "em5/Export.h" #include <vector> //[-------------------------------------------------------] //[ Forward declarations ] //[-------------------------------------------------------] namespace em5 { class FireComponent; } namespace qsf { class Entity; } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace em5 { //[-------------------------------------------------------] //[ Classes ] //[-------------------------------------------------------] /** * @brief * EMERGENCY 5 static fire helper class */ class EM5_API_EXPORT FireHelper { //[-------------------------------------------------------] //[ Public static methods ] //[-------------------------------------------------------] public: static float getAutomatismDistanceFromCaller(qsf::Entity& callerEntity); static qsf::Entity* getConnectedHydrantFromEntity(const qsf::Entity& firemanEntity); static const qsf::Entity* findFreeHydrantNearEntity(qsf::Entity& firemanEntity, qsf::Entity& targetEntity, bool& foundAtLeastOneInRange); static bool isHydrantInRange(const qsf::Entity& hydrantEntity, const glm::vec3& position, float radius); static bool isHydrantInRange(const qsf::Entity& hydrantEntity, const qsf::Entity& targetEntity, float radius); static void getExtinguishTargets(std::vector<qsf::Entity*>& outTargets, qsf::Entity& targetEntity, qsf::Entity& firefightingUnit); static void getSortedTargetsInRange(std::vector<FireComponent*>& outTargets, qsf::Entity& callerEntity, float range); static qsf::Entity* getAnyEffectTarget(qsf::Entity& callerEntity, qsf::Entity& targetEntity); static qsf::Entity* getEffectTargetInRange(qsf::Entity& callerEntity, qsf::Entity& targetEntity, float maxExtinguishRange); static bool isTargetInExtinguishRange(qsf::Entity& targetEntity, const glm::vec3& callerPosition, float maxExtinguishRange); static float getExtinguishRangeFromEntity(qsf::Entity& callerEntity); static float getHardRadius(qsf::Entity& callerEntity); //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: FireHelper() {} ~FireHelper() {} }; //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // em5
[ "christian.ofenberg@promotion-software.de" ]
christian.ofenberg@promotion-software.de
48ab90af8d284ee4ce3eccbefc7c4a835167d59e
1603bbbcb89e27beef7ae6a98de53297ebf93eb4
/esp8266-rain.ino
6ca5a615bf3fa6ce95990ee16e5c61797d5f6300
[]
no_license
ItownTech/nodemcu-rain-sensor
2725b8585d7f98deeaa4cc8870bd33cabb680a57
db2344b86b95f18985b761afc5a6b231460e5fc5
refs/heads/master
2021-05-07T22:00:56.033489
2017-11-01T02:47:12
2017-11-01T02:47:12
109,078,404
3
0
null
null
null
null
UTF-8
C++
false
false
3,762
ino
/* Projet Nodemcu-rain-sensor Copyright (C) 2017 by Leon This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <ESP8266WiFi.h> #include <PubSubClient.h> #include <Arduino.h> #define WIFI_SSID "wifissid" #define WIFI_PASSWORD "password" #define MQTT_SERVER "10.25.73.8" #define MQTT_PORT 1883 // use 8883 for SSL #define MQTT_USER "pi" //user for Mosquitto #define MQTT_PASSWORD "raspberry" //passord for Mosquitto #define rain_topic "sensor/rain" //Topic Rain const int sensorMin = 0; // sensor minimum const int sensorMax = 1024; // sensor maximum char message_buff[100]; bool debug = true; WiFiClient espClient; PubSubClient client(espClient); void setup() { Serial.begin(9600); pinMode(A0, INPUT); setup_wifi(); client.setServer(MQTT_SERVER, MQTT_PORT); client.setCallback(callback); //Connecfion WiFi void setup_wifi() { delay(10); // We start by connecting to a WiFi network Serial.println(); Serial.print("Connecting to "); Serial.println(WIFI_SSID); WiFi.mode(WIFI_STA); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.print("=> IP address: "); Serial.print(WiFi.localIP()); Serial.println(""); } //Reconnexion void reconnect() { while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect if (client.connect("ESP8266Client", MQTT_USER, MQTT_PASSWORD)) { Serial.println("Connected"); } else { Serial.print("Failed, Error: "); Serial.print(client.state()); Serial.println(" Retrying MQTT connection in 5 seconds..."); delay(5000); // Wait 5 seconds before retrying } } } void loop() { if (!client.connected()) { reconnect(); } client.loop(); int sensorReading = analogRead(A0); int range = map(sensorReading, sensorMin, sensorMax, 0, 3); // range value: switch (range) { case 0: // Sensor getting wet Serial.println("Flood"); client.publish(rain_topic, "Flood", true); break; case 1: // Sensor getting wet Serial.println("Rain Warning"); client.publish(rain_topic, "raining", true); break; case 2: // Sensor dry - To shut this up delete the " Serial.println("Not Raining"); " below. Serial.println("Sun"); client.publish(rain_topic, "sun", true); break; } delay(1000 * 10); // delay between reads } // Start after receiving the message void callback(char* topic, byte* payload, unsigned int length) { int i = 0; if ( debug ) { Serial.println("Message recu => topic: " + String(topic)); Serial.print(" | longueur: " + String(length, DEC)); } // create character buffer with ending null terminator (string) for (i = 0; i < length; i++) { message_buff[i] = payload[i]; } message_buff[i] = '\0'; String msgString = String(message_buff); if ( debug ) { Serial.println("Payload: " + msgString); } }
[ "noreply@github.com" ]
noreply@github.com
db2b02165f5ba0b505e6b37c7f2c83c983e1a25b
1320fed38d1acc437910fd28fbbda848d29c1ae9
/KernelVMFileSystem.cpp
ba80e27530f055f4d5ecdc4639f265d73a82fcc5
[]
no_license
z-hakuei/KernelVMFS
c78d4fa7060e28de66deb9b4623536768136df22
fc42ca6dfbc13a15840673833a69ad817c88284d
refs/heads/master
2020-03-21T17:46:47.044839
2018-06-27T08:43:36
2018-06-27T08:43:36
138,853,311
0
0
null
null
null
null
UTF-8
C++
false
false
25,565
cpp
#include "KernelVMFileSystem.h" #include "errno.h" #include "sys/types.h" #include "sys/stat.h" #define S_IFLNK 0x3000; const uint64_t VMFS_EXTENT_BASE(15472640); const uint64_t SECTER_SIZE(512); #define LE_AND_NO_ALIGN 1 int vmfs_file_close(vmfs_file *f) { if (f == NULL) return(-1); if (f->flags & VMFS_FILE_FLAG_FD) CloseHandle(f->fd); free(f); return(0); } static inline char *strndup(const char *s, size_t n) { char *result; n = strnlen(s, n); result = (char * )malloc(n + 1); if (!result) return NULL; memcpy(result, s, n); result[n] = 0; return result; } static inline uint16_t read_le16(const u_char *p,int offset) { #ifdef LE_AND_NO_ALIGN return(*((uint16_t *)&p[offset])); #else return((uint16_t)p[offset] | ((uint16_t)p[offset+1] << 8)); #endif } /* Read a 32-bit word in little endian format */ static inline uint32_t read_le32(const u_char *p,int offset) { #ifdef LE_AND_NO_ALIGN return(*((uint32_t *)&p[offset])); #else return((uint32_t)p[offset] | ((uint32_t)p[offset+1] << 8) | ((uint32_t)p[offset+2] << 16) | ((uint32_t)p[offset+3] << 24)); #endif } /* Read a 64-bit word in little endian format */ static inline uint64_t read_le64(const u_char *p,int offset) { #ifdef LE_AND_NO_ALIGN return(*((uint64_t *)&p[offset])); #else return((uint64_t)read_le32(p,offset) + ((uint64_t)read_le32(p,offset+4) << 32)); #endif } /* Allocate a buffer with alignment compatible for direct I/O */ u_char *iobuffer_alloc(size_t len) { size_t buf_len; void *buf; buf_len = ALIGN_NUM(len,M_DIO_BLK_SIZE); if (!(buf = _aligned_malloc(M_DIO_BLK_SIZE,buf_len))) return NULL; return (u_char * )buf; } ssize_t m_read(HANDLE hFile, byte * buffer, uint32_t size, uint64_t pos) { OVERLAPPED oTmp = {0}; pos += VMFS_EXTENT_BASE * SECTER_SIZE; oTmp.Offset = pos & 0xFFFFFFFF; oTmp.OffsetHigh = pos >> 32; DWORD lenRead; ReadFile(hFile, buffer, size, &lenRead, &oTmp); return (ssize_t)lenRead; } /* Read a raw block of data on logical volume */ ssize_t vmfs_vol_read(HANDLE hDevice,off_t pos, u_char *buf,size_t len) { pos += VMFS_VOLINFO_BASE + 0x1000000; return(m_read(hDevice, buf, len, pos)); } KernelVMFileSystem::KernelVMFileSystem():device(NULL) { } KernelVMFileSystem::KernelVMFileSystem(HANDLE hDisk):device(hDisk) { inode_hash_buckets = VMFS_INODE_HASH_BUCKETS; inodes = (vmfs_inode **)calloc(inode_hash_buckets,sizeof(vmfs_inode *)); if (vmfs_volinfo_read() == -1) { fprintf(stderr,"VMFS: Unable to read VOL information\n"); } /* Read FS info */ if (vmfs_fsinfo_read() == -1) { fprintf(stderr,"VMFS: Unable to read FS information\n"); } /* Read FDC base information */ if (vmfs_read_fdc_base() == -1) { fprintf(stderr,"VMFS: Unable to read FDC information\n"); } } KernelVMFileSystem::~KernelVMFileSystem() { } /* Read a block from the filesystem */ ssize_t KernelVMFileSystem::vmfs_fs_read(uint32_t blk,off_t offset, u_char *buf,size_t len) { off_t pos; pos = (uint64_t)blk * fs_info.block_size; pos += offset; return(vmfs_vol_read(device, pos, buf, len)); } /* Read volume information */ int KernelVMFileSystem::vmfs_volinfo_read() { DECL_ALIGNED_BUFFER(buf,1024); if (m_read(device, buf, buf_len, VMFS_VOLINFO_BASE) != buf_len) return(-1); vol_info.magic = read_le32(buf,VMFS_VOLINFO_OFS_MAGIC); if (vol_info.magic != VMFS_VOLINFO_MAGIC) { fprintf(stderr,"VMFS VolInfo: invalid magic number 0x%8.8x\n", vol_info.magic); return(-1); } vol_info.version = read_le32(buf,VMFS_VOLINFO_OFS_VER); vol_info.size = read_le32(buf,VMFS_VOLINFO_OFS_SIZE); vol_info.lun = buf[VMFS_VOLINFO_OFS_LUN]; vol_info.name = strndup((char *)buf+VMFS_VOLINFO_OFS_NAME, VMFS_VOLINFO_OFS_NAME_SIZE); memcpy_s(&vol_info.uuid, sizeof(MyUUID), buf + VMFS_VOLINFO_OFS_UUID, sizeof(MyUUID)); vol_info.lvm_size = read_le64(buf,VMFS_LVMINFO_OFS_SIZE); vol_info.blocks = read_le64(buf,VMFS_LVMINFO_OFS_BLKS); vol_info.num_segments = read_le32(buf,VMFS_LVMINFO_OFS_NUM_SEGMENTS); vol_info.first_segment = read_le32(buf,VMFS_LVMINFO_OFS_FIRST_SEGMENT); vol_info.last_segment = read_le32(buf,VMFS_LVMINFO_OFS_LAST_SEGMENT); vol_info.num_extents = read_le32(buf,VMFS_LVMINFO_OFS_NUM_EXTENTS); memcpy_s(&vol_info.lvm_uuid, sizeof(MyUUID), buf + VMFS_LVMINFO_OFS_UUID, sizeof(MyUUID)); return(0); } /* Read filesystem information */ int KernelVMFileSystem::vmfs_fsinfo_read() { DECL_ALIGNED_BUFFER(buf,512); if (vmfs_vol_read(device, VMFS_FSINFO_BASE, buf, buf_len) != buf_len) return(-1); fs_info.magic = read_le32(buf, VMFS_FSINFO_OFS_MAGIC); if (fs_info.magic != VMFS_FSINFO_MAGIC) { fprintf(stderr,"VMFS FSInfo: invalid magic number 0x%8.8x\n",fs_info.magic); return(-1); } fs_info.vol_version = read_le32(buf,VMFS_FSINFO_OFS_VOLVER); fs_info.version = buf[VMFS_FSINFO_OFS_VER]; fs_info.mode = read_le32(buf,VMFS_FSINFO_OFS_MODE); fs_info.block_size = read_le64(buf,VMFS_FSINFO_OFS_BLKSIZE); fs_info.subblock_size = read_le32(buf,VMFS_FSINFO_OFS_SBSIZE); fs_info.fdc_header_size = read_le32(buf,VMFS_FSINFO_OFS_FDC_HEADER_SIZE); fs_info.fdc_bitmap_count = read_le32(buf,VMFS_FSINFO_OFS_FDC_BITMAP_COUNT); fs_info.ctime = (time_t)read_le32(buf,VMFS_FSINFO_OFS_CTIME); memcpy_s(&fs_info.uuid, sizeof(MyUUID), buf + VMFS_FSINFO_OFS_UUID, sizeof(MyUUID)); fs_info.label = strndup((char *)buf+VMFS_FSINFO_OFS_LABEL, VMFS_FSINFO_OFS_LABEL_SIZE); memcpy_s(&fs_info.lvm_uuid, sizeof(MyUUID), buf + VMFS_FSINFO_OFS_LVM_UUID, sizeof(MyUUID)); return(0); } /* Get number of items per area */ inline u_int KernelVMFileSystem::vmfs_bitmap_get_items_per_area(const vmfs_bitmap_header *bmh) { return(bmh->bmp_entries_per_area * bmh->items_per_bitmap_entry); } /* Get position of an item */ off_t KernelVMFileSystem::vmfs_bitmap_get_item_pos(vmfs_bitmap *b,uint32_t entry,uint32_t item) { off_t pos; uint32_t addr; uint32_t items_per_area; u_int area; addr = (entry * b->bmh.items_per_bitmap_entry) + item; items_per_area = vmfs_bitmap_get_items_per_area(&b->bmh); area = addr / items_per_area; pos = b->bmh.hdr_size + (area * b->bmh.area_size); pos += b->bmh.bmp_entries_per_area * VMFS_BITMAP_ENTRY_SIZE; pos += (addr % items_per_area) * b->bmh.data_size; return(pos); } /* Read a bitmap item from its entry and item numbers */ bool KernelVMFileSystem::vmfs_bitmap_get_item(vmfs_bitmap *b, uint32_t entry, uint32_t item, u_char *buf) { off_t pos = vmfs_bitmap_get_item_pos(b,entry,item); return(vmfs_file_pread(b->f,buf,b->bmh.data_size,pos) == b->bmh.data_size); } /* Read a piece of a file block */ ssize_t KernelVMFileSystem::vmfs_block_read_fb(uint32_t blk_id,off_t pos, u_char *buf,size_t len) { uint64_t offset,n_offset,blk_size; size_t clen,n_clen; uint32_t fb_item; u_char *tmpbuf; blk_size = fs_info.block_size; offset = pos % blk_size; clen = m_min(blk_size - offset,len); /* Use "normalized" offset / length to access data (for direct I/O) */ n_offset = offset & ~(M_DIO_BLK_SIZE - 1); n_clen = ALIGN_NUM(clen + (offset - n_offset),M_DIO_BLK_SIZE); fb_item = VMFS_BLK_FB_ITEM(blk_id); /* If everything is aligned for direct I/O, store directly in user buffer */ if ((n_offset == offset) && (n_clen == clen) && ALIGN_CHECK((uintptr_t)buf,M_DIO_BLK_SIZE)) { if (vmfs_fs_read(fb_item,n_offset,buf,n_clen) != n_clen) return(-EIO); return(n_clen); } /* Allocate a temporary buffer and copy result to user buffer */ if (!(tmpbuf = new u_char[n_clen])) return(-1); if (vmfs_fs_read(fb_item,n_offset,tmpbuf,n_clen) != n_clen) { free(tmpbuf); return(-EIO); } memcpy(buf,tmpbuf+(offset-n_offset),clen); delete [] tmpbuf; return(clen); } /* Read a piece of a sub-block */ ssize_t KernelVMFileSystem::vmfs_block_read_sb(uint32_t blk_id,off_t pos, u_char *buf,size_t len) { u_char * tmpbuf(NULL); DECL_ALIGNED_BUFFER_WOL(tmpbuf,sbc->bmh.data_size); uint32_t offset,sbc_entry,sbc_item; size_t clen; offset = pos % sbc->bmh.data_size; clen = m_min(sbc->bmh.data_size - offset,len); sbc_entry = VMFS_BLK_SB_ENTRY(blk_id); sbc_item = VMFS_BLK_SB_ITEM(blk_id); if (!vmfs_bitmap_get_item(sbc,sbc_entry,sbc_item,tmpbuf)) return(-EIO); memcpy(buf,tmpbuf+offset,clen); return(clen); } int KernelVMFileSystem::vmfs_inode_get_block(const vmfs_inode *inode,off_t pos,uint32_t *blk_id) { u_int blk_index; uint32_t zla; int vmfs5_extension; *blk_id = 0; if (!inode->blk_size) return(-EIO); /* This doesn't make much sense but looks like how it's being coded. At * least, the result has some sense. */ zla = inode->zla; if (zla >= VMFS5_ZLA_BASE) { vmfs5_extension = 1; zla -= VMFS5_ZLA_BASE; } else vmfs5_extension = 0; switch(zla) { case VMFS_BLK_TYPE_FB: case VMFS_BLK_TYPE_SB: blk_index = pos / inode->blk_size; if (blk_index >= VMFS_INODE_BLK_COUNT) return(-EINVAL); *blk_id = inode->blocks[blk_index]; break; case VMFS_BLK_TYPE_PB: { u_char * buf(NULL); DECL_ALIGNED_BUFFER_WOL(buf,pbc->bmh.data_size); uint32_t pb_blk_id; uint32_t blk_per_pb; u_int pb_index; u_int sub_index; blk_per_pb = pbc->bmh.data_size / sizeof(uint32_t); blk_index = pos / inode->blk_size; pb_index = blk_index / blk_per_pb; sub_index = blk_index % blk_per_pb; if (pb_index >= VMFS_INODE_BLK_COUNT) return(-EINVAL); pb_blk_id = inode->blocks[pb_index]; if (!pb_blk_id) break; if (!vmfs_bitmap_get_item(pbc, VMFS_BLK_PB_ENTRY(pb_blk_id), VMFS_BLK_PB_ITEM(pb_blk_id), buf)) return(-EIO); memcpy_s(blk_id, sizeof(uint32_t),buf + sub_index*sizeof(uint32_t), sizeof(uint32_t)); delete buf; buf = NULL; break; } case VMFS_BLK_TYPE_FD: if (vmfs5_extension) { *blk_id = inode->id; break; } default: /* Unexpected ZLA type */ return(-EIO); } return(0); } /* Read data from a file at the specified position */ ssize_t KernelVMFileSystem::vmfs_file_pread(vmfs_file *f,u_char *buf,size_t len,off_t pos) { uint32_t blk_id,blk_type; uint64_t blk_size,blk_len; uint64_t file_size,offset; ssize_t res = 0,rlen = 0; size_t exp_len; int err; if (f->flags & VMFS_FILE_FLAG_FD) return m_read(f->fd, buf, len, pos); /* We don't handle RDM files */ if (f->inode->type == VMFS_FILE_TYPE_RDM) return(-EIO); blk_size = fs_info.block_size; file_size = f->GetFileSize(); while(len > 0) { if (pos >= file_size) break; if ((err = vmfs_inode_get_block(f->inode,pos,&blk_id)) < 0) return(err); blk_type = VMFS_BLK_FB_TBZ(blk_id) ? VMFS_BLK_TYPE_NONE : VMFS_BLK_TYPE(blk_id); switch(blk_type) { /* Unallocated block */ case VMFS_BLK_TYPE_NONE: offset = pos % blk_size; blk_len = blk_size - offset; exp_len = m_min(blk_len,len); res = m_min(exp_len,file_size - pos); memset(buf,0,res); break; /* File-Block */ case VMFS_BLK_TYPE_FB: exp_len = m_min(len,file_size - pos); res = vmfs_block_read_fb(blk_id,pos,buf,exp_len); break; /* Sub-Block */ case VMFS_BLK_TYPE_SB: { exp_len = m_min(len,file_size - pos); res = vmfs_block_read_sb(blk_id,pos,buf,exp_len); break; } /* Inline in the inode */ case VMFS_BLK_TYPE_FD: if (blk_id == f->inode->id) { exp_len = m_min(len,file_size - pos); memcpy(buf, f->inode->content + pos, exp_len); res = exp_len; break; } default: fprintf(stderr,"VMFS: unknown block type 0x%2.2x\n",blk_type); return(-EIO); } /* Error while reading block, abort immediately */ if (res < 0) return(res); /* Move file position and keep track of bytes currently read */ pos += res; rlen += res; /* Move buffer position */ buf += res; len -= res; } return(rlen); } /* Read a bitmap header */ int vmfs_bmh_read(vmfs_bitmap_header *bmh,const u_char *buf) { memcpy_s(bmh, sizeof(*bmh), buf, sizeof(*bmh)); return(0); } /* Open a bitmap file */ inline vmfs_bitmap * KernelVMFileSystem::vmfs_bitmap_open_from_file(vmfs_file *f) { DECL_ALIGNED_BUFFER(buf,512); vmfs_bitmap *b; if (!f) return NULL; if (vmfs_file_pread(f,buf,buf_len,0) != buf_len) { vmfs_file_close(f); return NULL; } if (!(b = (vmfs_bitmap *)calloc(1, sizeof(vmfs_bitmap)))) { vmfs_file_close(f); return NULL; } vmfs_bmh_read(&b->bmh, buf); b->f = f; return b; } /* Open a file based on an inode buffer */ vmfs_file *vmfs_file_open_from_inode(vmfs_inode *inode) { vmfs_file *f; if (!(f = (vmfs_file *)calloc(1,sizeof(*f)))) return NULL; f->inode = (vmfs_inode *)inode; return f; } vmfs_bitmap * KernelVMFileSystem::vmfs_bitmap_open_from_inode(vmfs_inode *inode) { return vmfs_bitmap_open_from_file(vmfs_file_open_from_inode(inode)); } /* Hash function to retrieve an in-core inode */ inline u_int KernelVMFileSystem::vmfs_inode_hash(uint32_t blk_id) { return( (blk_id ^ (blk_id >> 9)) & (inode_hash_buckets - 1) ); } /* Read a metadata header */ int vmfs_metadata_hdr_read(vmfs_metadata_hdr *mdh,const u_char *buf) { mdh->magic = read_le32(buf,VMFS_MDH_OFS_MAGIC); mdh->pos = read_le64(buf,VMFS_MDH_OFS_POS); mdh->hb_pos = read_le64(buf,VMFS_MDH_OFS_HB_POS); mdh->hb_seq = read_le64(buf,VMFS_MDH_OFS_HB_SEQ); mdh->obj_seq = read_le64(buf,VMFS_MDH_OFS_OBJ_SEQ); mdh->hb_lock = read_le32(buf,VMFS_MDH_OFS_HB_LOCK); mdh->mtime = read_le64(buf,VMFS_MDH_OFS_MTIME); memcpy_s(&mdh->hb_uuid, sizeof(MyUUID), buf + VMFS_MDH_OFS_HB_UUID, sizeof(MyUUID)); return(0); } inline uint32_t vmfs_file_type2mode(uint32_t type) { switch (type) { case VMFS_FILE_TYPE_DIR: return S_IFDIR; case VMFS_FILE_TYPE_SYMLINK: return S_IFLNK; default: return S_IFREG; } } static inline uint32_t vmfs_inode_read_blk_id(const u_char *buf,u_int index) { return(read_le32(buf,VMFS_INODE_OFS_BLK_ARRAY+(index*sizeof(uint32_t)))); } /* Read an inode */ int vmfs_inode_read(vmfs_inode *inode,u_char *buf) { int i; vmfs_metadata_hdr_read(&inode->mdh,buf); if (inode->mdh.magic != VMFS_INODE_MAGIC) return(-1); inode->id = read_le32(buf,VMFS_INODE_OFS_ID); inode->id2 = read_le32(buf,VMFS_INODE_OFS_ID2); inode->nlink = read_le32(buf,VMFS_INODE_OFS_NLINK); inode->type = read_le32(buf,VMFS_INODE_OFS_TYPE); inode->flags = read_le32(buf,VMFS_INODE_OFS_FLAGS); inode->size = read_le64(buf,VMFS_INODE_OFS_SIZE); inode->blk_size = read_le64(buf,VMFS_INODE_OFS_BLK_SIZE); inode->blk_count = read_le64(buf,VMFS_INODE_OFS_BLK_COUNT); inode->mtime = read_le32(buf,VMFS_INODE_OFS_MTIME); inode->ctime = read_le32(buf,VMFS_INODE_OFS_CTIME); inode->atime = read_le32(buf,VMFS_INODE_OFS_ATIME); inode->uid = read_le32(buf,VMFS_INODE_OFS_UID); inode->gid = read_le32(buf,VMFS_INODE_OFS_GID); inode->mode = read_le32(buf,VMFS_INODE_OFS_MODE); inode->zla = read_le32(buf,VMFS_INODE_OFS_ZLA); inode->tbz = read_le32(buf,VMFS_INODE_OFS_TBZ); inode->cow = read_le32(buf,VMFS_INODE_OFS_COW); /* "corrected" mode */ inode->cmode = inode->mode | vmfs_file_type2mode(inode->type); if (inode->type == VMFS_FILE_TYPE_RDM) { inode->rdm_id = read_le32(buf,VMFS_INODE_OFS_RDM_ID); } else if (inode->zla == VMFS5_ZLA_BASE + VMFS_BLK_TYPE_FD) { memcpy(inode->content, buf + VMFS_INODE_OFS_CONTENT, inode->size); } else { for(i=0;i<VMFS_INODE_BLK_COUNT;i++) inode->blocks[i] = vmfs_inode_read_blk_id(buf,i); } return(0); } /* Get inode corresponding to a block id */ int KernelVMFileSystem::vmfs_inode_get(uint32_t blk_id,vmfs_inode *inode) { u_char * buf(NULL); DECL_ALIGNED_BUFFER_WOL(buf,VMFS_INODE_SIZE); if (VMFS_BLK_TYPE(blk_id) != VMFS_BLK_TYPE_FD) return(-1); if (!vmfs_bitmap_get_item(fdc, VMFS_BLK_FD_ENTRY(blk_id), VMFS_BLK_FD_ITEM(blk_id), buf)) return(-1); return(vmfs_inode_read(inode,buf)); } /* Register an inode in the in-core inode hash table */ void KernelVMFileSystem::vmfs_inode_register(vmfs_inode *inode) { u_int hb; hb = vmfs_inode_hash(inode->id); inode->ref_count = 1; /* Insert into hash table */ inode->next = inodes[hb]; inode->pprev = &(inodes[hb]); if (inode->next != NULL) inode->next->pprev = &inode->next; inodes[hb] = inode; } /* Acquire an inode */ vmfs_inode * KernelVMFileSystem::vmfs_inode_acquire(uint32_t blk_id) { vmfs_inode *inode; u_int hb; hb = vmfs_inode_hash(blk_id); for(inode=inodes[hb];inode;inode=inode->next) if (inode->id == blk_id) { inode->ref_count++; return inode; } /* Inode not yet used, allocate room for it */ if (!(inode = (vmfs_inode *)calloc(1,sizeof(*inode)))) return NULL; if (vmfs_inode_get(blk_id,inode) == -1) { free(inode); return NULL; } vmfs_inode_register(inode); return inode; } /* Open a file based on a directory entry */ vmfs_file * KernelVMFileSystem::vmfs_file_open_from_blkid(uint32_t blk_id) { vmfs_inode *inode; if (!(inode = vmfs_inode_acquire(blk_id))) return NULL; return(vmfs_file_open_from_inode(inode)); } /* Open a directory */ vmfs_dir * KernelVMFileSystem::vmfs_dir_open_at(vmfs_dir *d,const char *path) { return vmfs_dir_open_from_file(vmfs_file_open_at(d,path)); } /* Cache content of a directory */ int KernelVMFileSystem::vmfs_dir_cache_entries(vmfs_dir *d) { off_t dir_size; if (d->buf != NULL) free(d->buf); dir_size = d->dir->GetFileSize(); if (!(d->buf = (u_char *)calloc(1,dir_size))) return(-1); if (vmfs_file_pread(d->dir,d->buf,dir_size,0) != dir_size) { free(d->buf); return(-1); } return(0); } /* Open a directory file */ vmfs_dir * KernelVMFileSystem::vmfs_dir_open_from_file(vmfs_file *file) { vmfs_dir *d; if (file == NULL) return NULL; if (!(d = (vmfs_dir *)calloc(1, sizeof(*d))) || (file->inode->type != VMFS_FILE_TYPE_DIR)) { vmfs_file_close(file); return NULL; } d->dir = file; vmfs_dir_cache_entries(d); return d; } /* Set position of the next entry that vmfs_dir_read will return */ inline void vmfs_dir_seek(vmfs_dir *d, uint32_t pos) { if (d) d->pos = pos; } /* Read a directory entry */ static int vmfs_dirent_read(vmfs_dirent *entry,const u_char *buf) { entry->type = read_le32(buf,VMFS_DIRENT_OFS_TYPE); entry->block_id = read_le32(buf,VMFS_DIRENT_OFS_BLK_ID); entry->record_id = read_le32(buf,VMFS_DIRENT_OFS_REC_ID); memcpy(entry->name,buf+VMFS_DIRENT_OFS_NAME,VMFS_DIRENT_OFS_NAME_SIZE); entry->name[VMFS_DIRENT_OFS_NAME_SIZE] = 0; return(0); } /* Return next entry in directory. Returned directory entry will be overwritten by subsequent calls */ vmfs_dirent * KernelVMFileSystem::vmfs_dir_read(vmfs_dir *d) { u_char *buf; if (d == NULL) return(NULL); if (d->buf) { if (d->pos*VMFS_DIRENT_SIZE >= d->dir->GetFileSize()) return(NULL); buf = &d->buf[d->pos*VMFS_DIRENT_SIZE]; } else { u_char _buf[VMFS_DIRENT_SIZE]; if ((vmfs_file_pread(d->dir,_buf,sizeof(_buf), d->pos*sizeof(_buf)) != sizeof(_buf))) return(NULL); buf = _buf; } vmfs_dirent_read(&d->dirent,buf); d->pos++; return &d->dirent; } /* Open a directory based on a directory entry */ vmfs_dir * KernelVMFileSystem::vmfs_dir_open_from_blkid(uint32_t blk_id) { return vmfs_dir_open_from_file(vmfs_file_open_from_blkid(blk_id)); } /* Search for an entry into a directory ; affects position of the next entry vmfs_dir_read will return */ vmfs_dirent * KernelVMFileSystem::vmfs_dir_lookup(vmfs_dir *d,const char *name) { vmfs_dirent *rec; vmfs_dir_seek(d,0); while((rec = vmfs_dir_read(d))) { if (!strcmp(rec->name,name)) return(rec); } return(NULL); } /* Read a symlink */ char *KernelVMFileSystem::vmfs_dirent_read_symlink(const vmfs_dirent *entry) { vmfs_file *f; size_t str_len; char *str = NULL; if (!(f = vmfs_file_open_from_blkid(entry->block_id))) return NULL; str_len = f->GetFileSize(); if (!(str = (char *)malloc(str_len+1))) goto done; if ((str_len = vmfs_file_pread(f,(u_char *)str,str_len,0)) == -1) { free(str); goto done; } str[str_len] = 0; done: vmfs_file_close(f); return str; } /* Close a directory */ int vmfs_dir_close(vmfs_dir *d) { if (d == NULL) return(-1); if (d->buf) free(d->buf); vmfs_file_close(d->dir); free(d); return(0); } /* Resolve a path name to a block id */ uint32_t KernelVMFileSystem::vmfs_dir_resolve_path(vmfs_dir *base_dir,const char *path, int follow_symlink) { vmfs_dir *cur_dir,*sub_dir; const vmfs_dirent *rec; char *nam, *ptr,*sl,*symlink; int close_dir = 0; uint32_t ret = 0; cur_dir = base_dir; if (*path == '/') { if (!(cur_dir = vmfs_dir_open_from_blkid(VMFS_BLK_FD_BUILD(0, 0, 0)))) return(0); path++; close_dir = 1; } if (!(rec = vmfs_dir_lookup(cur_dir,"."))) return(0); ret = rec->block_id; nam = ptr = _strdup(path); while(*ptr != 0) { sl = strchr(ptr,'/'); if (sl != NULL) *sl = 0; if (*ptr == 0) { ptr = sl + 1; continue; } if (!(rec = vmfs_dir_lookup(cur_dir,ptr))) { ret = 0; break; } ret = rec->block_id; if ((sl == NULL) && !follow_symlink) break; /* follow the symlink if we have an entry of this type */ if (rec->type == VMFS_FILE_TYPE_SYMLINK) { if (!(symlink = vmfs_dirent_read_symlink(rec))) { ret = 0; break; } ret = vmfs_dir_resolve_path(cur_dir,symlink,1); free(symlink); if (!ret) break; } /* last token */ if (sl == NULL) break; /* we must have a directory here */ if (!(sub_dir = vmfs_dir_open_from_blkid(ret))) { ret = 0; break; } if (close_dir) vmfs_dir_close(cur_dir); cur_dir = sub_dir; close_dir = 1; ptr = sl + 1; } free(nam); if (close_dir) vmfs_dir_close(cur_dir); return(ret); } /* Open a file */ vmfs_file * KernelVMFileSystem::vmfs_file_open_at(vmfs_dir *dir,const char *path) { uint32_t blk_id; if (!(blk_id = vmfs_dir_resolve_path(dir,path,1))) return(NULL); return(vmfs_file_open_from_blkid(blk_id)); } vmfs_bitmap * KernelVMFileSystem::vmfs_bitmap_open_at(vmfs_dir *d,const char *name) { return vmfs_bitmap_open_from_file(vmfs_file_open_at(d, name)); } /* Close a bitmap file */ void vmfs_bitmap_close(vmfs_bitmap *b) { if (b != NULL) { vmfs_file_close(b->f); free(b); } } vmfs_bitmap * KernelVMFileSystem::vmfs_open_meta_file(vmfs_dir *root_dir, char *name, uint32_t max_item, uint32_t max_entry, char *desc) { vmfs_bitmap *bitmap = vmfs_bitmap_open_at(root_dir, name); if (!bitmap) { fprintf(stderr, "Unable to open %s.\n", desc); return NULL; } if (bitmap->bmh.items_per_bitmap_entry > max_item) { fprintf(stderr, "Unsupported number of items per entry in %s.\n", desc); return NULL; } if ((bitmap->bmh.total_items + bitmap->bmh.items_per_bitmap_entry - 1) / bitmap->bmh.items_per_bitmap_entry > max_entry) { fprintf(stderr,"Unsupported number of entries in %s.\n", desc); return NULL; } return bitmap; } /* Open all the VMFS meta files */ int KernelVMFileSystem::vmfs_open_all_meta_files() { /* Read the first inode */ if (!(root_dir = vmfs_dir_open_from_blkid(VMFS_BLK_FD_BUILD(0, 0, 0)))) { fprintf(stderr,"VMFS: unable to open root directory\n"); return(-1); } if (!(fbb = vmfs_bitmap_open_at(root_dir,VMFS_FBB_FILENAME))) { fprintf(stderr,"Unable to open file-block bitmap (FBB).\n"); return(-1); } if (fbb->bmh.total_items > VMFS_BLK_FB_MAX_ITEM) { fprintf(stderr, "Unsupported number of items in file-block bitmap (FBB).\n"); return(-1); } fdc = vmfs_open_meta_file(root_dir, VMFS_FDC_FILENAME, VMFS_BLK_FD_MAX_ITEM, VMFS_BLK_FD_MAX_ENTRY, "file descriptor bitmap (FDC)"); if (!fdc) return(-1); pbc = vmfs_open_meta_file(root_dir, VMFS_PBC_FILENAME, VMFS_BLK_PB_MAX_ITEM, VMFS_BLK_PB_MAX_ENTRY, "pointer block bitmap (PBC)"); if (!pbc) return(-1); sbc = vmfs_open_meta_file(root_dir, VMFS_SBC_FILENAME, VMFS_BLK_SB_MAX_ITEM, VMFS_BLK_SB_MAX_ENTRY, "pointer block bitmap (PBC)"); if (!sbc) return(-1); return(0); } int KernelVMFileSystem::vmfs_read_fdc_base() { vmfs_inode inode = { { 0, }, }; uint32_t fdc_base; /* * Compute position of FDC base: it is located at the first * block after heartbeat information. * When blocksize = 8 Mb, there is free space between heartbeats * and FDC. */ fdc_base = m_max(1, (VMFS_HB_BASE + VMFS_HB_NUM * VMFS_HB_SIZE) / fs_info.block_size); inode.mdh.magic = VMFS_INODE_MAGIC; inode.size = fs_info.block_size; inode.type = VMFS_FILE_TYPE_META; inode.blk_size = fs_info.block_size; inode.blk_count = 1; inode.zla = VMFS_BLK_TYPE_FB; inode.blocks[0] = VMFS_BLK_FB_BUILD(fdc_base, 0); inode.ref_count = 1; fdc = vmfs_bitmap_open_from_inode(&inode); /* Read the meta files */ if (vmfs_open_all_meta_files() == -1) return(-1); return(0); } int KernelVMFileSystem::cmd_ls(vmfs_dir *base_dir, char * path) { vmfs_dir *d; const vmfs_dirent *entry; int long_format=0; if (!(d = vmfs_dir_open_at(base_dir, path))) { printf("Unable to open directory %s\n", path); return(-1); } while((entry = vmfs_dir_read(d))) { printf("%s\n",entry->name); } vmfs_dir_close(d); return(0); }
[ "z-hakuei@outlook.com" ]
z-hakuei@outlook.com
92cf866d8cb2fce878a022b03b29221614e92fe4
98f10c77b9932915eb9f37d9cf79a83094342444
/URI/1767.cpp
10aa2c0b57fb1436a65e825b3bff8d3cd85c254f
[]
no_license
lucianovr/competitive-programming
b5ba55a5055e486862c0c8b62e61c86e41b8f2b8
bd95492bb8a14563603a5a2d74e3c1676a4a61e6
refs/heads/master
2022-09-10T04:54:07.417831
2020-05-28T00:33:36
2020-05-28T00:33:36
267,455,557
0
0
null
null
null
null
UTF-8
C++
false
false
1,841
cpp
#include <algorithm> #include <iostream> #include <stdio.h> #include <string.h> #include <vector> using namespace std; #define pb push_back #define rep(i, a, b) for (int i(a); i < (b); i++) #define debgu(x) cout << #x << " = " << x; #define nl cout << "\n"; #define MAXP 50 + 5 #define MAXI 100 + 5 #define peso first #define valor second int pd[MAXP][MAXI], usado[MAXP][MAXI], n, PESO, CONT; vector<pair<int, int>> item; int solve(int s, int i) { if (i == n) return 0; if (pd[s][i] != -1) return pd[s][i]; int ret1, ret2; ret1 = ret2 = 0; if (s - item[i].peso >= 0) ret2 = solve(s - item[i].peso, i + 1) + item[i].valor; ret1 = solve(s, i + 1); if (ret2 > ret1) usado[s][i] = 1; return pd[s][i] = max(ret1, ret2); } void back(int s, int i) { if (i == n || s < 0) return; if (usado[s][i] == 1) { CONT++; PESO += item[i].peso; back(s - item[i].peso, i + 1); } else back(s, i + 1); } bool compare(pair<int, int> A, pair<int, int> B) { if (A.valor < B.valor) return true; if (A.valor > B.valor) return false; return A.peso > B.peso; } int main() { int casos; cin >> casos; while (casos--) { cin >> n; item.resize(n); PESO = CONT = 0; for (int i = 0; i < n; i++) cin >> item[i].valor >> item[i].peso; sort(item.begin(), item.end(), compare); memset(pd, -1, sizeof pd); memset(usado, 0, sizeof usado); int tot = solve(50, 0); back(50, 0); cout << tot << " brinquedos\n"; cout << "Peso: " << PESO << " kg\n"; cout << "sobra(m) " << n - CONT << " pacote(s)\n\n"; } return 0; }
[ "lucianovale@inatel.br" ]
lucianovale@inatel.br
43b6158e65646710b00fe9c2a3739bbd49f0157a
cfebe38545522d29a7b8b7346394c266bbbb87f7
/Pub-3/Pub-3/YardenSaredona.h
83669e88d41a563c619fe581bc270b82698b8694
[]
no_license
Yancale/CPP_Projects
c146058bb5d45b36b14965818ce10e65fbb007d1
7274278d41b304235ed6c58db3e23510ab8ea913
refs/heads/master
2021-01-18T03:22:20.213928
2017-03-22T16:07:00
2017-03-22T16:07:00
85,826,859
0
0
null
null
null
null
UTF-8
C++
false
false
229
h
#pragma once #include "WhiteWine.h" class YardenSaredona :public WhiteWine { public: virtual string getName(); virtual void prepare(); int getYear(); YardenSaredona(int year); ~YardenSaredona(); private: int m_year; };
[ "idantalor100@gmail.com" ]
idantalor100@gmail.com
5e6ef42c021edc130e9887689dff80cd7df6173c
64e4fabf9b43b6b02b14b9df7e1751732b30ad38
/src/chromium/gen/gen_combined/mojo/public/mojom/base/values.mojom-blink-forward.h
3805dc6eb0c5594e52ba73975e759601e949d80c
[ "BSD-3-Clause" ]
permissive
ivan-kits/skia-opengl-emscripten
8a5ee0eab0214c84df3cd7eef37c8ba54acb045e
79573e1ee794061bdcfd88cacdb75243eff5f6f0
refs/heads/master
2023-02-03T16:39:20.556706
2020-12-25T14:00:49
2020-12-25T14:00:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,059
h
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MOJO_PUBLIC_MOJOM_BASE_VALUES_MOJOM_BLINK_FORWARD_H_ #define MOJO_PUBLIC_MOJOM_BASE_VALUES_MOJOM_BLINK_FORWARD_H_ #include "mojo/public/cpp/bindings/struct_ptr.h" #include "mojo/public/cpp/bindings/lib/buffer.h" #include "mojo/public/cpp/bindings/lib/native_enum_serialization.h" #include "mojo/public/cpp/bindings/lib/native_struct_serialization.h" #include "base/component_export.h" namespace mojo_base { namespace mojom { } // namespace mojo_base } // namespace mojom namespace mojo_base { namespace mojom { namespace blink { class DictionaryValue; using DictionaryValuePtr = mojo::StructPtr<DictionaryValue>; class ListValue; using ListValuePtr = mojo::StructPtr<ListValue>; class Value; typedef mojo::StructPtr<Value> ValuePtr; } // namespace blink } // namespace mojom } // namespace mojo_base #endif // MOJO_PUBLIC_MOJOM_BASE_VALUES_MOJOM_BLINK_FORWARD_H_
[ "trofimov_d_a@magnit.ru" ]
trofimov_d_a@magnit.ru
b945a0e7b0c6a6dac3694603043893038b999296
bb302e87c3fbd88334cb7a8b97a97f08ded9c6df
/oopl-fnal/examples/c++/MethodOverriding2.c++
1b1c33aecbc68174b6edd84929ff8183025c1623
[]
no_license
zhwenyu/cppcourse_fnal
2b981824a410c69204442c8e2d4d8ec02297be83
1d8eb7b8b5886f9716f6bde7bb42eaa10845923e
refs/heads/main
2023-03-13T09:07:39.541962
2021-03-03T22:05:16
2021-03-03T22:05:16
344,272,394
0
0
null
null
null
null
UTF-8
C++
false
false
1,176
// --------------------- // MethodOverriding2.c++ // --------------------- #include <cassert> // assert #include <iostream> // cout, endl #include <string> // string, == struct A { virtual ~A() {} virtual std::string f (int) { return "A::f";} virtual std::string g (int) { // note: hidden overloaded virtual function 'A::g' declared return "A::g";} virtual std::string h (int) { // note: hidden overloaded virtual function 'A::h' declared return "A::h";}}; struct B : A { std::string f (int) { return "B::f";} std::string g (double) { // warning: 'B::g' hides overloaded virtual function return "B::g";} std::string h (int) const /* override */ { // error: non-virtual member function marked 'override' hides virtual member function return "B::h";}}; void test () { A* const p = new B(); assert(p->f(2) == "B::f"); assert(p->g(2) == "A::g"); assert(p->h(2) == "A::h"); delete p;} int main () { using namespace std; cout << "MethodOverriding2.c++" << endl; test(); cout << "Done." << endl; return 0;}
[ "wenyu_zhang@brown.edu" ]
wenyu_zhang@brown.edu
f8605b85589e6f19d96f0a1898dc8860a4da2543
1f11cdf6c6432c4d997b82c8cd8bc6b210e3a5f6
/ADARAIN/Anton-Solved/main.cpp
4cda6fc779281fca7aad871a18f1ed6fd267f37d
[]
no_license
BUW-Comp-Prog-Project/WS_19
6cb394bb838e5acc66f0ac40e22f591a23163b9a
c8eba3f5276ae479784756a94f6828ddb2dfcf0d
refs/heads/master
2020-09-04T11:40:30.235164
2020-04-23T19:41:43
2020-04-23T19:41:43
219,722,585
0
0
null
null
null
null
UTF-8
C++
false
false
830
cpp
// // Created by Mortiferum on 08.12.2019. // #include<bits/stdc++.h> #include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <set> #include <unordered_set> #include <map> #include <unordered_map> #include <stack> using namespace std; typedef unsigned short us; typedef unsigned long long int ulli; typedef unsigned long long ull; typedef long long int lli; typedef unsigned int ui; lli furrow[1000010]{0}; int main() { int n,m,w; scanf("%d %d %d", &n, &m, &w); while(n--){ int l,r; scanf("%d %d", &l,&r); //operation furrow[l] += 1; furrow[r+1] -= 1; } for(ui i = 1; i < w; ++i){ furrow[i] += furrow[i-1]; } while(m--){ int a; scanf("%d", &a); printf("%lld\n", furrow[a]); } return 0; }
[ "antonbenlammert@gmail.com" ]
antonbenlammert@gmail.com
55a9f0b48d9356925ddb07386aea2a3bdee4f8c2
2922fc19b62002972597f64a8eef5d471b90527f
/editor/dump/TestMD5Loader/OpenGLApp/MD5Model.h
8549783a1181515d41cf433709268033cec60a9a
[]
no_license
ruellm/demon_rpg
5b8dfa22784ffd0b88ed2ed474bcb94ce5774118
9c091a6d8b65eb14f9374beb9e87a3c0d5b029a3
refs/heads/master
2023-02-12T11:20:40.073004
2021-01-04T05:26:04
2021-01-04T05:26:04
326,578,287
0
0
null
null
null
null
UTF-8
C++
false
false
3,446
h
#pragma once #include "common.h" #include "Model3D.h" /////////////////////////////////////////////////////////////////////// // MD5 File structures typedef struct md5Joint { std::string name; int parentIdx; //Bone/joint matrices(?) relative to its parent bone glm::vec3 pos; glm::quat orientation; } MD5Joint; typedef struct md5Vertex { int vertIdx; glm::vec2 texCoords; int startWeight; int weightCount; } MD5Vertex; typedef struct md5Triangle { int triIdx; int vertIdx0; int vertIdx1; int vertIdx2; } MD5Triangle; typedef struct md5Weight { int weightIdx; int jointIdx; float bias; glm::vec3 weightPos; } MD5Weight; typedef struct md5Mesh { std::vector<std::string> textureList; int numVerts; int numTriangles; int numWeights; std::vector<md5Vertex> vertices; std::vector<md5Triangle> triangles; std::vector<md5Weight> weights; } MD5Mesh; //--------------------------------------------------------------------------------------- // MD5 Animation File Structures //--------------------------------------------------------------------------------------- typedef struct md5Hierarchy { std::string jointName; int parentIdx; int flags; int startIdx; }MD5Hierarchy; typedef struct md5Bounds { glm::vec3 boundMin; glm::vec3 boundMax; }MD5Bounds; typedef struct md5BaseFrame { glm::vec3 position; glm::quat orientation; }MD5BaseFrame; typedef struct md5Frame { int frameID; std::vector<float> frameData; }MD5Frame; struct md5FrameSkeleton { std::vector<md5Joint> joints; }; typedef struct md5Animation { int numFrames; int numJoints; int frameRate; int numAnimatedComponents; std::vector<md5Hierarchy> hierarchyList; std::vector<md5Bounds> boundsList; std::vector<md5BaseFrame> baseFrameList; std::vector<md5Frame> frameList; // The following section is related to rendering and NO CONNECTION to parsing std::vector<md5FrameSkeleton> frameSkeleton; // can be modified to use type definition instead float currAnimTime; // current animation time float perFrameTime; // time duration of each frame float totalAnimTime; // Total animation duration }MD5Animation; /////////////////////////////////////////////////////////////////////// class MD5Model : public Model3D { public: MD5Model(void); ~MD5Model(void); int AddAnimation(char* szPath); //----------------------------------------------------------------- // Functions inherited from Model3D //----------------------------------------------------------------- virtual int LoadFromFile(char* szFname, char* szDirectory); virtual void Update(float elapsed /*, ID3D11DeviceContext* context*/); virtual int BakeMesh(/*ID3D11Device* device*/); virtual void Draw(/*ID3D11DeviceContext* context*/); private: std::vector<md5Mesh> m_meshList; std::vector<md5Joint> m_jointList; std::vector<md5Animation> m_animationList; std::string GetNextToken( std::fstream* file ); std::string RemoveQuote( std::string source ); int GetIntToken( std::fstream* file ); float GetFloatToken( std::fstream* file ); int ParseJoints( std::fstream* file ); int ParseMesh( std::fstream* file ); //----------------------------------------------------------------- // Methods related to Rendering //----------------------------------------------------------------- void BuildFrameSkeleton(); void BuildBuffers(/*ID3D11Device* device*/); int UpdateVertices(const md5FrameSkeleton& skeleton ); void UpdateNormals( ); };
[ "ruellm@yahoo.com" ]
ruellm@yahoo.com
5f6e7ef9e6df297a40cc28c5eef2d84af26621c5
0e6e81a3788fd9847084991c3177481470546051
/AnswerByCpp/0286_Walls and Gates.cpp
9b102dcd756409611471fb26cec53fb3e85cf7fe
[]
no_license
Azhao1993/Leetcode
6f84c62620f1bb60f82d4383764b777a4caa2715
1c1f2438e80d7958736dbc28b7ede562ec1356f7
refs/heads/master
2020-03-25T19:34:30.946119
2020-03-05T14:28:17
2020-03-05T14:28:17
144,089,629
4
2
null
2019-11-18T00:30:31
2018-08-09T02:10:26
C++
UTF-8
C++
false
false
2,441
cpp
#include<iostream> #include<vector> #include<queue> using namespace std; /* 286. 墙与门 你被给定一个 m × n 的二维网格,网格中有以下三种可能的初始化值: -1 表示墙或是障碍物 0 表示一扇门 INF 无限表示一个空的房间。然后,我们用 231 - 1 = 2147483647 代表 INF。你可以认为通往门的距离总是小于 2147483647 的。 你要给每个空房间位上填上该房间到 最近 门的距离,如果无法到达门,则填 INF 即可。 示例: 给定二维网格: INF -1 0 INF INF INF INF -1 INF -1 INF -1 0 -1 INF INF 运行完你的函数后,该网格应该变成: 3 -1 0 1 2 2 1 -1 1 -1 2 -1 0 -1 3 4 */ const int INT_MAX = 109; static int x = [](){std::ios::sync_with_stdio(false); cin.tie(0); return 0;}(); class Solution { public: void wallsAndGates(vector<vector<int>>& rooms) { if (rooms.size() == 0) return ; int m = rooms.size(), n = rooms[0].size(), step = 0; vector<int> dx{0, 0, 1, -1}; vector<int> dy{1, -1, 0, 0}; queue<int> que; vector<vector<bool>> used(m, vector<bool>(n, false)); for (int i=0; i<m; i++) for (int j=0; j<n; j++) { if (rooms[i][j] == -1) used[i][j] = true; if (rooms[i][j] == 0) used[i][j] = true, que.push(i * n + j); } while (!que.empty()) { int len = que.size(); step++; for (int i=0; i<len; i++) { int cur = que.front(); que.pop(); int xx = cur / n, yy = cur % n; for (int j=0; j<4; j++) { int x = xx + dx[j], y = yy + dy[j]; if (x < 0 || y < 0 || x >= m || y >= n || used[x][y]) continue; rooms[x][y] = step; used[x][y] = true; que.push(x * n + y); } } } } }; int main(){ vector<vector<int>> arr{{INT_MAX, -1, 0, INT_MAX}, {INT_MAX, INT_MAX, INT_MAX, -1}, {INT_MAX, -1, INT_MAX, -1}, {0, -1, INT_MAX, INT_MAX}}; for (auto &it : arr) { for(auto &i : it) cout << i << "\t"; cout << endl; } Solution().wallsAndGates(arr); for (auto &it : arr) { for(auto &i : it) cout << i << "\t"; cout << endl; } return 0; }
[ "1358227862@qq.com" ]
1358227862@qq.com
add47144dd47dee62a8cf63ef1200b91d5643c2d
09368909e071abef47f2ec5f5887b65b5a73edd0
/samples/STL/make-loggable.cpp
51e7d3649b10cf3c76d05746ed93b2171fa819ad
[ "MIT" ]
permissive
FlyingZXC/easyloggingpp
f1d901211b4239edcc43a8544e8371753a95f9a4
6302e3614ec024bb373941ad8070837beef76ccf
refs/heads/master
2020-12-25T05:25:02.175329
2013-08-30T06:24:53
2013-08-30T06:24:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
988
cpp
// // This file is part of Easylogging++ samples // MAKE_LOGGABLE sample // // Feature since: v9.12 // Revision 1.0 // @author mkhan3189 // #include "easylogging++.h" _INITIALIZE_EASYLOGGINGPP class Integer { public: Integer(int i) : m_underlyingInt(i) {} Integer& operator=(const Integer& integer) { m_underlyingInt = integer.m_underlyingInt; return *this; } virtual ~Integer(void) { m_underlyingInt = -1; } int getInt(void) const { return m_underlyingInt; } inline operator int() const { return m_underlyingInt; } private: int m_underlyingInt; }; // Lets say Integer class is in some third party library // We use MAKE_LOGGABLE(class, instance, outputStream) to make it loggable inline MAKE_LOGGABLE(Integer, integer, os) { os << integer.getInt(); return os; } int main(void) { Integer count = 5; LOG(INFO) << "Integer count = " << count; int reverse = count; LOG(INFO) << "int reverse = " << reverse; return 0; }
[ "mkhan3189@gmail.com" ]
mkhan3189@gmail.com
c20b8c9e08613410f9eaab933358555ddbac2682
19920ea21e520da7a413d423a851e7cc43f270db
/WMS-master/WMS/build-TREKdisplay-Desktop_Qt_5_12_1_MSVC2017_32bit-Debug/ui_storage_modify2.h
ee97d1022662f625a74a4b2a64156d454c7de575
[]
no_license
519984307/wms-BASE
ab01196f15c0585ec31c6abc7cd030e7880c807d
91811aa427478b237092d68e7a78deb521497cb0
refs/heads/master
2023-03-19T21:56:36.168630
2020-10-30T07:16:47
2020-10-30T07:16:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,143
h
/******************************************************************************** ** Form generated from reading UI file 'storage_modify2.ui' ** ** Created by: Qt User Interface Compiler version 5.12.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_STORAGE_MODIFY2_H #define UI_STORAGE_MODIFY2_H #include <QtCore/QVariant> #include <QtGui/QIcon> #include <QtWidgets/QApplication> #include <QtWidgets/QComboBox> #include <QtWidgets/QGridLayout> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QPushButton> #include <QtWidgets/QSpacerItem> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_storage_modify2 { public: QGridLayout *gridLayout; QVBoxLayout *verticalLayout_3; QHBoxLayout *horizontalLayout_11; QLabel *label_1; QLineEdit *lineEdit1; QSpacerItem *horizontalSpacer_9; QLabel *label_2; QLineEdit *lineEdit2; QSpacerItem *verticalSpacer_4; QHBoxLayout *horizontalLayout_12; QLabel *label_3; QLineEdit *lineEdit3; QSpacerItem *horizontalSpacer_10; QLabel *label_4; QLineEdit *lineEdit4; QSpacerItem *verticalSpacer_8; QHBoxLayout *horizontalLayout_13; QLabel *label_5; QLineEdit *lineEdit5; QSpacerItem *horizontalSpacer_15; QLabel *label_6; QComboBox *comboBox; QSpacerItem *verticalSpacer_9; QHBoxLayout *horizontalLayout_14; QLabel *label_7; QComboBox *comboBox_2; QSpacerItem *horizontalSpacer_16; QLabel *label_8; QLineEdit *lineEdit8; QSpacerItem *horizontalSpacer_18; QSpacerItem *verticalSpacer_12; QSpacerItem *horizontalSpacer_17; QSpacerItem *verticalSpacer_11; QSpacerItem *verticalSpacer_10; QSpacerItem *verticalSpacer_13; QHBoxLayout *horizontalLayout_15; QPushButton *pushButton; QPushButton *pushButton_2; QPushButton *pushButton_3; QLabel *label; void setupUi(QWidget *storage_modify2) { if (storage_modify2->objectName().isEmpty()) storage_modify2->setObjectName(QString::fromUtf8("storage_modify2")); storage_modify2->resize(550, 350); storage_modify2->setMinimumSize(QSize(550, 0)); storage_modify2->setMaximumSize(QSize(550, 350)); QIcon icon; icon.addFile(QString::fromUtf8(":/qt \345\233\276\346\240\207/\344\277\256\346\224\271.png"), QSize(), QIcon::Normal, QIcon::On); storage_modify2->setWindowIcon(icon); storage_modify2->setStyleSheet(QString::fromUtf8("font: 75 12pt \"\346\245\267\344\275\223\";\n" "background-color: rgb(144, 144, 144);\n" "color:rgb(0, 0, 0)")); gridLayout = new QGridLayout(storage_modify2); gridLayout->setObjectName(QString::fromUtf8("gridLayout")); verticalLayout_3 = new QVBoxLayout(); verticalLayout_3->setObjectName(QString::fromUtf8("verticalLayout_3")); horizontalLayout_11 = new QHBoxLayout(); horizontalLayout_11->setObjectName(QString::fromUtf8("horizontalLayout_11")); label_1 = new QLabel(storage_modify2); label_1->setObjectName(QString::fromUtf8("label_1")); horizontalLayout_11->addWidget(label_1); lineEdit1 = new QLineEdit(storage_modify2); lineEdit1->setObjectName(QString::fromUtf8("lineEdit1")); lineEdit1->setEnabled(true); lineEdit1->setReadOnly(true); lineEdit1->setClearButtonEnabled(false); horizontalLayout_11->addWidget(lineEdit1); horizontalSpacer_9 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_11->addItem(horizontalSpacer_9); label_2 = new QLabel(storage_modify2); label_2->setObjectName(QString::fromUtf8("label_2")); horizontalLayout_11->addWidget(label_2); lineEdit2 = new QLineEdit(storage_modify2); lineEdit2->setObjectName(QString::fromUtf8("lineEdit2")); horizontalLayout_11->addWidget(lineEdit2); verticalLayout_3->addLayout(horizontalLayout_11); verticalSpacer_4 = new QSpacerItem(20, 18, QSizePolicy::Minimum, QSizePolicy::Expanding); verticalLayout_3->addItem(verticalSpacer_4); horizontalLayout_12 = new QHBoxLayout(); horizontalLayout_12->setObjectName(QString::fromUtf8("horizontalLayout_12")); label_3 = new QLabel(storage_modify2); label_3->setObjectName(QString::fromUtf8("label_3")); horizontalLayout_12->addWidget(label_3); lineEdit3 = new QLineEdit(storage_modify2); lineEdit3->setObjectName(QString::fromUtf8("lineEdit3")); horizontalLayout_12->addWidget(lineEdit3); horizontalSpacer_10 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_12->addItem(horizontalSpacer_10); label_4 = new QLabel(storage_modify2); label_4->setObjectName(QString::fromUtf8("label_4")); horizontalLayout_12->addWidget(label_4); lineEdit4 = new QLineEdit(storage_modify2); lineEdit4->setObjectName(QString::fromUtf8("lineEdit4")); horizontalLayout_12->addWidget(lineEdit4); verticalLayout_3->addLayout(horizontalLayout_12); verticalSpacer_8 = new QSpacerItem(20, 18, QSizePolicy::Minimum, QSizePolicy::Expanding); verticalLayout_3->addItem(verticalSpacer_8); horizontalLayout_13 = new QHBoxLayout(); horizontalLayout_13->setObjectName(QString::fromUtf8("horizontalLayout_13")); label_5 = new QLabel(storage_modify2); label_5->setObjectName(QString::fromUtf8("label_5")); horizontalLayout_13->addWidget(label_5); lineEdit5 = new QLineEdit(storage_modify2); lineEdit5->setObjectName(QString::fromUtf8("lineEdit5")); horizontalLayout_13->addWidget(lineEdit5); horizontalSpacer_15 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_13->addItem(horizontalSpacer_15); label_6 = new QLabel(storage_modify2); label_6->setObjectName(QString::fromUtf8("label_6")); horizontalLayout_13->addWidget(label_6); comboBox = new QComboBox(storage_modify2); comboBox->addItem(QString()); comboBox->setObjectName(QString::fromUtf8("comboBox")); comboBox->setMinimumSize(QSize(135, 0)); horizontalLayout_13->addWidget(comboBox); verticalLayout_3->addLayout(horizontalLayout_13); verticalSpacer_9 = new QSpacerItem(20, 18, QSizePolicy::Minimum, QSizePolicy::Expanding); verticalLayout_3->addItem(verticalSpacer_9); horizontalLayout_14 = new QHBoxLayout(); horizontalLayout_14->setObjectName(QString::fromUtf8("horizontalLayout_14")); label_7 = new QLabel(storage_modify2); label_7->setObjectName(QString::fromUtf8("label_7")); horizontalLayout_14->addWidget(label_7); comboBox_2 = new QComboBox(storage_modify2); comboBox_2->addItem(QString()); comboBox_2->setObjectName(QString::fromUtf8("comboBox_2")); comboBox_2->setMinimumSize(QSize(135, 0)); horizontalLayout_14->addWidget(comboBox_2); horizontalSpacer_16 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_14->addItem(horizontalSpacer_16); label_8 = new QLabel(storage_modify2); label_8->setObjectName(QString::fromUtf8("label_8")); horizontalLayout_14->addWidget(label_8); lineEdit8 = new QLineEdit(storage_modify2); lineEdit8->setObjectName(QString::fromUtf8("lineEdit8")); lineEdit8->setEnabled(true); QFont font; font.setFamily(QString::fromUtf8("\346\245\267\344\275\223")); font.setPointSize(12); font.setBold(false); font.setItalic(false); font.setWeight(9); lineEdit8->setFont(font); lineEdit8->setLayoutDirection(Qt::RightToLeft); lineEdit8->setReadOnly(true); horizontalLayout_14->addWidget(lineEdit8); verticalLayout_3->addLayout(horizontalLayout_14); gridLayout->addLayout(verticalLayout_3, 4, 1, 1, 3); horizontalSpacer_18 = new QSpacerItem(50, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); gridLayout->addItem(horizontalSpacer_18, 4, 4, 1, 1); verticalSpacer_12 = new QSpacerItem(20, 30, QSizePolicy::Minimum, QSizePolicy::Expanding); gridLayout->addItem(verticalSpacer_12, 5, 2, 1, 1); horizontalSpacer_17 = new QSpacerItem(50, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); gridLayout->addItem(horizontalSpacer_17, 4, 0, 1, 1); verticalSpacer_11 = new QSpacerItem(20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding); gridLayout->addItem(verticalSpacer_11, 0, 2, 1, 1); verticalSpacer_10 = new QSpacerItem(20, 31, QSizePolicy::Minimum, QSizePolicy::Expanding); gridLayout->addItem(verticalSpacer_10, 3, 2, 1, 1); verticalSpacer_13 = new QSpacerItem(20, 31, QSizePolicy::Minimum, QSizePolicy::Expanding); gridLayout->addItem(verticalSpacer_13, 7, 2, 1, 1); horizontalLayout_15 = new QHBoxLayout(); horizontalLayout_15->setSpacing(10); horizontalLayout_15->setObjectName(QString::fromUtf8("horizontalLayout_15")); horizontalLayout_15->setSizeConstraint(QLayout::SetDefaultConstraint); pushButton = new QPushButton(storage_modify2); pushButton->setObjectName(QString::fromUtf8("pushButton")); pushButton->setMinimumSize(QSize(50, 25)); pushButton->setMaximumSize(QSize(50, 25)); pushButton->setStyleSheet(QString::fromUtf8("QPushButton{\n" "font: 75 11pt \"\345\276\256\350\275\257\351\233\205\351\273\221\";\n" "color:rgb(255, 255, 255);\n" "background-color: rgb(83, 83, 83);\n" "border-radius: 8px;\n" "border: 3px groove rgb(98, 98, 98);\n" "border-style: outset;\n" "}\n" "QPushButton:pressed{\n" "border-style: inset;\n" "}\n" "QPushButton:hover{\n" "background-color:rgb(0, 0, 0);\n" "}\n" "\n" "")); horizontalLayout_15->addWidget(pushButton); pushButton_2 = new QPushButton(storage_modify2); pushButton_2->setObjectName(QString::fromUtf8("pushButton_2")); pushButton_2->setMinimumSize(QSize(50, 25)); pushButton_2->setMaximumSize(QSize(50, 25)); pushButton_2->setStyleSheet(QString::fromUtf8("QPushButton{\n" "font: 75 11pt \"\345\276\256\350\275\257\351\233\205\351\273\221\";\n" "color:rgb(255, 255, 255);\n" "background-color: rgb(83, 83, 83);\n" "border-radius: 8px;\n" "border: 3px groove rgb(98, 98, 98);\n" "border-style: outset;\n" "}\n" "QPushButton:pressed{\n" "border-style: inset;\n" "}\n" "QPushButton:hover{\n" "background-color:rgb(0, 0, 0);\n" "}\n" "\n" "")); horizontalLayout_15->addWidget(pushButton_2); pushButton_3 = new QPushButton(storage_modify2); pushButton_3->setObjectName(QString::fromUtf8("pushButton_3")); pushButton_3->setMinimumSize(QSize(50, 25)); pushButton_3->setMaximumSize(QSize(50, 25)); pushButton_3->setStyleSheet(QString::fromUtf8("QPushButton{\n" "font: 75 11pt \"\345\276\256\350\275\257\351\233\205\351\273\221\";\n" "color:rgb(255, 255, 255);\n" "background-color: rgb(83, 83, 83);\n" "border-radius: 8px;\n" "border: 3px groove rgb(98, 98, 98);\n" "border-style: outset;\n" "}\n" "QPushButton:pressed{\n" "border-style: inset;\n" "}\n" "QPushButton:hover{\n" "background-color:rgb(0, 0, 0);\n" "}\n" "\n" "")); horizontalLayout_15->addWidget(pushButton_3); gridLayout->addLayout(horizontalLayout_15, 6, 0, 1, 5); label = new QLabel(storage_modify2); label->setObjectName(QString::fromUtf8("label")); label->setStyleSheet(QString::fromUtf8("font: 75 14pt \"\346\245\267\344\275\223\";")); gridLayout->addWidget(label, 1, 2, 1, 1); label->raise(); retranslateUi(storage_modify2); QMetaObject::connectSlotsByName(storage_modify2); } // setupUi void retranslateUi(QWidget *storage_modify2) { storage_modify2->setWindowTitle(QApplication::translate("storage_modify2", "Form", nullptr)); label_1->setText(QApplication::translate("storage_modify2", "\350\256\242 \345\215\225 \345\217\267\357\274\232", nullptr)); label_2->setText(QApplication::translate("storage_modify2", "\344\272\247\345\223\201\345\220\215\347\247\260\357\274\232", nullptr)); label_3->setText(QApplication::translate("storage_modify2", "\344\272\247\345\223\201\347\274\226\345\217\267\357\274\232", nullptr)); label_4->setText(QApplication::translate("storage_modify2", "\346\240\207\347\255\276\347\274\226\345\217\267\357\274\232", nullptr)); label_5->setText(QApplication::translate("storage_modify2", "\346\225\260 \351\207\217\357\274\232", nullptr)); label_6->setText(QApplication::translate("storage_modify2", "\344\273\223 \345\272\223\357\274\232", nullptr)); comboBox->setItemText(0, QString()); label_7->setText(QApplication::translate("storage_modify2", "\347\256\241 \347\220\206 \345\221\230\357\274\232", nullptr)); comboBox_2->setItemText(0, QString()); label_8->setText(QApplication::translate("storage_modify2", "\345\205\245\345\272\223\346\227\266\351\227\264\357\274\232", nullptr)); pushButton->setText(QApplication::translate("storage_modify2", "\347\241\256\350\256\244", nullptr)); pushButton_2->setText(QApplication::translate("storage_modify2", "\351\207\215\347\275\256", nullptr)); pushButton_3->setText(QApplication::translate("storage_modify2", "\345\217\226\346\266\210", nullptr)); label->setText(QApplication::translate("storage_modify2", " \350\256\242\345\215\225\344\277\256\346\224\271", nullptr)); } // retranslateUi }; namespace Ui { class storage_modify2: public Ui_storage_modify2 {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_STORAGE_MODIFY2_H
[ "1335870469@qq.com" ]
1335870469@qq.com
6597a9b3f223f2591921482d6e805196d89753b6
fc6255f80200fb4287055cb363b9394affa24a54
/leetcode/merge_k_sorted_lists.cpp
cadf72bb712f2cb26c16b6b792fe958a957839db
[]
no_license
wjqmichael/workspace
347d8a699f9ca2fef3a321d292af2c8c9c5c1a1d
d946e9343c4ea92f2e4735c1d1c7fdefba840396
refs/heads/master
2021-01-10T19:13:54.597031
2014-03-12T22:01:43
2014-03-12T22:01:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,061
cpp
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: class Comparator { public: bool operator()(ListNode* left, ListNode* right) const { return (left->val > right->val); } }; ListNode * mergeKLists(vector<ListNode *> &lists) { typedef vector<ListNode *>::iterator it_t; it_t p = lists.begin(); while (p != lists.end()) { if (!*p) p = lists.erase(p); else ++p; } Comparator comp = Comparator(); ListNode *head = NULL, *tail = NULL; make_heap(lists.begin(), lists.end(), comp); while (!lists.empty()) { if (!head) head = tail = lists[0]; else tail = tail->next = lists[0]; pop_heap(lists.begin(), lists.end(), comp); size_t sz = lists.size(); if (lists[sz - 1]->next) { lists[sz - 1] = lists[sz - 1]->next; push_heap(lists.begin(), lists.end(), comp); } else lists.pop_back(); } return head; } };
[ "wjqmichael@gmail.com" ]
wjqmichael@gmail.com
1b76987156fe1dafbec843ad009d27c34abcb035
59138b1b34e2a9356ad7154a9705007349209e9a
/platform/JS/V8/v8/src/regexp/regexp-ast.cc
85babb1f74e76f8c2b015738d57bc4a895ff4b6c
[ "BSD-3-Clause", "bzip2-1.0.6", "SunPro", "Apache-2.0" ]
permissive
gboyraz/macchina.io
6b879fca2329e7060122adfc691b4870d4dc06ac
de79c4d2eace01e24d685ac7f7c2e8aadf6b2668
refs/heads/master
2020-06-29T13:18:05.975243
2019-08-04T22:43:08
2019-08-04T22:43:08
200,547,738
2
0
Apache-2.0
2019-08-04T22:29:19
2019-08-04T22:29:19
null
UTF-8
C++
false
false
8,900
cc
// Copyright 2016 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/ostreams.h" #include "src/regexp/regexp-ast.h" namespace v8 { namespace internal { #define MAKE_ACCEPT(Name) \ void* RegExp##Name::Accept(RegExpVisitor* visitor, void* data) { \ return visitor->Visit##Name(this, data); \ } FOR_EACH_REG_EXP_TREE_TYPE(MAKE_ACCEPT) #undef MAKE_ACCEPT #define MAKE_TYPE_CASE(Name) \ RegExp##Name* RegExpTree::As##Name() { return NULL; } \ bool RegExpTree::Is##Name() { return false; } FOR_EACH_REG_EXP_TREE_TYPE(MAKE_TYPE_CASE) #undef MAKE_TYPE_CASE #define MAKE_TYPE_CASE(Name) \ RegExp##Name* RegExp##Name::As##Name() { return this; } \ bool RegExp##Name::Is##Name() { return true; } FOR_EACH_REG_EXP_TREE_TYPE(MAKE_TYPE_CASE) #undef MAKE_TYPE_CASE static Interval ListCaptureRegisters(ZoneList<RegExpTree*>* children) { Interval result = Interval::Empty(); for (int i = 0; i < children->length(); i++) result = result.Union(children->at(i)->CaptureRegisters()); return result; } Interval RegExpAlternative::CaptureRegisters() { return ListCaptureRegisters(nodes()); } Interval RegExpDisjunction::CaptureRegisters() { return ListCaptureRegisters(alternatives()); } Interval RegExpLookaround::CaptureRegisters() { return body()->CaptureRegisters(); } Interval RegExpCapture::CaptureRegisters() { Interval self(StartRegister(index()), EndRegister(index())); return self.Union(body()->CaptureRegisters()); } Interval RegExpQuantifier::CaptureRegisters() { return body()->CaptureRegisters(); } bool RegExpAssertion::IsAnchoredAtStart() { return assertion_type() == RegExpAssertion::START_OF_INPUT; } bool RegExpAssertion::IsAnchoredAtEnd() { return assertion_type() == RegExpAssertion::END_OF_INPUT; } bool RegExpAlternative::IsAnchoredAtStart() { ZoneList<RegExpTree*>* nodes = this->nodes(); for (int i = 0; i < nodes->length(); i++) { RegExpTree* node = nodes->at(i); if (node->IsAnchoredAtStart()) { return true; } if (node->max_match() > 0) { return false; } } return false; } bool RegExpAlternative::IsAnchoredAtEnd() { ZoneList<RegExpTree*>* nodes = this->nodes(); for (int i = nodes->length() - 1; i >= 0; i--) { RegExpTree* node = nodes->at(i); if (node->IsAnchoredAtEnd()) { return true; } if (node->max_match() > 0) { return false; } } return false; } bool RegExpDisjunction::IsAnchoredAtStart() { ZoneList<RegExpTree*>* alternatives = this->alternatives(); for (int i = 0; i < alternatives->length(); i++) { if (!alternatives->at(i)->IsAnchoredAtStart()) return false; } return true; } bool RegExpDisjunction::IsAnchoredAtEnd() { ZoneList<RegExpTree*>* alternatives = this->alternatives(); for (int i = 0; i < alternatives->length(); i++) { if (!alternatives->at(i)->IsAnchoredAtEnd()) return false; } return true; } bool RegExpLookaround::IsAnchoredAtStart() { return is_positive() && type() == LOOKAHEAD && body()->IsAnchoredAtStart(); } bool RegExpCapture::IsAnchoredAtStart() { return body()->IsAnchoredAtStart(); } bool RegExpCapture::IsAnchoredAtEnd() { return body()->IsAnchoredAtEnd(); } // Convert regular expression trees to a simple sexp representation. // This representation should be different from the input grammar // in as many cases as possible, to make it more difficult for incorrect // parses to look as correct ones which is likely if the input and // output formats are alike. class RegExpUnparser final : public RegExpVisitor { public: RegExpUnparser(std::ostream& os, Zone* zone) : os_(os), zone_(zone) {} void VisitCharacterRange(CharacterRange that); #define MAKE_CASE(Name) void* Visit##Name(RegExp##Name*, void* data) override; FOR_EACH_REG_EXP_TREE_TYPE(MAKE_CASE) #undef MAKE_CASE private: std::ostream& os_; Zone* zone_; }; void* RegExpUnparser::VisitDisjunction(RegExpDisjunction* that, void* data) { os_ << "(|"; for (int i = 0; i < that->alternatives()->length(); i++) { os_ << " "; that->alternatives()->at(i)->Accept(this, data); } os_ << ")"; return NULL; } void* RegExpUnparser::VisitAlternative(RegExpAlternative* that, void* data) { os_ << "(:"; for (int i = 0; i < that->nodes()->length(); i++) { os_ << " "; that->nodes()->at(i)->Accept(this, data); } os_ << ")"; return NULL; } void RegExpUnparser::VisitCharacterRange(CharacterRange that) { os_ << AsUC32(that.from()); if (!that.IsSingleton()) { os_ << "-" << AsUC32(that.to()); } } void* RegExpUnparser::VisitCharacterClass(RegExpCharacterClass* that, void* data) { if (that->is_negated()) os_ << "^"; os_ << "["; for (int i = 0; i < that->ranges(zone_)->length(); i++) { if (i > 0) os_ << " "; VisitCharacterRange(that->ranges(zone_)->at(i)); } os_ << "]"; return NULL; } void* RegExpUnparser::VisitAssertion(RegExpAssertion* that, void* data) { switch (that->assertion_type()) { case RegExpAssertion::START_OF_INPUT: os_ << "@^i"; break; case RegExpAssertion::END_OF_INPUT: os_ << "@$i"; break; case RegExpAssertion::START_OF_LINE: os_ << "@^l"; break; case RegExpAssertion::END_OF_LINE: os_ << "@$l"; break; case RegExpAssertion::BOUNDARY: os_ << "@b"; break; case RegExpAssertion::NON_BOUNDARY: os_ << "@B"; break; } return NULL; } void* RegExpUnparser::VisitAtom(RegExpAtom* that, void* data) { os_ << "'"; Vector<const uc16> chardata = that->data(); for (int i = 0; i < chardata.length(); i++) { os_ << AsUC16(chardata[i]); } os_ << "'"; return NULL; } void* RegExpUnparser::VisitText(RegExpText* that, void* data) { if (that->elements()->length() == 1) { that->elements()->at(0).tree()->Accept(this, data); } else { os_ << "(!"; for (int i = 0; i < that->elements()->length(); i++) { os_ << " "; that->elements()->at(i).tree()->Accept(this, data); } os_ << ")"; } return NULL; } void* RegExpUnparser::VisitQuantifier(RegExpQuantifier* that, void* data) { os_ << "(# " << that->min() << " "; if (that->max() == RegExpTree::kInfinity) { os_ << "- "; } else { os_ << that->max() << " "; } os_ << (that->is_greedy() ? "g " : that->is_possessive() ? "p " : "n "); that->body()->Accept(this, data); os_ << ")"; return NULL; } void* RegExpUnparser::VisitCapture(RegExpCapture* that, void* data) { os_ << "(^ "; that->body()->Accept(this, data); os_ << ")"; return NULL; } void* RegExpUnparser::VisitGroup(RegExpGroup* that, void* data) { os_ << "(?: "; that->body()->Accept(this, data); os_ << ")"; return NULL; } void* RegExpUnparser::VisitLookaround(RegExpLookaround* that, void* data) { os_ << "("; os_ << (that->type() == RegExpLookaround::LOOKAHEAD ? "->" : "<-"); os_ << (that->is_positive() ? " + " : " - "); that->body()->Accept(this, data); os_ << ")"; return NULL; } void* RegExpUnparser::VisitBackReference(RegExpBackReference* that, void* data) { os_ << "(<- " << that->index() << ")"; return NULL; } void* RegExpUnparser::VisitEmpty(RegExpEmpty* that, void* data) { os_ << '%'; return NULL; } std::ostream& RegExpTree::Print(std::ostream& os, Zone* zone) { // NOLINT RegExpUnparser unparser(os, zone); Accept(&unparser, NULL); return os; } RegExpDisjunction::RegExpDisjunction(ZoneList<RegExpTree*>* alternatives) : alternatives_(alternatives) { DCHECK(alternatives->length() > 1); RegExpTree* first_alternative = alternatives->at(0); min_match_ = first_alternative->min_match(); max_match_ = first_alternative->max_match(); for (int i = 1; i < alternatives->length(); i++) { RegExpTree* alternative = alternatives->at(i); min_match_ = Min(min_match_, alternative->min_match()); max_match_ = Max(max_match_, alternative->max_match()); } } static int IncreaseBy(int previous, int increase) { if (RegExpTree::kInfinity - previous < increase) { return RegExpTree::kInfinity; } else { return previous + increase; } } RegExpAlternative::RegExpAlternative(ZoneList<RegExpTree*>* nodes) : nodes_(nodes) { DCHECK(nodes->length() > 1); min_match_ = 0; max_match_ = 0; for (int i = 0; i < nodes->length(); i++) { RegExpTree* node = nodes->at(i); int node_min_match = node->min_match(); min_match_ = IncreaseBy(min_match_, node_min_match); int node_max_match = node->max_match(); max_match_ = IncreaseBy(max_match_, node_max_match); } } } // namespace internal } // namespace v8
[ "guenter.obiltschnig@appinf.com" ]
guenter.obiltschnig@appinf.com
1ef2538bd22d6e9b8f9f6821efe4753dbfcefe5a
9dd074bda894f0f48ba1ba46f16e94847d987e50
/15_3Sum/main.cpp
e6609a2fcb1ff0c545bafcc1a21f5bd0f1735625
[]
no_license
maxyrepo/leetcode
f66af317467ff665a83328fc7d59d1da13e25ae5
259499434dd23212d8a494d41ace3c4b4906061d
refs/heads/master
2021-01-22T21:53:10.355319
2017-04-04T13:41:56
2017-04-04T13:41:56
85,484,634
0
0
null
null
null
null
UTF-8
C++
false
false
27,413
cpp
#include <vector> #include <iostream> #include <algorithm> using namespace std; void output(const vector<vector<int> > & vec) { for(size_t i = 0; i < vec.size(); ++i) { for (size_t j = 0; j < vec[i].size(); ++j) { cout << vec[i][j] << ", "; } cout << endl; } } class Solution { public: vector<vector<int> > threeSum(vector<int> &num) { vector<vector<int> > res; std::sort(num.begin(), num.end()); for (int i = 0; i < num.size(); i++) { int target = -num[i]; // if (target < 0) { // break; // } int front = i + 1; int back = num.size() - 1; while (front < back) { int sum = num[front] + num[back]; // Finding answer which start from number num[i] if (sum < target) front++; else if (sum > target) back--; else { vector<int> triplet(3, 0); triplet[0] = num[i]; triplet[1] = num[front]; triplet[2] = num[back]; res.push_back(triplet); // Processing duplicates of Number 2 // Rolling the front pointer to the next different number forwards while (front < back && num[front] == triplet[1]) front++; // Processing duplicates of Number 3 // Rolling the back pointer to the next different number backwards while (front < back && num[back] == triplet[2]) back--; } } // Processing duplicates of Number 1 while (i + 1 < num.size() && num[i + 1] == num[i]) i++; } return res; } }; int main() { Solution s; // vector<int> v1 = {-1, 0, 1, 2, -1, -4}; // output(s.threeSum(v1)); // // vector<int> v2 = {1,2,-2,-1}; // output(s.threeSum(v2)); vector<int> v3{82597,-9243,62390,83030,-97960,-26521,-61011,83390,-38677,12333,75987,46091,83794,19355,-71037,-6242,-28801,324,1202,-90885,-2989,-95597,-34333,35528,5680,89093,-90606,50360,-29393,-27012,53313,65213,99818,-82405,-41661,-3333,-51952,72135,-1523,26377,74685,96992,92263,15929,5467,-99555,-43348,-41689,-60383,-3990,32165,65265,-72973,-58372,12741,-48568,-46596,72419,-1859,34153,62937,81310,-61823,-96770,-54944,8845,-91184,24208,-29078,31495,65258,14198,85395,70506,-40908,56740,-12228,-40072,32429,93001,68445,-73927,25731,-91859,-24150,10093,-60271,-81683,-18126,51055,48189,-6468,25057,81194,-58628,74042,66158,-14452,-49851,-43667,11092,39189,-17025,-79173,13606,83172,92647,-59741,19343,-26644,-57607,82908,-20655,1637,80060,98994,39331,-31274,-61523,91225,-72953,13211,-75116,-98421,-41571,-69074,99587,39345,42151,-2460,98236,15690,-52507,-95803,-48935,-46492,-45606,-79254,-99851,52533,73486,39948,-7240,71815,-585,-96252,90990,-93815,93340,-71848,58733,-14859,-83082,-75794,-82082,-24871,-15206,91207,-56469,-93618,67131,-8682,75719,87429,-98757,-7535,-24890,-94160,85003,33928,75538,97456,-66424,-60074,-8527,-28697,-22308,2246,-70134,-82319,-10184,87081,-34949,-28645,-47352,-83966,-60418,-15293,-53067,-25921,55172,75064,95859,48049,34311,-86931,-38586,33686,-36714,96922,76713,-22165,-80585,-34503,-44516,39217,-28457,47227,-94036,43457,24626,-87359,26898,-70819,30528,-32397,-69486,84912,-1187,-98986,-32958,4280,-79129,-65604,9344,58964,50584,71128,-55480,24986,15086,-62360,-42977,-49482,-77256,-36895,-74818,20,3063,-49426,28152,-97329,6086,86035,-88743,35241,44249,19927,-10660,89404,24179,-26621,-6511,57745,-28750,96340,-97160,-97822,-49979,52307,79462,94273,-24808,77104,9255,-83057,77655,21361,55956,-9096,48599,-40490,-55107,2689,29608,20497,66834,-34678,23553,-81400,-66630,-96321,-34499,-12957,-20564,25610,-4322,-58462,20801,53700,71527,24669,-54534,57879,-3221,33636,3900,97832,-27688,-98715,5992,24520,-55401,-57613,-69926,57377,-77610,20123,52174,860,60429,-91994,-62403,-6218,-90610,-37263,-15052,62069,-96465,44254,89892,-3406,19121,-41842,-87783,-64125,-56120,73904,-22797,-58118,-4866,5356,75318,46119,21276,-19246,-9241,-97425,57333,-15802,93149,25689,-5532,95716,39209,-87672,-29470,-16324,-15331,27632,-39454,56530,-16000,29853,46475,78242,-46602,83192,-73440,-15816,50964,-36601,89758,38375,-40007,-36675,-94030,67576,46811,-64919,45595,76530,40398,35845,41791,67697,-30439,-82944,63115,33447,-36046,-50122,-34789,43003,-78947,-38763,-89210,32756,-20389,-31358,-90526,-81607,88741,86643,98422,47389,-75189,13091,95993,-15501,94260,-25584,-1483,-67261,-70753,25160,89614,-90620,-48542,83889,-12388,-9642,-37043,-67663,28794,-8801,13621,12241,55379,84290,21692,-95906,-85617,-17341,-63767,80183,-4942,-51478,30997,-13658,8838,17452,-82869,-39897,68449,31964,98158,-49489,62283,-62209,-92792,-59342,55146,-38533,20496,62667,62593,36095,-12470,5453,-50451,74716,-17902,3302,-16760,-71642,-34819,96459,-72860,21638,47342,-69897,-40180,44466,76496,84659,13848,-91600,-90887,-63742,-2156,-84981,-99280,94326,-33854,92029,-50811,98711,-36459,-75555,79110,-88164,-97397,-84217,97457,64387,30513,-53190,-83215,252,2344,-27177,-92945,-89010,82662,-11670,86069,53417,42702,97082,3695,-14530,-46334,17910,77999,28009,-12374,15498,-46941,97088,-35030,95040,92095,-59469,-24761,46491,67357,-66658,37446,-65130,-50416,99197,30925,27308,54122,-44719,12582,-99525,-38446,-69050,-22352,94757,-56062,33684,-40199,-46399,96842,-50881,-22380,-65021,40582,53623,-76034,77018,-97074,-84838,-22953,-74205,79715,-33920,-35794,-91369,73421,-82492,63680,-14915,-33295,37145,76852,-69442,60125,-74166,74308,-1900,-30195,-16267,-60781,-27760,5852,38917,25742,-3765,49097,-63541,98612,-92865,-30248,9612,-8798,53262,95781,-42278,-36529,7252,-27394,-5021,59178,80934,-48480,-75131,-54439,-19145,-48140,98457,-6601,-51616,-89730,78028,32083,-48904,16822,-81153,-8832,48720,-80728,-45133,-86647,-4259,-40453,2590,28613,50523,-4105,-27790,-74579,-17223,63721,33489,-47921,97628,-97691,-14782,-65644,18008,-93651,-71266,80990,-76732,-47104,35368,28632,59818,-86269,-89753,34557,-92230,-5933,-3487,-73557,-13174,-43981,-43630,-55171,30254,-83710,-99583,-13500,71787,5017,-25117,-78586,86941,-3251,-23867,-36315,75973,86272,-45575,77462,-98836,-10859,70168,-32971,-38739,-12761,93410,14014,-30706,-77356,-85965,-62316,63918,-59914,-64088,1591,-10957,38004,15129,-83602,-51791,34381,-89382,-26056,8942,5465,71458,-73805,-87445,-19921,-80784,69150,-34168,28301,-68955,18041,6059,82342,9947,39795,44047,-57313,48569,81936,-2863,-80932,32976,-86454,-84207,33033,32867,9104,-16580,-25727,80157,-70169,53741,86522,84651,68480,84018,61932,7332,-61322,-69663,76370,41206,12326,-34689,17016,82975,-23386,39417,72793,44774,-96259,3213,79952,29265,-61492,-49337,14162,65886,3342,-41622,-62659,-90402,-24751,88511,54739,-21383,-40161,-96610,-24944,-602,-76842,-21856,69964,43994,-15121,-85530,12718,13170,-13547,69222,62417,-75305,-81446,-38786,-52075,-23110,97681,-82800,-53178,11474,35857,94197,-58148,-23689,32506,92154,-64536,-73930,-77138,97446,-83459,70963,22452,68472,-3728,-25059,-49405,95129,-6167,12808,99918,30113,-12641,-26665,86362,-33505,50661,26714,33701,89012,-91540,40517,-12716,-57185,-87230,29914,-59560,13200,-72723,58272,23913,-45586,-96593,-26265,-2141,31087,81399,92511,-34049,20577,2803,26003,8940,42117,40887,-82715,38269,40969,-50022,72088,21291,-67280,-16523,90535,18669,94342,-39568,-88080,-99486,-20716,23108,-28037,63342,36863,-29420,-44016,75135,73415,16059,-4899,86893,43136,-7041,33483,-67612,25327,40830,6184,61805,4247,81119,-22854,-26104,-63466,63093,-63685,60369,51023,51644,-16350,74438,-83514,99083,10079,-58451,-79621,48471,67131,-86940,99093,11855,-22272,-67683,-44371,9541,18123,37766,-70922,80385,-57513,-76021,-47890,36154,72935,84387,-92681,-88303,-7810,59902,-90,-64704,-28396,-66403,8860,13343,33882,85680,7228,28160,-14003,54369,-58893,92606,-63492,-10101,64714,58486,29948,-44679,-22763,10151,-56695,4031,-18242,-36232,86168,-14263,9883,47124,47271,92761,-24958,-73263,-79661,-69147,-18874,29546,-92588,-85771,26451,-86650,-43306,-59094,-47492,-34821,-91763,-47670,33537,22843,67417,-759,92159,63075,94065,-26988,55276,65903,30414,-67129,-99508,-83092,-91493,-50426,14349,-83216,-76090,32742,-5306,-93310,-60750,-60620,-45484,-21108,-58341,-28048,-52803,69735,78906,81649,32565,-86804,-83202,-65688,-1760,89707,93322,-72750,84134,71900,-37720,19450,-78018,22001,-23604,26276,-21498,65892,-72117,-89834,-23867,55817,-77963,42518,93123,-83916,63260,-2243,-97108,85442,-36775,17984,-58810,99664,-19082,93075,-69329,87061,79713,16296,70996,13483,-74582,49900,-27669,-40562,1209,-20572,34660,83193,75579,7344,64925,88361,60969,3114,44611,-27445,53049,-16085,-92851,-53306,13859,-33532,86622,-75666,-18159,-98256,51875,-42251,-27977,-18080,23772,38160,41779,9147,94175,99905,-85755,62535,-88412,-52038,-68171,93255,-44684,-11242,-104,31796,62346,-54931,-55790,-70032,46221,56541,-91947,90592,93503,4071,20646,4856,-63598,15396,-50708,32138,-85164,38528,-89959,53852,57915,-42421,-88916,-75072,67030,-29066,49542,-71591,61708,-53985,-43051,28483,46991,-83216,80991,-46254,-48716,39356,-8270,-47763,-34410,874,-1186,-7049,28846,11276,21960,-13304,-11433,-4913,55754,79616,70423,-27523,64803,49277,14906,-97401,-92390,91075,70736,21971,-3303,55333,-93996,76538,54603,-75899,98801,46887,35041,48302,-52318,55439,24574,14079,-24889,83440,14961,34312,-89260,-22293,-81271,-2586,-71059,-10640,-93095,-5453,-70041,66543,74012,-11662,-52477,-37597,-70919,92971,-17452,-67306,-80418,7225,-89296,24296,86547,37154,-10696,74436,-63959,58860,33590,-88925,-97814,-83664,85484,-8385,-50879,57729,-74728,-87852,-15524,-91120,22062,28134,80917,32026,49707,-54252,-44319,-35139,13777,44660,85274,25043,58781,-89035,-76274,6364,-63625,72855,43242,-35033,12820,-27460,77372,-47578,-61162,-70758,-1343,-4159,64935,56024,-2151,43770,19758,-30186,-86040,24666,-62332,-67542,73180,-25821,-27826,-45504,-36858,-12041,20017,-24066,-56625,-52097,-47239,-90694,8959,7712,-14258,-5860,55349,61808,-4423,-93703,64681,-98641,-25222,46999,-83831,-54714,19997,-68477,66073,51801,-66491,52061,-52866,79907,-39736,-68331,68937,91464,98892,910,93501,31295,-85873,27036,-57340,50412,21,-2445,29471,71317,82093,-94823,-54458,-97410,39560,-7628,66452,39701,54029,37906,46773,58296,60370,-61090,85501,-86874,71443,-72702,-72047,14848,34102,77975,-66294,-36576,31349,52493,-70833,-80287,94435,39745,-98291,84524,-18942,10236,93448,50846,94023,-6939,47999,14740,30165,81048,84935,-19177,-13594,32289,62628,-90612,-542,-66627,64255,71199,-83841,-82943,-73885,8623,-67214,-9474,-35249,62254,-14087,-90969,21515,-83303,94377,-91619,19956,-98810,96727,-91939,29119,-85473,-82153,-69008,44850,74299,-76459,-86464,8315,-49912,-28665,59052,-69708,76024,-92738,50098,18683,-91438,18096,-19335,35659,91826,15779,-73070,67873,-12458,-71440,-46721,54856,97212,-81875,35805,36952,68498,81627,-34231,81712,27100,-9741,-82612,18766,-36392,2759,41728,69743,26825,48355,-17790,17165,56558,3295,-24375,55669,-16109,24079,73414,48990,-11931,-78214,90745,19878,35673,-15317,-89086,94675,-92513,88410,-93248,-19475,-74041,-19165,32329,-26266,-46828,-18747,45328,8990,-78219,-25874,-74801,-44956,-54577,-29756,-99822,-35731,-18348,-68915,-83518,-53451,95471,-2954,-13706,-8763,-21642,-37210,16814,-60070,-42743,27697,-36333,-42362,11576,85742,-82536,68767,-56103,-63012,71396,-78464,-68101,-15917,-11113,-3596,77626,-60191,-30585,-73584,6214,-84303,18403,23618,-15619,-89755,-59515,-59103,-74308,-63725,-29364,-52376,-96130,70894,-12609,50845,-2314,42264,-70825,64481,55752,4460,-68603,-88701,4713,-50441,-51333,-77907,97412,-66616,-49430,60489,-85262,-97621,-18980,44727,-69321,-57730,66287,-92566,-64427,-14270,11515,-92612,-87645,61557,24197,-81923,-39831,-10301,-23640,-76219,-68025,92761,-76493,68554,-77734,-95620,-11753,-51700,98234,-68544,-61838,29467,46603,-18221,-35441,74537,40327,-58293,75755,-57301,-7532,-94163,18179,-14388,-22258,-46417,-48285,18242,-77551,82620,250,-20060,-79568,-77259,82052,-98897,-75464,48773,-79040,-11293,45941,-67876,-69204,-46477,-46107,792,60546,-34573,-12879,-94562,20356,-48004,-62429,96242,40594,2099,99494,25724,-39394,-2388,-18563,-56510,-83570,-29214,3015,74454,74197,76678,-46597,60630,-76093,37578,-82045,-24077,62082,-87787,-74936,58687,12200,-98952,70155,-77370,21710,-84625,-60556,-84128,925,65474,-15741,-94619,88377,89334,44749,22002,-45750,-93081,-14600,-83447,46691,85040,-66447,-80085,56308,44310,24979,-29694,57991,4675,-71273,-44508,13615,-54710,23552,-78253,-34637,50497,68706,81543,-88408,-21405,6001,-33834,-21570,-46692,-25344,20310,71258,-97680,11721,59977,59247,-48949,98955,-50276,-80844,-27935,-76102,55858,-33492,40680,66691,-33188,8284,64893,-7528,6019,-85523,8434,-64366,-56663,26862,30008,-7611,-12179,-70076,21426,-11261,-36864,-61937,-59677,929,-21052,3848,-20888,-16065,98995,-32293,-86121,-54564,77831,68602,74977,31658,40699,29755,98424,80358,-69337,26339,13213,-46016,-18331,64713,-46883,-58451,-70024,-92393,-4088,70628,-51185,71164,-75791,-1636,-29102,-16929,-87650,-84589,-24229,-42137,-15653,94825,13042,88499,-47100,-90358,-7180,29754,-65727,-42659,-85560,-9037,-52459,20997,-47425,17318,21122,20472,-23037,65216,-63625,-7877,-91907,24100,-72516,22903,-85247,-8938,73878,54953,87480,-31466,-99524,35369,-78376,89984,-15982,94045,-7269,23319,-80456,-37653,-76756,2909,81936,54958,-12393,60560,-84664,-82413,66941,-26573,-97532,64460,18593,-85789,-38820,-92575,-43663,-89435,83272,-50585,13616,-71541,-53156,727,-27644,16538,34049,57745,34348,35009,16634,-18791,23271,-63844,95817,21781,16590,59669,15966,-6864,48050,-36143,97427,-59390,96931,78939,-1958,50777,43338,-51149,39235,-27054,-43492,67457,-83616,37179,10390,85818,2391,73635,87579,-49127,-81264,-79023,-81590,53554,-74972,-83940,-13726,-39095,29174,78072,76104,47778,25797,-29515,-6493,-92793,22481,-36197,-65560,42342,15750,97556,99634,-56048,-35688,13501,63969,-74291,50911,39225,93702,-3490,-59461,-30105,-46761,-80113,92906,-68487,50742,36152,-90240,-83631,24597,-50566,-15477,18470,77038,40223,-80364,-98676,70957,-63647,99537,13041,31679,86631,37633,-16866,13686,-71565,21652,-46053,-80578,-61382,68487,-6417,4656,20811,67013,-30868,-11219,46,74944,14627,56965,42275,-52480,52162,-84883,-52579,-90331,92792,42184,-73422,-58440,65308,-25069,5475,-57996,59557,-17561,2826,-56939,14996,-94855,-53707,99159,43645,-67719,-1331,21412,41704,31612,32622,1919,-69333,-69828,22422,-78842,57896,-17363,27979,-76897,35008,46482,-75289,65799,20057,7170,41326,-76069,90840,-81253,-50749,3649,-42315,45238,-33924,62101,96906,58884,-7617,-28689,-66578,62458,50876,-57553,6739,41014,-64040,-34916,37940,13048,-97478,-11318,-89440,-31933,-40357,-59737,-76718,-14104,-31774,28001,4103,41702,-25120,-31654,63085,-3642,84870,-83896,-76422,-61520,12900,88678,85547,33132,-88627,52820,63915,-27472,78867,-51439,33005,-23447,-3271,-39308,39726,-74260,-31874,-36893,93656,910,-98362,60450,-88048,99308,13947,83996,-90415,-35117,70858,-55332,-31721,97528,82982,-86218,6822,25227,36946,97077,-4257,-41526,56795,89870,75860,-70802,21779,14184,-16511,-89156,-31422,71470,69600,-78498,74079,-19410,40311,28501,26397,-67574,-32518,68510,38615,19355,-6088,-97159,-29255,-92523,3023,-42536,-88681,64255,41206,44119,52208,39522,-52108,91276,-70514,83436,63289,-79741,9623,99559,12642,85950,83735,-21156,-67208,98088,-7341,-27763,-30048,-44099,-14866,-45504,-91704,19369,13700,10481,-49344,-85686,33994,19672,36028,60842,66564,-24919,33950,-93616,-47430,-35391,-28279,56806,74690,39284,-96683,-7642,-75232,37657,-14531,-86870,-9274,-26173,98640,88652,64257,46457,37814,-19370,9337,-22556,-41525,39105,-28719,51611,-93252,98044,-90996,21710,-47605,-64259,-32727,53611,-31918,-3555,33316,-66472,21274,-37731,-2919,15016,48779,-88868,1897,41728,46344,-89667,37848,68092,-44011,85354,-43776,38739,-31423,-66330,65167,-22016,59405,34328,-60042,87660,-67698,-59174,-1408,-46809,-43485,-88807,-60489,13974,22319,55836,-62995,-37375,-4185,32687,-36551,-75237,58280,26942,-73756,71756,78775,-40573,14367,-71622,-77338,24112,23414,-7679,-51721,87492,85066,-21612,57045,10673,-96836,52461,-62218,-9310,65862,-22748,89906,-96987,-98698,26956,-43428,46141,47456,28095,55952,67323,-36455,-60202,-43302,-82932,42020,77036,10142,60406,70331,63836,58850,-66752,52109,21395,-10238,-98647,-41962,27778,69060,98535,-28680,-52263,-56679,66103,-42426,27203,80021,10153,58678,36398,63112,34911,20515,62082,-15659,-40785,27054,43767,-20289,65838,-6954,-60228,-72226,52236,-35464,25209,-15462,-79617,-41668,-84083,62404,-69062,18913,46545,20757,13805,24717,-18461,-47009,-25779,68834,64824,34473,39576,31570,14861,-15114,-41233,95509,68232,67846,84902,-83060,17642,-18422,73688,77671,-26930,64484,-99637,73875,6428,21034,-73471,19664,-68031,15922,-27028,48137,54955,-82793,-41144,-10218,-24921,-28299,-2288,68518,-54452,15686,-41814,66165,-72207,-61986,80020,50544,-99500,16244,78998,40989,14525,-56061,-24692,-94790,21111,37296,-90794,72100,70550,-31757,17708,-74290,61910,78039,-78629,-25033,73172,-91953,10052,64502,99585,-1741,90324,-73723,68942,28149,30218,24422,16659,10710,-62594,94249,96588,46192,34251,73500,-65995,-81168,41412,-98724,-63710,-54696,-52407,19746,45869,27821,-94866,-76705,-13417,-61995,-71560,43450,67384,-8838,-80293,-28937,23330,-89694,-40586,46918,80429,-5475,78013,25309,-34162,37236,-77577,86744,26281,-29033,-91813,35347,13033,-13631,-24459,3325,-71078,-75359,81311,19700,47678,-74680,-84113,45192,35502,37675,19553,76522,-51098,-18211,89717,4508,-82946,27749,85995,89912,-53678,-64727,-14778,32075,-63412,-40524,86440,-2707,-36821,63850,-30883,67294,-99468,-23708,34932,34386,98899,29239,-23385,5897,54882,98660,49098,70275,17718,88533,52161,63340,50061,-89457,19491,-99156,24873,-17008,64610,-55543,50495,17056,-10400,-56678,-29073,-42960,-76418,98562,-88104,-96255,10159,-90724,54011,12052,45871,-90933,-69420,67039,37202,78051,-52197,-40278,-58425,65414,-23394,-1415,6912,-53447,7352,17307,-78147,63727,98905,55412,-57658,-32884,-44878,22755,39730,3638,35111,39777,74193,38736,-11829,-61188,-92757,55946,-71232,-63032,-83947,39147,-96684,-99233,25131,-32197,24406,-55428,-61941,25874,-69453,64483,-19644,-68441,12783,87338,-48676,66451,-447,-61590,50932,-11270,29035,65698,-63544,10029,80499,-9461,86368,91365,-81810,-71914,-52056,-13782,44240,-30093,-2437,24007,67581,-17365,-69164,-8420,-69289,-29370,48010,90439,13141,69243,50668,39328,61731,78266,-81313,17921,-38196,55261,9948,-24970,75712,-72106,28696,7461,31621,61047,51476,56512,11839,-96916,-82739,28924,-99927,58449,37280,69357,11219,-32119,-62050,-48745,-83486,-52376,42668,82659,68882,38773,46269,-96005,97630,25009,-2951,-67811,99801,81587,-79793,-18547,-83086,69512,33127,-92145,-88497,47703,59527,1909,88785,-88882,69188,-46131,-5589,-15086,36255,-53238,-33009,82664,53901,35939,-42946,-25571,33298,69291,53199,74746,-40127,-39050,91033,51717,-98048,87240,36172,65453,-94425,-63694,-30027,59004,88660,3649,-20267,-52565,-67321,34037,4320,91515,-56753,60115,27134,68617,-61395,-26503,-98929,-8849,-63318,10709,-16151,61905,-95785,5262,23670,-25277,90206,-19391,45735,37208,-31992,-92450,18516,-90452,-58870,-58602,93383,14333,17994,82411,-54126,-32576,35440,-60526,-78764,-25069,-9022,-394,92186,-38057,55328,-61569,67780,77169,19546,-92664,-94948,44484,-13439,83529,27518,-48333,72998,38342,-90553,-98578,-76906,81515,-16464,78439,92529,35225,-39968,-10130,-7845,-32245,-74955,-74996,67731,-13897,-82493,33407,93619,59560,-24404,-57553,19486,-45341,34098,-24978,-33612,79058,71847,76713,-95422,6421,-96075,-59130,-28976,-16922,-62203,69970,68331,21874,40551,89650,51908,58181,66480,-68177,34323,-3046,-49656,-59758,43564,-10960,-30796,15473,-20216,46085,-85355,41515,-30669,-87498,57711,56067,63199,-83805,62042,91213,-14606,4394,-562,74913,10406,96810,-61595,32564,31640,-9732,42058,98052,-7908,-72330,1558,-80301,34878,32900,3939,-8824,88316,20937,21566,-3218,-66080,-31620,86859,54289,90476,-42889,-15016,-18838,75456,30159,-67101,42328,-92703,85850,-5475,23470,-80806,68206,17764,88235,46421,-41578,74005,-81142,80545,20868,-1560,64017,83784,68863,-97516,-13016,-72223,79630,-55692,82255,88467,28007,-34686,-69049,-41677,88535,-8217,68060,-51280,28971,49088,49235,26905,-81117,-44888,40623,74337,-24662,97476,79542,-72082,-35093,98175,-61761,-68169,59697,-62542,-72965,59883,-64026,-37656,-92392,-12113,-73495,98258,68379,-21545,64607,-70957,-92254,-97460,-63436,-8853,-19357,-51965,-76582,12687,-49712,45413,-60043,33496,31539,-57347,41837,67280,-68813,52088,-13155,-86430,-15239,-45030,96041,18749,-23992,46048,35243,-79450,85425,-58524,88781,-39454,53073,-48864,-82289,39086,82540,-11555,25014,-5431,-39585,-89526,2705,31953,-81611,36985,-56022,68684,-27101,11422,64655,-26965,-63081,-13840,-91003,-78147,-8966,41488,1988,99021,-61575,-47060,65260,-23844,-21781,-91865,-19607,44808,2890,63692,-88663,-58272,15970,-65195,-45416,-48444,-78226,-65332,-24568,42833,-1806,-71595,80002,-52250,30952,48452,-90106,31015,-22073,62339,63318,78391,28699,77900,-4026,-76870,-45943,33665,9174,-84360,-22684,-16832,-67949,-38077,-38987,-32847,51443,-53580,-13505,9344,-92337,26585,70458,-52764,-67471,-68411,-1119,-2072,-93476,67981,40887,-89304,-12235,41488,1454,5355,-34855,-72080,24514,-58305,3340,34331,8731,77451,-64983,-57876,82874,62481,-32754,-39902,22451,-79095,-23904,78409,-7418,77916}; s.threeSum(v3); vector<int> v4{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; s.threeSum(v4); }
[ "maxy218@debian.maxy218_debian.com" ]
maxy218@debian.maxy218_debian.com
0307a2fd69e6657cbe72fc5673bfd86898dc34bd
99a8814929551884efaf323025df2a5c698dd16c
/2. hafta uygulamaları1.cpp
1213b992423d91cc6010f9d3704048ea6b468f86
[]
no_license
sakgun165/C-ProgramlamaDiliDers
98eb6b00b29673c6212b5406c49d5f02dab26e05
45b9ab04fd87cdbf63e47dc16af9867eff3e1a18
refs/heads/master
2020-04-26T09:05:38.942170
2019-03-02T12:15:22
2019-03-02T12:15:22
173,443,808
0
0
null
null
null
null
UTF-8
C++
false
false
305
cpp
#include <stdio.h> #include <stdlib.h> main() { int i,vize1,toplam=0; float ortalama; for(i=0;i<10;i++) { printf("%d.nci ogrencinin vize notunu giriniz: ",i+1); scanf("%d",&vize1); toplam+=vize1; ortalama=toplam/10.0; } printf("Ogrencilerin vize ortalamalari: %5.2f",ortalama); return 0; }
[ "32776568+sakgun165@users.noreply.github.com" ]
32776568+sakgun165@users.noreply.github.com
a4a7542d097ab43a2a83db5e576dfd89524fab05
a4d2b46d1d9b6f9a64a0baaca04dcf474aa19c67
/Personal Works/Binary Search/208-Binary Search_ Min In A Canyon.cpp
0572b769b4f701e2e261e2b04fab1415a55f3166
[]
no_license
shanto-swe029/Data-Structure-And-Algorithm
967d1cec667afd828c4de17e037a0e2483c7148c
1b8c22fe66752b53cbab2cbd01ad63795928ded2
refs/heads/main
2023-05-21T10:06:53.992848
2021-06-08T09:29:12
2021-06-08T09:29:12
307,928,988
6
5
null
null
null
null
UTF-8
C++
false
false
1,892
cpp
/* BISMILLAHIR-RAHMANIR-RAHIM ____________________________________ | | | SHANTO_SUST_SWE-19__029 | | shanto-swe029.github.io | |____________________________________| */ /* Problem Statement: --------------------------------------------------------------------------------- Suppose, you have an array. The first part of the array is non-increasing and the final part of the array is non-decreasing. You have to find the minimum value of this array. For example : Let's consider an array like { 5, 4, 3, 2, 1, 3, 5, 7, 9 }. The minimum number of this array = 1. For calrification : size of any of the two parts ( but not both ) can be zero. Solution Approach: --------------------------------------------------------------------------------- Running Binary Search is the most efficient way here. But what will be the ITEM value here is the main query. Well, in this case, ITEM value is a variable. We have to compare DATA[MID] with DATA[MID - 1]. This is the key to solving this problem. I am throwing the rest understanding of this approach on my code. I hope you will get it. */ #include <bits/stdc++.h> using namespace std; int BinarySearch_MinInACanyon( int DATA[], int LB, int UB ) { int BEG = LB, END = UB, MID = ( int ) ( BEG + END ) / 2; int minimumNumber = max( DATA[LB], DATA[UB] ); while( BEG <= END ) { if( DATA[MID] <= DATA[MID - 1] ) { BEG = MID + 1; if( DATA[MID] < minimumNumber ) { minimumNumber = DATA[MID]; } } else { END = MID - 1; } MID = ( int ) ( BEG + END ) / 2; } return minimumNumber; } int main() { int ara[] = { 12, 9, 7, 6, 2, 1, 4, 8, 10 }; int lowerBound = 0; int upperBound = 8; int minimumNumber = BinarySearch_MinInACanyon( ara, lowerBound, upperBound ); std::cout << minimumNumber << endl; return 0; } //ALHAMDULILLAH
[ "noreply@github.com" ]
noreply@github.com
a0fe4c08eb891d7803645bef5584b6790b0a8b80
501591e4268ad9a5705012cd93d36bac884847b7
/src/server/pathfinding/recast/RecastAlloc.h
a525eaf83d2aeb21ab7073a459a0102454d3b6da
[]
no_license
CryNet/MythCore
f550396de5f6e20c79b4aa0eb0a78e5fea9d86ed
ffc5fa1c898d25235cec68c76ac94c3279df6827
refs/heads/master
2020-07-11T10:09:31.244662
2013-06-29T19:06:43
2013-06-29T19:06:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,029
h
/* * Copyright (C) 2008 - 2011 Trinity <http://www.trinitycore.org/> * * Copyright (C) 2010 - 2012 Myth Project <http://mythprojectnetwork.blogspot.com/> * * Copyright (C) 2012 SymphonyArt <http://symphonyart.com/> * * Myth Project's source is based on the Trinity Project source, you can find the * link to that easily in Trinity Copyrights. Myth Project is a private community. * To get access, you either have to donate or pass a developer test. * You may not share Myth Project's sources! For personal use only. */ #ifndef RECASTALLOC_H #define RECASTALLOC_H enum rcAllocHint { RC_ALLOC_PERM, // Memory persist after a function call. RC_ALLOC_TEMP // Memory used temporarily within a function. }; typedef void* (rcAllocFunc)(int size, rcAllocHint hint); typedef void (rcFreeFunc)(void* ptr); void rcAllocSetCustom(rcAllocFunc *allocFunc, rcFreeFunc *freeFunc); void* rcAlloc(int size, rcAllocHint hint); void rcFree(void* ptr); // Simple dynamic array ints. class rcIntArray { int* m_data; int m_size, m_cap; inline rcIntArray(const rcIntArray&); inline rcIntArray& operator=(const rcIntArray&); public: inline rcIntArray() : m_data(0), m_size(0), m_cap(0) { } inline rcIntArray(int n) : m_data(0), m_size(0), m_cap(0) { resize(n); } inline ~rcIntArray() { rcFree(m_data); } void resize(int n); inline void push(int item) { resize(m_size+1); m_data[m_size-1] = item; } inline int pop() { if(m_size > 0) m_size--; return m_data[m_size]; } inline const int& operator[](int i) const { return m_data[i]; } inline int& operator[](int i) { return m_data[i]; } inline int size() const { return m_size; } }; // Simple internal helper class to delete array in scope template<class T> class rcScopedDelete { T* ptr; inline T* operator=(T* p); public: inline rcScopedDelete() : ptr(0) { } inline rcScopedDelete(T* p) : ptr(p) { } inline ~rcScopedDelete() { rcFree(ptr); } inline operator T*() { return ptr; } }; #endif
[ "vitasic-pokataev@yandex.ru" ]
vitasic-pokataev@yandex.ru
6a1523f40a89598272141db2cfc2cae8a39c8f21
1a1fc3d5c216eb7f16c4be4d0739ccc7700d9555
/external/emmcdl/src/sparse.cpp
c5ebb4ea416f21af88809c3177811c5022f9c2ea
[]
no_license
kiddlu/android-platform-knife
cd637d1374e07600ae018cc5120e6e1fcd987b95
1c6ec4cdaa3d1d90262e0dd5c1212ebe0f3d417b
refs/heads/android-L
2021-01-17T01:50:49.929820
2017-09-04T03:41:35
2017-09-04T03:41:35
47,400,423
83
55
null
2018-08-15T07:13:43
2015-12-04T11:36:26
Shell
UTF-8
C++
false
false
4,904
cpp
/***************************************************************************** * sparse.cpp * * This class implements Sparse image support * * Copyright (c) 2007-2015 * Qualcomm Technologies Incorporated. * All Rights Reserved. * Qualcomm Confidential and Proprietary * *****************************************************************************/ /*============================================================================= Edit History $Header: //source/qcom/qct/platform/uefi/workspaces/pweber/apps/8x26_emmcdl/emmcdl/main/latest/src/sparse.cpp#3 $ $DateTime: 2015/07/15 15:43:47 $ $Author: pweber $ when who what, where, why ------------------------------------------------------------------------------- 02/05/15 pgw Initial version. =============================================================================*/ #include "stdio.h" #include "stdlib.h" #include "tchar.h" #include "sparse.h" #include "windows.h" #include "string.h" // Constructor SparseImage::SparseImage() { bSparseImage = false; } // Destructor SparseImage::~SparseImage() { if (bSparseImage) { CloseHandle(hSparseImage); } } // This will load a sparse image into memory and read headers if it is a sparse image // RETURN: // ERROR_SUCCESS - Image and headers we loaded successfully // int SparseImage::PreLoadImage(TCHAR *szSparseFile) { DWORD dwBytesRead; hSparseImage = CreateFile(szSparseFile, GENERIC_READ, FILE_SHARE_READ, // We only read from here so let others open the file as well NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hSparseImage == INVALID_HANDLE_VALUE) return GetLastError(); // Load the sparse file header and verify it is valid if (ReadFile(hSparseImage, &SparseHeader, sizeof(SparseHeader), &dwBytesRead, NULL)) { // Check the magic number in the sparse header to see if this is a vaild sparse file if (SparseHeader.dwMagic != SPARSE_MAGIC) { CloseHandle(hSparseImage); return ERROR_BAD_FORMAT; } } else { // Couldn't read the file likely someone else has it open for exclusive access CloseHandle(hSparseImage); return ERROR_READ_FAULT; } bSparseImage = true; return ERROR_SUCCESS; } int SparseImage::ProgramImage(Protocol *pProtocol, __int64 dwOffset) { CHUNK_HEADER ChunkHeader; BYTE *bpDataBuf = NULL; DWORD dwBytesRead; DWORD dwBytesOut; int status = ERROR_SUCCESS; // Make sure we have first successfully found a sparse file and headers are loaded okay if (!bSparseImage) { return ERROR_FILE_NOT_FOUND; } // Allocated a buffer // Main loop through all block entries in the sparse image for (UINT32 i=0; i < SparseHeader.dwTotalChunks; i++) { // Read chunk header if (ReadFile(hSparseImage, &ChunkHeader, sizeof(ChunkHeader), &dwBytesRead, NULL)){ UINT32 dwChunkSize = ChunkHeader.dwChunkSize*SparseHeader.dwBlockSize; // Allocate a buffer the size of the chunk and read in the data bpDataBuf = (BYTE *)malloc(dwChunkSize); if (bpDataBuf == NULL){ return ERROR_OUTOFMEMORY; } if (ChunkHeader.wChunkType == SPARSE_RAW_CHUNK){ if (ReadFile(hSparseImage, bpDataBuf, dwChunkSize, &dwBytesRead, NULL)) { // Now we have the data so use whatever protocol we need to write this out pProtocol->WriteData(bpDataBuf, dwOffset, dwChunkSize, &dwBytesOut,0); dwOffset += dwChunkSize; } else { status = GetLastError(); break; } } else if (ChunkHeader.wChunkType == SPARSE_FILL_CHUNK) { // Fill chunk with data byte given for now just skip over this area dwOffset += ChunkHeader.dwChunkSize*SparseHeader.dwBlockSize; } else if (ChunkHeader.wChunkType == SPARSE_DONT_CARE) { // Skip the specified number of bytes in the output file // Fill the buffer with 0 memset(bpDataBuf, 0, dwChunkSize); pProtocol->WriteData(bpDataBuf, dwOffset, dwChunkSize, &dwBytesOut, 0); dwOffset += dwChunkSize; } else { // We have no idea what type of chunk this is return a failure and close file status = ERROR_INVALID_DATA; break; } free(bpDataBuf); bpDataBuf = NULL; } else { // Failed to read data something is wrong with the file status = GetLastError(); break; } } // If we broke here from an error condition free the bpDataBuf if( bpDataBuf != NULL) { free(bpDataBuf); bpDataBuf = NULL; } // If we failed to load the file close the handle and set sparse image back to false if (status != ERROR_SUCCESS) { bSparseImage = false; CloseHandle(hSparseImage); } return status; }
[ "kidd.dawny.lu@gmail.com" ]
kidd.dawny.lu@gmail.com
2184418d6caf7d5ca155f52059b579a199459254
5d79ac250746dc8375c1dbe4ec8e4616a575cdc7
/GameOfLife/Source_Code/Windows_Version/InteractiveGoL/GameOfLife.h
ad3c7b10885f05069d300014524515e05a74ae07
[]
no_license
Nakul-08/Game-of-life
438cd23786837d1fedf415c605b0dc5079765254
b3d6867ac11dadc0f6413ec6a5797be8009e8879
refs/heads/master
2023-06-04T23:33:58.052663
2021-06-28T14:49:53
2021-06-28T14:49:53
381,042,112
0
0
null
null
null
null
UTF-8
C++
false
false
1,259
h
#pragma once #include "Cell.h" #include <SFML/System/Vector2.hpp> #include <cstdint> #include <vector> class GameOfLife { public: GameOfLife(sf::Vector2i size); // Set the value of the cell at the given grid position to the given alive state. void setCell(int x, int y, bool alive); // Updates the state of the game world by one tick. void update(); // Returns a reference to the cell value at the given grid position. std::uint8_t& getCell(int x, int y); // Returns a vector of the given cell's grid position by its cell index. sf::Vector2i get2D(int index) const; auto const& getLivingCells() const { return aliveCells; } // Returns a color to use for cells/backgrounds based on the thread ID #. static sf::Color getThreadColor(int index); // Represents the width and height of the simulated world. const sf::Vector2i worldSize; private: // A cache of all the alive cells at the end of the update() call. std::vector<Cell> aliveCells = {}; // A 1D representation of the 2D grid that is the world. std::vector<std::uint8_t> world; // A buffer where the next world state is prepared, swapped with world at end of update(). std::vector<std::uint8_t> worldBuffer; };
[ "nakulsaroha08@gmail.com" ]
nakulsaroha08@gmail.com
3ccefdda0ea30972dda4bbada08dde00bbff9743
0d74effba292cf0bcfd0f0280887f80c350dca59
/day-223.cpp
a0aea3b922a4bb0abdfe0a805a6dd5545305c830
[]
no_license
PranjalAgni/210DaysLeetCode
34ab549e3a8e284f98e083393cc300663739690e
b900c11bc50a0baa122e6cef302c1b0c8cb09723
refs/heads/master
2023-03-01T04:41:55.693293
2021-02-07T18:14:21
2021-02-07T18:14:21
252,403,305
10
5
null
null
null
null
UTF-8
C++
false
false
1,321
cpp
/* Maximum Difference Between Node and Ancestor Given the root of a binary tree, find the maximum value V for which there exist different nodes A and B where V = |A.val - B.val| and A is an ancestor of B. A node A is an ancestor of B if either: any child of A is equal to B, or any child of A is an ancestor of B. Example 1: Input: root = [8,3,10,1,6,null,14,null,null,4,7,13] Output: 7 Explanation: We have various ancestor-node differences, some of which are given below : |8 - 3| = 5 |3 - 7| = 4 |8 - 1| = 7 |10 - 13| = 3 Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7. Example 2: Input: root = [1,null,2,null,0,3] Output: 3 Constraints: The number of nodes in the tree is in the range [2, 5000]. 0 <= Node.val <= 105 */ // Recursivw solution class Solution { public: int rec(TreeNode* root, int minval, int maxval) { if (!root) { return maxval - minval; } minval = min(minval, root->val); maxval = max(maxval, root->val); int left = rec(root->left, minval, maxval); int right = rec(root->right, minval, maxval); return max(left, right); } // constraints: Tree has at least 2 nodes int maxAncestorDiff(TreeNode* root) { return rec(root, root->val, root->val); } };
[ "pranjal.agnihotri6@gmail.com" ]
pranjal.agnihotri6@gmail.com
6fca8a75c24b36f497260fbc340db5ba859f45a0
ce0539b7bff12d88fba5df4beed41c7315aed16e
/old/InputTouch.cpp
3b0148a02d2224b5930044c8267f50a639d1363e
[]
no_license
wppr/Source
a87c1bdb790747b06e6156a72968ff238a7ce771
eaad33c0149399001eb15f833c7fc3d189c77941
refs/heads/master
2020-07-10T18:02:15.766930
2016-10-30T11:34:28
2016-10-30T11:34:28
66,618,626
1
1
null
2016-08-26T07:31:24
2016-08-26T05:15:55
C++
UTF-8
C++
false
false
16,105
cpp
#include "InputTouch.h" #include "Logger.h" namespace HW { InputTouch::InputTouch() :m_system_message_processed(false) { m_index = true; m_gesture = GS_None; m_current_state = State_None; m_gesture_func[State_None] = &InputTouch::GestureStateNone; m_gesture_func[State_Pan] = &InputTouch::GestureStatePan; m_gesture_func[State_Tap] = &InputTouch::GestureStateTap; m_gesture_func[State_Press] = &InputTouch::GestureStatePress; m_gesture_func[State_DontHandle] = &InputTouch::GestureStateDontHandle; m_gesture_func[State_TwoFinger] = &InputTouch::GestureStateTwoFinger; m_current_gesture_func = &InputTouch::GestureStateNone; TAP_TIMEOUT = 180; PRESS_TIMEOUT = 250; Pan_dist = 25; } void InputTouch::CurrState(GestureState state) { m_current_gesture_func = m_gesture_func[state]; m_current_state = state; #ifdef ANDROID switch(state) { case State_None: LOGE("State_None"); break; case State_Pan: LOGE("State_Pan"); break; case State_Tap: LOGE("State_Tap"); break; case State_TwoFinger: LOGE("State_TwoFinger"); break; case State_Press: Logger::WriteAndroidInfoLog("State_Press"); break; case State_DontHandle: Logger::WriteAndroidInfoLog("State_DontHandle"); break; //case State_Zoom: // LOGE("State_Zoom"); // break; //case State_Rotate: // LOGE("State_Rotate"); // break; default: LOGE("State_Default"); break; } #endif } void InputTouch::GestureStateNone(float elapsed_time) { //Logger::WriteAndroidInfoLog("GestureStateNone num_touch = %d,elapsed_time = %f",(int)m_touch_count,elapsed_time); switch(m_touch_count) { case 1: { if(m_touch_downs[m_index][0]) { this->CurrState(State_Tap); m_one_finger_start_pos = m_touch_positions[m_index][0]; m_one_finger_timer = 0; } else if(m_touch_downs[m_index][1]) { this->CurrState(State_Tap); m_one_finger_start_pos = m_touch_positions[m_index][1]; m_one_finger_timer = 0; } }break; case 2: { if(m_touch_downs[m_index][0] && m_touch_downs[m_index][1]) { // different with klay ,temporaily has no intention to support press and tap this->CurrState(State_TwoFinger); m_two_finger_timer= 0; m_two_finger_start_vec = m_touch_positions[m_index][0] - m_touch_positions[m_index][1]; m_two_finger_start_length = m_two_finger_start_vec.normalize(); } }break; default: break; } } // void InputTouch::GestureStatePan(float elapsed_time) // { //#ifdef ANDROID // LOGE("GestureStatePan num_touch = %d ,elapsed_time = %f",m_touch_count,elapsed_time); //#endif // switch(m_touch_count) // { // case 0: // this->CurrState(State_None); // break; // } // m_gesture = GS_Pan; // Vector2 move_vec; // if(m_touch_downs[m_index][0] && m_touch_downs[!m_index][0]) // { // move_vec = m_touch_positions[m_index][0] - m_touch_positions[!m_index][0]; // } // else // { // move_vec = Vector2(0,0); // } //#ifdef ANDROID // LOGE("Gs_Pan move_vec = (%f,%f)",move_vec.x,move_vec.y); //#endif // m_touch_action_param.gesture = m_gesture; // m_touch_action_param.move_vec = move_vec; // m_touch_action_param.touch_center = m_touch_positions[m_index][0]; // } void InputTouch::GestureStateTap(float elapsed_time) { //Logger::WriteAndroidInfoLog("GestureStateTap num_touch = %d ,elapsed_time = %f",(int)m_touch_count,elapsed_time); //Logger::WriteAndroidInfoLog(" e time %f",elapsed_time); switch(m_touch_count) { case 0: { m_touch_action_param.gesture = m_gesture = GS_Tap; m_touch_action_param.touch_center = m_touch_positions[m_index][0]; this->CurrState(State_None); }break; case 2: { if(m_touch_downs[m_index][0] && m_touch_downs[m_index][1]) { // different with klay ,temporaily has no intention to support press and tap this->CurrState(State_TwoFinger); m_two_finger_timer= 0; m_two_finger_start_vec = m_touch_positions[m_index][0] - m_touch_positions[m_index][1]; m_two_finger_start_length = m_two_finger_start_vec.normalize(); } }break; case 1: { m_one_finger_timer += elapsed_time; float dist ; unsigned int down_index = 0; if(m_touch_downs[m_index][0]) down_index =0; else down_index =1; dist = (m_touch_positions[m_index][down_index] -m_one_finger_start_pos).length(); //Logger::WriteAndroidInfoLog("time %f ,dist %f",m_one_finger_timer,dist); if(m_one_finger_timer > PRESS_TIMEOUT && dist < Pan_dist ) { m_gesture = GS_Press; m_touch_action_param.gesture = m_gesture; m_touch_action_param.touch_center = m_touch_positions[m_index][down_index]; this->CurrState(State_Press); } else { // if(m_gesture == GS_Pan) // { // //m_touch_action_param.gesture = m_gesture = GS_Pan; // m_touch_action_param.touch_center = m_touch_positions[m_index][down_index]; // m_touch_action_param.move_vec += m_touch_positions[m_index][down_index] - m_one_finger_start_pos; // m_one_finger_start_pos = m_touch_positions[m_index][down_index]; // } // else if (dist>Pan_dist&&m_one_finger_timer>TAP_TIMEOUT) { m_touch_action_param.gesture = m_gesture = GS_Pan; m_touch_action_param.touch_center = m_touch_positions[m_index][down_index]; m_touch_action_param.move_vec = m_touch_positions[m_index][down_index] - m_one_finger_start_pos; m_one_finger_start_pos = m_touch_positions[m_index][down_index]; this->CurrState(State_Pan); } else { m_touch_action_param.gesture = m_gesture = GS_None; } } }break; } /* m_one_finger_timer += elapsed_time; float dist = (m_touch_positions[m_index][0] -m_one_finger_start_pos).length(); if((m_touch_count == 1) &&(m_one_finger_timer > 200) && dist < 5) { m_gesture = GS_Press; m_touch_action_param.gesture= m_gesture; m_touch_action_param.touch_center = m_touch_positions[m_index][0]; } else if(dist > 5) { this->CurrState(State_Pan); }*/ } /* void InputTouch::GestureStateTwoFinger(float elapsed_time) { //Logger::WriteAndroidInfoLog("GestureStateTwoFinger num_touch = %d,elapsed_time = %f",(int)m_touch_count,elapsed_time); switch(m_touch_count) { case 0: case 1: { if(m_gesture != Gs_Rotate && m_gesture != GS_Zoom) { m_touch_action_param.gesture= m_gesture = GS_None; // maybe has some bug } this->CurrState(State_None); }break; //means 0.2 second // if(m_gesture != Gs_Rotate && m_gesture != GS_Zoom) // { // m_touch_action_param.gesture= m_gesture = GS_None; // maybe has some bug // m_touch_action_param.touch_center = m_touch_positions[m_index][0]; // } // this->CurrState(State_Tap); // break; case 2: { // klay distinguish between zoom and rotate ,we didnt process rotate for temporarily m_two_finger_vec = m_touch_positions[m_index][0] - m_touch_positions[m_index][1]; m_two_finger_length = m_two_finger_vec.normalize(); //Vector2 old_vec = m_two_finger_vec; // old_vec.normalize(); float d = m_two_finger_start_vec.dotProduct(m_two_finger_vec); #ifdef ANDROID // LOGE("GestureStateTwoFinger new_vec(%f,%f) = %f,old_vec(%f,%f) = %f,%f",m_two_finger_vec.x,m_two_finger_vec.y,m_two_finger_length,m_two_finger_start_vec.x,m_two_finger_start_vec.y,m_two_finger_start_length,d); #endif if(abs(d) > 0.995) { if(abs(m_two_finger_length - m_two_finger_start_length) > 10) { #ifdef ANDROID // LOGE("Gesturezoom length = %f",m_two_finger_start_length - m_two_finger_start_length); #endif m_touch_action_param.old_length = m_two_finger_start_length; m_touch_action_param.new_length = m_two_finger_length; m_touch_action_param.touch_center = (m_touch_positions[m_index][0] + m_touch_positions[m_index][1])/2.0; // if(m_gesture == GS_Zoom || m_gesture == Gs_Rotate ) // { // m_two_finger_start_length = vec_len; // m_two_finger_vec = m_touch_positions[m_index][0] - m_touch_positions[m_index][1]; // } m_touch_action_param.gesture = m_gesture = GS_Zoom; } else m_touch_action_param.gesture = m_gesture = GS_None; } else { float rotate_angle = -asin(m_two_finger_start_vec.crossProduct(m_two_finger_vec)); #ifdef ANDROID // LOGE("GestureStateRotate rotate_angle = %f",rotate_angle); #endif if(abs(rotate_angle) > 0.01) { m_touch_action_param.touch_center = (m_touch_positions[m_index][0] +m_touch_positions[m_index][1])/2.0; m_touch_action_param.rotate_angle = rotate_angle; // if(m_gesture != GS_Zoom && m_gesture != Gs_Rotate ) // { // m_two_finger_vec = m_touch_positions[m_index][0] - m_touch_positions[m_index][1]; // m_two_finger_start_length = m_two_finger_vec.length(); // } m_touch_action_param.gesture = m_gesture = Gs_Rotate; } else { m_touch_action_param.gesture = m_gesture = GS_None; } } }break; } m_two_finger_timer += elapsed_time; } */ /*void InputTouch::GestureStateZoom(float elapsed_time) { #ifdef ANDROID LOGE("GestureStateZoom num_touch = %d,elapsed_time = %f",m_touch_count,elapsed_time); #endif switch(m_touch_count) { case 0: case 1: this->CurrState(State_None); break; case 2: { float vec_len = (m_touch_positions[m_index][0]- m_touch_positions[m_index][1]).length(); m_gesture = GS_Zoom; #ifdef ANDROID LOGE("Gs_Zoom,start_lenght = %f,new_length= %f",m_two_finger_start_length,vec_len); #endif m_touch_action_param.gesture = m_gesture; m_touch_action_param.touch_center = (m_touch_positions[m_index][0] + m_touch_positions[m_index][1])/2.0; m_touch_action_param.zoom_factor = vec_len/m_two_finger_start_length; m_touch_action_param.old_length = m_two_finger_start_length; m_touch_action_param.new_length = vec_len; m_two_finger_start_length =vec_len; } break; } m_two_finger_timer += elapsed_time; }*/ void InputTouch::GestureStateTwoFinger(float elaped_time) { switch(m_touch_count) { case 0: { m_touch_action_param.gesture = m_gesture = GS_None; this->CurrState(State_None); } break; case 1: { m_touch_action_param.gesture = m_gesture = GS_None; this->CurrState(State_DontHandle); } break; case 2: { m_two_finger_vec = m_touch_positions[m_index][0] - m_touch_positions[m_index][1]; m_two_finger_length = m_two_finger_vec.normalize(); float d = m_two_finger_start_vec.dotProduct(m_two_finger_vec); if(abs(d) > 0.995) { { m_touch_action_param.old_length = m_two_finger_start_length; m_touch_action_param.new_length = m_two_finger_length; m_touch_action_param.touch_center = (m_touch_positions[m_index][0] + m_touch_positions[m_index][1])/2.0; m_touch_action_param.gesture = m_gesture = GS_Zoom; } } else { float rotate_angle = -asin(m_two_finger_start_vec.crossProduct(m_two_finger_vec)); m_touch_action_param.touch_center = (m_touch_positions[m_index][0] +m_touch_positions[m_index][1])/2.0; m_touch_action_param.rotate_angle = rotate_angle; m_touch_action_param.gesture = m_gesture = GS_Rotate; } }break; } } void InputTouch::GestureStatePan(float elaped_time) { //Logger::WriteAndroidInfoLog("GestureStatePan num_touch = %d,elapsed_time = %f ",(int)m_touch_count,elaped_time); switch (m_touch_count) { case 0: { m_touch_action_param.gesture = m_gesture = GS_None; this->CurrState(State_None); } break; case 1: { unsigned int down_index = 0; if (m_touch_downs[m_index][0]) down_index = 0; else down_index = 1; if (m_gesture == GS_Pan) { m_touch_action_param.touch_center = m_touch_positions[m_index][down_index]; m_touch_action_param.move_vec += m_touch_positions[m_index][down_index] - m_one_finger_start_pos; m_one_finger_start_pos = m_touch_positions[m_index][down_index]; } else { m_touch_action_param.gesture = m_gesture = GS_Pan; m_touch_action_param.touch_center = m_touch_positions[m_index][down_index]; m_touch_action_param.move_vec = m_touch_positions[m_index][down_index] - m_one_finger_start_pos; m_one_finger_start_pos = m_touch_positions[m_index][down_index]; } } break; case 2: { m_touch_action_param.gesture = m_gesture = GS_None; if(m_touch_downs[m_index][0] && m_touch_downs[m_index][1]) { // different with klay ,temporaily has no intention to support press and tap this->CurrState(State_TwoFinger); m_two_finger_timer= 0; m_two_finger_start_vec = m_touch_positions[m_index][0] - m_touch_positions[m_index][1]; m_two_finger_start_length = m_two_finger_start_vec.normalize(); } } break; } } void InputTouch::GestureStatePress(float elapsed_time) { //Logger::WriteAndroidInfoLog("GestureStatePress num_touch = %d,elapsed_time = %f ",(int)m_touch_count,elapsed_time); switch (m_touch_count) { case 0: { m_touch_action_param.gesture = m_gesture = GS_None; this->CurrState(State_None); } break; case 1: { unsigned int down_index = 0; if (m_touch_downs[m_index][0]) down_index = 0; else down_index = 1; float dist = (m_touch_positions[m_index][down_index] - m_one_finger_start_pos).length(); if (dist < 15) { m_gesture = GS_Press; m_touch_action_param.gesture = m_gesture; m_touch_action_param.touch_center = m_touch_positions[m_index][down_index]; } else { m_touch_action_param.gesture = m_gesture = GS_Pan; m_touch_action_param.touch_center = m_touch_positions[m_index][down_index]; m_touch_action_param.move_vec = m_touch_positions[m_index][down_index] - m_one_finger_start_pos; m_one_finger_start_pos = m_touch_positions[m_index][down_index]; this->CurrState(State_Pan); } } break; case 2: { m_touch_action_param.gesture = m_gesture = GS_None; if(m_touch_downs[m_index][0] && m_touch_downs[m_index][1]) { // different with klay ,temporaily has no intention to support press and tap this->CurrState(State_TwoFinger); m_two_finger_timer= 0; m_two_finger_start_vec = m_touch_positions[m_index][0] - m_touch_positions[m_index][1]; m_two_finger_start_length = m_two_finger_start_vec.normalize(); } } break; } } void InputTouch::GestureStateDontHandle(float elapsed_time) { //Logger::WriteAndroidInfoLog("GestureStateDontHanle num_touch = %d,elapsed_time = %f ",(int)m_touch_count,elapsed_time); switch (m_touch_count) { case 0: { m_touch_action_param.gesture = m_gesture = GS_None; this->CurrState(State_None); }break; default: break; } } void InputTouch::everyFrameProcessed() { } /*void InputTouch::GestureStateRotate(float elapsed_time) { LOGE("GestureStateRotate num_touch = %d,elapsed_time = %f",m_touch_count,elapsed_time); switch(m_touch_count) { case 0: case 1: this->CurrState(State_None); break; case 2: { Vector2 new_vec= (m_touch_positions[m_index][0] -m_touch_positions[m_index][1]); new_vec.normalize(); Vector2 old_vec = m_two_finger_vec; old_vec.normalize(); float rotate_angle = atan2(old_vec.y,old_vec.x) - atan2(new_vec.y,new_vec.x); LOGE("GestureStateRotate rotate_angle = %f",rotate_angle); if(abs(rotate_angle) > 0.01) { m_two_finger_vec = m_touch_positions[m_index][0] - m_touch_positions[m_index][1]; m_two_finger_start_length = m_two_finger_vec.length(); m_touch_action_param.gesture = m_gesture = Gs_Rotate; m_touch_action_param.touch_center = (m_touch_positions[m_index][0] +m_touch_positions[m_index][1])/2.0; m_touch_action_param.rotate_angle = rotate_angle; } m_two_finger_timer += elapsed_time; }break; } }*/ }
[ "wpwp1992@qq.com" ]
wpwp1992@qq.com
f3062365676bfe2b5fc5c4e13116397d8bc26179
7e4d53b013fd939210ace98d9dcfbfccf1bd0b87
/libraries/SysAPI/src/Version.cpp
33d546fa4261f32afe00d90f1263b847bfa62528
[ "MIT" ]
permissive
erhankur/API
5c0db7c603be88618d1e068175f3909a12a37c7a
1dd2ff4558f66713881584afee14e1def5af7743
refs/heads/master
2023-02-12T00:18:23.459532
2021-01-05T18:02:50
2021-01-05T18:02:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,620
cpp
// Copyright 2011-2021 Tyler Gilbert and Stratify Labs, Inc; see LICENSE.md #include "sys/Version.hpp" using namespace sys; Version Version::from_triple(u16 major, u8 minor, u8 patch) { Version result; result.m_version.format("%d.%d.%d", major, minor, patch); return result; } Version Version::from_u16(u16 major_minor) { Version result; result.m_version.format("%d.%d", major_minor >> 8, major_minor & 0xff); return result; } u32 Version::to_bcd() const { var::StringViewList tokens = m_version.string_view().split("."); if (tokens.count() == 0) { return 0; } if (tokens.count() == 1) { return tokens.at(0).to_unsigned_long(); } if (tokens.count() == 2) { return (tokens.at(0).to_unsigned_long() << 16) | (tokens.at(1).to_unsigned_long() << 8); } return (tokens.at(0).to_unsigned_long() << 16) | (tokens.at(1).to_unsigned_long() << 8) | (tokens.at(2).to_unsigned_long()); } int Version::compare(const Version &a, const Version &b) { var::StringViewList a_tokens = a.m_version.string_view().split("."); var::StringViewList b_tokens = b.m_version.string_view().split("."); if (a_tokens.count() > b_tokens.count()) { return 1; } if (a_tokens.count() < b_tokens.count()) { return -1; } // count is equal -- check the numbers for (u32 i = 0; i < a_tokens.count(); i++) { if (a_tokens.at(i).to_unsigned_long() > b_tokens.at(i).to_unsigned_long()) { return 1; } if (a_tokens.at(i).to_unsigned_long() < b_tokens.at(i).to_unsigned_long()) { return -1; } } // versions are equal return 0; }
[ "tyler.w.gilbert@gmail.com" ]
tyler.w.gilbert@gmail.com
0ef6338a4ac07b6955ec416e85184b04bc0a6c85
a53a11a738828dcafaab5e3edc0e8756af4aceda
/sample/jni/SetBackgroundLogic.h
27649279cd06d5033f72db2f6139fb65a384f52b
[]
no_license
lennonchan/github
7786b82d91502019051b635b151b5d6e7f3a24e7
41dd280bf0d50fccd537a5e8af6e109b82ef5c3a
refs/heads/master
2021-01-20T04:33:27.918278
2013-03-12T09:42:57
2013-03-12T09:42:57
8,724,350
0
1
null
null
null
null
UTF-8
C++
false
false
532
h
#ifndef __SETBACKGROUNDLOGIC__ #define __SETBACKGROUNDLOGIC__ #include "BaseLogic.h" class WallpaperViewImpl; class SetBackgroundLogic : public BaseLogic { public: enum{ ENABLE = 10, }; DECLARE_SOCKET_TYPE(ENABLE, StateSet); SetBackgroundLogic(gkLogicTree* parent, size_t id); ~SetBackgroundLogic(); bool evaluate(gkScalar tick); private: void enterSetBackground(); void quitSetBackground(); void focusMove(); void changeBackground(); private: WallpaperViewImpl * mWallpaperView; bool isSetBackground; }; #endif
[ "qinlong.mkl@gmail.com" ]
qinlong.mkl@gmail.com
d21454740aa6863e40516facabacc60327748594
e8ecc5a25be493d2bed7df4305fa4b9933342d7e
/src/car.h
5d630e82d9a4b45e927b06f2d5ff411f05e2c4a8
[ "MIT" ]
permissive
friedcroc/tizen_spacerace
a3b01ff8797d6664984d2c7ba99706349d508451
08550b8ce4432f502da243522de375b52fdf5925
refs/heads/master
2020-06-05T02:30:25.322206
2018-04-28T21:45:54
2018-04-28T21:56:51
18,323,542
0
1
null
null
null
null
UTF-8
C++
false
false
2,633
h
/* vim: set ai noet ts=4 sw=4 tw=115: */ // // Copyright (c) 2014 FriedCroc Team (admin@friedcroc.com). // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #ifndef __d149337d1114d793c5d2fc18a8521e96__ #define __d149337d1114d793c5d2fc18a8521e96__ #include "game_object.h" #include "waypoints.h" #include "car_parameters.h" #include "car_wheel.h" #include "fixture_info.h" #include "gl-wrappers/gl_texture.h" #include "game-main/key_code.h" #include "box2d/Box2D/Box2D/Box2D.h" #include "tinyxml/tinyxml.h" #include <vector> #include <memory> class Car : public GameObject { public: Car(b2World * world, TiXmlElement * element, const CarParameters & params); ~Car(); inline const CarParameters & parameters() const { return m_Params; } inline b2Body * body() const { return m_Body; } void setWaypoints(Waypoints * waypoints); inline bool atFinish() const { return m_WaypointsIterator.get() && m_WaypointsIterator->atEnd(); } inline const b2Vec2 & wayDirection() const { return m_WayDirection; } void runFrame(const mat4 & proj) override; void onKeyPress(Sys::KeyCode key); void onKeyRelease(Sys::KeyCode key); private: CarParameters m_Params; b2Body * m_Body; b2Vec2 m_WayDirection; Waypoints * m_Waypoints; std::unique_ptr<FixtureInfo> m_FixtureInfo; std::unique_ptr<Waypoints::Iterator> m_WaypointsIterator; std::vector<std::unique_ptr<CarWheel>> m_Wheels; GL::TexturePtr m_Textures[2]; size_t m_TextureIndex; size_t m_TextureChangeTime; float m_Width; float m_Height; bool m_Left; bool m_Right; Car(const Car &) = delete; Car & operator=(const Car &) = delete; }; #endif
[ "zapolnov@gmail.com" ]
zapolnov@gmail.com
cf57fab8b42ad4d6ba9d72cd3ddd94dcd1ca8875
c583a5fd60d8497c82c2864e5dec2d1b0853f3b1
/0112-Path_Sum/main.cpp
5b90386d5c3bf1d1b8678191d816353b5ea838eb
[]
no_license
oliver-zeng/leetcode
401c9455c73cfe198b1d947407596aaa4d61f6fe
d98fbefb9c6fc0dc78da3cfabf7906f3fa712102
refs/heads/master
2020-12-19T19:17:45.522346
2020-06-04T12:25:03
2020-06-04T12:25:03
235,826,235
0
0
null
null
null
null
UTF-8
C++
false
false
898
cpp
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool hasPathSum(TreeNode* root, int sum) { if (!root) return false; if (root->left || root->right) { // 不是叶子,以sum - val的值在子树中判断 // 因为有负数-2 + -3 = -5 // 所以没法通过非叶子节点都值来提前结束 // 因此不做判断,直接在叶子判断即可 //if (root->val >= sum) // return false; return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val); } else { // 是叶子,判断sum if (root->val == sum) return true; return false; } } };
[ "964994927@qq.com" ]
964994927@qq.com
ffa0298eb6c4ead09816e7887070390cd1d84469
493ee99fd9c5a2aab24f2746ffbf69901c9f5e99
/Game.h
fff19902c0b4774568c0b0539ae669e7e5f2f0b1
[]
no_license
bmckalip/Threes
bbc597b091b95c4d8187cff180d5b70c01507dd2
f903485fd312ff513607b8bcc126ed867d543921
refs/heads/master
2021-01-09T20:39:12.377817
2016-07-14T21:21:17
2016-07-14T21:21:17
62,861,754
0
0
null
null
null
null
UTF-8
C++
false
false
561
h
#include "State.h" #include <vector> #pragma once using namespace std; class Game { public: Game(int[]); //constructor int play(); private: //object functions void printState(); void playerTurn(); void AITurn(); void checkForWinner(); pair<int, int> validateInput(pair<int, int>); bool IsInBounds(int value, int low, int high); void rigGame(); //object variables State currentState; int winner; //static member variables const static pair<int, int> INVALID_MOVE; const static bool ID_AI; const static bool ID_PLAYER; };
[ "brmckalip@gmail.com" ]
brmckalip@gmail.com
967c0be5d0ac6e0fb4550118530d585d5989989d
b0dd7779c225971e71ae12c1093dc75ed9889921
/libs/thread/test/sync/mutual_exclusion/locks/reverse_lock/copy_ctor_fail.cpp
18186249b045fa31f104a2426fe1cb9b907ff482
[ "LicenseRef-scancode-warranty-disclaimer", "BSL-1.0" ]
permissive
blackberry/Boost
6e653cd91a7806855a162347a5aeebd2a8c055a2
fc90c3fde129c62565c023f091eddc4a7ed9902b
refs/heads/1_48_0-gnu
2021-01-15T14:31:33.706351
2013-06-25T16:02:41
2013-06-25T16:02:41
2,599,411
244
154
BSL-1.0
2018-10-13T18:35:09
2011-10-18T14:25:18
C++
UTF-8
C++
false
false
839
cpp
// Copyright (C) 2012 Vicente J. Botet Escriba // // 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) // <boost/thread/locks.hpp> // template <class Mutex> class reverse_lock; // reverse_lock(reverse_lock const&) = delete; #include <boost/thread/locks.hpp> #include <boost/thread/reverse_lock.hpp> #include <boost/thread/mutex.hpp> #include <boost/detail/lightweight_test.hpp> boost::mutex m0; boost::mutex m1; int main() { boost::mutex m0; boost::unique_lock<boost::mutex> lk0(m0); { boost::reverse_lock<boost::unique_lock<boost::mutex> > lg0(lk0); boost::reverse_lock<boost::unique_lock<boost::mutex> > lg1(lg0); } } #include "../../../../remove_error_code_unused_warning.hpp"
[ "tvaneerd@rim.com" ]
tvaneerd@rim.com
f69ceefd764763c3a5412ac9c724ed7ef41999a2
1004f09987beda628ccf9b37817249a5e9d52b85
/engine/src/math/math.cxx
afba308165753cb09324f02d67dc0d818801a91d
[ "MIT" ]
permissive
Alabuta/VulkanIsland
195c97539c8b435ef81dea7ed0a1135b7d2683f3
eb22357be76df1b071d2dfedf798681f28044d6e
refs/heads/master
2023-08-09T05:22:55.834631
2023-07-25T16:59:05
2023-07-25T16:59:05
120,170,226
0
1
null
null
null
null
UTF-8
C++
false
false
456
cxx
#include "math.hxx" namespace math { glm::mat4 reversed_perspective(float vertical_fov, float aspect, float znear, float zfar) { auto const f = 1.f / std::tan(vertical_fov * .5f); auto const A = zfar / (zfar - znear) - 1.f; auto const B = zfar * znear / (zfar - znear); return glm::mat4{ f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, A, -1, 0, 0, B, 0 }; } }
[ "auqolaq@gmail.com" ]
auqolaq@gmail.com
2d05a670334606eaf136232e594f2603fa2dd3ba
f8bdd34a5a14910a4676357fff4514ba7a61eb9e
/cocos2dx.demos/TSTPROTOBUF/Classes/google/protobuf/text_format.cc
eda940d0cd77dad7da8a3f99b32b1a43d2be6038
[]
no_license
fU9ANg/GLdemos
89800e51d49c8654b7ea26e551511e26d498fd6b
c3200482f90fe68169f5b13710d4b215b2ba30c1
refs/heads/master
2021-01-02T22:39:04.415450
2014-07-15T08:18:32
2014-07-15T08:18:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
49,733
cc
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://code.google.com/p/protobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Author: jschorr@google.com (Joseph Schorr) // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. #include <float.h> #include <math.h> #include <stdio.h> #include <stack> #include <limits> #include <vector> #include <text_format.h> #include <descriptor.h> #include <io/coded_stream.h> #include <io/zero_copy_stream.h> #include <io/zero_copy_stream_impl.h> #include <unknown_field_set.h> #include <descriptor.pb.h> #include <io/tokenizer.h> #include <stubs/strutil.h> #include <stubs/map-util.h> #include <stubs/stl_util.h> namespace google { namespace protobuf { string Message::DebugString() const { string debug_string; TextFormat::PrintToString(*this, &debug_string); return debug_string; } string Message::ShortDebugString() const { string debug_string; TextFormat::Printer printer; printer.SetSingleLineMode(true); printer.PrintToString(*this, &debug_string); // Single line mode currently might have an extra space at the end. if (debug_string.size() > 0 && debug_string[debug_string.size() - 1] == ' ') { debug_string.resize(debug_string.size() - 1); } return debug_string; } string Message::Utf8DebugString() const { string debug_string; TextFormat::Printer printer; printer.SetUseUtf8StringEscaping(true); printer.PrintToString(*this, &debug_string); return debug_string; } void Message::PrintDebugString() const { printf("%s", DebugString().c_str()); } // =========================================================================== // Implementation of the parse information tree class. TextFormat::ParseInfoTree::ParseInfoTree() { } TextFormat::ParseInfoTree::~ParseInfoTree() { // Remove any nested information trees, as they are owned by this tree. for (NestedMap::iterator it = nested_.begin(); it != nested_.end(); ++it) { STLDeleteElements(&(it->second)); } } void TextFormat::ParseInfoTree::RecordLocation( const FieldDescriptor* field, TextFormat::ParseLocation location) { locations_[field].push_back(location); } TextFormat::ParseInfoTree* TextFormat::ParseInfoTree::CreateNested( const FieldDescriptor* field) { // Owned by us in the map. TextFormat::ParseInfoTree* instance = new TextFormat::ParseInfoTree(); vector<TextFormat::ParseInfoTree*>* trees = &nested_[field]; GOOGLE_CHECK(trees); trees->push_back(instance); return instance; } void CheckFieldIndex(const FieldDescriptor* field, int index) { if (field == NULL) { return; } if (field->is_repeated() && index == -1) { GOOGLE_LOG(DFATAL) << "Index must be in range of repeated field values. " << "Field: " << field->name(); } else if (!field->is_repeated() && index != -1) { GOOGLE_LOG(DFATAL) << "Index must be -1 for singular fields." << "Field: " << field->name(); } } TextFormat::ParseLocation TextFormat::ParseInfoTree::GetLocation( const FieldDescriptor* field, int index) const { CheckFieldIndex(field, index); if (index == -1) { index = 0; } const vector<TextFormat::ParseLocation>* locations = FindOrNull(locations_, field); if (locations == NULL || index >= locations->size()) { return TextFormat::ParseLocation(); } return (*locations)[index]; } TextFormat::ParseInfoTree* TextFormat::ParseInfoTree::GetTreeForNested( const FieldDescriptor* field, int index) const { CheckFieldIndex(field, index); if (index == -1) { index = 0; } const vector<TextFormat::ParseInfoTree*>* trees = FindOrNull(nested_, field); if (trees == NULL || index >= trees->size()) { return NULL; } return (*trees)[index]; } // =========================================================================== // Internal class for parsing an ASCII representation of a Protocol Message. // This class makes use of the Protocol Message compiler's tokenizer found // in //google/protobuf/io/tokenizer.h. Note that class's Parse // method is *not* thread-safe and should only be used in a single thread at // a time. // Makes code slightly more readable. The meaning of "DO(foo)" is // "Execute foo and fail if it fails.", where failure is indicated by // returning false. Borrowed from parser.cc (Thanks Kenton!). #define DO(STATEMENT) if (STATEMENT) {} else return false class TextFormat::Parser::ParserImpl { public: // Determines if repeated values for a non-repeated field are // permitted, e.g., the string "foo: 1 foo: 2" for a // required/optional field named "foo". enum SingularOverwritePolicy { ALLOW_SINGULAR_OVERWRITES = 0, // the last value is retained FORBID_SINGULAR_OVERWRITES = 1, // an error is issued }; ParserImpl(const Descriptor* root_message_type, io::ZeroCopyInputStream* input_stream, io::ErrorCollector* error_collector, TextFormat::Finder* finder, ParseInfoTree* parse_info_tree, SingularOverwritePolicy singular_overwrite_policy, bool allow_unknown_field) : error_collector_(error_collector), finder_(finder), parse_info_tree_(parse_info_tree), tokenizer_error_collector_(this), tokenizer_(input_stream, &tokenizer_error_collector_), root_message_type_(root_message_type), singular_overwrite_policy_(singular_overwrite_policy), allow_unknown_field_(allow_unknown_field), had_errors_(false) { // For backwards-compatibility with proto1, we need to allow the 'f' suffix // for floats. tokenizer_.set_allow_f_after_float(true); // '#' starts a comment. tokenizer_.set_comment_style(io::Tokenizer::SH_COMMENT_STYLE); // Consume the starting token. tokenizer_.Next(); } ~ParserImpl() { } // Parses the ASCII representation specified in input and saves the // information into the output pointer (a Message). Returns // false if an error occurs (an error will also be logged to // GOOGLE_LOG(ERROR)). bool Parse(Message* output) { // Consume fields until we cannot do so anymore. while(true) { if (LookingAtType(io::Tokenizer::TYPE_END)) { return !had_errors_; } DO(ConsumeField(output)); } } bool ParseField(const FieldDescriptor* field, Message* output) { bool suc; if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { suc = ConsumeFieldMessage(output, output->GetReflection(), field); } else { suc = ConsumeFieldValue(output, output->GetReflection(), field); } return suc && LookingAtType(io::Tokenizer::TYPE_END); } void ReportError(int line, int col, const string& message) { had_errors_ = true; if (error_collector_ == NULL) { if (line >= 0) { GOOGLE_LOG(ERROR) << "Error parsing text-format " << root_message_type_->full_name() << ": " << (line + 1) << ":" << (col + 1) << ": " << message; } else { GOOGLE_LOG(ERROR) << "Error parsing text-format " << root_message_type_->full_name() << ": " << message; } } else { error_collector_->AddError(line, col, message); } } void ReportWarning(int line, int col, const string& message) { if (error_collector_ == NULL) { if (line >= 0) { GOOGLE_LOG(WARNING) << "Warning parsing text-format " << root_message_type_->full_name() << ": " << (line + 1) << ":" << (col + 1) << ": " << message; } else { GOOGLE_LOG(WARNING) << "Warning parsing text-format " << root_message_type_->full_name() << ": " << message; } } else { error_collector_->AddWarning(line, col, message); } } private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ParserImpl); // Reports an error with the given message with information indicating // the position (as derived from the current token). void ReportError(const string& message) { ReportError(tokenizer_.current().line, tokenizer_.current().column, message); } // Reports a warning with the given message with information indicating // the position (as derived from the current token). void ReportWarning(const string& message) { ReportWarning(tokenizer_.current().line, tokenizer_.current().column, message); } // Consumes the specified message with the given starting delimeter. // This method checks to see that the end delimeter at the conclusion of // the consumption matches the starting delimeter passed in here. bool ConsumeMessage(Message* message, const string delimeter) { while (!LookingAt(">") && !LookingAt("}")) { DO(ConsumeField(message)); } // Confirm that we have a valid ending delimeter. DO(Consume(delimeter)); return true; } // Consumes the current field (as returned by the tokenizer) on the // passed in message. bool ConsumeField(Message* message) { const Reflection* reflection = message->GetReflection(); const Descriptor* descriptor = message->GetDescriptor(); string field_name; const FieldDescriptor* field = NULL; int start_line = tokenizer_.current().line; int start_column = tokenizer_.current().column; if (TryConsume("[")) { // Extension. DO(ConsumeIdentifier(&field_name)); while (TryConsume(".")) { string part; DO(ConsumeIdentifier(&part)); field_name += "."; field_name += part; } DO(Consume("]")); field = (finder_ != NULL ? finder_->FindExtension(message, field_name) : reflection->FindKnownExtensionByName(field_name)); if (field == NULL) { if (!allow_unknown_field_) { ReportError("Extension \"" + field_name + "\" is not defined or " "is not an extension of \"" + descriptor->full_name() + "\"."); return false; } else { ReportWarning("Extension \"" + field_name + "\" is not defined or " "is not an extension of \"" + descriptor->full_name() + "\"."); } } } else { DO(ConsumeIdentifier(&field_name)); field = descriptor->FindFieldByName(field_name); // Group names are expected to be capitalized as they appear in the // .proto file, which actually matches their type names, not their field // names. if (field == NULL) { string lower_field_name = field_name; LowerString(&lower_field_name); field = descriptor->FindFieldByName(lower_field_name); // If the case-insensitive match worked but the field is NOT a group, if (field != NULL && field->type() != FieldDescriptor::TYPE_GROUP) { field = NULL; } } // Again, special-case group names as described above. if (field != NULL && field->type() == FieldDescriptor::TYPE_GROUP && field->message_type()->name() != field_name) { field = NULL; } if (field == NULL) { if (!allow_unknown_field_) { ReportError("Message type \"" + descriptor->full_name() + "\" has no field named \"" + field_name + "\"."); return false; } else { ReportWarning("Message type \"" + descriptor->full_name() + "\" has no field named \"" + field_name + "\"."); } } } // Skips unknown field. if (field == NULL) { GOOGLE_CHECK(allow_unknown_field_); // Try to guess the type of this field. // If this field is not a message, there should be a ":" between the // field name and the field value and also the field value should not // start with "{" or "<" which indicates the begining of a message body. // If there is no ":" or there is a "{" or "<" after ":", this field has // to be a message or the input is ill-formed. if (TryConsume(":") && !LookingAt("{") && !LookingAt("<")) { return SkipFieldValue(); } else { return SkipFieldMessage(); } } // Fail if the field is not repeated and it has already been specified. if ((singular_overwrite_policy_ == FORBID_SINGULAR_OVERWRITES) && !field->is_repeated() && reflection->HasField(*message, field)) { ReportError("Non-repeated field \"" + field_name + "\" is specified multiple times."); return false; } // Perform special handling for embedded message types. if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { // ':' is optional here. TryConsume(":"); DO(ConsumeFieldMessage(message, reflection, field)); } else { DO(Consume(":")); if (field->is_repeated() && TryConsume("[")) { // Short repeated format, e.g. "foo: [1, 2, 3]" while (true) { DO(ConsumeFieldValue(message, reflection, field)); if (TryConsume("]")) { break; } DO(Consume(",")); } } else { DO(ConsumeFieldValue(message, reflection, field)); } } // For historical reasons, fields may optionally be separated by commas or // semicolons. TryConsume(";") || TryConsume(","); if (field->options().deprecated()) { ReportWarning("text format contains deprecated field \"" + field_name + "\""); } // If a parse info tree exists, add the location for the parsed // field. if (parse_info_tree_ != NULL) { RecordLocation(parse_info_tree_, field, ParseLocation(start_line, start_column)); } return true; } // Skips the next field including the field's name and value. bool SkipField() { string field_name; if (TryConsume("[")) { // Extension name. DO(ConsumeIdentifier(&field_name)); while (TryConsume(".")) { string part; DO(ConsumeIdentifier(&part)); field_name += "."; field_name += part; } DO(Consume("]")); } else { DO(ConsumeIdentifier(&field_name)); } // Try to guess the type of this field. // If this field is not a message, there should be a ":" between the // field name and the field value and also the field value should not // start with "{" or "<" which indicates the begining of a message body. // If there is no ":" or there is a "{" or "<" after ":", this field has // to be a message or the input is ill-formed. if (TryConsume(":") && !LookingAt("{") && !LookingAt("<")) { DO(SkipFieldValue()); } else { DO(SkipFieldMessage()); } // For historical reasons, fields may optionally be separated by commas or // semicolons. TryConsume(";") || TryConsume(","); return true; } bool ConsumeFieldMessage(Message* message, const Reflection* reflection, const FieldDescriptor* field) { // If the parse information tree is not NULL, create a nested one // for the nested message. ParseInfoTree* parent = parse_info_tree_; if (parent != NULL) { parse_info_tree_ = CreateNested(parent, field); } string delimeter; if (TryConsume("<")) { delimeter = ">"; } else { DO(Consume("{")); delimeter = "}"; } if (field->is_repeated()) { DO(ConsumeMessage(reflection->AddMessage(message, field), delimeter)); } else { DO(ConsumeMessage(reflection->MutableMessage(message, field), delimeter)); } // Reset the parse information tree. parse_info_tree_ = parent; return true; } // Skips the whole body of a message including the begining delimeter and // the ending delimeter. bool SkipFieldMessage() { string delimeter; if (TryConsume("<")) { delimeter = ">"; } else { DO(Consume("{")); delimeter = "}"; } while (!LookingAt(">") && !LookingAt("}")) { DO(SkipField()); } DO(Consume(delimeter)); return true; } bool ConsumeFieldValue(Message* message, const Reflection* reflection, const FieldDescriptor* field) { // Define an easy to use macro for setting fields. This macro checks // to see if the field is repeated (in which case we need to use the Add // methods or not (in which case we need to use the Set methods). #define SET_FIELD(CPPTYPE, VALUE) \ if (field->is_repeated()) { \ reflection->Add##CPPTYPE(message, field, VALUE); \ } else { \ reflection->Set##CPPTYPE(message, field, VALUE); \ } \ switch(field->cpp_type()) { case FieldDescriptor::CPPTYPE_INT32: { int64 value; DO(ConsumeSignedInteger(&value, kint32max)); SET_FIELD(Int32, static_cast<int32>(value)); break; } case FieldDescriptor::CPPTYPE_UINT32: { uint64 value; DO(ConsumeUnsignedInteger(&value, kuint32max)); SET_FIELD(UInt32, static_cast<uint32>(value)); break; } case FieldDescriptor::CPPTYPE_INT64: { int64 value; DO(ConsumeSignedInteger(&value, kint64max)); SET_FIELD(Int64, value); break; } case FieldDescriptor::CPPTYPE_UINT64: { uint64 value; DO(ConsumeUnsignedInteger(&value, kuint64max)); SET_FIELD(UInt64, value); break; } case FieldDescriptor::CPPTYPE_FLOAT: { double value; DO(ConsumeDouble(&value)); SET_FIELD(Float, static_cast<float>(value)); break; } case FieldDescriptor::CPPTYPE_DOUBLE: { double value; DO(ConsumeDouble(&value)); SET_FIELD(Double, value); break; } case FieldDescriptor::CPPTYPE_STRING: { string value; DO(ConsumeString(&value)); SET_FIELD(String, value); break; } case FieldDescriptor::CPPTYPE_BOOL: { if (LookingAtType(io::Tokenizer::TYPE_INTEGER)) { uint64 value; DO(ConsumeUnsignedInteger(&value, 1)); SET_FIELD(Bool, value); } else { string value; DO(ConsumeIdentifier(&value)); if (value == "true" || value == "t") { SET_FIELD(Bool, true); } else if (value == "false" || value == "f") { SET_FIELD(Bool, false); } else { ReportError("Invalid value for boolean field \"" + field->name() + "\". Value: \"" + value + "\"."); return false; } } break; } case FieldDescriptor::CPPTYPE_ENUM: { string value; const EnumDescriptor* enum_type = field->enum_type(); const EnumValueDescriptor* enum_value = NULL; if (LookingAtType(io::Tokenizer::TYPE_IDENTIFIER)) { DO(ConsumeIdentifier(&value)); // Find the enumeration value. enum_value = enum_type->FindValueByName(value); } else if (LookingAt("-") || LookingAtType(io::Tokenizer::TYPE_INTEGER)) { int64 int_value; DO(ConsumeSignedInteger(&int_value, kint32max)); value = SimpleItoa(int_value); // for error reporting enum_value = enum_type->FindValueByNumber(int_value); } else { ReportError("Expected integer or identifier."); return false; } if (enum_value == NULL) { ReportError("Unknown enumeration value of \"" + value + "\" for " "field \"" + field->name() + "\"."); return false; } SET_FIELD(Enum, enum_value); break; } case FieldDescriptor::CPPTYPE_MESSAGE: { // We should never get here. Put here instead of a default // so that if new types are added, we get a nice compiler warning. GOOGLE_LOG(FATAL) << "Reached an unintended state: CPPTYPE_MESSAGE"; break; } } #undef SET_FIELD return true; } bool SkipFieldValue() { if (LookingAtType(io::Tokenizer::TYPE_STRING)) { while (LookingAtType(io::Tokenizer::TYPE_STRING)) { tokenizer_.Next(); } return true; } // Possible field values other than string: // 12345 => TYPE_INTEGER // -12345 => TYPE_SYMBOL + TYPE_INTEGER // 1.2345 => TYPE_FLOAT // -1.2345 => TYPE_SYMBOL + TYPE_FLOAT // inf => TYPE_IDENTIFIER // -inf => TYPE_SYMBOL + TYPE_IDENTIFIER // TYPE_INTEGER => TYPE_IDENTIFIER // Divides them into two group, one with TYPE_SYMBOL // and the other without: // Group one: // 12345 => TYPE_INTEGER // 1.2345 => TYPE_FLOAT // inf => TYPE_IDENTIFIER // TYPE_INTEGER => TYPE_IDENTIFIER // Group two: // -12345 => TYPE_SYMBOL + TYPE_INTEGER // -1.2345 => TYPE_SYMBOL + TYPE_FLOAT // -inf => TYPE_SYMBOL + TYPE_IDENTIFIER // As we can see, the field value consists of an optional '-' and one of // TYPE_INTEGER, TYPE_FLOAT and TYPE_IDENTIFIER. bool has_minus = TryConsume("-"); if (!LookingAtType(io::Tokenizer::TYPE_INTEGER) && !LookingAtType(io::Tokenizer::TYPE_FLOAT) && !LookingAtType(io::Tokenizer::TYPE_IDENTIFIER)) { return false; } // Combination of '-' and TYPE_IDENTIFIER may result in an invalid field // value while other combinations all generate valid values. // We check if the value of this combination is valid here. // TYPE_IDENTIFIER after a '-' should be one of the float values listed // below: // inf, inff, infinity, nan if (has_minus && LookingAtType(io::Tokenizer::TYPE_IDENTIFIER)) { string text = tokenizer_.current().text; LowerString(&text); if (text != "inf" && text != "infinity" && text != "nan") { ReportError("Invalid float number: " + text); return false; } } tokenizer_.Next(); return true; } // Returns true if the current token's text is equal to that specified. bool LookingAt(const string& text) { return tokenizer_.current().text == text; } // Returns true if the current token's type is equal to that specified. bool LookingAtType(io::Tokenizer::TokenType token_type) { return tokenizer_.current().type == token_type; } // Consumes an identifier and saves its value in the identifier parameter. // Returns false if the token is not of type IDENTFIER. bool ConsumeIdentifier(string* identifier) { if (!LookingAtType(io::Tokenizer::TYPE_IDENTIFIER)) { ReportError("Expected identifier."); return false; } *identifier = tokenizer_.current().text; tokenizer_.Next(); return true; } // Consumes a string and saves its value in the text parameter. // Returns false if the token is not of type STRING. bool ConsumeString(string* text) { if (!LookingAtType(io::Tokenizer::TYPE_STRING)) { ReportError("Expected string."); return false; } text->clear(); while (LookingAtType(io::Tokenizer::TYPE_STRING)) { io::Tokenizer::ParseStringAppend(tokenizer_.current().text, text); tokenizer_.Next(); } return true; } // Consumes a uint64 and saves its value in the value parameter. // Returns false if the token is not of type INTEGER. bool ConsumeUnsignedInteger(uint64* value, uint64 max_value) { if (!LookingAtType(io::Tokenizer::TYPE_INTEGER)) { ReportError("Expected integer."); return false; } if (!io::Tokenizer::ParseInteger(tokenizer_.current().text, max_value, value)) { ReportError("Integer out of range."); return false; } tokenizer_.Next(); return true; } // Consumes an int64 and saves its value in the value parameter. // Note that since the tokenizer does not support negative numbers, // we actually may consume an additional token (for the minus sign) in this // method. Returns false if the token is not an integer // (signed or otherwise). bool ConsumeSignedInteger(int64* value, uint64 max_value) { bool negative = false; if (TryConsume("-")) { negative = true; // Two's complement always allows one more negative integer than // positive. ++max_value; } uint64 unsigned_value; DO(ConsumeUnsignedInteger(&unsigned_value, max_value)); *value = static_cast<int64>(unsigned_value); if (negative) { *value = -*value; } return true; } // Consumes a double and saves its value in the value parameter. // Note that since the tokenizer does not support negative numbers, // we actually may consume an additional token (for the minus sign) in this // method. Returns false if the token is not a double // (signed or otherwise). bool ConsumeDouble(double* value) { bool negative = false; if (TryConsume("-")) { negative = true; } // A double can actually be an integer, according to the tokenizer. // Therefore, we must check both cases here. if (LookingAtType(io::Tokenizer::TYPE_INTEGER)) { // We have found an integer value for the double. uint64 integer_value; DO(ConsumeUnsignedInteger(&integer_value, kuint64max)); *value = static_cast<double>(integer_value); } else if (LookingAtType(io::Tokenizer::TYPE_FLOAT)) { // We have found a float value for the double. *value = io::Tokenizer::ParseFloat(tokenizer_.current().text); // Mark the current token as consumed. tokenizer_.Next(); } else if (LookingAtType(io::Tokenizer::TYPE_IDENTIFIER)) { string text = tokenizer_.current().text; LowerString(&text); if (text == "inf" || text == "infinity") { *value = std::numeric_limits<double>::infinity(); tokenizer_.Next(); } else if (text == "nan") { *value = std::numeric_limits<double>::quiet_NaN(); tokenizer_.Next(); } else { ReportError("Expected double."); return false; } } else { ReportError("Expected double."); return false; } if (negative) { *value = -*value; } return true; } // Consumes a token and confirms that it matches that specified in the // value parameter. Returns false if the token found does not match that // which was specified. bool Consume(const string& value) { const string& current_value = tokenizer_.current().text; if (current_value != value) { ReportError("Expected \"" + value + "\", found \"" + current_value + "\"."); return false; } tokenizer_.Next(); return true; } // Attempts to consume the supplied value. Returns false if a the // token found does not match the value specified. bool TryConsume(const string& value) { if (tokenizer_.current().text == value) { tokenizer_.Next(); return true; } else { return false; } } // An internal instance of the Tokenizer's error collector, used to // collect any base-level parse errors and feed them to the ParserImpl. class ParserErrorCollector : public io::ErrorCollector { public: explicit ParserErrorCollector(TextFormat::Parser::ParserImpl* parser) : parser_(parser) { } virtual ~ParserErrorCollector() { }; virtual void AddError(int line, int column, const string& message) { parser_->ReportError(line, column, message); } virtual void AddWarning(int line, int column, const string& message) { parser_->ReportWarning(line, column, message); } private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ParserErrorCollector); TextFormat::Parser::ParserImpl* parser_; }; io::ErrorCollector* error_collector_; TextFormat::Finder* finder_; ParseInfoTree* parse_info_tree_; ParserErrorCollector tokenizer_error_collector_; io::Tokenizer tokenizer_; const Descriptor* root_message_type_; SingularOverwritePolicy singular_overwrite_policy_; bool allow_unknown_field_; bool had_errors_; }; #undef DO // =========================================================================== // Internal class for writing text to the io::ZeroCopyOutputStream. Adapted // from the Printer found in //google/protobuf/io/printer.h class TextFormat::Printer::TextGenerator { public: explicit TextGenerator(io::ZeroCopyOutputStream* output, int initial_indent_level) : output_(output), buffer_(NULL), buffer_size_(0), at_start_of_line_(true), failed_(false), indent_(""), initial_indent_level_(initial_indent_level) { indent_.resize(initial_indent_level_ * 2, ' '); } ~TextGenerator() { // Only BackUp() if we're sure we've successfully called Next() at least // once. if (!failed_ && buffer_size_ > 0) { output_->BackUp(buffer_size_); } } // Indent text by two spaces. After calling Indent(), two spaces will be // inserted at the beginning of each line of text. Indent() may be called // multiple times to produce deeper indents. void Indent() { indent_ += " "; } // Reduces the current indent level by two spaces, or crashes if the indent // level is zero. void Outdent() { if (indent_.empty() || indent_.size() < initial_indent_level_ * 2) { GOOGLE_LOG(DFATAL) << " Outdent() without matching Indent()."; return; } indent_.resize(indent_.size() - 2); } // Print text to the output stream. void Print(const string& str) { Print(str.data(), str.size()); } // Print text to the output stream. void Print(const char* text) { Print(text, strlen(text)); } // Print text to the output stream. void Print(const char* text, int size) { int pos = 0; // The number of bytes we've written so far. for (int i = 0; i < size; i++) { if (text[i] == '\n') { // Saw newline. If there is more text, we may need to insert an indent // here. So, write what we have so far, including the '\n'. Write(text + pos, i - pos + 1); pos = i + 1; // Setting this true will cause the next Write() to insert an indent // first. at_start_of_line_ = true; } } // Write the rest. Write(text + pos, size - pos); } // True if any write to the underlying stream failed. (We don't just // crash in this case because this is an I/O failure, not a programming // error.) bool failed() const { return failed_; } private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TextGenerator); void Write(const char* data, int size) { if (failed_) return; if (size == 0) return; if (at_start_of_line_) { // Insert an indent. at_start_of_line_ = false; Write(indent_.data(), indent_.size()); if (failed_) return; } while (size > buffer_size_) { // Data exceeds space in the buffer. Copy what we can and request a // new buffer. memcpy(buffer_, data, buffer_size_); data += buffer_size_; size -= buffer_size_; void* void_buffer; failed_ = !output_->Next(&void_buffer, &buffer_size_); if (failed_) return; buffer_ = reinterpret_cast<char*>(void_buffer); } // Buffer is big enough to receive the data; copy it. memcpy(buffer_, data, size); buffer_ += size; buffer_size_ -= size; } io::ZeroCopyOutputStream* const output_; char* buffer_; int buffer_size_; bool at_start_of_line_; bool failed_; string indent_; int initial_indent_level_; }; // =========================================================================== TextFormat::Finder::~Finder() { } TextFormat::Parser::Parser() : error_collector_(NULL), finder_(NULL), parse_info_tree_(NULL), allow_partial_(false), allow_unknown_field_(false) { } TextFormat::Parser::~Parser() {} bool TextFormat::Parser::Parse(io::ZeroCopyInputStream* input, Message* output) { output->Clear(); ParserImpl parser(output->GetDescriptor(), input, error_collector_, finder_, parse_info_tree_, ParserImpl::FORBID_SINGULAR_OVERWRITES, allow_unknown_field_); return MergeUsingImpl(input, output, &parser); } bool TextFormat::Parser::ParseFromString(const string& input, Message* output) { io::ArrayInputStream input_stream(input.data(), input.size()); return Parse(&input_stream, output); } bool TextFormat::Parser::Merge(io::ZeroCopyInputStream* input, Message* output) { ParserImpl parser(output->GetDescriptor(), input, error_collector_, finder_, parse_info_tree_, ParserImpl::ALLOW_SINGULAR_OVERWRITES, allow_unknown_field_); return MergeUsingImpl(input, output, &parser); } bool TextFormat::Parser::MergeFromString(const string& input, Message* output) { io::ArrayInputStream input_stream(input.data(), input.size()); return Merge(&input_stream, output); } bool TextFormat::Parser::MergeUsingImpl(io::ZeroCopyInputStream* input, Message* output, ParserImpl* parser_impl) { if (!parser_impl->Parse(output)) return false; if (!allow_partial_ && !output->IsInitialized()) { vector<string> missing_fields; output->FindInitializationErrors(&missing_fields); parser_impl->ReportError(-1, 0, "Message missing required fields: " + JoinStrings(missing_fields, ", ")); return false; } return true; } bool TextFormat::Parser::ParseFieldValueFromString( const string& input, const FieldDescriptor* field, Message* output) { io::ArrayInputStream input_stream(input.data(), input.size()); ParserImpl parser(output->GetDescriptor(), &input_stream, error_collector_, finder_, parse_info_tree_, ParserImpl::ALLOW_SINGULAR_OVERWRITES, allow_unknown_field_); return parser.ParseField(field, output); } /* static */ bool TextFormat::Parse(io::ZeroCopyInputStream* input, Message* output) { return Parser().Parse(input, output); } /* static */ bool TextFormat::Merge(io::ZeroCopyInputStream* input, Message* output) { return Parser().Merge(input, output); } /* static */ bool TextFormat::ParseFromString(const string& input, Message* output) { return Parser().ParseFromString(input, output); } /* static */ bool TextFormat::MergeFromString(const string& input, Message* output) { return Parser().MergeFromString(input, output); } // =========================================================================== TextFormat::Printer::Printer() : initial_indent_level_(0), single_line_mode_(false), use_short_repeated_primitives_(false), utf8_string_escaping_(false) {} TextFormat::Printer::~Printer() {} bool TextFormat::Printer::PrintToString(const Message& message, string* output) const { GOOGLE_DCHECK(output) << "output specified is NULL"; output->clear(); io::StringOutputStream output_stream(output); bool result = Print(message, &output_stream); return result; } bool TextFormat::Printer::PrintUnknownFieldsToString( const UnknownFieldSet& unknown_fields, string* output) const { GOOGLE_DCHECK(output) << "output specified is NULL"; output->clear(); io::StringOutputStream output_stream(output); return PrintUnknownFields(unknown_fields, &output_stream); } bool TextFormat::Printer::Print(const Message& message, io::ZeroCopyOutputStream* output) const { TextGenerator generator(output, initial_indent_level_); Print(message, generator); // Output false if the generator failed internally. return !generator.failed(); } bool TextFormat::Printer::PrintUnknownFields( const UnknownFieldSet& unknown_fields, io::ZeroCopyOutputStream* output) const { TextGenerator generator(output, initial_indent_level_); PrintUnknownFields(unknown_fields, generator); // Output false if the generator failed internally. return !generator.failed(); } void TextFormat::Printer::Print(const Message& message, TextGenerator& generator) const { const Reflection* reflection = message.GetReflection(); vector<const FieldDescriptor*> fields; reflection->ListFields(message, &fields); for (int i = 0; i < fields.size(); i++) { PrintField(message, reflection, fields[i], generator); } PrintUnknownFields(reflection->GetUnknownFields(message), generator); } void TextFormat::Printer::PrintFieldValueToString( const Message& message, const FieldDescriptor* field, int index, string* output) const { GOOGLE_DCHECK(output) << "output specified is NULL"; output->clear(); io::StringOutputStream output_stream(output); TextGenerator generator(&output_stream, initial_indent_level_); PrintFieldValue(message, message.GetReflection(), field, index, generator); } void TextFormat::Printer::PrintField(const Message& message, const Reflection* reflection, const FieldDescriptor* field, TextGenerator& generator) const { if (use_short_repeated_primitives_ && field->is_repeated() && field->cpp_type() != FieldDescriptor::CPPTYPE_STRING && field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) { PrintShortRepeatedField(message, reflection, field, generator); return; } int count = 0; if (field->is_repeated()) { count = reflection->FieldSize(message, field); } else if (reflection->HasField(message, field)) { count = 1; } for (int j = 0; j < count; ++j) { PrintFieldName(message, reflection, field, generator); if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { if (single_line_mode_) { generator.Print(" { "); } else { generator.Print(" {\n"); generator.Indent(); } } else { generator.Print(": "); } // Write the field value. int field_index = j; if (!field->is_repeated()) { field_index = -1; } PrintFieldValue(message, reflection, field, field_index, generator); if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { if (single_line_mode_) { generator.Print("} "); } else { generator.Outdent(); generator.Print("}\n"); } } else { if (single_line_mode_) { generator.Print(" "); } else { generator.Print("\n"); } } } } void TextFormat::Printer::PrintShortRepeatedField( const Message& message, const Reflection* reflection, const FieldDescriptor* field, TextGenerator& generator) const { // Print primitive repeated field in short form. PrintFieldName(message, reflection, field, generator); int size = reflection->FieldSize(message, field); generator.Print(": ["); for (int i = 0; i < size; i++) { if (i > 0) generator.Print(", "); PrintFieldValue(message, reflection, field, i, generator); } if (single_line_mode_) { generator.Print("] "); } else { generator.Print("]\n"); } } void TextFormat::Printer::PrintFieldName(const Message& message, const Reflection* reflection, const FieldDescriptor* field, TextGenerator& generator) const { if (field->is_extension()) { generator.Print("["); // We special-case MessageSet elements for compatibility with proto1. if (field->containing_type()->options().message_set_wire_format() && field->type() == FieldDescriptor::TYPE_MESSAGE && field->is_optional() && field->extension_scope() == field->message_type()) { generator.Print(field->message_type()->full_name()); } else { generator.Print(field->full_name()); } generator.Print("]"); } else { if (field->type() == FieldDescriptor::TYPE_GROUP) { // Groups must be serialized with their original capitalization. generator.Print(field->message_type()->name()); } else { generator.Print(field->name()); } } } void TextFormat::Printer::PrintFieldValue( const Message& message, const Reflection* reflection, const FieldDescriptor* field, int index, TextGenerator& generator) const { GOOGLE_DCHECK(field->is_repeated() || (index == -1)) << "Index must be -1 for non-repeated fields"; switch (field->cpp_type()) { #define OUTPUT_FIELD(CPPTYPE, METHOD, TO_STRING) \ case FieldDescriptor::CPPTYPE_##CPPTYPE: \ generator.Print(TO_STRING(field->is_repeated() ? \ reflection->GetRepeated##METHOD(message, field, index) : \ reflection->Get##METHOD(message, field))); \ break; \ OUTPUT_FIELD( INT32, Int32, SimpleItoa); OUTPUT_FIELD( INT64, Int64, SimpleItoa); OUTPUT_FIELD(UINT32, UInt32, SimpleItoa); OUTPUT_FIELD(UINT64, UInt64, SimpleItoa); OUTPUT_FIELD( FLOAT, Float, SimpleFtoa); OUTPUT_FIELD(DOUBLE, Double, SimpleDtoa); #undef OUTPUT_FIELD case FieldDescriptor::CPPTYPE_STRING: { string scratch; const string& value = field->is_repeated() ? reflection->GetRepeatedStringReference( message, field, index, &scratch) : reflection->GetStringReference(message, field, &scratch); generator.Print("\""); if (utf8_string_escaping_) { generator.Print(strings::Utf8SafeCEscape(value)); } else { generator.Print(CEscape(value)); } generator.Print("\""); break; } case FieldDescriptor::CPPTYPE_BOOL: if (field->is_repeated()) { generator.Print(reflection->GetRepeatedBool(message, field, index) ? "true" : "false"); } else { generator.Print(reflection->GetBool(message, field) ? "true" : "false"); } break; case FieldDescriptor::CPPTYPE_ENUM: generator.Print(field->is_repeated() ? reflection->GetRepeatedEnum(message, field, index)->name() : reflection->GetEnum(message, field)->name()); break; case FieldDescriptor::CPPTYPE_MESSAGE: Print(field->is_repeated() ? reflection->GetRepeatedMessage(message, field, index) : reflection->GetMessage(message, field), generator); break; } } /* static */ bool TextFormat::Print(const Message& message, io::ZeroCopyOutputStream* output) { return Printer().Print(message, output); } /* static */ bool TextFormat::PrintUnknownFields( const UnknownFieldSet& unknown_fields, io::ZeroCopyOutputStream* output) { return Printer().PrintUnknownFields(unknown_fields, output); } /* static */ bool TextFormat::PrintToString( const Message& message, string* output) { return Printer().PrintToString(message, output); } /* static */ bool TextFormat::PrintUnknownFieldsToString( const UnknownFieldSet& unknown_fields, string* output) { return Printer().PrintUnknownFieldsToString(unknown_fields, output); } /* static */ void TextFormat::PrintFieldValueToString( const Message& message, const FieldDescriptor* field, int index, string* output) { return Printer().PrintFieldValueToString(message, field, index, output); } /* static */ bool TextFormat::ParseFieldValueFromString( const string& input, const FieldDescriptor* field, Message* message) { return Parser().ParseFieldValueFromString(input, field, message); } // Prints an integer as hex with a fixed number of digits dependent on the // integer type. template<typename IntType> static string PaddedHex(IntType value) { string result; result.reserve(sizeof(value) * 2); for (int i = sizeof(value) * 2 - 1; i >= 0; i--) { result.push_back(int_to_hex_digit(value >> (i*4) & 0x0F)); } return result; } void TextFormat::Printer::PrintUnknownFields( const UnknownFieldSet& unknown_fields, TextGenerator& generator) const { for (int i = 0; i < unknown_fields.field_count(); i++) { const UnknownField& field = unknown_fields.field(i); string field_number = SimpleItoa(field.number()); switch (field.type()) { case UnknownField::TYPE_VARINT: generator.Print(field_number); generator.Print(": "); generator.Print(SimpleItoa(field.varint())); if (single_line_mode_) { generator.Print(" "); } else { generator.Print("\n"); } break; case UnknownField::TYPE_FIXED32: { generator.Print(field_number); generator.Print(": 0x"); char buffer[kFastToBufferSize]; generator.Print(FastHex32ToBuffer(field.fixed32(), buffer)); if (single_line_mode_) { generator.Print(" "); } else { generator.Print("\n"); } break; } case UnknownField::TYPE_FIXED64: { generator.Print(field_number); generator.Print(": 0x"); char buffer[kFastToBufferSize]; generator.Print(FastHex64ToBuffer(field.fixed64(), buffer)); if (single_line_mode_) { generator.Print(" "); } else { generator.Print("\n"); } break; } case UnknownField::TYPE_LENGTH_DELIMITED: { generator.Print(field_number); const string& value = field.length_delimited(); UnknownFieldSet embedded_unknown_fields; if (!value.empty() && embedded_unknown_fields.ParseFromString(value)) { // This field is parseable as a Message. // So it is probably an embedded message. if (single_line_mode_) { generator.Print(" { "); } else { generator.Print(" {\n"); generator.Indent(); } PrintUnknownFields(embedded_unknown_fields, generator); if (single_line_mode_) { generator.Print("} "); } else { generator.Outdent(); generator.Print("}\n"); } } else { // This field is not parseable as a Message. // So it is probably just a plain string. generator.Print(": \""); generator.Print(CEscape(value)); generator.Print("\""); if (single_line_mode_) { generator.Print(" "); } else { generator.Print("\n"); } } break; } case UnknownField::TYPE_GROUP: generator.Print(field_number); if (single_line_mode_) { generator.Print(" { "); } else { generator.Print(" {\n"); generator.Indent(); } PrintUnknownFields(field.group(), generator); if (single_line_mode_) { generator.Print("} "); } else { generator.Outdent(); generator.Print("}\n"); } break; } } } } // namespace protobuf } // namespace google
[ "bb.newlife@gmail.com" ]
bb.newlife@gmail.com
d1c334e181468a31edb0193f958b50c7cd78c9dd
8c5f7ef81a92887fcadfe9ef0c62db5d68d49659
/src/common/types/timestamp.cpp
39297e6236522557255548ebca1774d9a74d934b
[ "MIT" ]
permissive
xunliu/guinsoodb
37657f00456a053558e3abc433606bc6113daee5
0e90f0743c3b69f8a8c2c03441f5bb1232ffbcf0
refs/heads/main
2023-04-10T19:53:35.624158
2021-04-21T03:25:44
2021-04-21T03:25:44
378,399,976
0
1
MIT
2021-06-19T11:51:49
2021-06-19T11:51:48
null
UTF-8
C++
false
false
3,852
cpp
#include "guinsoodb/common/types/timestamp.hpp" #include "guinsoodb/common/exception.hpp" #include "guinsoodb/common/types/date.hpp" #include "guinsoodb/common/types/interval.hpp" #include "guinsoodb/common/types/time.hpp" #include "guinsoodb/common/string_util.hpp" #include "guinsoodb/common/chrono.hpp" #include <ctime> namespace guinsoodb { // timestamp/datetime uses 64 bits, high 32 bits for date and low 32 bits for time // string format is YYYY-MM-DDThh:mm:ssZ // T may be a space // Z is optional // ISO 8601 timestamp_t Timestamp::FromCString(const char *str, idx_t len) { idx_t pos; date_t date; dtime_t time; if (!Date::TryConvertDate(str, len, pos, date)) { throw ConversionException("timestamp field value out of range: \"%s\", " "expected format is (YYYY-MM-DD HH:MM:SS[.MS])", string(str, len)); } if (pos == len) { // no time: only a date return Timestamp::FromDatetime(date, 0); } // try to parse a time field if (str[pos] == ' ' || str[pos] == 'T') { pos++; } idx_t time_pos = 0; if (!Time::TryConvertTime(str + pos, len - pos, time_pos, time)) { throw ConversionException("timestamp field value out of range: \"%s\", " "expected format is (YYYY-MM-DD HH:MM:SS[.MS])", string(str, len)); } pos += time_pos; if (pos < len) { // skip a "Z" at the end (as per the ISO8601 specs) if (str[pos] == 'Z') { pos++; } // skip any spaces at the end while (pos < len && StringUtil::CharacterIsSpace(str[pos])) { pos++; } if (pos < len) { throw ConversionException("timestamp field value out of range: \"%s\", " "expected format is (YYYY-MM-DD HH:MM:SS[.MS])", string(str, len)); } } return Timestamp::FromDatetime(date, time); } timestamp_t Timestamp::FromString(const string &str) { return Timestamp::FromCString(str.c_str(), str.size()); } string Timestamp::ToString(timestamp_t timestamp) { date_t date; dtime_t time; Timestamp::Convert(timestamp, date, time); return Date::ToString(date) + " " + Time::ToString(time); } date_t Timestamp::GetDate(timestamp_t timestamp) { return (timestamp + (timestamp < 0)) / Interval::MICROS_PER_DAY - (timestamp < 0); } dtime_t Timestamp::GetTime(timestamp_t timestamp) { date_t date = Timestamp::GetDate(timestamp); return timestamp - (int64_t(date) * int64_t(Interval::MICROS_PER_DAY)); } timestamp_t Timestamp::FromDatetime(date_t date, dtime_t time) { return date * Interval::MICROS_PER_DAY + time; } void Timestamp::Convert(timestamp_t timestamp, date_t &out_date, dtime_t &out_time) { out_date = GetDate(timestamp); out_time = timestamp - (int64_t(out_date) * int64_t(Interval::MICROS_PER_DAY)); D_ASSERT(timestamp == Timestamp::FromDatetime(out_date, out_time)); } timestamp_t Timestamp::GetCurrentTimestamp() { auto now = system_clock::now(); auto epoch_ms = duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count(); return Timestamp::FromEpochMs(epoch_ms); } timestamp_t Timestamp::FromEpochSeconds(int64_t sec) { return sec * Interval::MICROS_PER_SEC; } timestamp_t Timestamp::FromEpochMs(int64_t ms) { return ms * Interval::MICROS_PER_MSEC; } timestamp_t Timestamp::FromEpochMicroSeconds(int64_t micros) { return micros; } timestamp_t Timestamp::FromEpochNanoSeconds(int64_t ns) { return ns / 1000; } int64_t Timestamp::GetEpochSeconds(timestamp_t timestamp) { return timestamp / Interval::MICROS_PER_SEC; } int64_t Timestamp::GetEpochMs(timestamp_t timestamp) { return timestamp / Interval::MICROS_PER_MSEC; } int64_t Timestamp::GetEpochMicroSeconds(timestamp_t timestamp) { return timestamp; } int64_t Timestamp::GetEpochNanoSeconds(timestamp_t timestamp) { return timestamp * 1000; } } // namespace guinsoodb
[ "bqjimaster@gmail.com" ]
bqjimaster@gmail.com
f5c413ee3dcb17de9d2b695272e31c046cba137b
365fdd982afe7e2a381afebcd7cee7a410265375
/mlcommon/include/mda/diskwritemda.h
e7034ca71d8cc80a5e563b53689da2e1c43d0b9b
[]
no_license
DupretLab/mountainlab
e413fc8c24111cf70f799697aae13ce16eb3e93c
baa9a70d0860f29515538682a4bb7f55208514f7
refs/heads/master
2021-01-20T13:49:59.878154
2017-02-21T14:33:55
2017-02-21T14:33:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,225
h
/****************************************************** ** See the accompanying README and LICENSE files ** Author(s): Jeremy Magland *******************************************************/ #ifndef DISKWRITEMDA_H #define DISKWRITEMDA_H #include "mda.h" #include "mda32.h" #include <QString> #include <mdaio.h> class DiskWriteMdaPrivate; class DiskWriteMda { public: friend class DiskWriteMdaPrivate; DiskWriteMda(); DiskWriteMda(int data_type, const QString& path, long N1, long N2, long N3 = 1, long N4 = 1, long N5 = 1, long N6 = 1); virtual ~DiskWriteMda(); bool open(int data_type, const QString& path, long N1, long N2, long N3 = 1, long N4 = 1, long N5 = 1, long N6 = 1); bool open(const QString& path); void close(); long N1(); long N2(); long N3(); long N4(); long N5(); long N6(); long totalSize(); bool writeChunk(Mda& X, long i); bool writeChunk(Mda& X, long i1, long i2); bool writeChunk(Mda& X, long i1, long i2, long i3); bool writeChunk(Mda32& X, long i); bool writeChunk(Mda32& X, long i1, long i2); bool writeChunk(Mda32& X, long i1, long i2, long i3); private: DiskWriteMdaPrivate* d; }; #endif // DISKWRITEMDA_H
[ "jeremy.magland@gmail.com" ]
jeremy.magland@gmail.com
01004143102db11cc202aff109580f6049d29b1b
557bec2f83e2e9d014c1334d0b17fee1d441e0b6
/src/item/StaticObject.h
fd4528bc8e26f872ec48d3770e6733cc7a3437a2
[]
no_license
thanhhuydev77/game
850720a180e78d1f285de84530b950a7b9136dc8
e77533254783dc3e273ac052f96ab07be68e6685
refs/heads/master
2020-08-17T00:30:50.740540
2020-01-05T15:49:07
2020-01-05T15:49:07
215,579,322
1
0
null
null
null
null
UTF-8
C++
false
false
656
h
#pragma once #include "../sample/GameObject.h" #include "../sample/Textures.h" #include "../utility/LoadResourceHelper.h" #include "../sample/Const_Value.h" #include "../character/Simon.h" class StaticObject : public CGameObject { int Type; bool opening; DWORD disappear_start; public: StaticObject(); ~StaticObject(); void setType(int type) { Type = type; } int getType() { return Type; } void start_open(); // Inherited via CGameObject virtual void Update(DWORD dt, vector<LPGAMEOBJECT> *coObjects = NULL); virtual void GetBoundingBox(float & left, float & top, float & right, float & bottom) override; virtual void Render() override; };
[ "thanhhuydev77@gmail.com" ]
thanhhuydev77@gmail.com
891b548e2185be143f4ac5ffc0820b1fca0f7b49
faef8b1d911dc6e599cb9d2c73e955c5cb373feb
/led_contoller/led_contoller.ino
890d71afffe4c51356a7cb99aca08a6b0943b2d4
[]
no_license
jangjinkyu/mark6-arduino
6f14e46a037b46e901c0b44829d9602bc328d3f6
966126e26a1ed10bafb39c182f3355eba10f5367
refs/heads/main
2023-01-31T22:29:12.219955
2020-12-19T05:22:59
2020-12-19T05:22:59
322,773,536
0
0
null
2020-12-19T05:23:50
2020-12-19T05:23:49
null
UTF-8
C++
false
false
1,191
ino
#define GREEN 6 #define BLUE 3 #define RED 5 void red_on(); void green_on(); void blue_on(); int ptRMeter = A0; int ptGMeter = A1; int ptBMeter = A2; int ptRValue = 0; int ptGValue = 0; int ptBValue = 0; void setup() { pinMode(RED, OUTPUT); pinMode(GREEN, OUTPUT); pinMode(BLUE, OUTPUT); pinMode(ptRMeter, INPUT); pinMode(ptGMeter, INPUT); pinMode(ptBMeter, INPUT); Serial.begin(9600); Serial.println("==Serial START=="); } void loop() { ptRValue = analogRead(ptRMeter); ptGValue = analogRead(ptGMeter); ptBValue = analogRead(ptBMeter); analogWrite(RED,map(ptRValue, 0, 1023, 0, 255)); analogWrite(GREEN,map(ptGValue, 0, 1023, 0, 255)); analogWrite(BLUE,map(ptBValue, 0, 1023, 0, 255)); delay(500); } void red_on(){ analogWrite(RED,map(ptRValue, 0, 1023, 0, 255)); } void red_off(){ analogWrite(RED,0); } void green_on(){ analogWrite(GREEN,map(ptGValue, 0, 1023, 0, 255)); } void green_off(){ analogWrite(GREEN,0); } void blue_on(){ analogWrite(BLUE,map(ptBValue, 0, 1023, 0, 255)); } void blue_off(){ analogWrite(BLUE,0); } void all_on(){ red_on(); green_on(); blue_on(); } void all_off(){ red_off(); green_off(); blue_off(); }
[ "cresh0105@gmail.com" ]
cresh0105@gmail.com
eca8bc1b96be1c06e8080f215a7b4a434742d5a4
243badce529a2d7a640bf3aee863753f4848ae18
/Aurora Borealis Source/sphere.h
a57a6d4f63c125781ebb6629c59063b61df46e10
[ "MIT" ]
permissive
aloudasian/graphics2014
c91c0d44023ef01c9bf2c81cf1f52c5c9befe910
1dc6d3310965f9c2ff8845f7c72cd22461edec9e
refs/heads/master
2021-01-10T14:30:10.166498
2015-10-28T23:33:41
2015-10-28T23:33:41
45,080,512
0
0
null
null
null
null
UTF-8
C++
false
false
940
h
/* UW Madison, CS 559 - Fall Semester * By Zhouyang Michael Ye and Steve Ledvina * * Header file for sphereMesh class * Based upon top.h provided by Perry Kivolowitz */ /* UW- Madison CS 559 - Fall Semester By Zhouyang Michael Ye Header file for Sphere class */ #pragma once #include <vector> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "meshBase.h" #include "shader.h" class Sphere : public MeshBase { public: Sphere(); virtual bool Initialize(float radius, glm::vec2 dim, char * vertexShader, char* fragShader); virtual void Draw(const glm::mat4 & projection, glm::mat4 modelview, const glm::ivec2 & size, const float time = 0); void TakeDown(); Shader starShader; float radius; float toRadians(float d); glm::vec4 xzRotate(vec4 pos, float offset); glm::vec4 yRotate(vec4 pos, float offset); std::vector<VertexPCNT> vertices; typedef MeshBase super; };
[ "aloudasian@gmail.com" ]
aloudasian@gmail.com
d35e9355dcfcbc705879d28bf31b66f30663fcde
4380643af55bb10e2a0ba30a736cef5436cded61
/Chapter 11/11.5/Header.h
1159527f9fd145cf83ba164e73e41da692df61d5
[]
no_license
iurii22/Prata
2d38de83d697ae88b47253328431c616f459dcc0
4348d994d5f9e3e9792c7cc404e8715bf9dbabff
refs/heads/master
2020-06-05T08:13:50.426503
2014-02-24T16:25:47
2014-02-24T16:25:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,020
h
// stonewt.h -- definition for the Stonewt class #ifndef STONEWT_H_ #define STONEWT_H_ class Stonewt { public: enum Mode {STONE_INT, POUNDS_INT, POUNDS_DOUBLE}; // 3 modes (1 the object is interpreted in stone form, 2 integer pounds form , 3 floating - point pounds form) private: Mode mode; enum {Lbs_per_stn = 14 }; // pounds per stone int stone; // whole stones double pounds; public: Stonewt(); Stonewt(double lbs, Mode form = STONE_INT); // constructor for double pounds Stonewt(int lbs, Mode form = STONE_INT); // constructor for stone, lbs ~Stonewt(); Stonewt operator+(const Stonewt & d) const; //const told, that he won't change an object which we're calling Stonewt operator-(const Stonewt & d) const; Stonewt operator*(double n) const; friend std::ostream & operator <<(std::ostream & os, const Stonewt & c); // show weight in pounds or stone format friend Stonewt operator*(double n, const Stonewt & g); }; #endif
[ "iurii.kryvenko@globallogic.com" ]
iurii.kryvenko@globallogic.com
8f611b97544bd768e33c8948b7dab5cb31945562
18ab0cf313a9d0176ba4b752b3d24dea9a987081
/kernel/SC_Parser/SC_Parser.cpp
8a346d66834b0ab8c6fa2786a976d41d086b20cf
[]
no_license
funningboy/iso_cell_rc1
8a9eb86859456a999a20f852366ea5abc3ecd015
fe92b3b052e089f4806f9f78129d1ea47fe7e647
refs/heads/master
2020-05-20T01:48:22.832512
2011-06-15T15:13:19
2011-06-15T15:13:19
1,900,779
0
1
null
null
null
null
UTF-8
C++
false
false
137,106
cpp
/* A Bison parser, made by GNU Bison 2.4.1. */ /* Skeleton implementation for Bison's Yacc-like parsers in C Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Identify Bison output. */ #define YYBISON 1 /* Bison version. */ #define YYBISON_VERSION "2.4.1" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 0 /* Push parsers. */ #define YYPUSH 0 /* Pull parsers. */ #define YYPULL 1 /* Using locations. */ #define YYLSP_NEEDED 0 /* Substitute the variable and function names. */ #define yyparse SC_parse #define yylex SC_lex #define yyerror SC_error #define yylval SC_lval #define yychar SC_char #define yydebug SC_debug #define yynerrs SC_nerrs /* Copy the first part of user declarations. */ /* Line 189 of yacc.c */ #line 1 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" #include <iostream> #include <sstream> #include <vector> #include <map> #include <string> #include <stdlib.h> #include <stdio.h> #include <assert.h> #include "kernel/SC_Context/SC_Define.h" #include "kernel/SC_Context/SC_Module.h" #include "kernel/SC_Context/SC_Port.h" #include "kernel/SC_Context/SC_Cell.h" #include "kernel/SC_Context/SC_Table.h" #include "kernel/SC_Context/SC_Time.h" #include "kernel/SC_Context/SC_Power.h" #include "kernel/SC_Context/SC_Logic.h" #include "kernel/SC_Context/SC_Type.h" #include "kernel/SC_Context/SC_Domain.h" #include "kernel/SC_Context/SC_Pass.h" using namespace std; using namespace xVerilog; SC_Module *t_sc_module; SC_Module::SC_Port_D *t_sc_port; SC_Module::SC_Cell_D *t_sc_cell; SC_Table *t_sc_table = new SC_Table(); typedef SC_Time< Def_Arrive_Time > SC_Time_D; typedef SC_Power< Def_Switch_Power > SC_Power_D; typedef SC_Logic SC_Logic_D; typedef SC_Type SC_Type_D; typedef SC_Domain SC_Domain_D; typedef SC_Pass SC_Pass_D; std::string sc_module_str; // module name std::string sc_cell_m_str; // cell module name std::string sc_cell_u_str; // cell unique name std::string sc_cell_p_str; // cell port name std::string sc_token_str; bool sc_pass; // Design = true, Library = false int sc_msb; int sc_lsb; int sc_cell_u_inx =0; // cell unique inx typedef std::vector<std::string> sc_vv_D; typedef std::vector<std::string>::iterator sc_vv_iter; typedef std::vector<std::string>::reverse_iterator sc_vv_rev_iter; typedef std::vector<std::string>::iterator sc_inv_iter; typedef std::vector<std::string>::iterator sc_sig_pt_iter; typedef std::map<std::string, SC_Module::SC_Port_D* >::iterator sc_in_pt_iter; typedef std::map<std::string, SC_Module::SC_Port_D* >::iterator sc_ot_pt_iter; typedef std::map<std::string, SC_Module::SC_Port_D* >::iterator sc_wr_pt_iter; typedef std::map<std::string, SC_Module::SC_Cell_D* >::iterator sc_cell_iter; typedef std::vector< SC_Module::SC_Port_D* >::iterator sc_cell_pt_iter; std::vector<std::string> sc_vv; std::vector<std::string> sc_inv; std::vector<std::string> sc_sig_pt_vec; std::map<std::string, SC_Module::SC_Port_D* > sc_in_pt_map; std::map<std::string, SC_Module::SC_Port_D* > sc_ot_pt_map; std::map<std::string, SC_Module::SC_Port_D* > sc_wr_pt_map; std::map<std::string, sc_vv_D > sc_div_in_pt_map; std::map<std::string, sc_vv_D > sc_div_ot_pt_map; std::map<std::string, sc_vv_D > sc_div_wr_pt_map; std::map<std::string, SC_Module::SC_Cell_D* > sc_cell_map; std::vector< SC_Module::SC_Port_D* > sc_cell_pt_vec; extern int SC_lex(); void SC_error(const char *s) { printf("ERROR: %s\n", s); } void sc_dump(std::string str ) { std::cout << str << std::endl; } /* Line 189 of yacc.c */ #line 91 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" bool stringCompare( const string &left, const string &right ){ for( string::const_iterator lit = left.begin(), rit = right.begin(); lit != left.end() && rit != right.end(); ++lit, ++rit ) if( tolower( *lit ) < tolower( *rit ) ) return true; else if( tolower( *lit ) > tolower( *rit ) ) return false; if( left.size() < right.size() ) return true; return false; } /* Line 189 of yacc.c */ #line 108 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" void set_module(){ assert( !sc_module_str.empty() && !sc_in_pt_map.empty() && !sc_ot_pt_map.empty() && !sc_cell_map.empty() && "Parser->module" ); SC_Module *sc_module = new SC_Module(); assert( sc_module != NULL && "Parser->module" ); sc_module->set_ModuleName(sc_module_str); SC_Domain_D *sc_module_d = dynamic_cast<SC_Domain_D*>(sc_module); SC_Pass_D *sc_module_p = dynamic_cast<SC_Pass_D*>(sc_module); ( sc_pass == true )? sc_module_p->set_Pass(true) : sc_module_p->set_Pass(false); // @ input insert for(sc_in_pt_iter in = sc_in_pt_map.begin(); in != sc_in_pt_map.end(); ++in){ SC_Module::SC_Port_D *pp = static_cast<SC_Module::SC_Port_D*>(in->second); assert( pp != NULL && "Parser->module" ); pp->set_Parent(sc_module); sc_module->set_InputPortVec(pp); } // @ output insert for(sc_ot_pt_iter ot = sc_ot_pt_map.begin(); ot != sc_ot_pt_map.end(); ++ot){ SC_Module::SC_Port_D *pp = static_cast<SC_Module::SC_Port_D*>(ot->second); assert( pp != NULL && "Parser->module" ); pp->set_Parent(sc_module); sc_module->set_OutputPortVec(pp); } // @ wire insert for(sc_wr_pt_iter wr = sc_wr_pt_map.begin(); wr != sc_wr_pt_map.end(); ++wr ){ SC_Module::SC_Port_D *pp = static_cast<SC_Module::SC_Port_D*>(wr->second); assert( pp != NULL && "Parser->module" ); pp->set_Parent(sc_module); sc_module->set_WirePortVec(pp); } // @ Cell insert for(sc_cell_iter cell = sc_cell_map.begin(); cell != sc_cell_map.end(); ++cell ){ SC_Module::SC_Cell_D *cc = static_cast<SC_Module::SC_Cell_D*>(cell->second); assert( cc != NULL && "Parser->module" ); cc->set_Parent(sc_module); cc->set_Self(NULL); sc_module->set_CellVec(cc); } // @ Signal update int inx = 0; for(sc_sig_pt_iter sig = sc_sig_pt_vec.begin(); sig != sc_sig_pt_vec.end(); ++sig){ // @ input div if( sc_div_in_pt_map.find((*sig)) != sc_div_in_pt_map.end() ){ sc_vv_D sc_vvi = sc_div_in_pt_map[(*sig)]; assert( !sc_vvi.empty() && "Parser->module"); for(sc_vv_iter vvi = sc_vvi.begin(); vvi != sc_vvi.end(); ++vvi){ SC_Module::SC_Port_D *sc_module_p = sc_in_pt_map[(*vvi)]; assert( sc_module_p !=NULL && "Parser->module"); sc_module->set_SignalVec((*vvi),sc_module_p,inx++); } } // @ output div if( sc_div_ot_pt_map.find((*sig)) != sc_div_ot_pt_map.end() ){ sc_vv_D sc_vvi = sc_div_ot_pt_map[(*sig)]; assert( !sc_vvi.empty() && "Parser->module"); for(sc_vv_iter vvi = sc_vvi.begin(); vvi != sc_vvi.end(); ++vvi){ SC_Module::SC_Port_D *sc_module_p = sc_ot_pt_map[(*vvi)]; assert( sc_module_p !=NULL && "Parser->module"); sc_module->set_SignalVec((*vvi),sc_module_p,inx++); } } // @ no div if( sc_div_in_pt_map.find((*sig)) == sc_div_in_pt_map.end() && sc_div_ot_pt_map.find((*sig)) == sc_div_ot_pt_map.end() ){ // @ map SC_Module::SC_Port_D *sc_module_p = ( sc_in_pt_map.find((*sig)) != sc_in_pt_map.end() )? sc_in_pt_map[(*sig)] : ( sc_ot_pt_map.find((*sig)) != sc_ot_pt_map.end() )? sc_ot_pt_map[(*sig)] : NULL; assert( sc_module_p !=NULL && "Parser->module"); sc_module->set_SignalVec((*sig),sc_module_p,inx++); } } // @ push 2 SC_Table t_sc_table->set_ModuleMap(sc_module_str,sc_module); sc_in_pt_map.clear(); sc_ot_pt_map.clear(); sc_wr_pt_map.clear(); sc_div_in_pt_map.clear(); sc_div_ot_pt_map.clear(); sc_div_wr_pt_map.clear(); sc_cell_map.clear(); sc_cell_pt_vec.clear(); sc_sig_pt_vec.clear(); sc_vv.clear(); sc_inv.clear(); } /* Line 189 of yacc.c */ #line 260 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" void set_module_signal(){ assert( !sc_vv.empty() && "Parser->module_signal" ); sc_sig_pt_vec = sc_vv; sc_vv.clear(); } /* Line 189 of yacc.c */ #line 276 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" void set_module_input_div(){ std::string nm = ""; std::stringstream ss; std::vector<std::string> tp_vec; tp_vec.clear(); assert( sc_msb > sc_lsb && sc_lsb ==0 && !sc_vv.empty() && "Parser->module_input_div"); for(sc_vv_iter vi = sc_vv.begin(); vi != sc_vv.end(); ++vi){ for(int i=sc_msb; i>=sc_lsb; --i){ ss << i; nm = std::string((*vi)) + "[" + ss.str() + "]"; ss.str(""); SC_Module::SC_Port_D *sc_module_p = new SC_Module::SC_Port_D(); assert( sc_module_p !=NULL && "Parser->module_input_div"); sc_module_p->set_Name(nm); sc_module_p->set_Parent(NULL); SC_Time_D *sc_module_p_tm = dynamic_cast<SC_Time_D*> (sc_module_p); SC_Power_D *sc_module_p_pr = dynamic_cast<SC_Power_D*> (sc_module_p); SC_Logic_D *sc_module_p_lg = dynamic_cast<SC_Logic_D*> (sc_module_p); SC_Type_D *sc_module_p_tp = dynamic_cast<SC_Type_D*> (sc_module_p); SC_Domain_D *sc_module_p_dm = dynamic_cast<SC_Domain_D*>(sc_module_p); SC_Pass_D *sc_module_p_ps = dynamic_cast<SC_Pass_D*> (sc_module_p); sc_module_p_tm->set_ArriveTime(0); sc_module_p_pr->set_SwitchPower(0); sc_module_p_lg->set_PreLogic(SC_Logic_D::SC_LOGIC_x); sc_module_p_lg->set_CurLogic(SC_Logic_D::SC_LOGIC_x); sc_module_p_tp->set_Type(SC_Type_D::SC_TYPE_WIRE); ( sc_pass == true )? sc_module_p_ps->set_Pass(true) : sc_module_p_ps->set_Pass(false); sc_in_pt_map[nm] = sc_module_p; tp_vec.push_back(nm); } sc_div_in_pt_map[(*vi)] = tp_vec; } sc_vv.clear(); } /* Line 189 of yacc.c */ #line 335 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" void set_module_input_only(){ std::string nm; assert( (!sc_vv.empty()) && "Parser->module_input_only"); for(sc_vv_iter vi = sc_vv.begin(); vi != sc_vv.end(); ++vi){ nm = std::string((*vi)); SC_Module::SC_Port_D *sc_module_p = new SC_Module::SC_Port_D(); assert( sc_module_p !=NULL && "Parser->module_input_div"); sc_module_p->set_Name(nm); sc_module_p->set_Parent(NULL); SC_Time_D *sc_module_p_tm = dynamic_cast<SC_Time_D*> (sc_module_p); SC_Power_D *sc_module_p_pr = dynamic_cast<SC_Power_D*> (sc_module_p); SC_Logic_D *sc_module_p_lg = dynamic_cast<SC_Logic_D*> (sc_module_p); SC_Type_D *sc_module_p_tp = dynamic_cast<SC_Type_D*> (sc_module_p); SC_Domain_D *sc_module_p_dm = dynamic_cast<SC_Domain_D*>(sc_module_p); SC_Pass_D *sc_module_p_ps = dynamic_cast<SC_Pass_D*> (sc_module_p); sc_module_p_tm->set_ArriveTime(0); sc_module_p_pr->set_SwitchPower(0); sc_module_p_lg->set_PreLogic(SC_Logic_D::SC_LOGIC_x); sc_module_p_lg->set_CurLogic(SC_Logic_D::SC_LOGIC_x); sc_module_p_tp->set_Type(SC_Type_D::SC_TYPE_WIRE); ( sc_pass == true )? sc_module_p_ps->set_Pass(true) : sc_module_p_ps->set_Pass(false); sc_in_pt_map[nm] = sc_module_p; } sc_vv.clear(); } /* Line 189 of yacc.c */ #line 382 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" void set_module_output_div(){ std::string nm = ""; std::stringstream ss; std::vector<std::string> tp_vec; tp_vec.clear(); assert( sc_msb > sc_lsb && sc_lsb ==0 && !sc_vv.empty() && "Parser->module_output_div"); for(sc_vv_iter vi = sc_vv.begin(); vi != sc_vv.end(); ++vi){ for(int i=sc_msb; i>=sc_lsb; --i){ ss << i; nm = std::string((*vi)) + "[" + ss.str() + "]"; ss.str(""); SC_Module::SC_Port_D *sc_module_p = new SC_Module::SC_Port_D(); assert( sc_module_p !=NULL && "Parser->module_input_div"); sc_module_p->set_Name(nm); sc_module_p->set_Parent(NULL); SC_Time_D *sc_module_p_tm = dynamic_cast<SC_Time_D*> (sc_module_p); SC_Power_D *sc_module_p_pr = dynamic_cast<SC_Power_D*> (sc_module_p); SC_Logic_D *sc_module_p_lg = dynamic_cast<SC_Logic_D*> (sc_module_p); SC_Type_D *sc_module_p_tp = dynamic_cast<SC_Type_D*> (sc_module_p); SC_Domain_D *sc_module_p_dm = dynamic_cast<SC_Domain_D*>(sc_module_p); SC_Pass_D *sc_module_p_ps = dynamic_cast<SC_Pass_D*> (sc_module_p); sc_module_p_tm->set_ArriveTime(0); sc_module_p_pr->set_SwitchPower(0); sc_module_p_lg->set_PreLogic(SC_Logic_D::SC_LOGIC_x); sc_module_p_lg->set_CurLogic(SC_Logic_D::SC_LOGIC_x); sc_module_p_tp->set_Type(SC_Type_D::SC_TYPE_WIRE); ( sc_pass == true )? sc_module_p_ps->set_Pass(true) : sc_module_p_ps->set_Pass(false); sc_ot_pt_map[nm] = sc_module_p; tp_vec.push_back(nm); } sc_div_ot_pt_map[(*vi)] = tp_vec; } sc_vv.clear(); } /* Line 189 of yacc.c */ #line 441 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" void set_module_output_only(){ std::string nm; assert( (!sc_vv.empty()) && "Parser->module_output_only"); for(sc_vv_iter vi = sc_vv.begin(); vi != sc_vv.end(); ++vi){ nm = std::string((*vi)); SC_Module::SC_Port_D *sc_module_p = new SC_Module::SC_Port_D(); assert( sc_module_p !=NULL && "Parser->module_output_only"); sc_module_p->set_Name(nm); sc_module_p->set_Parent(NULL); SC_Time_D *sc_module_p_tm = dynamic_cast<SC_Time_D*> (sc_module_p); SC_Power_D *sc_module_p_pr = dynamic_cast<SC_Power_D*> (sc_module_p); SC_Logic_D *sc_module_p_lg = dynamic_cast<SC_Logic_D*> (sc_module_p); SC_Type_D *sc_module_p_tp = dynamic_cast<SC_Type_D*> (sc_module_p); SC_Domain_D *sc_module_p_dm = dynamic_cast<SC_Domain_D*>(sc_module_p); SC_Pass_D *sc_module_p_ps = dynamic_cast<SC_Pass_D*> (sc_module_p); sc_module_p_tm->set_ArriveTime(0); sc_module_p_pr->set_SwitchPower(0); sc_module_p_lg->set_PreLogic(SC_Logic_D::SC_LOGIC_x); sc_module_p_lg->set_CurLogic(SC_Logic_D::SC_LOGIC_x); sc_module_p_tp->set_Type(SC_Type_D::SC_TYPE_WIRE); ( sc_pass == true )? sc_module_p_ps->set_Pass(true) : sc_module_p_ps->set_Pass(false); sc_ot_pt_map[nm] = sc_module_p; } sc_vv.clear(); } /* Line 189 of yacc.c */ #line 486 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" void set_module_wire_div(){ std::string nm = ""; std::stringstream ss; std::vector<std::string> tp_vec; tp_vec.clear(); assert( sc_msb > sc_lsb && sc_lsb ==0 && !sc_vv.empty() && "Parser->module_wire_div"); for(sc_vv_iter vi = sc_vv.begin(); vi != sc_vv.end(); ++vi){ for(int i=sc_msb; i>=sc_lsb; --i){ ss << i; nm = std::string((*vi)) + "[" + ss.str() + "]"; ss.str(""); SC_Module::SC_Port_D *sc_module_p = new SC_Module::SC_Port_D(); assert( sc_module_p !=NULL && "Parser->module_wire_div"); sc_module_p->set_Name(nm); sc_module_p->set_Parent(NULL); SC_Time_D *sc_module_p_tm = dynamic_cast<SC_Time_D*> (sc_module_p); SC_Power_D *sc_module_p_pr = dynamic_cast<SC_Power_D*> (sc_module_p); SC_Logic_D *sc_module_p_lg = dynamic_cast<SC_Logic_D*> (sc_module_p); SC_Type_D *sc_module_p_tp = dynamic_cast<SC_Type_D*> (sc_module_p); SC_Domain_D *sc_module_p_dm = dynamic_cast<SC_Domain_D*>(sc_module_p); SC_Pass_D *sc_module_p_ps = dynamic_cast<SC_Pass_D*> (sc_module_p); sc_module_p_tm->set_ArriveTime(0); sc_module_p_pr->set_SwitchPower(0); sc_module_p_lg->set_PreLogic(SC_Logic_D::SC_LOGIC_x); sc_module_p_lg->set_CurLogic(SC_Logic_D::SC_LOGIC_x); sc_module_p_tp->set_Type(SC_Type_D::SC_TYPE_WIRE); ( sc_pass == true )? sc_module_p_ps->set_Pass(true) : sc_module_p_ps->set_Pass(false); sc_wr_pt_map[nm] = sc_module_p; tp_vec.push_back(nm); } sc_div_wr_pt_map[(*vi)] = tp_vec; } sc_vv.clear(); } /* Line 189 of yacc.c */ #line 545 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" void set_module_wire_only(){ std::string nm; assert( (!sc_vv.empty()) && "Parser->module_wire_only"); for(sc_vv_iter vi = sc_vv.begin(); vi != sc_vv.end(); ++vi){ nm = std::string((*vi)); SC_Module::SC_Port_D *sc_module_p = new SC_Module::SC_Port_D(); assert( sc_module_p !=NULL && "Parser->module_wire_only"); sc_module_p->set_Name(nm); sc_module_p->set_Parent(NULL); SC_Time_D *sc_module_p_tm = dynamic_cast<SC_Time_D*> (sc_module_p); SC_Power_D *sc_module_p_pr = dynamic_cast<SC_Power_D*> (sc_module_p); SC_Logic_D *sc_module_p_lg = dynamic_cast<SC_Logic_D*> (sc_module_p); SC_Type_D *sc_module_p_tp = dynamic_cast<SC_Type_D*> (sc_module_p); SC_Domain_D *sc_module_p_dm = dynamic_cast<SC_Domain_D*>(sc_module_p); SC_Pass_D *sc_module_p_ps = dynamic_cast<SC_Pass_D*> (sc_module_p); sc_module_p_tm->set_ArriveTime(0); sc_module_p_pr->set_SwitchPower(0); sc_module_p_lg->set_PreLogic(SC_Logic_D::SC_LOGIC_x); sc_module_p_lg->set_CurLogic(SC_Logic_D::SC_LOGIC_x); sc_module_p_tp->set_Type(SC_Type_D::SC_TYPE_WIRE); ( sc_pass == true )? sc_module_p_ps->set_Pass(true) : sc_module_p_ps->set_Pass(false); sc_wr_pt_map[nm] = sc_module_p; } sc_vv.clear(); } /* Line 189 of yacc.c */ #line 594 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" void set_cell_unique_name(){ assert( !sc_cell_m_str.empty() && "Parser->cell_unique_name" ); std::stringstream ss; ss << sc_cell_u_inx++; sc_cell_u_str = "_" + sc_cell_m_str + "_" + ss.str() + "_"; ss.str(""); } /* Line 189 of yacc.c */ #line 613 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" void set_module_cell(){ assert( !sc_cell_m_str.empty() && !sc_cell_u_str.empty() && !sc_cell_pt_vec.empty() && "Parser->module_cell"); SC_Module::SC_Cell_D *sc_cell = new SC_Module::SC_Cell_D(); assert( sc_cell!=NULL && "Parser->module_cell"); sc_cell->set_Parent(NULL); sc_cell->set_Self(NULL); sc_cell->set_ModuleName(sc_cell_m_str); sc_cell->set_CellName(sc_cell_u_str); sc_cell->set_TLib(SC_Cell::SC_TLIB_undef); SC_Domain_D *sc_cell_dm = dynamic_cast<SC_Domain_D*>(sc_cell); SC_Pass_D *sc_cell_ps = dynamic_cast<SC_Pass_D*> (sc_cell); ( sc_pass == true )? sc_cell_ps->set_Pass(true) : sc_cell_ps->set_Pass(false); for(sc_cell_pt_iter cp = sc_cell_pt_vec.begin(); cp != sc_cell_pt_vec.end(); ++cp){ SC_Module::SC_Port_D *pp = static_cast<SC_Module::SC_Port_D*>(*cp); assert( pp != NULL && "Parser->module_cell"); sc_cell->set_PortVec(pp); } sc_cell_map[sc_cell_u_str] = sc_cell; sc_cell_pt_vec.clear(); } /* Line 189 of yacc.c */ #line 656 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" void set_module_links_indirect(){ std::stringstream ss; std::string nm = ""; int inx = 0; assert( !sc_vv.empty() && !sc_cell_p_str.empty() && "Parser->module_links_indirect"); for(sc_vv_rev_iter vv = sc_vv.rbegin(); vv != sc_vv.rend(); ++vv){ if( sc_div_in_pt_map.find((*vv)) != sc_div_in_pt_map.end() ){ sc_vv_D sc_vvi = sc_div_in_pt_map[(*vv)]; assert( !sc_vvi.empty() && "Parser->module_links_indirect"); for(sc_vv_rev_iter vvi = sc_vvi.rbegin(); vvi != sc_vvi.rend(); ++vvi){ ss << inx++; nm = sc_cell_p_str + "[" + ss.str() + "]"; ss.str(""); SC_Module::SC_Port_D *sc_cell_p = new SC_Module::SC_Port_D(); assert( sc_cell_p !=NULL && "Parser->module_links_indirect"); sc_cell_p->set_Name(nm); sc_cell_p->set_Parent(NULL); SC_Time_D *sc_cell_p_tm = dynamic_cast<SC_Time_D*> (sc_cell_p); SC_Power_D *sc_cell_p_pr = dynamic_cast<SC_Power_D*> (sc_cell_p); SC_Logic_D *sc_cell_p_lg = dynamic_cast<SC_Logic_D*> (sc_cell_p); SC_Type_D *sc_cell_p_tp = dynamic_cast<SC_Type_D*> (sc_cell_p); SC_Domain_D *sc_cell_p_dm = dynamic_cast<SC_Domain_D*>(sc_cell_p); SC_Pass_D *sc_cell_p_ps = dynamic_cast<SC_Pass_D*> (sc_cell_p); sc_cell_p_tm->set_ArriveTime(0); sc_cell_p_pr->set_SwitchPower(0); sc_cell_p_lg->set_PreLogic(SC_Logic_D::SC_LOGIC_x); sc_cell_p_lg->set_CurLogic(SC_Logic_D::SC_LOGIC_x); sc_cell_p_tp->set_Type(SC_Type_D::SC_TYPE_WIRE); ( sc_pass == true )? sc_cell_p_ps->set_Pass(true) : sc_cell_p_ps->set_Pass(false); SC_Module::SC_Port_D *sc_module_p = sc_in_pt_map[(*vvi)]; assert( sc_module_p !=NULL && "Parser->module_links_indirect"); sc_module_p->set_NxtPortVec(sc_cell_p); sc_cell_p->set_PrePortVec(sc_module_p); sc_cell_pt_vec.push_back(sc_cell_p); } } if( sc_div_ot_pt_map.find((*vv)) != sc_div_ot_pt_map.end() ){ sc_vv_D sc_vvi = sc_div_ot_pt_map[(*vv)]; assert( !sc_vvi.empty() && "Parser->module_links_indirect"); for(sc_vv_rev_iter vvi = sc_vvi.rbegin(); vvi != sc_vvi.rend(); ++vvi){ ss << inx++; nm = sc_cell_p_str + "[" + ss.str() + "]"; ss.str(""); SC_Module::SC_Port_D *sc_cell_p = new SC_Module::SC_Port_D(); assert( sc_cell_p !=NULL && "Parser->module_links_indirect"); sc_cell_p->set_Name(nm); sc_cell_p->set_Parent(NULL); SC_Time_D *sc_cell_p_tm = dynamic_cast<SC_Time_D*> (sc_cell_p); SC_Power_D *sc_cell_p_pr = dynamic_cast<SC_Power_D*> (sc_cell_p); SC_Logic_D *sc_cell_p_lg = dynamic_cast<SC_Logic_D*> (sc_cell_p); SC_Type_D *sc_cell_p_tp = dynamic_cast<SC_Type_D*> (sc_cell_p); SC_Domain_D *sc_cell_p_dm = dynamic_cast<SC_Domain_D*>(sc_cell_p); SC_Pass_D *sc_cell_p_ps = dynamic_cast<SC_Pass_D*> (sc_cell_p); sc_cell_p_tm->set_ArriveTime(0); sc_cell_p_pr->set_SwitchPower(0); sc_cell_p_lg->set_PreLogic(SC_Logic_D::SC_LOGIC_x); sc_cell_p_lg->set_CurLogic(SC_Logic_D::SC_LOGIC_x); sc_cell_p_tp->set_Type(SC_Type_D::SC_TYPE_WIRE); ( sc_pass == true )? sc_cell_p_ps->set_Pass(true) : sc_cell_p_ps->set_Pass(false); SC_Module::SC_Port_D *sc_module_p = sc_ot_pt_map[(*vvi)]; assert( sc_module_p !=NULL && "Parser->module_links_indirect"); sc_module_p->set_NxtPortVec(sc_cell_p); sc_cell_p->set_PrePortVec(sc_module_p); sc_cell_pt_vec.push_back(sc_cell_p); } } // @ wire div if( sc_div_wr_pt_map.find((*vv)) != sc_div_wr_pt_map.end() && sc_div_in_pt_map.find((*vv)) == sc_div_in_pt_map.end() && sc_div_ot_pt_map.find((*vv)) == sc_div_ot_pt_map.end() ){ sc_vv_D sc_vvi = sc_div_wr_pt_map[(*vv)]; assert( !sc_vvi.empty() && "Parser->module_links_indirect"); for(sc_vv_rev_iter vvi = sc_vvi.rbegin(); vvi != sc_vvi.rend(); ++vvi){ ss << inx++; nm = sc_cell_p_str + "[" + ss.str() + "]"; ss.str(""); SC_Module::SC_Port_D *sc_cell_p = new SC_Module::SC_Port_D(); assert( sc_cell_p !=NULL && "Parser->module_links_indirect"); sc_cell_p->set_Name(nm); sc_cell_p->set_Parent(NULL); SC_Time_D *sc_cell_p_tm = dynamic_cast<SC_Time_D*> (sc_cell_p); SC_Power_D *sc_cell_p_pr = dynamic_cast<SC_Power_D*> (sc_cell_p); SC_Logic_D *sc_cell_p_lg = dynamic_cast<SC_Logic_D*> (sc_cell_p); SC_Type_D *sc_cell_p_tp = dynamic_cast<SC_Type_D*> (sc_cell_p); SC_Domain_D *sc_cell_p_dm = dynamic_cast<SC_Domain_D*>(sc_cell_p); SC_Pass_D *sc_cell_p_ps = dynamic_cast<SC_Pass_D*> (sc_cell_p); sc_cell_p_tm->set_ArriveTime(0); sc_cell_p_pr->set_SwitchPower(0); sc_cell_p_lg->set_PreLogic(SC_Logic_D::SC_LOGIC_x); sc_cell_p_lg->set_CurLogic(SC_Logic_D::SC_LOGIC_x); sc_cell_p_tp->set_Type(SC_Type_D::SC_TYPE_WIRE); ( sc_pass == true )? sc_cell_p_ps->set_Pass(true) : sc_cell_p_ps->set_Pass(false); SC_Module::SC_Port_D *sc_module_p = sc_wr_pt_map[(*vvi)]; assert( sc_module_p !=NULL && "Parser->module_links_indirect"); sc_module_p->set_NxtPortVec(sc_cell_p); sc_cell_p->set_PrePortVec(sc_module_p); sc_cell_pt_vec.push_back(sc_cell_p); } } if( sc_div_wr_pt_map.find((*vv)) == sc_div_wr_pt_map.end() && sc_div_in_pt_map.find((*vv)) == sc_div_in_pt_map.end() && sc_div_ot_pt_map.find((*vv)) == sc_div_ot_pt_map.end() ){ if( sc_vv.size()==1 ){ nm = sc_cell_p_str; } else { ss << inx++; nm = sc_cell_p_str + "[" + ss.str() + "]"; ss.str(""); } SC_Module::SC_Port_D *sc_cell_p = new SC_Module::SC_Port_D(); assert( sc_cell_p !=NULL && "Parser->module_links_indirect"); sc_cell_p->set_Name(nm); sc_cell_p->set_Parent(NULL); SC_Time_D *sc_cell_p_tm = dynamic_cast<SC_Time_D*> (sc_cell_p); SC_Power_D *sc_cell_p_pr = dynamic_cast<SC_Power_D*> (sc_cell_p); SC_Logic_D *sc_cell_p_lg = dynamic_cast<SC_Logic_D*> (sc_cell_p); SC_Type_D *sc_cell_p_tp = dynamic_cast<SC_Type_D*> (sc_cell_p); SC_Domain_D *sc_cell_p_dm = dynamic_cast<SC_Domain_D*>(sc_cell_p); SC_Pass_D *sc_cell_p_ps = dynamic_cast<SC_Pass_D*> (sc_cell_p); sc_cell_p_tm->set_ArriveTime(0); sc_cell_p_pr->set_SwitchPower(0); sc_cell_p_lg->set_PreLogic(SC_Logic_D::SC_LOGIC_x); sc_cell_p_lg->set_CurLogic(SC_Logic_D::SC_LOGIC_x); sc_cell_p_tp->set_Type(SC_Type_D::SC_TYPE_WIRE); ( sc_pass == true )? sc_cell_p_ps->set_Pass(true) : sc_cell_p_ps->set_Pass(false); SC_Module::SC_Port_D *sc_module_p = ( sc_in_pt_map.find((*vv)) != sc_in_pt_map.end() )? sc_in_pt_map[(*vv)] : ( sc_ot_pt_map.find((*vv)) != sc_ot_pt_map.end() )? sc_ot_pt_map[(*vv)] : ( sc_wr_pt_map.find((*vv)) != sc_wr_pt_map.end() )? sc_wr_pt_map[(*vv)] : NULL; assert( sc_module_p !=NULL && "Parser->module_links_indirect"); sc_module_p->set_NxtPortVec(sc_cell_p); sc_cell_p->set_PrePortVec(sc_module_p); sc_cell_pt_vec.push_back(sc_cell_p); } } sc_vv.clear(); } /* Line 189 of yacc.c */ #line 865 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" void set_module_links_direct(){ assert( sc_cell_p_str.empty() && !sc_vv.empty() && "Parser->module_links_direct"); for(sc_vv_rev_iter vv = sc_vv.rbegin(); vv != sc_vv.rend(); ++vv){ if( sc_div_in_pt_map.find((*vv)) != sc_div_in_pt_map.end() ){ sc_vv_D sc_vvi = sc_div_in_pt_map[(*vv)]; assert( !sc_vvi.empty() && "Parser->module_links_direct"); for(sc_vv_rev_iter vvi = sc_vvi.rbegin(); vvi != sc_vvi.rend(); ++vvi){ SC_Module::SC_Port_D *sc_cell_p = new SC_Module::SC_Port_D(); assert( sc_cell_p !=NULL && "Parser->module_links_direct"); sc_cell_p->set_Name((*vvi)); sc_cell_p->set_Parent(NULL); SC_Time_D *sc_cell_p_tm = dynamic_cast<SC_Time_D*> (sc_cell_p); SC_Power_D *sc_cell_p_pr = dynamic_cast<SC_Power_D*> (sc_cell_p); SC_Logic_D *sc_cell_p_lg = dynamic_cast<SC_Logic_D*> (sc_cell_p); SC_Type_D *sc_cell_p_tp = dynamic_cast<SC_Type_D*> (sc_cell_p); SC_Domain_D *sc_cell_p_dm = dynamic_cast<SC_Domain_D*>(sc_cell_p); SC_Pass_D *sc_cell_p_ps = dynamic_cast<SC_Pass_D*> (sc_cell_p); sc_cell_p_tm->set_ArriveTime(0); sc_cell_p_pr->set_SwitchPower(0); sc_cell_p_lg->set_PreLogic(SC_Logic_D::SC_LOGIC_x); sc_cell_p_lg->set_CurLogic(SC_Logic_D::SC_LOGIC_x); sc_cell_p_tp->set_Type(SC_Type_D::SC_TYPE_WIRE); ( sc_pass == true )? sc_cell_p_ps->set_Pass(true) : sc_cell_p_ps->set_Pass(false); SC_Module::SC_Port_D *sc_module_p = sc_in_pt_map[(*vvi)]; assert( sc_module_p !=NULL && "Parser->module_links_direct"); sc_module_p->set_NxtPortVec(sc_cell_p); sc_cell_p->set_PrePortVec(sc_module_p); sc_cell_pt_vec.push_back(sc_cell_p); } } if( sc_div_ot_pt_map.find((*vv)) != sc_div_ot_pt_map.end() ){ sc_vv_D sc_vvi = sc_div_ot_pt_map[(*vv)]; assert( !sc_vvi.empty() && "Parser->module_links_direct"); for(sc_vv_rev_iter vvi = sc_vvi.rbegin(); vvi != sc_vvi.rend(); ++vvi){ SC_Module::SC_Port_D *sc_cell_p = new SC_Module::SC_Port_D(); assert( sc_cell_p !=NULL && "Parser->module_links_direct"); sc_cell_p->set_Name((*vvi)); sc_cell_p->set_Parent(NULL); SC_Time_D *sc_cell_p_tm = dynamic_cast<SC_Time_D*> (sc_cell_p); SC_Power_D *sc_cell_p_pr = dynamic_cast<SC_Power_D*> (sc_cell_p); SC_Logic_D *sc_cell_p_lg = dynamic_cast<SC_Logic_D*> (sc_cell_p); SC_Type_D *sc_cell_p_tp = dynamic_cast<SC_Type_D*> (sc_cell_p); SC_Domain_D *sc_cell_p_dm = dynamic_cast<SC_Domain_D*>(sc_cell_p); SC_Pass_D *sc_cell_p_ps = dynamic_cast<SC_Pass_D*> (sc_cell_p); sc_cell_p_tm->set_ArriveTime(0); sc_cell_p_pr->set_SwitchPower(0); sc_cell_p_lg->set_PreLogic(SC_Logic_D::SC_LOGIC_x); sc_cell_p_lg->set_CurLogic(SC_Logic_D::SC_LOGIC_x); sc_cell_p_tp->set_Type(SC_Type_D::SC_TYPE_WIRE); ( sc_pass == true )? sc_cell_p_ps->set_Pass(true) : sc_cell_p_ps->set_Pass(false); SC_Module::SC_Port_D *sc_module_p = sc_ot_pt_map[(*vvi)]; assert( sc_module_p !=NULL && "Parser->module_links_direct"); sc_module_p->set_PrePortVec(sc_cell_p); sc_cell_p->set_NxtPortVec(sc_module_p); sc_cell_pt_vec.push_back(sc_cell_p); } } if( sc_div_wr_pt_map.find((*vv)) != sc_div_wr_pt_map.end() && sc_div_in_pt_map.find((*vv)) == sc_div_in_pt_map.end() && sc_div_ot_pt_map.find((*vv)) == sc_div_ot_pt_map.end() ){ sc_vv_D sc_vvi = sc_div_wr_pt_map[(*vv)]; assert( !sc_vvi.empty() && "Parser->module_links_direct"); for(sc_vv_rev_iter vvi = sc_vvi.rbegin(); vvi != sc_vvi.rend(); ++vvi){ SC_Module::SC_Port_D *sc_cell_p = new SC_Module::SC_Port_D(); assert( sc_cell_p !=NULL && "Parser->module_links_direct"); sc_cell_p->set_Name((*vvi)); sc_cell_p->set_Parent(NULL); SC_Time_D *sc_cell_p_tm = dynamic_cast<SC_Time_D*> (sc_cell_p); SC_Power_D *sc_cell_p_pr = dynamic_cast<SC_Power_D*> (sc_cell_p); SC_Logic_D *sc_cell_p_lg = dynamic_cast<SC_Logic_D*> (sc_cell_p); SC_Type_D *sc_cell_p_tp = dynamic_cast<SC_Type_D*> (sc_cell_p); SC_Domain_D *sc_cell_p_dm = dynamic_cast<SC_Domain_D*>(sc_cell_p); SC_Pass_D *sc_cell_p_ps = dynamic_cast<SC_Pass_D*> (sc_cell_p); sc_cell_p_tm->set_ArriveTime(0); sc_cell_p_pr->set_SwitchPower(0); sc_cell_p_lg->set_PreLogic(SC_Logic_D::SC_LOGIC_x); sc_cell_p_lg->set_CurLogic(SC_Logic_D::SC_LOGIC_x); sc_cell_p_tp->set_Type(SC_Type_D::SC_TYPE_WIRE); ( sc_pass == true )? sc_cell_p_ps->set_Pass(true) : sc_cell_p_ps->set_Pass(false); SC_Module::SC_Port_D *sc_module_p = sc_wr_pt_map[(*vvi)]; assert( sc_module_p !=NULL && "Parser->module_links_direct"); sc_module_p->set_NxtPortVec(sc_cell_p); sc_cell_p->set_PrePortVec(sc_module_p); sc_cell_pt_vec.push_back(sc_cell_p); } } if( sc_div_wr_pt_map.find((*vv)) == sc_div_wr_pt_map.end() && sc_div_in_pt_map.find((*vv)) == sc_div_in_pt_map.end() && sc_div_ot_pt_map.find((*vv)) == sc_div_ot_pt_map.end() ){ SC_Module::SC_Port_D *sc_cell_p = new SC_Module::SC_Port_D(); assert( sc_cell_p !=NULL && "Parser->module_links_direct"); sc_cell_p->set_Name((*vv)); sc_cell_p->set_Parent(NULL); SC_Time_D *sc_cell_p_tm = dynamic_cast<SC_Time_D*> (sc_cell_p); SC_Power_D *sc_cell_p_pr = dynamic_cast<SC_Power_D*> (sc_cell_p); SC_Logic_D *sc_cell_p_lg = dynamic_cast<SC_Logic_D*> (sc_cell_p); SC_Type_D *sc_cell_p_tp = dynamic_cast<SC_Type_D*> (sc_cell_p); SC_Domain_D *sc_cell_p_dm = dynamic_cast<SC_Domain_D*>(sc_cell_p); SC_Pass_D *sc_cell_p_ps = dynamic_cast<SC_Pass_D*> (sc_cell_p); sc_cell_p_tm->set_ArriveTime(0); sc_cell_p_pr->set_SwitchPower(0); sc_cell_p_lg->set_PreLogic(SC_Logic_D::SC_LOGIC_x); sc_cell_p_lg->set_CurLogic(SC_Logic_D::SC_LOGIC_x); sc_cell_p_tp->set_Type(SC_Type_D::SC_TYPE_WIRE); ( sc_pass == true )? sc_cell_p_ps->set_Pass(true) : sc_cell_p_ps->set_Pass(false); SC_Module::SC_Port_D *sc_module_p = ( sc_in_pt_map.find((*vv)) != sc_in_pt_map.end() )? sc_in_pt_map[(*vv)] : ( sc_ot_pt_map.find((*vv)) != sc_ot_pt_map.end() )? sc_ot_pt_map[(*vv)] : ( sc_wr_pt_map.find((*vv)) != sc_wr_pt_map.end() )? sc_wr_pt_map[(*vv)] : NULL; assert( sc_module_p !=NULL && "Parser->module_links_direct"); sc_module_p->set_NxtPortVec(sc_cell_p); sc_cell_p->set_PrePortVec(sc_module_p); sc_cell_pt_vec.push_back(sc_cell_p); } } sc_vv.clear(); } /* Line 189 of yacc.c */ #line 1053 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" void set_module_vector_div(){ std::stringstream ss; std::string nm = ""; assert( sc_msb > sc_lsb && "Parser->module_vector_stmt"); for(int i=sc_msb; i>=sc_lsb; --i){ ss << i; nm = sc_token_str + "[" + ss.str() + "]"; sc_vv.push_back(nm); ss.str(""); } } /* Line 189 of yacc.c */ #line 1075 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" void set_moudle_vector_inv_div(){ std::stringstream ss; std::string nm = ""; assert( sc_msb > sc_lsb && "Parser->module_vector_stmt"); for(int i=sc_msb; i>=sc_lsb; --i){ ss << i; nm = sc_token_str + "[" + ss.str() + "]"; sc_vv.push_back("__sc_inv__"+ nm); sc_inv.push_back(nm); ss.str(""); } } /* Line 189 of yacc.c */ #line 1098 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" void set_and_logic_module_cell(){ int inx = 0; assert( !sc_cell_m_str.empty() && !sc_cell_u_str.empty() && !sc_cell_pt_vec.empty() && "Parser->and_logic_module_cell"); SC_Module::SC_Cell_D *sc_cell = new SC_Module::SC_Cell_D(); SC_LIB::SC_AND *sc_and = dynamic_cast<SC_LIB::SC_AND*>(sc_cell); assert( sc_cell!=NULL && "Parser->and_logic_module_cell"); sc_cell->set_Parent(NULL); sc_cell->set_Self(NULL); sc_cell->set_ModuleName(sc_cell_m_str); sc_cell->set_CellName(sc_cell_u_str); sc_cell->set_TLib(SC_Cell::SC_TLIB_AND); sc_cell->set_Pass(false); assert( (int)sc_cell_pt_vec.size() == 3 && "Parser->and_logic_module_cell"); for(sc_cell_pt_iter cp = sc_cell_pt_vec.begin(); cp != sc_cell_pt_vec.end(); ++cp){ SC_Module::SC_Port_D *pp = static_cast<SC_Module::SC_Port_D*>(*cp); assert( pp!= NULL && "Parser->and_logic_module_cell"); sc_cell->set_PortVec(pp); if(inx == 0){ sc_and->set_Dst(pp); } else if(inx == 1){ sc_and->set_Src1(pp); } else { sc_and->set_Src2(pp); } inx++; } sc_cell_map[sc_cell_u_str] = sc_cell; sc_cell_pt_vec.clear(); } /* Line 189 of yacc.c */ #line 1147 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" void set_nand_logic_module_cell(){ int inx = 0; assert( !sc_cell_m_str.empty() && !sc_cell_u_str.empty() && !sc_cell_pt_vec.empty() && "Parser->nand_logic_module_cell"); SC_Module::SC_Cell_D *sc_cell = new SC_Module::SC_Cell_D(); SC_LIB::SC_NAND *sc_nand = dynamic_cast<SC_LIB::SC_NAND*>(sc_cell); assert( sc_cell!=NULL && "Parser->nand_logic_module_cell"); sc_cell->set_Parent(NULL); sc_cell->set_Self(NULL); sc_cell->set_ModuleName(sc_cell_m_str); sc_cell->set_CellName(sc_cell_u_str); sc_cell->set_TLib(SC_Cell::SC_TLIB_NAND); sc_cell->set_Pass(false); assert( (int)sc_cell_pt_vec.size() == 3 && "Parser->nand_logic_module_cell"); for(sc_cell_pt_iter cp = sc_cell_pt_vec.begin(); cp != sc_cell_pt_vec.end(); ++cp){ SC_Module::SC_Port_D *pp = static_cast<SC_Module::SC_Port_D*>(*cp); assert( pp!= NULL && "Parser->nand_logic_module_cell"); sc_cell->set_PortVec(pp); if(inx == 0){ sc_nand->set_Dst(pp); } else if(inx == 1){ sc_nand->set_Src1(pp); } else { sc_nand->set_Src2(pp); } inx++; } sc_cell_map[sc_cell_u_str] = sc_cell; sc_cell_pt_vec.clear(); } /* Line 189 of yacc.c */ #line 1196 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" void set_or_logic_module_cell(){ int inx = 0; assert( !sc_cell_m_str.empty() && !sc_cell_u_str.empty() && !sc_cell_pt_vec.empty() && "Parser->or_logic_module_cell"); SC_Module::SC_Cell_D *sc_cell = new SC_Module::SC_Cell_D(); SC_LIB::SC_OR *sc_or = dynamic_cast<SC_LIB::SC_OR*>(sc_cell); assert( sc_cell!=NULL && "Parser->or_logic_module_cell"); sc_cell->set_Parent(NULL); sc_cell->set_Self(NULL); sc_cell->set_ModuleName(sc_cell_m_str); sc_cell->set_CellName(sc_cell_u_str); sc_cell->set_TLib(SC_Cell::SC_TLIB_OR); sc_cell->set_Pass(false); assert( (int)sc_cell_pt_vec.size() == 3 && "Parser->or_logic_module_cell"); for(sc_cell_pt_iter cp = sc_cell_pt_vec.begin(); cp != sc_cell_pt_vec.end(); ++cp){ SC_Module::SC_Port_D *pp = static_cast<SC_Module::SC_Port_D*>(*cp); assert( pp!= NULL && "Parser->or_logic_module_cell"); sc_cell->set_PortVec(pp); if(inx == 0){ sc_or->set_Dst(pp); } else if(inx == 1){ sc_or->set_Src1(pp); } else { sc_or->set_Src2(pp); } inx++; } sc_cell_map[sc_cell_u_str] = sc_cell; sc_cell_pt_vec.clear(); } /* Line 189 of yacc.c */ #line 1245 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" void set_nor_logic_module_cell(){ int inx = 0; assert( !sc_cell_m_str.empty() && !sc_cell_u_str.empty() && !sc_cell_pt_vec.empty() && "Parser->nor_logic_module_cell"); SC_Module::SC_Cell_D *sc_cell = new SC_Module::SC_Cell_D(); SC_LIB::SC_NOR *sc_nor = dynamic_cast<SC_LIB::SC_NOR*>(sc_cell); assert( sc_cell!=NULL && "Parser->nor_logic_module_cell"); sc_cell->set_Parent(NULL); sc_cell->set_Self(NULL); sc_cell->set_ModuleName(sc_cell_m_str); sc_cell->set_CellName(sc_cell_u_str); sc_cell->set_TLib(SC_Cell::SC_TLIB_NOR); sc_cell->set_Pass(false); assert( (int)sc_cell_pt_vec.size() == 3 && "Parser->nor_logic_module_cell"); for(sc_cell_pt_iter cp = sc_cell_pt_vec.begin(); cp != sc_cell_pt_vec.end(); ++cp){ SC_Module::SC_Port_D *pp = static_cast<SC_Module::SC_Port_D*>(*cp); assert( pp!= NULL && "Parser->nor_logic_module_cell"); sc_cell->set_PortVec(pp); if(inx == 0){ sc_nor->set_Dst(pp); } else if(inx == 1){ sc_nor->set_Src1(pp); } else { sc_nor->set_Src2(pp); } inx++; } sc_cell_map[sc_cell_u_str] = sc_cell; sc_cell_pt_vec.clear(); } /* Line 189 of yacc.c */ #line 1294 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" void set_xor_logic_module_cell(){ int inx = 0; assert( !sc_cell_m_str.empty() && !sc_cell_u_str.empty() && !sc_cell_pt_vec.empty() && "Parser->xor_logic_module_cell"); SC_Module::SC_Cell_D *sc_cell = new SC_Module::SC_Cell_D(); SC_LIB::SC_XOR *sc_xor = dynamic_cast<SC_LIB::SC_XOR*>(sc_cell); assert( sc_cell!=NULL && "Parser->xor_logic_module_cell"); sc_cell->set_Parent(NULL); sc_cell->set_Self(NULL); sc_cell->set_ModuleName(sc_cell_m_str); sc_cell->set_CellName(sc_cell_u_str); sc_cell->set_TLib(SC_Cell::SC_TLIB_XOR); sc_cell->set_Pass(false); assert( (int)sc_cell_pt_vec.size() == 3 && "Parser->xor_logic_module_cell"); for(sc_cell_pt_iter cp = sc_cell_pt_vec.begin(); cp != sc_cell_pt_vec.end(); ++cp){ SC_Module::SC_Port_D *pp = static_cast<SC_Module::SC_Port_D*>(*cp); assert( pp!= NULL && "Parser->xor_logic_module_cell"); sc_cell->set_PortVec(pp); if(inx == 0){ sc_xor->set_Dst(pp); } else if(inx == 1){ sc_xor->set_Src1(pp); } else { sc_xor->set_Src2(pp); } inx++; } sc_cell_map[sc_cell_u_str] = sc_cell; sc_cell_pt_vec.clear(); } /* Line 189 of yacc.c */ #line 1343 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" void set_xnor_logic_module_cell(){ int inx = 0; assert( !sc_cell_m_str.empty() && !sc_cell_u_str.empty() && !sc_cell_pt_vec.empty() && "Parser->xnor_logic_module_cell"); SC_Module::SC_Cell_D *sc_cell = new SC_Module::SC_Cell_D(); SC_LIB::SC_XNOR *sc_xnor = dynamic_cast<SC_LIB::SC_XNOR*>(sc_cell); assert( sc_cell!=NULL && "Parser->xor_logic_module_cell"); sc_cell->set_Parent(NULL); sc_cell->set_Self(NULL); sc_cell->set_ModuleName(sc_cell_m_str); sc_cell->set_CellName(sc_cell_u_str); sc_cell->set_TLib(SC_Cell::SC_TLIB_XOR); sc_cell->set_Pass(false); assert( (int)sc_cell_pt_vec.size() == 3 && "Parser->xnor_logic_module_cell"); for(sc_cell_pt_iter cp = sc_cell_pt_vec.begin(); cp != sc_cell_pt_vec.end(); ++cp){ SC_Module::SC_Port_D *pp = static_cast<SC_Module::SC_Port_D*>(*cp); assert( pp!= NULL && "Parser->xnor_logic_module_cell"); sc_cell->set_PortVec(pp); if(inx == 0){ sc_xnor->set_Dst(pp); } else if(inx == 1){ sc_xnor->set_Src1(pp); } else { sc_xnor->set_Src2(pp); } inx++; } sc_cell_map[sc_cell_u_str] = sc_cell; sc_cell_pt_vec.clear(); } /* Line 189 of yacc.c */ #line 1392 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" void set_buf_logic_module_cell(){ int inx = 0; assert( !sc_cell_m_str.empty() && !sc_cell_u_str.empty() && !sc_cell_pt_vec.empty() && "Parser->buf_logic_module_cell"); SC_Module::SC_Cell_D *sc_cell = new SC_Module::SC_Cell_D(); SC_LIB::SC_BUF *sc_buf = dynamic_cast<SC_LIB::SC_BUF*>(sc_cell); assert( sc_cell!=NULL && "Parser->buf_logic_module_cell"); sc_cell->set_Parent(NULL); sc_cell->set_Self(NULL); sc_cell->set_ModuleName(sc_cell_m_str); sc_cell->set_CellName(sc_cell_u_str); sc_cell->set_TLib(SC_Cell::SC_TLIB_BUF); sc_cell->set_Pass(false); assert( (int)sc_cell_pt_vec.size() == 2 && "Parser->buf_logic_module_cell"); for(sc_cell_pt_iter cp = sc_cell_pt_vec.begin(); cp != sc_cell_pt_vec.end(); ++cp){ SC_Module::SC_Port_D *pp = static_cast<SC_Module::SC_Port_D*>(*cp); assert( pp!= NULL && "Parser->buf_logic_module_cell"); sc_cell->set_PortVec(pp); if(inx == 0){ sc_buf->set_Dst(pp); } else { sc_buf->set_Src(pp); } inx++; } sc_cell_map[sc_cell_u_str] = sc_cell; sc_cell_pt_vec.clear(); } /* Line 189 of yacc.c */ #line 1440 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" void set_inv_logic_module_cell(){ int inx = 0; assert( !sc_cell_m_str.empty() && !sc_cell_u_str.empty() && !sc_cell_pt_vec.empty() && "Parser->inv_logic_module_cell"); SC_Module::SC_Cell_D *sc_cell = new SC_Module::SC_Cell_D(); SC_LIB::SC_INV *sc_inv = dynamic_cast<SC_LIB::SC_INV*>(sc_cell); assert( sc_cell!=NULL && "Parser->inv_logic_module_cell"); sc_cell->set_Parent(NULL); sc_cell->set_Self(NULL); sc_cell->set_ModuleName(sc_cell_m_str); sc_cell->set_CellName(sc_cell_u_str); sc_cell->set_TLib(SC_Cell::SC_TLIB_INV); ( sc_pass == true )? sc_cell->set_Pass(true) : sc_cell->set_Pass(false); assert( (int)sc_cell_pt_vec.size() == 2 && "Parser->inv_logic_module_cell"); for(sc_cell_pt_iter cp = sc_cell_pt_vec.begin(); cp != sc_cell_pt_vec.end(); ++cp){ SC_Module::SC_Port_D *pp = static_cast<SC_Module::SC_Port_D*>(*cp); assert( pp!= NULL && "Parser->inv_logic_module_cell"); sc_cell->set_PortVec(pp); if(inx == 0){ sc_inv->set_Dst(pp); } else { sc_inv->set_Src(pp); } inx++; } sc_cell_map[sc_cell_u_str] = sc_cell; sc_cell_pt_vec.clear(); } /* Line 189 of yacc.c */ #line 1490 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" void add_inv_logic_module_cell(){ for( sc_inv_iter inv_it = sc_inv.begin(); inv_it != sc_inv.end(); ++inv_it){ sc_cell_m_str = "not"; set_cell_unique_name(); SC_Module::SC_Cell_D *sc_cell = new SC_Module::SC_Cell_D(); SC_LIB::SC_INV *sc_inv = dynamic_cast<SC_LIB::SC_INV*>(sc_cell); assert( sc_cell!=NULL && "Parser->add_inv_logic_module_cell"); sc_cell->set_Parent(NULL); sc_cell->set_Self(NULL); sc_cell->set_ModuleName(sc_cell_m_str); sc_cell->set_CellName(sc_cell_u_str); sc_cell->set_TLib(SC_Cell::SC_TLIB_INV); SC_Domain_D *sc_cell_dm = dynamic_cast<SC_Domain_D*>(sc_cell); SC_Pass_D *sc_cell_ps = dynamic_cast<SC_Pass_D*> (sc_cell); ( sc_pass == true )? sc_cell_ps->set_Pass(true) : sc_cell_ps->set_Pass(false); SC_Module::SC_Port_D *sc_module_org_p = ( sc_in_pt_map.find((*inv_it)) != sc_in_pt_map.end() )? sc_in_pt_map[(*inv_it)] : ( sc_ot_pt_map.find((*inv_it)) != sc_ot_pt_map.end() )? sc_ot_pt_map[(*inv_it)] : ( sc_wr_pt_map.find((*inv_it)) != sc_wr_pt_map.end() )? sc_wr_pt_map[(*inv_it)] : NULL; SC_Module::SC_Port_D *sc_module_new_p = new SC_Module::SC_Port_D(); assert( sc_module_org_p!=NULL && sc_module_new_p!=NULL && "Parser->add_inv_logic_module_cell"); sc_module_new_p->set_Name("__sc_inv__"+(*inv_it)); sc_module_new_p->set_Parent(NULL); SC_Time_D *sc_module_new_tm = dynamic_cast<SC_Time_D*> (sc_module_new_p); SC_Power_D *sc_module_new_pr = dynamic_cast<SC_Power_D*> (sc_module_new_p); SC_Logic_D *sc_module_new_lg = dynamic_cast<SC_Logic_D*> (sc_module_new_p); SC_Type_D *sc_module_new_tp = dynamic_cast<SC_Type_D*> (sc_module_new_p); SC_Domain_D *sc_module_new_dm = dynamic_cast<SC_Domain_D*>(sc_module_new_p); SC_Pass_D *sc_module_new_ps = dynamic_cast<SC_Pass_D*> (sc_module_new_p); sc_module_new_tm->set_ArriveTime(0); sc_module_new_pr->set_SwitchPower(0); sc_module_new_lg->set_PreLogic(SC_Logic_D::SC_LOGIC_x); sc_module_new_lg->set_CurLogic(SC_Logic_D::SC_LOGIC_x); sc_module_new_tp->set_Type(SC_Type_D::SC_TYPE_WIRE); ( sc_pass == true )? sc_module_new_ps->set_Pass(true) : sc_module_new_ps->set_Pass(false); sc_wr_pt_map["__sc_inv__"+(*inv_it)] = sc_module_new_p; SC_Module::SC_Port_D *sc_inv_s_p = new SC_Module::SC_Port_D(); SC_Module::SC_Port_D *sc_inv_d_p = new SC_Module::SC_Port_D(); assert( sc_inv_s_p!=NULL && sc_inv_d_p!=NULL && "Parser->add_inv_logic_module_cell"); sc_inv_s_p->set_Name((*inv_it)); sc_inv_s_p->set_Parent(NULL); SC_Time_D *sc_inv_s_tm = dynamic_cast<SC_Time_D*> (sc_inv_s_p); SC_Power_D *sc_inv_s_pr = dynamic_cast<SC_Power_D*> (sc_inv_s_p); SC_Logic_D *sc_inv_s_lg = dynamic_cast<SC_Logic_D*> (sc_inv_s_p); SC_Type_D *sc_inv_s_tp = dynamic_cast<SC_Type_D*> (sc_inv_s_p); SC_Domain_D *sc_inv_s_dm = dynamic_cast<SC_Domain_D*>(sc_inv_s_p); SC_Pass_D *sc_inv_s_ps = dynamic_cast<SC_Pass_D*> (sc_inv_s_p); sc_inv_s_tm->set_ArriveTime(0); sc_inv_s_pr->set_SwitchPower(0); sc_inv_s_lg->set_PreLogic(SC_Logic_D::SC_LOGIC_x); sc_inv_s_lg->set_CurLogic(SC_Logic_D::SC_LOGIC_x); sc_inv_s_tp->set_Type(SC_Type_D::SC_TYPE_WIRE); ( sc_pass == true )? sc_inv_s_ps->set_Pass(true) : sc_inv_s_ps->set_Pass(false); sc_inv_d_p->set_Name("__sc_inv__"+(*inv_it)); sc_inv_d_p->set_Parent(NULL); SC_Time_D *sc_inv_d_tm = dynamic_cast<SC_Time_D*> (sc_inv_d_p); SC_Power_D *sc_inv_d_pr = dynamic_cast<SC_Power_D*> (sc_inv_d_p); SC_Logic_D *sc_inv_d_lg = dynamic_cast<SC_Logic_D*> (sc_inv_d_p); SC_Type_D *sc_inv_d_tp = dynamic_cast<SC_Type_D*> (sc_inv_d_p); SC_Domain_D *sc_inv_d_dm = dynamic_cast<SC_Domain_D*>(sc_inv_d_p); SC_Pass_D *sc_inv_d_ps = dynamic_cast<SC_Pass_D*> (sc_inv_d_p); sc_inv_d_tm->set_ArriveTime(0); sc_inv_d_pr->set_SwitchPower(0); sc_inv_d_lg->set_PreLogic(SC_Logic_D::SC_LOGIC_x); sc_inv_d_lg->set_CurLogic(SC_Logic_D::SC_LOGIC_x); sc_inv_d_tp->set_Type(SC_Type_D::SC_TYPE_WIRE); ( sc_pass == true )? sc_inv_d_ps->set_Pass(true) : sc_inv_d_ps->set_Pass(false); sc_cell->set_PortVec(sc_inv_d_p); sc_cell->set_PortVec(sc_inv_s_p); sc_module_org_p->set_NxtPortVec(sc_inv_s_p); sc_inv_s_p->set_PrePortVec(sc_module_org_p); sc_module_new_p->set_NxtPortVec(sc_inv_d_p); sc_inv_d_p->set_PrePortVec(sc_module_new_p); sc_inv->set_Src(sc_inv_s_p); sc_inv->set_Dst(sc_inv_d_p); sc_cell_map[sc_cell_u_str] = sc_cell; } sc_inv.clear(); } /* Line 189 of yacc.c */ #line 1635 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.cpp" /* Enabling traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 0 #endif /* Enabling the token table. */ #ifndef YYTOKEN_TABLE # define YYTOKEN_TABLE 0 #endif /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ enum yytokentype { TMODULE = 258, TEDMODULE = 259, TINPUT = 260, TOUTPUT = 261, TWIRE = 262, TEND = 263, TRSQUARE = 264, TLSQUARE = 265, TCOLON = 266, TINV = 267, TAND = 268, TNAND = 269, TOR = 270, TNOR = 271, TXOR = 272, TXNOR = 273, TBUF = 274, TNOT = 275, TDFF = 276, TLIBRARY = 277, TDESIGN = 278, TIDENTIFIER = 279, TINTEGER = 280, TDOUBLE = 281, TCEQ = 282, TCNE = 283, TCLT = 284, TCLE = 285, TCGT = 286, TCGE = 287, TEQUAL = 288, TLPAREN = 289, TRPAREN = 290, TLBRACE = 291, TRBRACE = 292, TCOMMA = 293, TDOT = 294, TPLUS = 295, TMINUS = 296, TMUL = 297, TDIV = 298 }; #endif #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE { /* Line 214 of yacc.c */ #line 1628 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" std::string *sc_string; int *sc_int; int token; /* Line 214 of yacc.c */ #line 1723 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.cpp" } YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 #endif /* Copy the second part of user declarations. */ /* Line 264 of yacc.c */ #line 1735 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.cpp" #ifdef short # undef short #endif #ifdef YYTYPE_UINT8 typedef YYTYPE_UINT8 yytype_uint8; #else typedef unsigned char yytype_uint8; #endif #ifdef YYTYPE_INT8 typedef YYTYPE_INT8 yytype_int8; #elif (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) typedef signed char yytype_int8; #else typedef short int yytype_int8; #endif #ifdef YYTYPE_UINT16 typedef YYTYPE_UINT16 yytype_uint16; #else typedef unsigned short int yytype_uint16; #endif #ifdef YYTYPE_INT16 typedef YYTYPE_INT16 yytype_int16; #else typedef short int yytype_int16; #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned int # endif #endif #define YYSIZE_MAXIMUM ((YYSIZE_T) -1) #ifndef YY_ # if YYENABLE_NLS # if ENABLE_NLS # include <libintl.h> /* INFRINGES ON USER NAME SPACE */ # define YY_(msgid) dgettext ("bison-runtime", msgid) # endif # endif # ifndef YY_ # define YY_(msgid) msgid # endif #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(e) ((void) (e)) #else # define YYUSE(e) /* empty */ #endif /* Identity function, used to suppress warnings about constant conditions. */ #ifndef lint # define YYID(n) (n) #else #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static int YYID (int yyi) #else static int YYID (yyi) int yyi; #endif { return yyi; } #endif #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include <alloca.h> /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include <malloc.h> /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef _STDLIB_H # define _STDLIB_H 1 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's `empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0)) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined _STDLIB_H \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef _STDLIB_H # define _STDLIB_H 1 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yytype_int16 yyss_alloc; YYSTYPE yyvs_alloc; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \ + YYSTACK_GAP_MAXIMUM) /* Copy COUNT objects from FROM to TO. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(To, From, Count) \ __builtin_memcpy (To, From, (Count) * sizeof (*(From))) # else # define YYCOPY(To, From, Count) \ do \ { \ YYSIZE_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (To)[yyi] = (From)[yyi]; \ } \ while (YYID (0)) # endif # endif /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack_alloc, Stack) \ do \ { \ YYSIZE_T yynewbytes; \ YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ Stack = &yyptr->Stack_alloc; \ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / sizeof (*yyptr); \ } \ while (YYID (0)) #endif /* YYFINAL -- State number of the termination state. */ #define YYFINAL 5 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 306 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 44 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 15 /* YYNRULES -- Number of rules. */ #define YYNRULES 67 /* YYNRULES -- Number of states. */ #define YYNSTATES 236 /* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */ #define YYUNDEFTOK 2 #define YYMAXUTOK 298 #define YYTRANSLATE(YYX) \ ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */ static const yytype_uint8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43 }; #if YYDEBUG /* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in YYRHS. */ static const yytype_uint16 yyprhs[] = { 0, 0, 3, 5, 6, 16, 17, 28, 33, 39, 45, 47, 49, 51, 53, 56, 59, 62, 65, 74, 78, 87, 91, 100, 104, 111, 117, 124, 130, 137, 143, 150, 156, 163, 169, 176, 182, 189, 195, 202, 208, 215, 221, 227, 235, 237, 241, 249, 259, 263, 269, 271, 274, 279, 285, 292, 300, 302, 305, 310, 316, 323, 331, 335, 340, 347, 355, 364 }; /* YYRHS -- A `-1'-separated list of the rules' RHS. */ static const yytype_int8 yyrhs[] = { 45, 0, -1, 46, -1, -1, 29, 22, 47, 31, 49, 29, 43, 22, 31, -1, -1, 46, 29, 23, 48, 31, 49, 29, 43, 23, 31, -1, 3, 50, 51, 4, -1, 49, 3, 50, 51, 4, -1, 24, 34, 58, 35, 8, -1, 52, -1, 53, -1, 54, -1, 55, -1, 51, 52, -1, 51, 53, -1, 51, 54, -1, 51, 55, -1, 5, 10, 25, 11, 25, 9, 58, 8, -1, 5, 58, 8, -1, 6, 10, 25, 11, 25, 9, 58, 8, -1, 6, 58, 8, -1, 7, 10, 25, 11, 25, 9, 58, 8, -1, 7, 58, 8, -1, 13, 24, 34, 56, 35, 8, -1, 13, 34, 56, 35, 8, -1, 14, 24, 34, 56, 35, 8, -1, 14, 34, 56, 35, 8, -1, 15, 24, 34, 56, 35, 8, -1, 15, 34, 56, 35, 8, -1, 16, 24, 34, 56, 35, 8, -1, 16, 34, 56, 35, 8, -1, 17, 24, 34, 56, 35, 8, -1, 17, 34, 56, 35, 8, -1, 18, 24, 34, 56, 35, 8, -1, 18, 34, 56, 35, 8, -1, 19, 24, 34, 56, 35, 8, -1, 19, 34, 56, 35, 8, -1, 20, 24, 34, 56, 35, 8, -1, 20, 34, 56, 35, 8, -1, 24, 24, 34, 56, 35, 8, -1, 24, 34, 56, 35, 8, -1, 39, 24, 34, 58, 35, -1, 39, 24, 34, 36, 58, 37, 35, -1, 57, -1, 36, 58, 37, -1, 56, 38, 39, 24, 34, 58, 35, -1, 56, 38, 39, 24, 34, 36, 58, 37, 35, -1, 56, 38, 57, -1, 56, 38, 36, 58, 37, -1, 24, -1, 12, 24, -1, 24, 10, 25, 9, -1, 12, 24, 10, 25, 9, -1, 24, 10, 25, 11, 25, 9, -1, 12, 24, 10, 25, 11, 25, 9, -1, 24, -1, 12, 24, -1, 24, 10, 25, 9, -1, 12, 24, 10, 25, 9, -1, 24, 10, 25, 11, 25, 9, -1, 12, 24, 10, 25, 11, 25, 9, -1, 58, 38, 24, -1, 58, 38, 12, 24, -1, 58, 38, 24, 10, 25, 9, -1, 58, 38, 12, 24, 10, 25, 9, -1, 58, 38, 24, 10, 25, 11, 25, 9, -1, 58, 38, 12, 24, 10, 25, 11, 25, 9, -1 }; /* YYRLINE[YYN] -- source line where rule number YYN was defined. */ static const yytype_uint16 yyrline[] = { 0, 1663, 1663, 1667, 1667, 1668, 1668, 1671, 1680, 1695, 1705, 1710, 1715, 1720, 1725, 1730, 1735, 1740, 1750, 1758, 1770, 1778, 1789, 1797, 1808, 1816, 1824, 1832, 1840, 1848, 1856, 1864, 1872, 1880, 1888, 1896, 1904, 1912, 1920, 1928, 1936, 1944, 1956, 1963, 1970, 1977, 1984, 1992, 2000, 2008, 2019, 2024, 2031, 2037, 2044, 2053, 2065, 2070, 2077, 2083, 2090, 2099, 2109, 2114, 2121, 2127, 2134, 2143 }; #endif #if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "$end", "error", "$undefined", "TMODULE", "TEDMODULE", "TINPUT", "TOUTPUT", "TWIRE", "TEND", "TRSQUARE", "TLSQUARE", "TCOLON", "TINV", "TAND", "TNAND", "TOR", "TNOR", "TXOR", "TXNOR", "TBUF", "TNOT", "TDFF", "TLIBRARY", "TDESIGN", "TIDENTIFIER", "TINTEGER", "TDOUBLE", "TCEQ", "TCNE", "TCLT", "TCLE", "TCGT", "TCGE", "TEQUAL", "TLPAREN", "TRPAREN", "TLBRACE", "TRBRACE", "TCOMMA", "TDOT", "TPLUS", "TMINUS", "TMUL", "TDIV", "$accept", "program", "top_stmt", "$@1", "$@2", "modules_stmt", "module_signal_stmt", "module_contains_stmt", "module_input_stmt", "module_output_stmt", "module_wire_stmt", "module_cell_stmt", "module_links_stmt", "module_ident_stmt", "module_vector_stmt", 0 }; #endif # ifdef YYPRINT /* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to token YYLEX-NUM. */ static const yytype_uint16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298 }; # endif /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_uint8 yyr1[] = { 0, 44, 45, 47, 46, 48, 46, 49, 49, 50, 51, 51, 51, 51, 51, 51, 51, 51, 52, 52, 53, 53, 54, 54, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 56, 56, 56, 56, 56, 56, 56, 56, 57, 57, 57, 57, 57, 57, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58 }; /* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */ static const yytype_uint8 yyr2[] = { 0, 2, 1, 0, 9, 0, 10, 4, 5, 5, 1, 1, 1, 1, 2, 2, 2, 2, 8, 3, 8, 3, 8, 3, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 5, 7, 1, 3, 7, 9, 3, 5, 1, 2, 4, 5, 6, 7, 1, 2, 4, 5, 6, 7, 3, 4, 6, 7, 8, 9 }; /* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state STATE-NUM when YYTABLE doesn't specify something else to do. Zero means the default is an error. */ static const yytype_uint8 yydefact[] = { 0, 0, 0, 2, 3, 1, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 11, 12, 13, 0, 0, 0, 0, 56, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 14, 15, 16, 17, 0, 0, 0, 57, 0, 0, 0, 0, 19, 0, 21, 0, 23, 0, 0, 50, 0, 0, 0, 44, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 4, 0, 0, 0, 9, 0, 62, 0, 0, 0, 0, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 58, 0, 63, 0, 0, 0, 0, 0, 0, 0, 45, 0, 25, 0, 0, 48, 0, 27, 0, 29, 0, 31, 0, 33, 0, 35, 0, 37, 0, 39, 0, 41, 59, 0, 0, 0, 0, 0, 0, 0, 24, 0, 52, 0, 0, 0, 0, 0, 26, 28, 30, 32, 34, 36, 38, 40, 0, 60, 0, 64, 0, 0, 0, 0, 53, 0, 0, 0, 42, 49, 0, 61, 65, 0, 0, 18, 20, 22, 0, 54, 0, 0, 0, 0, 66, 55, 43, 0, 46, 67, 0, 47 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int8 yydefgoto[] = { -1, 2, 3, 7, 10, 12, 15, 32, 33, 34, 35, 36, 90, 91, 42 }; /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ #define YYPACT_NINF -50 static const yytype_int16 yypact[] = { -6, 12, 82, 54, -50, -50, 93, 65, -50, 133, 99, 124, 11, 133, 104, 127, 124, 117, 34, 8, 6, 9, 15, 7, 45, 46, 47, 73, 74, 85, 94, 105, 86, -50, -50, -50, -50, 127, 181, 122, 188, 201, 0, 189, 4, 192, 14, 193, 16, 179, 48, 182, 48, 185, 48, 194, 48, 196, 48, 197, 48, 198, 48, 199, 48, 200, 48, -50, -50, -50, -50, -50, 107, 184, 202, 210, 204, 213, 52, 211, -50, 212, -50, 215, -50, 48, 203, 214, 8, 216, 40, -50, 48, 114, 48, 115, 48, 119, 48, 120, 48, 121, 48, 129, 48, 131, 48, 135, -50, -50, 205, 217, 106, -50, 219, 225, 220, 221, 222, 136, 227, 223, 29, 207, 230, 49, 137, 231, 141, 236, 142, 241, 143, 242, 147, 243, 148, 244, 149, 245, 153, 246, -50, 186, -50, 232, 248, 234, 247, 251, 252, 254, 238, 187, -50, 50, -50, 8, 240, -50, 257, -50, 258, -50, 259, -50, 260, -50, 261, -50, 262, -50, 263, -50, 264, -50, -50, 249, 266, 253, 190, 8, 8, 8, -50, 191, -50, 255, 8, 154, 57, 239, -50, -50, -50, -50, -50, -50, -50, -50, 267, -50, 195, -50, 256, 18, 20, 21, -50, 265, 268, 170, -50, -50, 53, -50, -50, 269, 270, -50, -50, -50, 273, -50, 250, 8, 155, 274, -50, -50, -50, 172, -50, -50, 271, -50 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int16 yypgoto[] = { -50, -50, -50, -50, -50, 275, 276, 218, -28, -26, -24, -22, -49, 159, -20 }; /* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule which number is the opposite. If zero, do what YYDEFACT says. If YYTABLE_NINF, syntax error. */ #define YYTABLE_NINF -1 static const yytype_uint8 yytable[] = { 44, 46, 48, 93, 68, 95, 69, 97, 70, 99, 71, 101, 80, 103, 16, 105, 43, 107, 40, 45, 40, 40, 82, 1, 84, 47, 219, 40, 220, 221, 41, 49, 41, 41, 4, 77, 119, 16, 78, 41, 17, 50, 78, 126, 68, 128, 69, 130, 70, 132, 71, 134, 78, 136, 78, 138, 78, 140, 78, 78, 86, 86, 40, 39, 114, 40, 154, 78, 122, 51, 53, 55, 87, 87, 41, 124, 115, 41, 125, 52, 54, 56, 5, 6, 88, 157, 188, 89, 158, 225, 67, 20, 21, 22, 213, 78, 9, 57, 59, 23, 24, 25, 26, 27, 28, 29, 30, 58, 60, 61, 31, 108, 20, 21, 22, 144, 8, 145, 63, 62, 23, 24, 25, 26, 27, 28, 29, 30, 64, 65, 13, 31, 20, 21, 22, 189, 11, 190, 19, 66, 23, 24, 25, 26, 27, 28, 29, 30, 14, 127, 129, 31, 125, 125, 131, 133, 135, 125, 125, 125, 38, 205, 206, 207, 137, 74, 139, 125, 211, 125, 141, 151, 160, 125, 125, 125, 162, 164, 166, 125, 125, 125, 168, 170, 172, 125, 125, 125, 174, 212, 232, 125, 78, 78, 226, 176, 186, 177, 187, 203, 208, 204, 209, 73, 216, 231, 217, 224, 78, 234, 78, 76, 75, 85, 79, 109, 92, 81, 83, 94, 111, 113, 116, 117, 121, 110, 118, 120, 96, 112, 98, 100, 102, 104, 106, 147, 142, 152, 156, 161, 123, 155, 143, 146, 163, 148, 149, 150, 153, 165, 167, 169, 171, 173, 175, 72, 181, 178, 179, 180, 182, 183, 184, 185, 191, 192, 193, 194, 195, 196, 197, 198, 199, 214, 200, 201, 215, 223, 202, 228, 210, 218, 229, 233, 159, 230, 0, 0, 18, 0, 222, 0, 37, 0, 227, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 235 }; static const yytype_int16 yycheck[] = { 20, 21, 22, 52, 32, 54, 32, 56, 32, 58, 32, 60, 8, 62, 3, 64, 10, 66, 12, 10, 12, 12, 8, 29, 8, 10, 8, 12, 8, 8, 24, 24, 24, 24, 22, 35, 85, 3, 38, 24, 29, 34, 38, 92, 72, 94, 72, 96, 72, 98, 72, 100, 38, 102, 38, 104, 38, 106, 38, 38, 12, 12, 12, 29, 12, 12, 37, 38, 88, 24, 24, 24, 24, 24, 24, 35, 24, 24, 38, 34, 34, 34, 0, 29, 36, 36, 36, 39, 39, 36, 4, 5, 6, 7, 37, 38, 31, 24, 24, 13, 14, 15, 16, 17, 18, 19, 20, 34, 34, 24, 24, 4, 5, 6, 7, 9, 23, 11, 24, 34, 13, 14, 15, 16, 17, 18, 19, 20, 34, 24, 31, 24, 5, 6, 7, 155, 3, 157, 34, 34, 13, 14, 15, 16, 17, 18, 19, 20, 24, 35, 35, 24, 38, 38, 35, 35, 35, 38, 38, 38, 43, 181, 182, 183, 35, 43, 35, 38, 188, 38, 35, 35, 35, 38, 38, 38, 35, 35, 35, 38, 38, 38, 35, 35, 35, 38, 38, 38, 35, 35, 35, 38, 38, 38, 214, 9, 9, 11, 11, 9, 9, 11, 11, 22, 9, 225, 11, 37, 38, 37, 38, 10, 24, 34, 25, 31, 34, 25, 25, 34, 10, 8, 11, 11, 10, 23, 11, 24, 34, 25, 34, 34, 34, 34, 34, 10, 31, 10, 8, 8, 24, 34, 25, 24, 8, 25, 25, 25, 25, 8, 8, 8, 8, 8, 8, 37, 9, 25, 10, 25, 9, 9, 8, 25, 24, 8, 8, 8, 8, 8, 8, 8, 8, 34, 25, 9, 9, 9, 25, 9, 25, 25, 9, 9, 125, 35, -1, -1, 13, -1, 25, -1, 16, -1, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 35 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_uint8 yystos[] = { 0, 29, 45, 46, 22, 0, 29, 47, 23, 31, 48, 3, 49, 31, 24, 50, 3, 29, 49, 34, 5, 6, 7, 13, 14, 15, 16, 17, 18, 19, 20, 24, 51, 52, 53, 54, 55, 50, 43, 29, 12, 24, 58, 10, 58, 10, 58, 10, 58, 24, 34, 24, 34, 24, 34, 24, 34, 24, 34, 24, 34, 24, 34, 24, 34, 24, 34, 4, 52, 53, 54, 55, 51, 22, 43, 24, 10, 35, 38, 25, 8, 25, 8, 25, 8, 34, 12, 24, 36, 39, 56, 57, 34, 56, 34, 56, 34, 56, 34, 56, 34, 56, 34, 56, 34, 56, 34, 56, 4, 31, 23, 10, 25, 8, 12, 24, 11, 11, 11, 56, 24, 10, 58, 24, 35, 38, 56, 35, 56, 35, 56, 35, 56, 35, 56, 35, 56, 35, 56, 35, 56, 35, 31, 25, 9, 11, 24, 10, 25, 25, 25, 35, 10, 25, 37, 34, 8, 36, 39, 57, 35, 8, 35, 8, 35, 8, 35, 8, 35, 8, 35, 8, 35, 8, 35, 8, 9, 11, 25, 10, 25, 9, 9, 9, 8, 25, 9, 11, 36, 58, 58, 24, 8, 8, 8, 8, 8, 8, 8, 8, 25, 9, 25, 9, 11, 58, 58, 58, 9, 11, 25, 58, 35, 37, 34, 9, 9, 11, 25, 8, 8, 8, 25, 9, 37, 36, 58, 25, 9, 9, 35, 58, 35, 9, 37, 35 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab /* Like YYERROR except do call yyerror. This remains here temporarily to ease the transition to the new meaning of YYERROR, for GCC. Once GCC version 2 has supplanted version 1, this can go. */ #define YYFAIL goto yyerrlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY && yylen == 1) \ { \ yychar = (Token); \ yylval = (Value); \ yytoken = YYTRANSLATE (yychar); \ YYPOPSTACK (1); \ goto yybackup; \ } \ else \ { \ yyerror (YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (YYID (0)) #define YYTERROR 1 #define YYERRCODE 256 /* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. If N is 0, then set CURRENT to the empty location which ends the previous symbol: RHS[0] (always defined). */ #define YYRHSLOC(Rhs, K) ((Rhs)[K]) #ifndef YYLLOC_DEFAULT # define YYLLOC_DEFAULT(Current, Rhs, N) \ do \ if (YYID (N)) \ { \ (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \ (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \ (Current).last_line = YYRHSLOC (Rhs, N).last_line; \ (Current).last_column = YYRHSLOC (Rhs, N).last_column; \ } \ else \ { \ (Current).first_line = (Current).last_line = \ YYRHSLOC (Rhs, 0).last_line; \ (Current).first_column = (Current).last_column = \ YYRHSLOC (Rhs, 0).last_column; \ } \ while (YYID (0)) #endif /* YY_LOCATION_PRINT -- Print the location on the stream. This macro was not mandated originally: define only if we know we won't break user code: when these are the locations we know. */ #ifndef YY_LOCATION_PRINT # if YYLTYPE_IS_TRIVIAL # define YY_LOCATION_PRINT(File, Loc) \ fprintf (File, "%d.%d-%d.%d", \ (Loc).first_line, (Loc).first_column, \ (Loc).last_line, (Loc).last_column) # else # define YY_LOCATION_PRINT(File, Loc) ((void) 0) # endif #endif /* YYLEX -- calling `yylex' with the right arguments. */ #ifdef YYLEX_PARAM # define YYLEX yylex (YYLEX_PARAM) #else # define YYLEX yylex () #endif /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include <stdio.h> /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (YYID (0)) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value); \ YYFPRINTF (stderr, "\n"); \ } \ } while (YYID (0)) /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) #else static void yy_symbol_value_print (yyoutput, yytype, yyvaluep) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; #endif { if (!yyvaluep) return; # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); # else YYUSE (yyoutput); # endif switch (yytype) { default: break; } } /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) #else static void yy_symbol_print (yyoutput, yytype, yyvaluep) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; #endif { if (yytype < YYNTOKENS) YYFPRINTF (yyoutput, "token %s (", yytname[yytype]); else YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]); yy_symbol_value_print (yyoutput, yytype, yyvaluep); YYFPRINTF (yyoutput, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop) #else static void yy_stack_print (yybottom, yytop) yytype_int16 *yybottom; yytype_int16 *yytop; #endif { YYFPRINTF (stderr, "Stack now"); for (; yybottom <= yytop; yybottom++) { int yybot = *yybottom; YYFPRINTF (stderr, " %d", yybot); } YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (YYID (0)) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_reduce_print (YYSTYPE *yyvsp, int yyrule) #else static void yy_reduce_print (yyvsp, yyrule) YYSTYPE *yyvsp; int yyrule; #endif { int yynrhs = yyr2[yyrule]; int yyi; unsigned long int yylno = yyrline[yyrule]; YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { YYFPRINTF (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi], &(yyvsp[(yyi + 1) - (yynrhs)]) ); YYFPRINTF (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyvsp, Rule); \ } while (YYID (0)) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen strlen # else /* Return the length of YYSTR. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static YYSIZE_T yystrlen (const char *yystr) #else static YYSIZE_T yystrlen (yystr) const char *yystr; #endif { YYSIZE_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static char * yystpcpy (char *yydest, const char *yysrc) #else static char * yystpcpy (yydest, yysrc) char *yydest; const char *yysrc; #endif { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYSIZE_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYSIZE_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (! yyres) return yystrlen (yystr); return yystpcpy (yyres, yystr) - yyres; } # endif /* Copy into YYRESULT an error message about the unexpected token YYCHAR while in state YYSTATE. Return the number of bytes copied, including the terminating null byte. If YYRESULT is null, do not copy anything; just return the number of bytes that would be copied. As a special case, return 0 if an ordinary "syntax error" message will do. Return YYSIZE_MAXIMUM if overflow occurs during size calculation. */ static YYSIZE_T yysyntax_error (char *yyresult, int yystate, int yychar) { int yyn = yypact[yystate]; if (! (YYPACT_NINF < yyn && yyn <= YYLAST)) return 0; else { int yytype = YYTRANSLATE (yychar); YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]); YYSIZE_T yysize = yysize0; YYSIZE_T yysize1; int yysize_overflow = 0; enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; int yyx; # if 0 /* This is so xgettext sees the translatable formats that are constructed on the fly. */ YY_("syntax error, unexpected %s"); YY_("syntax error, unexpected %s, expecting %s"); YY_("syntax error, unexpected %s, expecting %s or %s"); YY_("syntax error, unexpected %s, expecting %s or %s or %s"); YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"); # endif char *yyfmt; char const *yyf; static char const yyunexpected[] = "syntax error, unexpected %s"; static char const yyexpecting[] = ", expecting %s"; static char const yyor[] = " or %s"; char yyformat[sizeof yyunexpected + sizeof yyexpecting - 1 + ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2) * (sizeof yyor - 1))]; char const *yyprefix = yyexpecting; /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yycount = 1; yyarg[0] = yytname[yytype]; yyfmt = yystpcpy (yyformat, yyunexpected); for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; yyformat[sizeof yyunexpected - 1] = '\0'; break; } yyarg[yycount++] = yytname[yyx]; yysize1 = yysize + yytnamerr (0, yytname[yyx]); yysize_overflow |= (yysize1 < yysize); yysize = yysize1; yyfmt = yystpcpy (yyfmt, yyprefix); yyprefix = yyor; } yyf = YY_(yyformat); yysize1 = yysize + yystrlen (yyf); yysize_overflow |= (yysize1 < yysize); yysize = yysize1; if (yysize_overflow) return YYSIZE_MAXIMUM; if (yyresult) { /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ char *yyp = yyresult; int yyi = 0; while ((*yyp = *yyf) != '\0') { if (*yyp == '%' && yyf[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyf += 2; } else { yyp++; yyf++; } } } return yysize; } } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep) #else static void yydestruct (yymsg, yytype, yyvaluep) const char *yymsg; int yytype; YYSTYPE *yyvaluep; #endif { YYUSE (yyvaluep); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); switch (yytype) { default: break; } } /* Prevent warnings from -Wmissing-prototypes. */ #ifdef YYPARSE_PARAM #if defined __STDC__ || defined __cplusplus int yyparse (void *YYPARSE_PARAM); #else int yyparse (); #endif #else /* ! YYPARSE_PARAM */ #if defined __STDC__ || defined __cplusplus int yyparse (void); #else int yyparse (); #endif #endif /* ! YYPARSE_PARAM */ /* The lookahead symbol. */ int yychar; /* The semantic value of the lookahead symbol. */ YYSTYPE yylval; /* Number of syntax errors so far. */ int yynerrs; /*-------------------------. | yyparse or yypush_parse. | `-------------------------*/ #ifdef YYPARSE_PARAM #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (void *YYPARSE_PARAM) #else int yyparse (YYPARSE_PARAM) void *YYPARSE_PARAM; #endif #else /* ! YYPARSE_PARAM */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (void) #else int yyparse () #endif #endif { int yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: `yyss': related to states. `yyvs': related to semantic values. Refer to the stacks thru separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; YYSIZE_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yytoken = 0; yyss = yyssa; yyvs = yyvsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ /* Initialize stack pointers. Waste one element of value and location stack so that they stay on the same level as the state stack. The wasted elements are never initialized. */ yyssp = yyss; yyvsp = yyvs; goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yyn == YYPACT_NINF) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = YYLEX; } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yyn == 0 || yyn == YYTABLE_NINF) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token. */ yychar = YYEMPTY; yystate = yyn; *++yyvsp = yylval; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: `$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { case 2: /* Line 1455 of yacc.c */ #line 1663 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" {;} break; case 3: /* Line 1455 of yacc.c */ #line 1667 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_pass = false; ;} break; case 5: /* Line 1455 of yacc.c */ #line 1668 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_pass = true; ;} break; case 7: /* Line 1455 of yacc.c */ #line 1672 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { set_module(); #ifdef SC_Debug sc_dump("@ SC_Module " + sc_module_str + " Pass"); #endif ;} break; case 8: /* Line 1455 of yacc.c */ #line 1681 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { set_module(); #ifdef SC_Debug sc_dump("@ SC_Module " + sc_module_str + " Pass"); #endif ;} break; case 9: /* Line 1455 of yacc.c */ #line 1696 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_module_str = (*(yyvsp[(1) - (5)].sc_string)); set_module_signal(); ;} break; case 10: /* Line 1455 of yacc.c */ #line 1705 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { #ifdef SC_Debug sc_dump(" SC_Module_Input_Pass"); #endif ;} break; case 11: /* Line 1455 of yacc.c */ #line 1710 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { #ifdef SC_Debug sc_dump(" SC_Module_Output_Pass"); #endif ;} break; case 12: /* Line 1455 of yacc.c */ #line 1715 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { #ifdef SC_Debug sc_dump(" SC_Module_Wire_Pass"); #endif ;} break; case 13: /* Line 1455 of yacc.c */ #line 1720 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { #ifdef SC_Debug sc_dump(" SC_Module_Cell_Pass"); #endif ;} break; case 14: /* Line 1455 of yacc.c */ #line 1725 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { #ifdef SC_Debug sc_dump(" SC_Module_Input_Pass"); #endif ;} break; case 15: /* Line 1455 of yacc.c */ #line 1730 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { #ifdef SC_Debug sc_dump(" SC_Module_Output_Pass"); #endif ;} break; case 16: /* Line 1455 of yacc.c */ #line 1735 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { #ifdef SC_Debug sc_dump(" SC_Module_Wire_Pass"); #endif ;} break; case 17: /* Line 1455 of yacc.c */ #line 1740 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { #ifdef SC_Debug sc_dump(" SC_Module_Cell_Pass"); #endif ;} break; case 18: /* Line 1455 of yacc.c */ #line 1751 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_msb = atoi((*(yyvsp[(3) - (8)].sc_string)).c_str()); sc_lsb = atoi((*(yyvsp[(5) - (8)].sc_string)).c_str()); set_module_input_div(); ;} break; case 19: /* Line 1455 of yacc.c */ #line 1759 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_msb = 0; sc_lsb = 0; set_module_input_only(); ;} break; case 20: /* Line 1455 of yacc.c */ #line 1771 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_msb = atoi((*(yyvsp[(3) - (8)].sc_string)).c_str()); sc_lsb = atoi((*(yyvsp[(5) - (8)].sc_string)).c_str()); set_module_output_div(); ;} break; case 21: /* Line 1455 of yacc.c */ #line 1779 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_msb = 0; sc_lsb = 0; set_module_output_only(); ;} break; case 22: /* Line 1455 of yacc.c */ #line 1790 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_msb = atoi((*(yyvsp[(3) - (8)].sc_string)).c_str()); sc_lsb = atoi((*(yyvsp[(5) - (8)].sc_string)).c_str()); set_module_wire_div(); ;} break; case 23: /* Line 1455 of yacc.c */ #line 1798 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_msb = 0; sc_lsb = 0; set_module_wire_only(); ;} break; case 24: /* Line 1455 of yacc.c */ #line 1809 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_cell_m_str = "and"; sc_cell_u_str = (*(yyvsp[(2) - (6)].sc_string)); set_and_logic_module_cell(); ;} break; case 25: /* Line 1455 of yacc.c */ #line 1817 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_cell_m_str = "and"; set_cell_unique_name(); set_and_logic_module_cell(); ;} break; case 26: /* Line 1455 of yacc.c */ #line 1825 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_cell_m_str = "nand"; sc_cell_u_str = (*(yyvsp[(2) - (6)].sc_string)); set_nand_logic_module_cell(); ;} break; case 27: /* Line 1455 of yacc.c */ #line 1833 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_cell_m_str = "nand"; set_cell_unique_name(); set_nand_logic_module_cell(); ;} break; case 28: /* Line 1455 of yacc.c */ #line 1841 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_cell_m_str = "or"; sc_cell_u_str = (*(yyvsp[(2) - (6)].sc_string)); set_or_logic_module_cell(); ;} break; case 29: /* Line 1455 of yacc.c */ #line 1849 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_cell_m_str = "or"; set_cell_unique_name(); set_or_logic_module_cell(); ;} break; case 30: /* Line 1455 of yacc.c */ #line 1857 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_cell_m_str = "nor"; sc_cell_u_str = (*(yyvsp[(2) - (6)].sc_string)); set_nor_logic_module_cell(); ;} break; case 31: /* Line 1455 of yacc.c */ #line 1865 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_cell_m_str = "nor"; set_cell_unique_name(); set_nor_logic_module_cell(); ;} break; case 32: /* Line 1455 of yacc.c */ #line 1873 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_cell_m_str = "xor"; sc_cell_u_str = (*(yyvsp[(2) - (6)].sc_string)); set_xor_logic_module_cell(); ;} break; case 33: /* Line 1455 of yacc.c */ #line 1881 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_cell_m_str = "xor"; set_cell_unique_name(); set_xor_logic_module_cell(); ;} break; case 34: /* Line 1455 of yacc.c */ #line 1889 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_cell_m_str = "xnor"; sc_cell_u_str = (*(yyvsp[(2) - (6)].sc_string)); set_xnor_logic_module_cell(); ;} break; case 35: /* Line 1455 of yacc.c */ #line 1897 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_cell_m_str = "xnor"; set_cell_unique_name(); set_xnor_logic_module_cell(); ;} break; case 36: /* Line 1455 of yacc.c */ #line 1905 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_cell_m_str = "buf"; sc_cell_u_str = (*(yyvsp[(2) - (6)].sc_string)); set_buf_logic_module_cell(); ;} break; case 37: /* Line 1455 of yacc.c */ #line 1913 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_cell_m_str = "buf"; set_cell_unique_name(); set_buf_logic_module_cell(); ;} break; case 38: /* Line 1455 of yacc.c */ #line 1921 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_cell_m_str = "not"; sc_cell_u_str = (*(yyvsp[(2) - (6)].sc_string)); set_inv_logic_module_cell(); ;} break; case 39: /* Line 1455 of yacc.c */ #line 1929 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_cell_m_str = "not"; set_cell_unique_name(); set_inv_logic_module_cell(); ;} break; case 40: /* Line 1455 of yacc.c */ #line 1937 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_cell_m_str = (*(yyvsp[(1) - (6)].sc_string)); sc_cell_u_str = (*(yyvsp[(2) - (6)].sc_string)); set_module_cell(); ;} break; case 41: /* Line 1455 of yacc.c */ #line 1945 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_cell_m_str = (*(yyvsp[(1) - (5)].sc_string)); set_cell_unique_name(); set_module_cell(); ;} break; case 42: /* Line 1455 of yacc.c */ #line 1957 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_cell_p_str = (*(yyvsp[(2) - (5)].sc_string)); add_inv_logic_module_cell(); set_module_links_indirect(); ;} break; case 43: /* Line 1455 of yacc.c */ #line 1964 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_cell_p_str = (*(yyvsp[(2) - (7)].sc_string)); add_inv_logic_module_cell(); set_module_links_indirect(); ;} break; case 44: /* Line 1455 of yacc.c */ #line 1971 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_cell_p_str = ""; add_inv_logic_module_cell(); set_module_links_direct(); ;} break; case 45: /* Line 1455 of yacc.c */ #line 1978 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_cell_p_str = ""; add_inv_logic_module_cell(); set_module_links_direct(); ;} break; case 46: /* Line 1455 of yacc.c */ #line 1985 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_cell_p_str = (*(yyvsp[(4) - (7)].sc_string)); add_inv_logic_module_cell(); set_module_links_indirect(); ;} break; case 47: /* Line 1455 of yacc.c */ #line 1993 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_cell_p_str = (*(yyvsp[(4) - (9)].sc_string)); add_inv_logic_module_cell(); set_module_links_indirect(); ;} break; case 48: /* Line 1455 of yacc.c */ #line 2001 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_cell_p_str = ""; add_inv_logic_module_cell(); set_module_links_direct(); ;} break; case 49: /* Line 1455 of yacc.c */ #line 2009 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_cell_p_str = ""; add_inv_logic_module_cell(); set_module_links_direct(); ;} break; case 50: /* Line 1455 of yacc.c */ #line 2020 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_vv.push_back(*(yyvsp[(1) - (1)].sc_string)); ;} break; case 51: /* Line 1455 of yacc.c */ #line 2025 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { std::string nm = (*(yyvsp[(2) - (2)].sc_string)); sc_vv.push_back("__sc_inv__"+nm); sc_inv.push_back((*(yyvsp[(2) - (2)].sc_string))); ;} break; case 52: /* Line 1455 of yacc.c */ #line 2032 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { std::string nm = (*(yyvsp[(1) - (4)].sc_string)) + "[" + (*(yyvsp[(3) - (4)].sc_string)) + "]"; sc_vv.push_back(nm); ;} break; case 53: /* Line 1455 of yacc.c */ #line 2038 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { std::string nm = (*(yyvsp[(2) - (5)].sc_string)) + "[" + (*(yyvsp[(4) - (5)].sc_string)) + "]"; sc_vv.push_back("__sc_inv__"+nm); sc_inv.push_back(nm); ;} break; case 54: /* Line 1455 of yacc.c */ #line 2045 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_msb = atoi((*(yyvsp[(3) - (6)].sc_string)).c_str()); sc_lsb = atoi((*(yyvsp[(5) - (6)].sc_string)).c_str()); sc_token_str = (*(yyvsp[(1) - (6)].sc_string)); set_module_vector_div(); ;} break; case 55: /* Line 1455 of yacc.c */ #line 2054 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_msb = atoi((*(yyvsp[(4) - (7)].sc_string)).c_str()); sc_lsb = atoi((*(yyvsp[(6) - (7)].sc_string)).c_str()); sc_token_str = (*(yyvsp[(2) - (7)].sc_string)); set_moudle_vector_inv_div(); ;} break; case 56: /* Line 1455 of yacc.c */ #line 2066 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_vv.push_back((*(yyvsp[(1) - (1)].sc_string))); ;} break; case 57: /* Line 1455 of yacc.c */ #line 2071 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { std::string nm = (*(yyvsp[(2) - (2)].sc_string)); sc_vv.push_back("__sc_inv__"+nm); sc_inv.push_back(nm); ;} break; case 58: /* Line 1455 of yacc.c */ #line 2078 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { std::string nm = (*(yyvsp[(1) - (4)].sc_string)) + "[" + (*(yyvsp[(3) - (4)].sc_string)) + "]"; sc_vv.push_back(nm); ;} break; case 59: /* Line 1455 of yacc.c */ #line 2084 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { std::string nm = (*(yyvsp[(2) - (5)].sc_string)) + "[" + (*(yyvsp[(4) - (5)].sc_string)) + "]"; sc_vv.push_back("__sc_inv__"+nm); sc_inv.push_back(nm); ;} break; case 60: /* Line 1455 of yacc.c */ #line 2091 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_msb = atoi((*(yyvsp[(3) - (6)].sc_string)).c_str()); sc_lsb = atoi((*(yyvsp[(5) - (6)].sc_string)).c_str()); sc_token_str = (*(yyvsp[(1) - (6)].sc_string)); set_module_vector_div(); ;} break; case 61: /* Line 1455 of yacc.c */ #line 2100 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_msb = atoi((*(yyvsp[(4) - (7)].sc_string)).c_str()); sc_lsb = atoi((*(yyvsp[(6) - (7)].sc_string)).c_str()); sc_token_str = (*(yyvsp[(2) - (7)].sc_string)); set_moudle_vector_inv_div(); ;} break; case 62: /* Line 1455 of yacc.c */ #line 2110 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_vv.push_back((*(yyvsp[(3) - (3)].sc_string))); ;} break; case 63: /* Line 1455 of yacc.c */ #line 2115 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { std::string nm = (*(yyvsp[(2) - (4)].sc_string)); sc_vv.push_back("__sc_inv__"+nm); sc_inv.push_back(nm); ;} break; case 64: /* Line 1455 of yacc.c */ #line 2122 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { std::string nm = (*(yyvsp[(1) - (6)].sc_string)) + "[" + (*(yyvsp[(3) - (6)].sc_string)) + "]"; sc_vv.push_back(nm); ;} break; case 65: /* Line 1455 of yacc.c */ #line 2128 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { std::string nm = (*(yyvsp[(2) - (7)].sc_string)) + "[" + (*(yyvsp[(4) - (7)].sc_string)) + "]"; sc_vv.push_back("__sc_inv__"+nm); sc_inv.push_back(nm); ;} break; case 66: /* Line 1455 of yacc.c */ #line 2135 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_msb = atoi((*(yyvsp[(5) - (8)].sc_string)).c_str()); sc_lsb = atoi((*(yyvsp[(7) - (8)].sc_string)).c_str()); sc_token_str = (*(yyvsp[(3) - (8)].sc_string)); set_module_vector_div(); ;} break; case 67: /* Line 1455 of yacc.c */ #line 2144 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y" { sc_msb = atoi((*(yyvsp[(6) - (9)].sc_string)).c_str()); sc_lsb = atoi((*(yyvsp[(8) - (9)].sc_string)).c_str()); sc_token_str = (*(yyvsp[(4) - (9)].sc_string)); set_moudle_vector_inv_div(); ;} break; /* Line 1455 of yacc.c */ #line 3848 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.cpp" default: break; } YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; /* Now `shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*------------------------------------. | yyerrlab -- here on detecting error | `------------------------------------*/ yyerrlab: /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (YY_("syntax error")); #else { YYSIZE_T yysize = yysyntax_error (0, yystate, yychar); if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM) { YYSIZE_T yyalloc = 2 * yysize; if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM)) yyalloc = YYSTACK_ALLOC_MAXIMUM; if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yyalloc); if (yymsg) yymsg_alloc = yyalloc; else { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; } } if (0 < yysize && yysize <= yymsg_alloc) { (void) yysyntax_error (yymsg, yystate, yychar); yyerror (yymsg); } else { yyerror (YY_("syntax error")); if (yysize != 0) goto yyexhaustedlab; } } #endif } if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; /* Do not reclaim the symbols of the rule which action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (yyn != YYPACT_NINF) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yydestruct ("Error: popping", yystos[yystate], yyvsp); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } *++yyvsp = yylval; /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined(yyoverflow) || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEMPTY) yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval); /* Do not reclaim the symbols of the rule which action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif /* Make sure YYID is used. */ return YYID (yyresult); } /* Line 1675 of yacc.c */ #line 2156 "/home/sean/桌面/iso_cell_rc1/kernel/SC_Parser/SC_Parser.y"
[ "funningboy@gmail.com" ]
funningboy@gmail.com
7df3d36b281aeb5817eea6504d3586e7525a50c8
c72fe4de1f61e28d9f72bbae8e195937a54026c4
/include/RE/B/BGSHazard.h
1adb15b01d15f9dedd61358e93e5e7f118d68bdf
[ "MIT" ]
permissive
r-neal-kelly/CommonLibSSE
01bf6766472a25b938b52ee5d57964077052557a
aefeb91d38cad750bc9f36f6260a05e7b1b094fd
refs/heads/master
2023-02-12T22:57:52.643926
2021-01-08T09:55:30
2021-01-08T09:55:30
318,849,540
1
0
MIT
2021-01-08T09:55:31
2020-12-05T17:35:50
C++
UTF-8
C++
false
false
1,716
h
#pragma once #include "RE/B/BGSPreloadable.h" #include "RE/F/FormTypes.h" #include "RE/T/TESBoundObject.h" #include "RE/T/TESFullName.h" #include "RE/T/TESImageSpaceModifiableForm.h" #include "RE/T/TESModel.h" namespace RE { struct BGSHazardData // DATA { public: enum class BGSHazardFlags { kNone = 0, kPCOnly = 1 << 0, kInheritDuration = 1 << 1, kAlignToNormal = 1 << 2, kInheritRadius = 1 << 3, kDropToGround = 1 << 4 }; std::uint32_t limit; // 00 float radius; // 04 float lifetime; // 08 float imageSpaceRadius; // 0C float targetInterval; // 10 stl::enumeration<BGSHazardFlags, std::uint32_t> flags; // 14 SpellItem* spell; // 18 TESObjectLIGH* light; // 20 BGSImpactDataSet* impactDataSet; // 28 BGSSoundDescriptorForm* sound; // 30 }; static_assert(sizeof(BGSHazardData) == 0x38); class BGSHazard : public TESBoundObject, // 00 public TESFullName, // 30 public TESModel, // 40 public BGSPreloadable, // 68 public TESImageSpaceModifiableForm // 70 { public: inline static constexpr auto RTTI = RTTI_BGSHazard; inline static constexpr auto FORMTYPE = FormType::Hazard; struct RecordFlags { enum RecordFlag : std::uint32_t { kDeleted = 1 << 5, kIgnored = 1 << 12 }; }; virtual ~BGSHazard(); // 00 // override (TESBoundObject) virtual void InitializeData() override; // 04 virtual bool Load(TESFile* a_mod) override; // 06 virtual void InitItemImpl() override; // 13 // members BGSHazardData data; // 80 - DATA }; static_assert(sizeof(BGSHazard) == 0xB8); }
[ "ryan__mckenzie@hotmail.com" ]
ryan__mckenzie@hotmail.com
4a604ebfc716ac35da42801c47dd0afc4a1f9de6
31dff889e5fb426341a0fed9808b7b593370aca1
/Decode.h
4abec087987318e59305d661cb259b18c925bc78
[]
no_license
heylakshya/CAbackupphase3
88d3735ccc12b19059c3f65b3b87784ad4d1fa6a
d50fa993ca65a99b114a17ce1c40d8b14330554f
refs/heads/master
2022-04-23T14:45:31.124491
2020-04-28T15:46:29
2020-04-28T15:46:29
258,190,220
0
1
null
null
null
null
UTF-8
C++
false
false
15,872
h
#pragma once #include "InterStateBuffers.h" #include "RegistryFile.h" #include<iostream> #include<fstream> #include<sstream> #include<string.h> #include<bitset> using namespace std; class Decode{ private: vector <string> instructionName, aluString, relevantstr; public: // Declaring Variables bitset<7> opcode; bitset<3> func3; bitset<7> func7; bitset<12> imm1; bitset<20> imm2; bitset<5> rs1; bitset<5> rs2; bitset<5> rd; int locA, locB, locC; bool hasFunc3 = true; bool hasFunc7 = true; bool stallA = false; bool stallB = false; bool stallC = false; // initialising function void initialise() { ifstream ifile("ALU.txt"); string line,temp; while(getline(ifile,line)) { stringstream ss(line); ss >> temp; // temp now has the instruction name ex : add, sub etc, instructionName.push_back(temp); ss >> temp; aluString.push_back(temp); // ALU INSTRUCTION given to the ALU guy ss >> temp ; // temp now has the concatenated string. we'll use this to map to name of instruction relevantstr.push_back(temp); } ifile.close(); } //actual decoder void decoder(InterStateBuffers &ibs, Registry_File &regFile){ // initialising actual valies of immediate int immVal1; int immVal2; //initialising class variables func3 = -1; func7 = -1; imm1 = -1; imm2 = -1; rs1 = 0; rs2 = 0; rd = 0; int insType; if(!ibs.enablePipe) insType = ibs.insType; else insType = ibs.insTypeD; bitset<32> IR(ibs.IR.readInt()); if(insType == 0){ opcode = 51; func3 = 0; func7 = 0; rs1 = 0; rs2 = 0; rd = 0; ibs.ALU_OP = "add"; hasFunc3 = true; hasFunc7 = true; } if(insType == 1){ // RType | opcode (7) | rd (5) | funct3 | rs1(5) | rs2 (5) | funct7 | for(int i=0;i<7;i++){ opcode[i] = IR[i]; } for(int i=0; i<5; i++){ rd[i] = IR[7+i]; } for(int i=0; i<3; i++){ func3[i] = IR[12+i]; } for(int i=0; i<5; i++){ rs1[i] = IR[15+i]; } for(int i=0; i<5; i++){ rs2[i] = IR[20+i]; } for(int i=0; i<7; i++){ func7[i] = IR[25+i]; } hasFunc3 = true; hasFunc7 = true; ibs.write_back_location = rd.to_ulong(); } if(insType == 2){ // IType 0->31 | opcode (7) | rd (5) | funct3 | rs1(5) | immediate(12) | for(int i=0;i<7;i++){ opcode[i] = IR[i]; } for(int i=0; i<5; i++){ rd[i] = IR[7+i]; } for(int i=0; i<3; i++){ func3[i] = IR[12+i]; } for(int i=0; i<5; i++){ rs1[i] = IR[15+i]; } for(int i=0; i<12; i++){ imm1[i] = IR[20+i]; } hasFunc7 = false; hasFunc3 = true; ibs.write_back_location = rd.to_ulong(); } if(insType == 3){ // SBType imm[12] | imm [10:5] | rs2 | rs1 | funct3 | imm[4:1] | imm[11] | opcode for(int i=0;i<7;i++){ opcode[i] = IR[i]; } imm1[10] = IR[7]; for(int i=0;i<4;i++){ imm1[i] = IR[8+i]; } for(int i=0;i<3;i++){ func3[i] = IR[12+i]; } for(int i=0;i<5;i++){ rs1[i] = IR[15+i]; } for(int i=0;i<5;i++){ rs2[i] = IR[20+i]; } for(int i=0;i<6;i++){ imm1[i+4] = IR[25+i]; } imm1[11] = IR[31]; hasFunc7 = false; hasFunc3 = true; ibs.write_back_location = -1; } if(insType == 4){ // SType immediate (7) | rs2 (5) | rs1 (5) | func3 | immediate (5) | opcode (7) | // rs1 replaced by rd to symbolize reading on that register, rs2 replaced by rs1 to leave room for writing for(int i=0;i<7;i++){ opcode[i] = IR[i]; } for(int i=0;i<5; i++){ imm1[i] = IR[7+i]; } for(int i=0; i<3; i++){ func3[i] = IR[12+i]; } for(int i=0; i<5; i++){ rd[i] = IR[15+i]; } for(int i=0; i<5; i++){ rs1[i] = IR[20+i]; } for(int i=0; i<7; i++){ imm1[i+5] = IR[25+i]; } hasFunc7 = false; hasFunc3 = true; ibs.write_back_location = -1 ; } if(insType == 5){ // UJType imm[20][10:1][11][19:12] | rd[11:7] | opcode[6:0] for(int i=0; i<7;i++){ opcode[i] = IR[i]; } for(int i=0; i<5; i++){ rd[i] = IR[7+i]; } for(int i=0; i<8; i++){ imm2[11+i] = IR[12+i]; } imm2[10] = IR[20]; for(int i=0; i<10; i++){ imm2[i] = IR[21+i]; } imm2[19] = IR[31]; hasFunc7 = false; hasFunc3 = false; ibs.write_back_location = rd.to_ulong(); } if(insType == 6){ // UType imm[31:12] | rd[11:7] | opcode[6:0] for(int i=0;i<7;i++){ opcode[i] = IR[i]; } for(int i=0;i<5;i++){ rd[i] = IR[i+7]; } for(int i=0;i<20;i++){ imm2[i] = IR[12+i]; } hasFunc7 = false; hasFunc3 = false; ibs.write_back_location = rd.to_ulong(); } // Also add the same to the register files once made locA = rs1.to_ulong(); locB = rs2.to_ulong(); locC = rd.to_ulong(); //Concatenated opcode func3 and func7 and checked for ALU_OP string relStr; relStr = opcode.to_string(); if(hasFunc3){ relStr = relStr + func3.to_string(); if(hasFunc7){ relStr = relStr + func7.to_string(); } else{ relStr = relStr + "-1"; } } else{ relStr = relStr + "-1"; } //Register file object will be passed and values will be read // MUX B Implementation //Uncomment the following lines once the register file has been created and update the names. //Feeding buffer RA if(locA == ibs.pWrite && ibs.pWrite!=0 && ibs.enablePipe == true){ // if pipelining and data forwarding is true ibs.dataHazardNumber++; if(ibs.enableDF == true){ if(ibs.pInst == "lw" || ibs.pInst == "lb" || ibs.pInst == "lh"){ stallA = true; } else{ stallA = false; ibs.RA.writeInt(ibs.RZ.readInt()); } } // if only pipelining is true else{ // ibs.stall the pipeline stallA = true; } } else if(locA == ibs.ppWrite && ibs.ppWrite != 0 && ibs.enablePipe == true){ ibs.dataHazardNumber++; if(ibs.enableDF == true){ // for general instruction, no load exceptions are here stallA = false; ibs.RA.writeInt(ibs.RY.readInt()); } // if only pipelining is true else{ // ibs.stall the pipeline stallA = true; } } else{ stallA = false; ibs.RA.writeInt(regFile.readInt(locA)); } //Feeding in RB //Negations have been added, in case a new function is made replace it here. if(insType == 1 || insType ==3){ if(locB == ibs.pWrite && ibs.pWrite !=0 && ibs.enablePipe == true){ ibs.dataHazardNumber++; if(ibs.enableDF == true){ if(ibs.pInst == "lw" || ibs.pInst == "lb" || ibs.pInst == "lh"){ stallB = true; } else{ stallB = false; ibs.RB.writeInt(ibs.RZ.readInt()); } } // if only pipelining is true else{ // ibs.stall stallB = true; } } else if(locB == ibs.ppWrite && ibs.ppWrite != 0 && ibs.enablePipe == true){ ibs.dataHazardNumber++; if(ibs.enableDF == true){ stallB = false; ibs.RB.writeInt(ibs.RY.readInt()); } else{ stallB = true; } } else{ stallB = false; ibs.RB.writeInt(regFile.readInt(locB)); } } else if(insType == 2 || insType == 4){ if(imm1[11] == 0){ immVal1 = imm1.to_ulong(); } else{ immVal1 = imm1.flip().to_ulong(); immVal1++; immVal1 = immVal1*-1; } ibs.RB.writeInt(immVal1); } else if(insType == 6){ if(imm2[19] == 0){ immVal2 = imm2.to_ulong(); } else{ immVal2 = imm2.flip().to_ulong(); immVal2++; immVal2 = immVal2*-1; } ibs.RB.writeInt(immVal2); } if(insType==3){ if(imm1[11] == 0){ immVal1 = imm1.to_ulong(); } else{ immVal1 = imm1.flip().to_ulong(); immVal1++; immVal1 = immVal1*-1; } ibs.pc_offset = immVal1; } else if(insType==5){ if(imm2[19] == 0){ immVal2 = imm2.to_ulong(); } else{ immVal2 = imm2.flip().to_ulong(); immVal2++; immVal2 = immVal2*-1; } ibs.pc_offset = immVal2; } else{ ibs.pc_offset = 0; } ibs.RM = ibs.RMD; if(insType == 4){ if(locC == ibs.pWrite && ibs.pWrite !=0 && ibs.enablePipe == true){ ibs.dataHazardNumber++; if(ibs.enableDF == true){ if(ibs.pInst == "lw" || ibs.pInst == "lb" || ibs.pInst == "lh"){ stallC = true; } else{ stallC = false; ibs.RMD.writeInt(ibs.RZ.readInt()); } } else{ //ibs.stall stallC = true; } } else if(locC == ibs.ppWrite && ibs.ppWrite !=0 && ibs.enablePipe == true){ ibs.dataHazardNumber++; if(ibs.enableDF == true){ stallC = false; ibs.RMD.writeInt(ibs.RY.readInt()); } else{ //ibs.stall stallC = true; } } else{ stallC = false; ibs.RMD.writeInt(regFile.readInt(locC)); } } if(!ibs.enablePipe){ ibs.RM = ibs.RMD; } if(ibs.hazard_type == 2){ int ra = ibs.RA.readInt(); int rb = ibs.RB.readInt(); ibs.branch_address = ra + rb; } //Branch prediction checking bool state; if(insType == 3){ int ra = ibs.RA.readInt(); int rb = ibs.RB.readInt(); int rau; int rbu; if(ra >= 0){ rau = ra; } else{ rau = INT_MAX -ra; } if(rb >= 0){ rbu = rb; } else{ rbu = INT_MAX -rb; } if(relStr == "1100011000-1"){ // beq instruction state = (ra == rb) ? 1 : 0; } if(relStr == "1100011001-1"){ // bne instruction state = (ra != rb) ? 1 : 0; } if(relStr == "1100011100-1"){ // blt instruction state = (ra < rb) ? 1 : 0; } if(relStr == "1100011101-1"){ // bge instruction state = (ra >= rb) ? 1 : 0; } if(relStr == "1100011110-1"){ // bltu instruction state = (rau < rbu) ? 1 : 0; } if(relStr == "1100011111-1"){ // bgeu instruction state = (rau >= rbu) ? 1 : 0; } if(ibs.btb[ibs.PC-1] == true && state == false){ ibs.mispredNumber++; ibs.isMispred = true; // Implement flush logic // Put ba_def in PC ibs.nextPC = ibs.branch_address_def; //update btb ibs.btb[ibs.PC-1] = state; } else if(ibs.btb[ibs.PC-1] == false && state == true){ ibs.mispredNumber++; ibs.isMispred = true; // Implement flush logic // Put ba in PC ibs.nextPC = ibs.branch_address; //update btb ibs.btb[ibs.PC-1] = state; } else{ //Sab sahi hai bero ibs.isMispred = false; } } if((ibs.hazard_type == 1 || ibs.hazard_type == 2) && ibs.enablePipe){ // locC value save karni hai ie register number regFile.writeInt(locC, ibs.returnAddD); } //Updated ALU_OP if(stallA || stallB || stallC){ ibs.stall = true; ibs.numStall++; } else{ ibs.stall = false; } for(int i=0;i<instructionName.size(); i++){ if(relevantstr[i] == relStr){ ibs.ALU_OP = aluString[i]; if(instructionName[i]== "jalr"){ ibs.isjalr = true; } else{ ibs.isjalr = false; } ibs.ppInst = ibs.pInst; ibs.pInst = instructionName[i]; if(instructionName[i] == "lb" || instructionName[i] == "lw" || instructionName[i] == "lh" || instructionName[i] == "ld" || instructionName[i] == "lbu" || instructionName[i] == "lhu" ||instructionName[i] == "lwu" || ibs.insType == 4){ ibs.isMem = true; } else{ ibs.isMem = false; } } } // Updating the previous write registers // if ibs.stall is activated, feed ibs.pWrite with 0 or insType == 4 ?? ibs.ppWrite = ibs.pWrite; if(insType == 4 || ibs.stall == true){ ibs.pWrite = 0; } else{ ibs.pWrite = locC; } } };
[ "noreply@github.com" ]
noreply@github.com
9706577709597901c05c75a4b452c2bfbbb61269
b53795b88ab0201e48c5dc5737e97dfd27e07b22
/extern/include/Eigen/src/Core/StableNorm.h
5a53ff8d5a6268980ec90981b687e64f3ca78b2f
[]
no_license
davidkm2/globalmetin
9cc63395974eb74b5784a1bf5e733622c7303aa4
d1a21b549c68e311416544e03ca6218351e12d2f
refs/heads/main
2023-05-27T08:10:08.506239
2021-05-24T01:57:37
2021-05-24T01:57:37
370,181,109
2
1
null
null
null
null
UTF-8
C++
false
false
7,913
h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef EIGEN_STABLENORM_H #define EIGEN_STABLENORM_H namespace Eigen { namespace internal { template<typename ExpressionType, typename Scalar> inline void stable_norm_kernel(const ExpressionType& bl, Scalar& ssq, Scalar& scale, Scalar& invScale) { Scalar maxCoeff = bl.cwiseAbs().maxCoeff(); if(maxCoeff>scale) { ssq = ssq * numext::abs2(scale/maxCoeff); Scalar tmp = Scalar(1)/maxCoeff; if(tmp > NumTraits<Scalar>::highest()) { invScale = NumTraits<Scalar>::highest(); scale = Scalar(1)/invScale; } else if(maxCoeff>NumTraits<Scalar>::highest()) // we got a INF { invScale = Scalar(1); scale = maxCoeff; } else { scale = maxCoeff; invScale = tmp; } } else if(maxCoeff!=maxCoeff) // we got a NaN { scale = maxCoeff; } // TODO if the maxCoeff is much much smaller than the current scale, // then we can neglect this sub vector if(scale>Scalar(0)) // if scale==0, then bl is 0 ssq += (bl*invScale).squaredNorm(); } template<typename Derived> inline typename NumTraits<typename traits<Derived>::Scalar>::Real blueNorm_impl(const EigenBase<Derived>& _vec) { typedef typename Derived::RealScalar RealScalar; using std::pow; using std::sqrt; using std::abs; const Derived& vec(_vec.derived()); static bool initialized = false; static RealScalar b1, b2, s1m, s2m, rbig, relerr; if(!initialized) { int ibeta, it, iemin, iemax, iexp; RealScalar eps; // This program calculates the machine-dependent constants // bl, b2, slm, s2m, relerr overfl // from the "basic" machine-dependent numbers // nbig, ibeta, it, iemin, iemax, rbig. // The following define the basic machine-dependent constants. // For portability, the PORT subprograms "ilmaeh" and "rlmach" // are used. For any specific computer, each of the assignment // statements can be replaced ibeta = std::numeric_limits<RealScalar>::radix; // base for floating-point numbers it = NumTraits<RealScalar>::digits(); // number of base-beta digits in mantissa iemin = std::numeric_limits<RealScalar>::min_exponent; // minimum exponent iemax = std::numeric_limits<RealScalar>::max_exponent; // maximum exponent rbig = (std::numeric_limits<RealScalar>::max)(); // largest floating-point number iexp = -((1-iemin)/2); b1 = RealScalar(pow(RealScalar(ibeta),RealScalar(iexp))); // lower boundary of midrange iexp = (iemax + 1 - it)/2; b2 = RealScalar(pow(RealScalar(ibeta),RealScalar(iexp))); // upper boundary of midrange iexp = (2-iemin)/2; s1m = RealScalar(pow(RealScalar(ibeta),RealScalar(iexp))); // scaling factor for lower range iexp = - ((iemax+it)/2); s2m = RealScalar(pow(RealScalar(ibeta),RealScalar(iexp))); // scaling factor for upper range eps = RealScalar(pow(double(ibeta), 1-it)); relerr = sqrt(eps); // tolerance for neglecting asml initialized = true; } Index n = vec.size(); RealScalar ab2 = b2 / RealScalar(n); RealScalar asml = RealScalar(0); RealScalar amed = RealScalar(0); RealScalar abig = RealScalar(0); for(typename Derived::InnerIterator it(vec, 0); it; ++it) { RealScalar ax = abs(it.value()); if(ax > ab2) abig += numext::abs2(ax*s2m); else if(ax < b1) asml += numext::abs2(ax*s1m); else amed += numext::abs2(ax); } if(amed!=amed) return amed; // we got a NaN if(abig > RealScalar(0)) { abig = sqrt(abig); if(abig > rbig) // overflow, or *this contains INF values return abig; // return INF if(amed > RealScalar(0)) { abig = abig/s2m; amed = sqrt(amed); } else return abig/s2m; } else if(asml > RealScalar(0)) { if (amed > RealScalar(0)) { abig = sqrt(amed); amed = sqrt(asml) / s1m; } else return sqrt(asml)/s1m; } else return sqrt(amed); asml = numext::mini(abig, amed); abig = numext::maxi(abig, amed); if(asml <= abig*relerr) return abig; else return abig * sqrt(RealScalar(1) + numext::abs2(asml/abig)); } } // end namespace internal /** \returns the \em l2 norm of \c *this avoiding underflow and overflow. * This version use a blockwise two passes algorithm: * 1 - find the absolute largest coefficient \c s * 2 - compute \f$ s \Vert \frac{*this}{s} \Vert \f$ in a standard way * * For architecture/scalar types supporting vectorization, this version * is faster than blueNorm(). Otherwise the blueNorm() is much faster. * * \sa norm(), blueNorm(), hypotNorm() */ template<typename Derived> inline typename NumTraits<typename internal::traits<Derived>::Scalar>::Real MatrixBase<Derived>::stableNorm() const { using std::sqrt; using std::abs; const Index blockSize = 4096; RealScalar scale(0); RealScalar invScale(1); RealScalar ssq(0); // sum of square typedef typename internal::nested_eval<Derived,2>::type DerivedCopy; typedef typename internal::remove_all<DerivedCopy>::type DerivedCopyClean; const DerivedCopy copy(derived()); enum { CanAlign = ( (int(DerivedCopyClean::Flags)&DirectAccessBit) || (int(internal::evaluator<DerivedCopyClean>::Alignment)>0) // FIXME Alignment)>0 might not be enough ) && (blockSize*sizeof(Scalar)*2<EIGEN_STACK_ALLOCATION_LIMIT) && (EIGEN_MAX_STATIC_ALIGN_BYTES>0) // if we cannot allocate on the stack, then let's not bother about this optimization }; typedef typename internal::conditional<CanAlign, Ref<const Matrix<Scalar,Dynamic,1,0,blockSize,1>, internal::evaluator<DerivedCopyClean>::Alignment>, typename DerivedCopyClean::ConstSegmentReturnType>::type SegmentWrapper; Index n = size(); if(n==1) return abs(this->coeff(0)); Index bi = internal::first_default_aligned(copy); if (bi>0) internal::stable_norm_kernel(copy.head(bi), ssq, scale, invScale); for (; bi<n; bi+=blockSize) internal::stable_norm_kernel(SegmentWrapper(copy.segment(bi,numext::mini(blockSize, n - bi))), ssq, scale, invScale); return scale * sqrt(ssq); } /** \returns the \em l2 norm of \c *this using the Blue's algorithm. * A Portable Fortran Program to Find the Euclidean Norm of a Vector, * ACM TOMS, Vol 4, Issue 1, 1978. * * For architecture/scalar types without vectorization, this version * is much faster than stableNorm(). Otherwise the stableNorm() is faster. * * \sa norm(), stableNorm(), hypotNorm() */ template<typename Derived> inline typename NumTraits<typename internal::traits<Derived>::Scalar>::Real MatrixBase<Derived>::blueNorm() const { return internal::blueNorm_impl(*this); } /** \returns the \em l2 norm of \c *this avoiding undeflow and overflow. * This version use a concatenation of hypot() calls, and it is very slow. * * \sa norm(), stableNorm() */ template<typename Derived> inline typename NumTraits<typename internal::traits<Derived>::Scalar>::Real MatrixBase<Derived>::hypotNorm() const { return this->cwiseAbs().redux(internal::scalar_hypot_op<RealScalar>()); } } // end namespace Eigen #endif // EIGEN_STABLENORM_H
[ "davidkm2012@gmail.com" ]
davidkm2012@gmail.com
92cbcf013ba83a323e59515bda348c4a5cf92c50
408d1ef3f5ca139830139eeb9458377f455b8422
/tests/unittests/TFLiteImporterTest.cpp
77d110248bf8b2815f2471ce8d3592ad629a584a
[ "Apache-2.0" ]
permissive
zrphercule/glow
2049f87c898a5464862dff58acc562bf23481850
3dab5984680e9acc3dd2b96157ff205b1ef46c93
refs/heads/master
2021-06-09T01:44:09.854553
2021-04-27T06:29:20
2021-04-27T06:29:20
150,164,968
0
0
Apache-2.0
2018-09-24T20:33:17
2018-09-24T20:33:17
null
UTF-8
C++
false
false
8,309
cpp
/** * Copyright (c) Glow Contributors. See CONTRIBUTORS file. * * 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 "ImporterTestUtils.h" #include "glow/ExecutionEngine/ExecutionEngine.h" #include "glow/Graph/Graph.h" #include "glow/Graph/Nodes.h" #include "glow/Graph/PlaceholderBindings.h" #include "glow/Importer/TFLiteModelLoader.h" #include "gtest/gtest.h" #include "llvm/Support/CommandLine.h" #include <fstream> namespace { llvm::cl::OptionCategory tfliteModelTestCat("TFLITE Test Options"); llvm::cl::opt<bool> tflitePrintTestTensorsOpt( "tflite-dump-test-tensors", llvm::cl::init(false), llvm::cl::Optional, llvm::cl::desc( "Print input/expected tensors from test files. Default is false."), llvm::cl::cat(tfliteModelTestCat)); } // namespace using namespace glow; class TFLiteImporterTest : public ::testing::Test {}; /// \p returns the full path of the TensorFlowLite model \p name. static std::string getModelPath(std::string name) { return "tests/models/tfliteModels/" + name; } /// Utility function to load a binary file from \p fileName into \p tensor. /// The binary files have a special format with an extra byte of '0' at the /// start of the file followed by the actual tensor binary content. The extra /// '0' leading byte was required in order for the GIT system to correctly /// recognize the files as being binary files. static void loadTensor(Tensor *tensor, const std::string &fileName) { std::ifstream file; file.open(fileName, std::ios::binary); assert(file.is_open() && "Error opening tensor file!"); file.seekg(1); file.read(tensor->getUnsafePtr(), tensor->getSizeInBytes()); file.close(); } /// Utility function to load and run TensorFlowLite model named \p modelName. /// The model with the name <name>.tflite is also associated with binary files /// used to validate numerically the model. The binary files have the following /// naming convention: <name>.inp0, <name>.inp1, etc for the model inputs and /// <name>.out0, <name>.out1, etc for the model reference outputs. When testing /// the output of the model a maximum error of \p maxError is allowed. static void loadAndRunModel(std::string modelName, float maxError = 1e-6) { ExecutionEngine EE; auto &mod = EE.getModule(); Function *F = mod.createFunction("main"); // Load TensorFlowLite model. std::string modelPath = getModelPath(modelName); { TFLiteModelLoader(modelPath, F); } // Allocate tensors for all placeholders. PlaceholderBindings bindings; bindings.allocate(mod.getPlaceholders()); // Get model input/output placeholders. PlaceholderList inputPH; PlaceholderList outputPH; for (const auto &ph : mod.getPlaceholders()) { if (isInput(ph, *F)) { inputPH.push_back(ph); } else { outputPH.push_back(ph); } } // Load data into the input placeholders. size_t dotPos = llvm::StringRef(modelPath).find_first_of('.'); std::string dataBasename = llvm::StringRef(modelPath).substr(0, dotPos); size_t inpIdx = 0; for (const auto &inpPH : inputPH) { std::string inpFilename = dataBasename + ".inp" + std::to_string(inpIdx++); Tensor *inpT = bindings.get(inpPH); loadTensor(inpT, inpFilename); if (tflitePrintTestTensorsOpt) { llvm::outs() << "Input Placeholder: " << inpPH->getName() << "\n"; inpT->dump(); } } // Run model. EE.compile(CompilationMode::Infer); EE.run(bindings); // Compare output data versus reference. size_t outIdx = 0; for (const auto &outPH : outputPH) { std::string refFilename = dataBasename + ".out" + std::to_string(outIdx++); // Get output tensor. Tensor *outT = bindings.get(outPH); // Load reference tensor. Tensor refT(outT->getType()); loadTensor(&refT, refFilename); if (tflitePrintTestTensorsOpt) { llvm::outs() << "Reference Tensor:\n"; refT.dump(); llvm::outs() << "Output Placeholder: " << outPH->getName() << "\n"; outT->dump(); } // Compare. ASSERT_TRUE(outT->isEqual(refT, maxError, /* verbose */ true)); } } #define TFLITE_UNIT_TEST(name, model) \ TEST(TFLiteImporterTest, name) { loadAndRunModel(model); } #define TFLITE_UNIT_TEST_MAX_ERR(name, model, maxErr) \ TEST(TFLiteImporterTest, name) { loadAndRunModel(model, maxErr); } TFLITE_UNIT_TEST(Add, "add.tflite") TFLITE_UNIT_TEST(AvgPool2D_PaddingSame, "avgpool2d_same.tflite") TFLITE_UNIT_TEST(AvgPool2D_PaddingValid, "avgpool2d_valid.tflite") TFLITE_UNIT_TEST(Concat, "concat.tflite") TFLITE_UNIT_TEST(ConcatNegAxis, "concat_neg_axis.tflite") TFLITE_UNIT_TEST(Conv2D_PaddingSame, "conv2d_same.tflite") TFLITE_UNIT_TEST(Conv2D_PaddingValid, "conv2d_valid.tflite") TFLITE_UNIT_TEST(Conv2D_FusedRelu, "conv2d_relu.tflite") TFLITE_UNIT_TEST(DepthwiseConv2D_Ch1Mult1, "depthwise_conv2d_c1_m1.tflite") TFLITE_UNIT_TEST(DepthwiseConv2D_Ch1Mult2, "depthwise_conv2d_c1_m2.tflite") TFLITE_UNIT_TEST(DepthwiseConv2D_Ch2Mult1, "depthwise_conv2d_c2_m1.tflite") TFLITE_UNIT_TEST(DepthwiseConv2D_Ch2Mult2, "depthwise_conv2d_c2_m2.tflite") TFLITE_UNIT_TEST(HardSwish, "hardSwish.tflite") TFLITE_UNIT_TEST(Floor, "floor.tflite") TFLITE_UNIT_TEST(FullyConnected, "fully_connected.tflite") TFLITE_UNIT_TEST(Sigmoid, "sigmoid.tflite") TFLITE_UNIT_TEST(MaxPool2D_PaddingSame, "maxpool2d_same.tflite") TFLITE_UNIT_TEST(MaxPool2D_PaddingValid, "maxpool2d_valid.tflite") TFLITE_UNIT_TEST(Mul, "mul.tflite") TFLITE_UNIT_TEST(Relu, "relu.tflite") TFLITE_UNIT_TEST(ReluN1To1, "relu_n1to1.tflite") TFLITE_UNIT_TEST(Relu6, "relu6.tflite") TFLITE_UNIT_TEST(Reshape, "reshape.tflite") TFLITE_UNIT_TEST(ReshapeNegShape, "reshape_neg_shape.tflite") TFLITE_UNIT_TEST(Softmax, "softmax.tflite") TFLITE_UNIT_TEST(Tanh, "tanh.tflite") TFLITE_UNIT_TEST(Pad, "pad.tflite") TFLITE_UNIT_TEST(Transpose, "transpose.tflite") TFLITE_UNIT_TEST(MeanKeepDims, "mean_keep_dims.tflite") TFLITE_UNIT_TEST(MeanNoKeepDims, "mean_no_keep_dims.tflite") TFLITE_UNIT_TEST(MeanMultipleAxisKeepDims, "mean_multiple_axis_keep_dims.tflite") TFLITE_UNIT_TEST(MeanMultipleAxisNoKeepDims, "mean_multiple_axis_no_keep_dims.tflite") TFLITE_UNIT_TEST(Sub, "sub.tflite") TFLITE_UNIT_TEST(Div, "div.tflite") TFLITE_UNIT_TEST(Exp, "exp.tflite") TFLITE_UNIT_TEST(Split, "split.tflite") TFLITE_UNIT_TEST(PRelu, "prelu.tflite") TFLITE_UNIT_TEST(Maximum, "max.tflite") TFLITE_UNIT_TEST(ArgMax, "arg_max.tflite") TFLITE_UNIT_TEST(Minimum, "min.tflite") TFLITE_UNIT_TEST(Less, "less.tflite") TFLITE_UNIT_TEST(Neg, "neg.tflite") TFLITE_UNIT_TEST(Greater, "greater.tflite") TFLITE_UNIT_TEST(GreaterEqual, "greater_equal.tflite") TFLITE_UNIT_TEST(LessEqual, "less_equal.tflite") TFLITE_UNIT_TEST(Slice, "slice.tflite") TFLITE_UNIT_TEST(SliceNegSize, "slice_neg_size.tflite") TFLITE_UNIT_TEST(Sin, "sin.tflite") TFLITE_UNIT_TEST(Tile, "tile.tflite") TFLITE_UNIT_TEST_MAX_ERR(ResizeBilinear, "resize_bilinear.tflite", 2e-6) TFLITE_UNIT_TEST(Equal, "equal.tflite") TFLITE_UNIT_TEST(NotEqual, "not_equal.tflite") TFLITE_UNIT_TEST(Log, "log.tflite") TFLITE_UNIT_TEST(Sqrt, "sqrt.tflite") TFLITE_UNIT_TEST(Rsqrt, "rsqrt.tflite") TFLITE_UNIT_TEST(Pow, "pow.tflite") TFLITE_UNIT_TEST(ArgMin, "arg_min.tflite") TFLITE_UNIT_TEST(Pack, "pack.tflite") TFLITE_UNIT_TEST(LogicalOr, "logical_or.tflite") TFLITE_UNIT_TEST(LogicalAnd, "logical_and.tflite") TFLITE_UNIT_TEST(LogicalNot, "logical_not.tflite") TFLITE_UNIT_TEST(Unpack, "unpack.tflite") TFLITE_UNIT_TEST(Square, "square.tflite") TFLITE_UNIT_TEST(LeakyRelu, "leaky_relu.tflite") TFLITE_UNIT_TEST(Abs, "abs.tflite") TFLITE_UNIT_TEST(Ceil, "ceil.tflite") TFLITE_UNIT_TEST(Cos, "cos.tflite") TFLITE_UNIT_TEST(Round, "round.tflite") #undef TFLITE_UNIT_TEST
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
f847c534c5419af6702a19b877bf43e1b642168c
f730a391f83486a28cadc58b6daec2d0a5fab761
/OperatorOverloading/AComplexNumberClass/Complex.cpp
a69219d5436c9d4444ddbffba89ad0fa703afadc
[]
no_license
amorales2/UdemyC-Class
1ccabd76fb5922acb0418923620015805b4f30b5
f52f394b56371601383b8cb24f406109a09633f8
refs/heads/master
2020-12-24T20:42:19.129640
2016-05-22T18:13:05
2016-05-22T18:13:05
56,029,060
0
0
null
null
null
null
UTF-8
C++
false
false
627
cpp
/////////////////////////////////////////////////////////////////////////////// //Complex.cpp // #include "Complex.h" Complex::Complex(): real(0), imaginary(0) { } Complex::Complex(double real, double imaginary): real(real), imaginary(imaginary) { } Complex::Complex(const Complex & other) { real = other.real; imaginary = other.imaginary; } const Complex & Complex::operator=(const Complex & other) { real = other.real; imaginary = other.imaginary; return *this; } std::ostream & operator<<(std::ostream & out, const Complex & c) { out << "(" << c.getReal() << "," << c.getImagionary() << ")"; return out; }
[ "amorales2@live.com" ]
amorales2@live.com
f649ef850282a5f158ed633bd0f65a5ed10a386f
a36c53e2019d005bbafc7e861d9d885c3462b216
/TextureManager.h
3e7cc793265767b1a6c4128f5721c0a7e750ee2d
[]
no_license
zzyclark/SDL_Net
14843e9ebb52f076aee0c4d888e244c26457c100
b59d0c0730ba67e312c4c6d270805f09358bc0a8
refs/heads/master
2020-06-01T11:34:47.945026
2014-05-21T07:26:44
2014-05-21T07:26:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
955
h
/* * File: TextureManager.h * Author: clark * * Created on December 22, 2013, 12:36 AM */ #pragma once #include <string> #include <map> #include "SDL2/SDL.h" class TextureManager { public: static TextureManager* Instance() { if(s_Instance == NULL) { s_Instance = new TextureManager(); return s_Instance; } return s_Instance; }; bool load(std::string fileName, std::string id, SDL_Renderer*); void draw(std::string id, int x, int y, int width, int height, SDL_Renderer* myRenderer, SDL_RendererFlip flip = SDL_FLIP_NONE); void drawframe(std::string id, int x, int y, int width, int height, int currentRow, int currentFrame, SDL_Renderer* myRenderer, SDL_RendererFlip flip = SDL_FLIP_NONE); void clearFromTextureMap(std::string id); private: TextureManager(void); ~TextureManager(void); static TextureManager* s_Instance; std::map<std::string, SDL_Texture*> myTextureMap; }; typedef TextureManager MyTextureManager;
[ "zhangzongyangclark@gmail.com" ]
zhangzongyangclark@gmail.com
f6e34c39b66ae518e518266ca145d736b0c698fd
dba34fbb6ca594e96be1a982c2cf12f23dee78a0
/emdhelper.cpp
0200eaf75f3c43a42d54d89cacdb105dd900634e
[]
no_license
RicoP/emdGLViewer
3835fb0bdda86b708730061085004c08a17a9bcc
1fa2ee543fef65ea3c17abbaa06733e87fad2f97
refs/heads/master
2021-01-01T20:11:38.624907
2012-07-10T09:12:44
2012-07-10T09:12:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
311
cpp
#include "emdhelper.h" EmdHelper::Dictionary EmdHelper::getDictionary(QByteArray blob) { int filelength = blob.length(); int* raw = (int*)(blob.data() + filelength - 16); //Last 4 int's are indice to the subfiles EmdHelper::Dictionary dict = { raw[0], raw[1], raw[2], raw[3] }; return dict; }
[ "MailToRico@googlemail.com" ]
MailToRico@googlemail.com
a25566cdb09fb34c605010b863bd1fdb06fbd694
117a2f4adf639ce689f34acd0909b4eba311133a
/clientUI.hpp
b2b03efca8f98fed82061ecb9a65e9b7d585524a
[]
no_license
Aleuck/FileSync
9408f38a954e2c55d4ea4e9aada4d6bf2d9a2958
87d078f6afda5201acdc68763516583a51a81185
refs/heads/master
2021-09-03T23:54:24.056370
2018-01-13T01:38:13
2018-01-13T01:38:13
104,791,226
0
0
null
null
null
null
UTF-8
C++
false
false
482
hpp
#ifndef HEADER_CLIENTUI #define HEADER_CLIENTUI #include "userInterface.hpp" class FSClientUI; class FSClientUI : public FilesyncUI { public: FSClientUI(FileSyncClient *client); void start(); void close(); protected: FileSyncClient *client; std::thread thread; pthread_t pthread; bool running; void run(); void exec_cmd(std::string cmd); void output(std::string cmd); WINDOW* log_win; WINDOW* cmd_win; WINDOW* files_win; WINDOW* queue_win; }; #endif
[ "aleuck2004@gmail.com" ]
aleuck2004@gmail.com
05d63fb3c5229da96e46ce76a592c03e3500160e
40b8b95d4481ab74783d8fff4ee6e2e418f130e7
/ConvergenceVST/Source/libtwitcurl/twitcurlurls.h
034b3502cc57adf97f8ec5e9233adc0cecf3becc
[ "MIT" ]
permissive
thenoiseindex/convergence
89ea4f172f3a7d81d60006946d4aaf5495a85866
8b90f005e05488f4748680c27e56f74219a8b338
refs/heads/master
2016-08-07T15:13:26.093995
2014-05-08T09:48:47
2014-05-08T09:48:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,530
h
#ifndef _TWITCURLURLS_H_ #define _TWITCURLURLS_H_ #include <string> #include <cstring> /* Default values used in twitcurl */ namespace twitCurlDefaults { /* Constants */ const int TWITCURL_DEFAULT_BUFFSIZE = 1024; const std::string TWITCURL_COLON = ":"; const char TWITCURL_EOS = '\0'; const unsigned int MAX_TIMELINE_TWEET_COUNT = 200; /* Miscellaneous data used to build twitter URLs*/ const std::string TWITCURL_STATUSSTRING = "status="; const std::string TWITCURL_TEXTSTRING = "text="; const std::string TWITCURL_QUERYSTRING = "query="; const std::string TWITCURL_SEARCHQUERYSTRING = "q="; const std::string TWITCURL_SCREENNAME = "screen_name="; const std::string TWITCURL_USERID = "user_id="; const std::string TWITCURL_EXTENSIONFORMATS[2] = { ".json", ".xml" }; const std::string TWITCURL_PROTOCOLS[2] = { "https://", "http://" }; const std::string TWITCURL_TARGETSCREENNAME = "target_screen_name="; const std::string TWITCURL_TARGETUSERID = "target_id="; const std::string TWITCURL_SINCEID = "since_id="; const std::string TWITCURL_TRIMUSER = "trim_user=true"; const std::string TWITCURL_INCRETWEETS = "include_rts=true"; const std::string TWITCURL_COUNT = "count="; const std::string TWITCURL_NEXT_CURSOR = "cursor="; const std::string TWITCURL_SKIP_STATUS = "skip_status="; const std::string TWITCURL_INCLUDE_ENTITIES = "include_entities="; const std::string TWITCURL_STRINGIFY_IDS = "stringify_ids="; const std::string TWITCURL_INREPLYTOSTATUSID = "in_reply_to_status_id="; const std::string TWITCURL_WOEID_REQUEST = "id="; /* URL separators */ const std::string TWITCURL_URL_SEP_AMP = "&"; const std::string TWITCURL_URL_SEP_QUES = "?"; }; /* Default twitter URLs */ namespace twitterDefaults { /* Base URL */ const std::string TWITCURL_BASE_URL = "api.twitter.com/1.1/"; /* Search URLs */ const std::string TWITCURL_SEARCH_URL = TWITCURL_BASE_URL + "search/tweets"; /* Status URLs */ const std::string TWITCURL_STATUSUPDATE_URL = TWITCURL_BASE_URL + "statuses/update"; const std::string TWITCURL_STATUSSHOW_URL = TWITCURL_BASE_URL + "statuses/show/"; const std::string TWITCURL_STATUDESTROY_URL = TWITCURL_BASE_URL + "statuses/destroy/"; const std::string TWITCURL_RETWEET_URL = TWITCURL_BASE_URL + "statuses/retweet/"; /* Timeline URLs */ const std::string TWITCURL_HOME_TIMELINE_URL = TWITCURL_BASE_URL + "statuses/home_timeline"; const std::string TWITCURL_PUBLIC_TIMELINE_URL = TWITCURL_BASE_URL + "statuses/public_timeline"; const std::string TWITCURL_FEATURED_USERS_URL = TWITCURL_BASE_URL + "statuses/featured"; const std::string TWITCURL_FRIENDS_TIMELINE_URL = TWITCURL_BASE_URL + "statuses/friends_timeline"; const std::string TWITCURL_MENTIONS_URL = TWITCURL_BASE_URL + "statuses/mentions"; const std::string TWITCURL_USERTIMELINE_URL = TWITCURL_BASE_URL + "statuses/user_timeline"; /* Users URLs */ const std::string TWITCURL_LOOKUPUSERS_URL = TWITCURL_BASE_URL + "users/lookup"; const std::string TWITCURL_SHOWUSERS_URL = TWITCURL_BASE_URL + "users/show"; const std::string TWITCURL_SHOWFRIENDS_URL = TWITCURL_BASE_URL + "statuses/friends"; const std::string TWITCURL_SHOWFOLLOWERS_URL = TWITCURL_BASE_URL + "statuses/followers"; /* Direct messages URLs */ const std::string TWITCURL_DIRECTMESSAGES_URL = TWITCURL_BASE_URL + "direct_messages"; const std::string TWITCURL_DIRECTMESSAGENEW_URL = TWITCURL_BASE_URL + "direct_messages/new"; const std::string TWITCURL_DIRECTMESSAGESSENT_URL = TWITCURL_BASE_URL + "direct_messages/sent"; const std::string TWITCURL_DIRECTMESSAGEDESTROY_URL = TWITCURL_BASE_URL + "direct_messages/destroy/"; /* Friendships URLs */ const std::string TWITCURL_FRIENDSHIPSCREATE_URL = TWITCURL_BASE_URL + "friendships/create"; const std::string TWITCURL_FRIENDSHIPSDESTROY_URL = TWITCURL_BASE_URL + "friendships/destroy"; const std::string TWITCURL_FRIENDSHIPSSHOW_URL = TWITCURL_BASE_URL + "friendships/show"; /* Social graphs URLs */ const std::string TWITCURL_FRIENDSIDS_URL = TWITCURL_BASE_URL + "friends/ids"; const std::string TWITCURL_FOLLOWERSIDS_URL = TWITCURL_BASE_URL + "followers/ids"; /* Account URLs */ const std::string TWITCURL_ACCOUNTRATELIMIT_URL = TWITCURL_BASE_URL + "account/rate_limit_status"; const std::string TWITCURL_ACCOUNTVERIFYCRED_URL = TWITCURL_BASE_URL + "account/verify_credentials"; /* Favorites URLs */ const std::string TWITCURL_FAVORITESGET_URL = TWITCURL_BASE_URL + "favorites"; const std::string TWITCURL_FAVORITECREATE_URL = TWITCURL_BASE_URL + "favorites/create/"; const std::string TWITCURL_FAVORITEDESTROY_URL = TWITCURL_BASE_URL + "favorites/destroy/"; /* Block URLs */ const std::string TWITCURL_BLOCKSCREATE_URL = TWITCURL_BASE_URL + "blocks/create/"; const std::string TWITCURL_BLOCKSDESTROY_URL = TWITCURL_BASE_URL + "blocks/destroy/"; const std::string TWITCURL_BLOCKSLIST_URL = TWITCURL_BASE_URL + "blocks/list"; const std::string TWITCURL_BLOCKSIDS_URL = TWITCURL_BASE_URL + "blocks/ids"; /* Saved Search URLs */ const std::string TWITCURL_SAVEDSEARCHGET_URL = TWITCURL_BASE_URL + "saved_searches"; const std::string TWITCURL_SAVEDSEARCHSHOW_URL = TWITCURL_BASE_URL + "saved_searches/show/"; const std::string TWITCURL_SAVEDSEARCHCREATE_URL = TWITCURL_BASE_URL + "saved_searches/create"; const std::string TWITCURL_SAVEDSEARCHDESTROY_URL = TWITCURL_BASE_URL + "saved_searches/destroy/"; /* Trends URLs */ const std::string TWITCURL_TRENDS_URL = TWITCURL_BASE_URL + "trends"; const std::string TWITCURL_TRENDSDAILY_URL = TWITCURL_BASE_URL + "trends/daily"; const std::string TWITCURL_TRENDSCURRENT_URL = TWITCURL_BASE_URL + "trends/current"; const std::string TWITCURL_TRENDSWEEKLY_URL = TWITCURL_BASE_URL + "trends/weekly"; const std::string TWITCURL_TRENDSAVAILABLE_URL = TWITCURL_BASE_URL + "trends/available"; const std::string TWITCURL_PLACE_URL = TWITCURL_BASE_URL + "trends/place"; }; namespace oAuthLibDefaults { /* Constants */ const int OAUTHLIB_BUFFSIZE = 1024; const int OAUTHLIB_BUFFSIZE_LARGE = 1024; const std::string OAUTHLIB_CONSUMERKEY_KEY = "oauth_consumer_key"; const std::string OAUTHLIB_CALLBACK_KEY = "oauth_callback"; const std::string OAUTHLIB_VERSION_KEY = "oauth_version"; const std::string OAUTHLIB_SIGNATUREMETHOD_KEY = "oauth_signature_method"; const std::string OAUTHLIB_SIGNATURE_KEY = "oauth_signature"; const std::string OAUTHLIB_TIMESTAMP_KEY = "oauth_timestamp"; const std::string OAUTHLIB_NONCE_KEY = "oauth_nonce"; const std::string OAUTHLIB_TOKEN_KEY = "oauth_token"; const std::string OAUTHLIB_TOKENSECRET_KEY = "oauth_token_secret"; const std::string OAUTHLIB_VERIFIER_KEY = "oauth_verifier"; const std::string OAUTHLIB_SCREENNAME_KEY = "screen_name"; const std::string OAUTHLIB_AUTHENTICITY_TOKEN_KEY = "authenticity_token"; const std::string OAUTHLIB_SESSIONUSERNAME_KEY = "session[username_or_email]"; const std::string OAUTHLIB_SESSIONPASSWORD_KEY = "session[password]"; const std::string OAUTHLIB_AUTHENTICITY_TOKEN_TWITTER_RESP_KEY = "authenticity_token\" type=\"hidden\" value=\""; const std::string OAUTHLIB_TOKEN_TWITTER_RESP_KEY = "oauth_token\" type=\"hidden\" value=\""; const std::string OAUTHLIB_PIN_TWITTER_RESP_KEY = "code-desc\"><code>"; const std::string OAUTHLIB_TOKEN_END_TAG_TWITTER_RESP = "\" />"; const std::string OAUTHLIB_PIN_END_TAG_TWITTER_RESP = "</code>"; const std::string OAUTHLIB_AUTHHEADER_STRING = "Authorization: OAuth "; }; namespace oAuthTwitterApiUrls { /* Twitter OAuth API URLs */ const std::string OAUTHLIB_TWITTER_REQUEST_TOKEN_URL = "api.twitter.com/oauth/request_token"; const std::string OAUTHLIB_TWITTER_AUTHORIZE_URL = "api.twitter.com/oauth/authorize?oauth_token="; const std::string OAUTHLIB_TWITTER_ACCESS_TOKEN_URL = "api.twitter.com/oauth/access_token"; }; #endif // _TWITCURLURLS_H_
[ "owensvallis@gmail.com" ]
owensvallis@gmail.com
edebd9f1ee19735ab1a8f33bc184278a2e832f4d
12683aa9117a195e21bf4aafa9ee75969a82cc86
/src/SimpleAccessory.cxx
d552264acc5728d7beaa03d46eda9e2e3a1b5217
[ "BSD-2-Clause" ]
permissive
dd0vs/SoDaRadio
e1807069f41fa7630947d7d012da3f81ac7d7dfc
0a41fa3d795b1c93795ad62ad17bf2de5f60a752
refs/heads/master
2023-01-21T16:11:59.327065
2020-12-01T21:13:37
2020-12-01T21:13:37
258,309,147
1
0
null
2020-04-23T19:27:13
2020-04-23T19:27:13
null
UTF-8
C++
false
false
2,561
cxx
/* Copyright (c) 2019 Matthew H. Reilly (kb1vc) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "SimpleAccessory.hxx" #include <boost/format.hpp> #include <iostream> #include <string> // namespace doesn't matter here... let's do without. /** * To make an accessory thread that gets loaded and connected automagically, * just create a normal thread object. Like this: */ SimpleAccessory my_accessory(std::string("Accessory1")); SimpleAccessory::SimpleAccessory(const std::string & name) : SoDa::Thread(name) { get_count = set_count = rep_count = 0; } void SimpleAccessory::printReport() { std::cerr << boost::format("Accessory named %s reports: Get: %8d Set: %8d Rep: %8d\n") % getObjName() % get_count % set_count % rep_count; } void SimpleAccessory::run() { bool exitflag = false; while(!exitflag) { auto cmd = cmd_stream->get(cmd_subs); while (cmd != NULL) { execCommand(cmd); exitflag |= (cmd->target == SoDa::Command::STOP); cmd_stream->free(cmd); cmd = cmd_stream->get(cmd_subs); } usleep(10000); } } void SimpleAccessory::subscribeToMailBox(const std::string & mbox_name, SoDa::BaseMBox * mbox_p) { if(SoDa::connectMailBox<SoDa::CmdMBox>(this, cmd_stream, "CMD", mbox_name, mbox_p)) { cmd_subs = cmd_stream->subscribe(); } }
[ "kb1vc@kb1vc.org" ]
kb1vc@kb1vc.org
83afce22a27eba5e8819996b47062c5d4b3e0bee
ec8118f8bc19611e205c57dce39c6c9102c5a00f
/baekjoon/10866_덱.cpp
c066690a61d800c428e3425aae77a6d74eef4a92
[]
no_license
sjsjsj1246/Algorithm_study
a5433223741ffda89b2b63c22e876920c46882ea
5a45b1f64991138fdb0fdb02b0f345e07d2f6a74
refs/heads/master
2021-06-06T08:40:47.275376
2019-12-09T14:31:22
2019-12-09T14:31:22
143,863,615
1
0
null
null
null
null
UTF-8
C++
false
false
2,582
cpp
#pragma region preset_for_PS // need #include <iostream> #include <algorithm> // data structure #include <bitset> #include <map> #include <queue> #include <set> #include <stack> #include <string> #include <vector> #include <deque> #include <array> // stream #include <istream> #include <sstream> #include <ostream> // etc #include <cstdlib> #include <cmath> #include <functional> #include <chrono> #include <random> #include <cstring> using namespace std; typedef long long int ll; // input #define ALL(a) (a).begin(),(a).end() #define ZERO(a) memset(a,0,sizeof(a)) #define MINUS(a) memset(a,-1,sizeof(a)) #define CASES(t) int t; cin >> t; while(t--) #define FAST ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); #define MOD 1000000009 #define INF 987654321 #define SUB(a) cout << a << "\n"; // output #define SP << " " #define BR << "\n" #define SPBR(i, n) <<(i + 1 == n ? '\n' : ' '); #define SHOWVECTOR(v) {std::cerr << #v << "\t:";for(const auto& xxx : v){std::cerr << xxx << " ";}std::cerr << "\n";} #define SHOWVECTOR2(v) {std::cerr << #v << "\t:\n";for(const auto& xxx : v){for(const auto& yyy : xxx){std::cerr << yyy << " ";}std::cerr << "\n";}} #define SHOWQUEUE(a) {auto tmp(a);std::cerr << #a << "\t:";while(!tmp.empty()){std::cerr << tmp.front() << " ";tmp.pop();}std::cerr << "\n";} // utility #define FOR(w, a, n) for(int w=(a);w<(n);++w) #define RFOR(w, a, n) for(int w=(n)-1;w>=(a);--w) #define ITR(it, vec) for(auto it = vec.begin(); it!= vec.end(); it++) #define RITR(it, vec) for(auto it = vec.rbegin(); it!= vec.rend(); it++) template<typename S, typename T> std::ostream& operator<<(std::ostream& os, std::pair<S, T> p) { os << "(" << p.first << ", " << p.second << ")"; return os; } #pragma endregion int main() { FAST; deque<int> dq; CASES(t) { int n; string s; cin >> s; if (s == "push_front") { cin >> n; dq.push_front(n); } else if (s == "push_back") { cin >> n; dq.push_back(n); } else if (s == "pop_front") { if (dq.empty()) cout << -1 << "\n"; else { cout << dq.front() << "\n"; dq.pop_front(); } } else if (s == "pop_back") { if (dq.empty()) cout << -1 << "\n"; else { cout << dq.back() << "\n"; dq.pop_back(); } } else if (s == "size") { cout << dq.size() << "\n"; } else if (s == "empty") { cout << dq.empty() << "\n"; } else if (s == "front") { if (dq.empty()) cout << -1 << "\n"; else cout << dq.front() << "\n"; } else if (s == "back") { if (dq.empty()) cout << -1 << "\n"; else cout << dq.back() << "\n"; } } }
[ "sjsjsj1246@gmail.com" ]
sjsjsj1246@gmail.com
08abbd839dbb70dad55f34ca15e2d5977073ca7d
b71b8bd385c207dffda39d96c7bee5f2ccce946c
/testcases/CWE122_Heap_Based_Buffer_Overflow/s04/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_snprintf_08.cpp
159d57b541dfcc995bc058e182dd0bd4ca4b7df9
[]
no_license
Sporknugget/Juliet_prep
e9bda84a30bdc7938bafe338b4ab2e361449eda5
97d8922244d3d79b62496ede4636199837e8b971
refs/heads/master
2023-05-05T14:41:30.243718
2021-05-25T16:18:13
2021-05-25T16:18:13
369,334,230
0
0
null
null
null
null
UTF-8
C++
false
false
4,100
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_snprintf_08.cpp Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805.string.label.xml Template File: sources-sink-08.tmpl.cpp */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Allocate using new[] and set data pointer to a small buffer * GoodSource: Allocate using new[] and set data pointer to a large buffer * Sink: swprintf * BadSink : Copy string to data using swprintf * Flow Variant: 08 Control flow: if(staticReturnsTrue()) and if(staticReturnsFalse()) * * */ #include "std_testcase.h" #include <wchar.h> #ifdef _WIN32 #define SNPRINTF _snwprintf #else #define SNPRINTF swprintf #endif /* The two function below always return the same value, so a tool should be able to identify that calls to the functions will always return a fixed value. */ static int staticReturnsTrue() { return 1; } static int staticReturnsFalse() { return 0; } namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_snprintf_08 { #ifndef OMITBAD void bad() { wchar_t * data; data = NULL; { /* FLAW: Allocate using new[] and point data to a small buffer that is smaller than the large buffer used in the sinks */ data = new wchar_t[50]; data[0] = L'\0'; /* null terminate */ } { wchar_t source[100]; wmemset(source, L'C', 100-1); /* fill with L'C's */ source[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ SNPRINTF(data, 100, L"%s", source); printWLine(data); delete [] data; } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B1() - use goodsource and badsink by changing the staticReturnsTrue() to staticReturnsFalse() */ static void goodG2B1() { wchar_t * data; data = NULL; { /* FIX: Allocate using new[] and point data to a large buffer that is at least as large as the large buffer used in the sink */ data = new wchar_t[100]; data[0] = L'\0'; /* null terminate */ } { wchar_t source[100]; wmemset(source, L'C', 100-1); /* fill with L'C's */ source[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ SNPRINTF(data, 100, L"%s", source); printWLine(data); delete [] data; } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ static void goodG2B2() { wchar_t * data; data = NULL; { /* FIX: Allocate using new[] and point data to a large buffer that is at least as large as the large buffer used in the sink */ data = new wchar_t[100]; data[0] = L'\0'; /* null terminate */ } { wchar_t source[100]; wmemset(source, L'C', 100-1); /* fill with L'C's */ source[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ SNPRINTF(data, 100, L"%s", source); printWLine(data); delete [] data; } } void good() { goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_snprintf_08; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
[ "jaredzap@rams.colostate.edu" ]
jaredzap@rams.colostate.edu
452e9f039ff331096f5bbd1a40cfd0103479acd4
6bd9d7679011042f46104d97080786423ae58879
/1344/c/c.cc
f7247b76bc9991c25f3c6f0c5d5f0032263d9371
[ "CC-BY-4.0" ]
permissive
lucifer1004/codeforces
20b77bdd707a1e04bc5b1230f5feb4452d5f4c78
d1fe331d98d6d379723939db287a499dff24c519
refs/heads/master
2023-04-28T16:00:37.673566
2023-04-17T03:40:27
2023-04-17T03:40:27
212,258,015
3
1
null
2020-10-27T06:54:02
2019-10-02T04:53:36
C++
UTF-8
C++
false
false
2,217
cc
#include <algorithm> #include <bitset> #include <climits> #include <cmath> #include <complex> #include <cstdio> #include <cstring> #include <ctime> #include <deque> #include <functional> #include <iostream> #include <iterator> #include <list> #include <map> #include <numeric> #include <queue> #include <random> #include <set> #include <stack> #include <unordered_map> #include <unordered_set> #include <vector> #define INF 0x3f3f3f3f #define MOD 1000000007 using namespace std; typedef long long ll; mt19937 mrand(random_device{}()); int rnd(int x) { return mrand() % x; } class Solution { public: void solve() { int n, m; cin >> n >> m; vector<vector<int>> adj_less(n + 1), adj_greater(n + 1); vector<int> in_less(n + 1), in_greater(n + 1); vector<int> min_less(n + 1), min_greater(n + 1); for (int i = 1; i <= n; ++i) min_less[i] = min_greater[i] = i; set<int> vis; for (int i = 0; i < m; ++i) { int u, v; cin >> u >> v; adj_less[u].emplace_back(v); adj_greater[v].emplace_back(u); in_less[v]++; in_greater[u]++; vis.insert(u), vis.insert(v); } auto topo_sort = [&](vector<vector<int>> &adj, vector<int> &in, vector<int> &min_idx) { vector<int> topo; queue<int> q; for (int i = 1; i <= n; ++i) if (in[i] == 0) q.push(i); while (!q.empty()) { int u = q.front(); q.pop(); topo.emplace_back(u); for (int v : adj[u]) { in[v]--; min_idx[v] = min(min_idx[v], min_idx[u]); if (in[v] == 0) q.push(v); } } return topo.size() == n; }; if (!topo_sort(adj_less, in_less, min_less) || !topo_sort(adj_greater, in_greater, min_greater)) { cout << -1; return; } string ans; int a_count = 0; for (int i = 1; i <= n; ++i) { if (min(min_less[i], min_greater[i]) >= i) { a_count++; ans.push_back('A'); } else ans.push_back('E'); } cout << a_count << endl << ans << endl; } }; int main() { ios::sync_with_stdio(false); cin.tie(0); Solution solution = Solution(); solution.solve(); }
[ "qqbbnease1004@126.com" ]
qqbbnease1004@126.com