blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1d29b5c6d2fbc944e5cf2fdbff71b0db6f064374 | 136b76fbc57d9d9d7e761b1481a18184bf10fee2 | /src/ighost/cigi/IgThread.hpp | 3673982329b27818713f4d72279cd72cff0ca80b | [] | no_license | WarfareCode/mixr | c2487869fa22e7df667d822982d8fff04cf9f05e | baecfda072c783bb72bf9874ca58436989af5389 | refs/heads/master | 2022-10-02T22:01:53.224217 | 2022-08-11T12:48:58 | 2022-08-11T12:48:58 | 193,439,718 | 0 | 0 | null | 2019-06-24T05:29:49 | 2019-06-24T05:29:49 | null | UTF-8 | C++ | false | false | 335 | hpp | IgThread.hpp |
#ifndef __mixr_ighost_cigi3_IgThread_HPP__
#define __mixr_ighost_cigi3_IgThread_HPP__
#include "mixr/base/threads/OneShotThread.hpp"
namespace mixr {
namespace cigi {
class IgThread final : public base::OneShotThread
{
public: IgThread(base::Component* const parent);
private: unsigned long userFunc() final;
};
}
}
#endif
|
6fcf9971cf7a34fc545d63f730508756c67b88f7 | d3d4aeb81cc5027102da1ad6b1cf75f568dead07 | /Complex.h | eec3552f87c7698ef4fe9175606fdb9e4320d167 | [] | no_license | AlexPriahin/BPZ1802-Priahin | ff83c731856a5f20907c18e4bb369a94f5b24cc4 | 698ea7e6c3d5bc75df7f9cec16939386926a1a6e | refs/heads/main | 2023-04-05T03:08:32.643354 | 2021-04-22T19:11:26 | 2021-04-22T19:11:26 | 338,126,839 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 711 | h | Complex.h | #pragma once
#include "iostream"
#include<cmath>
using namespace std;
class Complex
{
private:
double r;//������
double phi;//��������
public:
double R() const;
double Phi() const;
double Re() const
{
return r * cos(phi);
}
double Im() const
{
return r * sin(phi);
}
Complex();
Complex(double digit);
Complex(double r, double phi);
friend Complex tg(const Complex& z);
Complex operator+(const Complex& rhs);
Complex operator*(const Complex& rhs);
Complex operator-(const Complex& rhs);
Complex operator/(const Complex& rhs);
friend ostream& operator<<(ostream & stream, const Complex& z);
};
Complex y(const Complex& z);
|
70c07bc7f39ec3034d8647f52210083b6b735429 | 745a07345c377a99a6c85f3fba037feb7594ac18 | /Injector/src/Console.h | 3c70ba55999171690c5b630ef8c2771f316b3c4b | [
"MIT"
] | permissive | robindittmar/mechanics | a1974bf2bd8cede2d905140bd1d69453b695e7dc | ea62f750d3cd448cbd708dee972d5a5b9a1464a0 | refs/heads/master | 2020-07-30T23:38:31.054009 | 2020-01-13T13:29:59 | 2020-01-13T13:29:59 | 210,399,723 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 152 | h | Console.h | #ifndef __CONSOLE_H__
#define __CONSOLE_H__
#include <cstdio>
class CConsole
{
public:
CConsole();
~CConsole();
private:
};
#endif // __CONSOLE_H__ |
3accaf12de0a77afbe3c888c0ed7d5d18f9ce2d1 | 5431d4b4d12c4d48a7aac199d18ba7a1ab9835d5 | /boxes626.cpp | 1b8211d81c8a2a54eb41f04943f804370accedfb | [] | no_license | quintuskilbourn/Competitive_Programming | 35370e6d4f12aede50f5201f2019132ee6e4da1e | d31422774fb7f169705d6b317aaa564e27749fe5 | refs/heads/master | 2020-12-24T02:25:55.160075 | 2020-05-04T03:26:42 | 2020-05-04T03:26:42 | 237,350,835 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 448 | cpp | boxes626.cpp | #include <iostream>
#include <math.h>
#include <string.h>
using namespace std;
int main(){
long dp[1000001];
int m,n;
while(cin>>n>>m){
memset(dp,0,sizeof(long)*1000001);
dp[0]=1;
for(long val=1;val<=n;val*=m){
for(int j=1;j<=n;j++){
if(val>j){
j+= val-j-1;
}else{
dp[j] = (dp[j]+dp[j-val])%1000000007;
}
}
// cout<<val<<" "<<dp[n]<<endl;
}
cout<<dp[n]<<endl;
// cout<<"----"<<endl;
}
return 0;
}
|
abea3a3685ece8594991d9a83ad35830a176a2ff | 7eb711cd921c0e2a4bf9f68a5bd024e0fe6e0c93 | /Lab 8/ArrayQueue.cpp | 35e750c115a21696a3a8e740dc8f6a3e1432b63a | [] | no_license | catfinch/CS-112-class-programs | ba92a1a960d3e93dd6bc87bd1cdfc54e7c8cabd4 | 314e97a30099dd597c4ba6726c028b1bae74051b | refs/heads/master | 2021-01-10T13:22:09.820919 | 2015-11-10T15:17:49 | 2015-11-10T15:17:49 | 45,403,806 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,162 | cpp | ArrayQueue.cpp | /* ArrayQueue.cpp defines the methods for class ArrayQueue.
* Joel Adams, for CS 112 at Calvin College.
* Student name:
* Date:
*/
#include "ArrayQueue.h"
#include <cstring> // memcpy()
using namespace std;
//ArrayQueue::ArrayQueue(const ArrayQueue& original) {
// makeCopyOf(original);
//}
//
//void ArrayQueue::makeCopyOf(const ArrayQueue& original) {
// mySize = original.mySize;
// myCapacity = original.myCapacity;
// myFirst = original.myFirst;
// myLast = original.myLast;
// myArray = new Item[myCapacity];
// memcpy(myArray, original.myArray, myCapacity*sizeof(Item) );
//}
//
//ArrayQueue::~ArrayQueue() {
// delete [] myArray;
// myArray = NULL;
// mySize = myFirst = myLast = 0;
//}
//
//
//ArrayQueue& ArrayQueue::operator=(const ArrayQueue& aQueue) {
// if (this != &aQueue) {
// delete [] myArray;
// makeCopyOf(aQueue);
// }
// return *this;
//}
//
//bool ArrayQueue::isEmpty() const {
// return mySize == 0;
//}
//
//bool ArrayQueue::isFull() const {
// return getSize() == myCapacity;
//}
//
//unsigned ArrayQueue::getCapacity() const {
// return myCapacity;
//}
//
//unsigned ArrayQueue::getSize() const {
// return mySize;
//}
|
5ccd966df29b27e93a636fed4b98f1d04e5f5077 | fb6c9780e08996b4d2aaa686c920285c4d0f6b70 | /codeforces/Codeforces Round #575 (Div. 3)/A. Three Piles of Candies/solution.cc | 2336e0c02044785cbad97d91cfb73581d62d071b | [] | no_license | Diegores14/CompetitiveProgramming | 7c05e241f48a44de0973cfb2f407d77dcbad7b59 | 466ee2ec9a8c17d58866129c6c12fc176cb9ba0c | refs/heads/master | 2021-06-25T08:21:45.341172 | 2020-10-14T03:39:11 | 2020-10-14T03:39:11 | 136,670,647 | 6 | 2 | null | 2018-10-26T23:36:43 | 2018-06-08T22:15:18 | C++ | UTF-8 | C++ | false | false | 258 | cc | solution.cc | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false); cin.tie(NULL);
long long q, a, b, c;
cin >> q;
while(q--) {
cin >> a >> b >> c;
cout << (a + b + c)/2 << '\n';
}
return 0;
} |
a3fe4386f6f67353666386d3226f36f6f841bb94 | 0f9c22ada8f186340366df595cf5fb4f23364b98 | /src/Dessin.cpp | 6df15901fd3589bc70eca41c3beec3a240a0d66f | [] | no_license | dovotori/FourrierGhost | c0fdc58271bd9e6e62b861b633703af476deb002 | f61d5330ae99d0015866c0fb6b53354dd9baf318 | refs/heads/master | 2016-09-11T00:58:54.109472 | 2014-09-19T13:16:42 | 2014-09-19T13:16:42 | 20,031,648 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,451 | cpp | Dessin.cpp | #include "Dessin.h"
Dessin::Dessin()
{
}
Dessin::~Dessin()
{
}
void Dessin::setup()
{
Forme::common();
this->forme.setup();
this->grille.setup(100, 2.0);
this->grille.setStrength(0.1);
this->echange.setup();
int nbLiaison = this->grille.getNbNodes();
if(nbLiaison > this->forme.getNbPoints()){ nbLiaison = this->forme.getNbPoints(); }
this->liaison.setup(nbLiaison);
this->liaison.setColor(255, 100, 100, 0.2);
this->voile.setup();
}
void Dessin::update()
{
this->echange.update();
this->forme.update();
this->grille.update(this->liaison.getNb(), this->liaison.getMesh(), this->forme.getMesh(), this->forme.getModelMatrix());
if(this->echange.getDraw(3)){ this->voile.update(); }
}
void Dessin::draw(Camera camera)
{
this->grille.setRotation(0.1, 1.0, 1.0, 0.0);
this->grille.draw(&camera);
this->forme.draw(&camera);
this->liaison.draw(&camera);
if(this->echange.getDraw(3)){ this->voile.draw(); }
}
//--------------------------------------------------------------
void Dessin::mouseDragged(int x, int y){
this->grille.setAttractorPosition(x, y, ofRandom(-10.0, 10.0));
}
//--------------------------------------------------------------
void Dessin::mousePressed(){
this->grille.setActive(true);
}
//--------------------------------------------------------------
void Dessin::mouseReleased(){
//this->grille.reset();
this->grille.setActive(false);
}
|
325f9ec7a3a65d917121fb566ec5f2b034aee137 | 319884441ea89619ca8f1ca91063a70e141846e5 | /TechniqueDemos/D3D12MemoryManagement/src/Context.h | 724417b0814ad9b190aaec1032ba8d4673f80f3a | [
"MIT"
] | permissive | GPUOpen-LibrariesAndSDKs/nBodyD3D12 | 930a86508ea6fc024b9dfc12e18f2fb9c5ba8fbc | 08ea79b0c2f0dbd9e7f21b85f078ce856c87ad06 | refs/heads/master | 2023-08-12T07:50:47.774564 | 2019-07-14T07:22:44 | 2019-07-14T07:22:44 | 50,424,410 | 60 | 24 | MIT | 2019-07-14T07:22:45 | 2016-01-26T11:27:57 | C | UTF-8 | C++ | false | false | 3,585 | h | Context.h | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#pragma once
//
// A Frame object stores information about each iteration of the pipeline.
// For rendering, this would correspond 1:1 with a real rendering frame (i.e. from
// one Present() call to the next).
// For paging, a frame corresponds to each unique paging operation.
// Each frame belongs to a Context object (defined below), and operations are queued
// on that Context's D3D12 command queue. At the end of each frame, the frame's
// completion fence is signaled on the command queue, allowing us to monitor
// completion of GPU work for that frame.
//
struct Frame : LIST_ENTRY
{
ID3D12CommandAllocator* pCommandAllocator;
ID3D12GraphicsCommandList* pCommandList;
UINT64 CompletionFence;
};
//
// A context is used to abstract GPU scheduling state. Each context contains a command
// queue, a fence object used to signal and track GPU work, and a list of frames that
// can be running in parallel.
// The Context object is subclassed into a RenderContext and PagingContext, which create
// unique queue types and perform unique operations.
//
class Context
{
protected:
DX12Framework* m_pFramework;
// List entry head storing a list of all actively running frames. All actively running
// frames are assumed to be running on the GPU until they are retired.
LIST_ENTRY m_ActiveFrameListHead;
// List entry head storing a list of free frame objects which can be reused.
LIST_ENTRY m_FreeFrameListHead;
// The current fence for this command queue. This fence value is incremented once per frame.
UINT64 m_CurrentFence = 0;
// Stores the fence of the most recently completed and retired frame. It can safely be
// assumed that any fence value lower than this is referring to work that has completed
// on the GPU, and is safe to reuse.
UINT64 m_LastCompletedFence = 0;
// The frame currently being recorded by the context. This value is null outside of
// calls to Begin() and End().
Frame* m_pCurrentFrame = nullptr;
// The D3D12 command queue object to which all work is submitted.
ID3D12CommandQueue* m_pCommandQueue = nullptr;
// The D3D12 fence object used track progress on the command queue.
ID3D12Fence* m_pFenceObject = nullptr;
// A handle (allocated per thread with TLS) allowing a thread to safely wait on this context.
HANDLE m_hFlushEvent = nullptr;
// The number of active frames in flight that are accessing the GPU.
UINT32 m_ActiveFrames = 0;
protected:
HRESULT InitializeFrame(Frame* pFrame, D3D12_COMMAND_LIST_TYPE Type);
virtual void RetireFrame(Frame* /*pFrame*/) { }
private:
void RetireFrameInternal(Frame* pFrame);
public:
Context(DX12Framework* pFramework);
~Context();
HRESULT CreateDeviceDependentState(D3D12_COMMAND_LIST_TYPE Type);
void DestroyDeviceDependentState();
void Begin();
HRESULT Execute();
void End();
void WaitForFence(UINT64 Fence);
void WaitForSingleFrame();
void WaitForAllFrames();
void Flush();
inline ID3D12CommandQueue* GetCommandQueue()
{
return m_pCommandQueue;
}
inline UINT32 GetActiveFrameCount() const
{
return m_ActiveFrames;
}
inline UINT64 GetLastCompletedFence() const
{
return m_LastCompletedFence;
}
};
|
09d770327bb0ebe49ea1b73450cb39beda4d988a | 00d8ad3327c9793cd287e0d2a4296407b1917d53 | /include/shaderweaver/node/PositionTransOld.h | 6b64b4bd670a68457f7003e1d78fb3388d8c25c8 | [
"MIT"
] | permissive | xzrunner/shaderweaver | 1221f80bbc6f606472e1faf9734e885101b0f338 | d1a5fff073684d896398eab47268370baed95af1 | refs/heads/master | 2021-07-09T01:35:45.802253 | 2020-07-06T21:39:50 | 2020-07-06T21:39:50 | 147,682,676 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,111 | h | PositionTransOld.h | #pragma once
#include "shaderweaver/Node.h"
#include "shaderweaver/VariableType.h"
#include <assert.h>
namespace sw
{
namespace node
{
class PositionTransOld : public sw::Node
{
public:
PositionTransOld(int dim = 2)
: Node("PositionTransOld")
, m_dim(dim)
{
SetDim(dim);
}
void SetDim(int dim)
{
uint32_t pos_type;
switch (dim) {
case 2:
pos_type = t_pos2;
break;
case 3:
pos_type = t_pos3;
break;
case 4:
pos_type = t_pos4;
break;
default:
assert(0);
}
InitVariables({
{ t_mat4, "proj" },
{ t_mat4, "modelview" },
{ pos_type, "pos" },
}, {
{ t_pos4, "_out" },
}, {
});
}
enum InputID
{
ID_PROJ = 0,
ID_MODELVIEW,
ID_POS,
};
protected:
virtual std::string GetBody() const override
{
switch (m_dim)
{
case 2:
return "#_out# = #proj# * #modelview# * vec4(#pos#, 0.0, 1.0);\n";
case 3:
return "#_out# = #proj# * #modelview# * vec4(#pos#, 1.0);\n";
case 4:
return "#_out# = #proj# * #modelview# * #pos#;\n";
default:
return "";
}
}
private:
int m_dim;
RTTR_ENABLE(Node)
}; // PositionTransOld
}
} |
a5a4e6c04ff9df52c11eae6f6db8890e2f1a3ff3 | ce2b2d4b3a1f216086236a2403e6e435892a6706 | /Maze2.h | 6ba6cf85a3b425f589c06e239a20fc30bdd73dcf | [] | no_license | closortiz/maze2_queues | 4271ef1c13fcdc48b4794dddb48b92f31c8eb05b | d4eefffefad0a0e4c2ffb5035167f4a0e16286aa | refs/heads/master | 2021-01-10T13:10:04.162870 | 2016-03-21T19:58:32 | 2016-03-21T19:58:32 | 54,418,175 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,029 | h | Maze2.h | #ifndef __MAZE1
#define __MAZE1
#include <iostream>
#include <cstdlib> // for the exit function
#include <cassert> // for the assert function
#include "Position.h"
#include <queue>
using namespace std;
typedef enum{OPEN,WALL,VISITED} state;
class Maze2
{
public:
// Constructor - sets size to n, allocates the nxn state array
// and sets the state of every array element to WALL
Maze2(int n);
// Destructor - deallocates the state array
~Maze2();
// Copy constructor and assignment disabled
Maze2(const Maze2 & other);
Maze2 & operator=(const Maze2 & origMaze);
void initialize();
// inputs the start and exit positions and sets their state to OPEN;
// then inputs the other OPEN positions; prompts will be printed to
// cout only if in == cin
void display() const;
// Print the contents of the maze, one row per line
// For each Position P, print 'b' if P is both the start and exit position;
// print 's' if P is the start, print 'e' is P is the exit;
// print '*' if the P's state is WALL and print a space
// if P's state is OPEN
void printExitPath();
// If the path stack is empty, output "No way out\; otherwise, output
// "Exit path:" then call reverseStackPrint to print the exit path
// In any case, at the last, insert endl into the output stream.
private:
int size;
Position start;
Position exitpos;
queue<Position> Q;
Position **pred; // initialized to all entries = NULLPOS; findExit will
// set M[i][j] to the predecessor of Position(i,j) in a
// shortest path from start to Position(i,j)
// if there is no such path
state **M; // two-dimensional array of state values
void find_exit();
// Use the BFS method to fill the array of predecessors
void printPredPath(Position P);
// If there is no path from start to P, returns false; otherwise,
// prints the path to P determined by the pred array and returns true
};
#endif
|
ce41dc0797e251517bc232d170a33e37012c2923 | cec53f5c55134af017a9d11d6ab2c21d6341674f | /Winapi2DGame/SpriteManager.cpp | d422bdfb67d0ff87ba30a8c379d51468076fb353 | [] | no_license | juhyupLee/Winapi2DGame | 63aa3906b891cdd8c33c7b5b83fb3ec7753fc3ff | c9e4f0d8469e345780dae4875b39c91e28da0f82 | refs/heads/master | 2023-01-09T15:00:31.455815 | 2020-11-08T18:06:35 | 2020-11-08T18:06:35 | 304,220,805 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 3,828 | cpp | SpriteManager.cpp | #include <iostream>
#include <Windows.h>
#include "SpriteManager.h"
//#include "MemoryTracer.h"
CSpriteManager::CSpriteManager()
:
m_stSprite{ 0, },
m_stAnimationStatus{ 0, }
{
}
CSpriteManager::~CSpriteManager()
{
for (size_t index1 = 0; index1 < OBJECT_MAX; index1++)
{
for (size_t index2 = 0; index2 < DIRECTION_MAX; index2++)
{
for (size_t index3 = 0; index3 < STATUS_MAX; index3++)
{
for (size_t index4 = 0; index4 < FRAME_MAX; index4++)
{
delete[] m_stSprite[index1][index2][index3][index4].m_bypImage;;
}
}
}
}
}
CSpriteManager* CSpriteManager::GetInstance()
{
static CSpriteManager spriteManager;
return &spriteManager;
}
bool CSpriteManager::LoadingSprite(__int32 iObjectType, __int32 iDirection, __int32 iStatus, __int32 iFrame, const WCHAR* szFileName, __int32 iOriginX, __int32 iOriginY, RECT rectCollisionBox, RECT rectHitBox)
{
FILE* filePtr = nullptr;
while (filePtr == nullptr)
{
_wfopen_s(&filePtr, szFileName, L"rb");
}
BITMAPFILEHEADER bitFileHeader;
BITMAPINFOHEADER bitmapInfoHeder;
if (0 == fread(&bitFileHeader, 1, sizeof(BITMAPFILEHEADER), filePtr))
{
MessageBox(nullptr, L"fread 오류", MB_OK, MB_OK);
fclose(filePtr);
return false;
}
if (*((short*)&bitFileHeader) != 0x4d42)
{
MessageBox(nullptr, L"BM 오류", MB_OK, MB_OK);
fclose(filePtr);
return false;
}
if (0 == fread(&bitmapInfoHeder, 1, sizeof(BITMAPINFOHEADER), filePtr))
{
MessageBox(nullptr, L"fread 오류", MB_OK, MB_OK);
fclose(filePtr);
return false;
}
int pitch = bitmapInfoHeder.biWidth * (bitmapInfoHeder.biBitCount / 8);
pitch = (pitch + 3) & ~3;
//-----------------------------------
m_stSprite[iObjectType][iDirection][iStatus][iFrame].m_iPitch = pitch;
m_stSprite[iObjectType][iDirection][iStatus][iFrame].m_iHeight = bitmapInfoHeder.biHeight;
m_stSprite[iObjectType][iDirection][iStatus][iFrame].m_iWidth = bitmapInfoHeder.biWidth;
m_stSprite[iObjectType][iDirection][iStatus][iFrame].m_rectCollisionBox = rectCollisionBox;
m_stSprite[iObjectType][iDirection][iStatus][iFrame].m_rectHitBox = rectHitBox;
m_stSprite[iObjectType][iDirection][iStatus][iFrame].m_iOriginX = iOriginX;
m_stSprite[iObjectType][iDirection][iStatus][iFrame].m_iOriginY = iOriginY;
int fileSize = pitch * bitmapInfoHeder.biHeight;
m_stSprite[iObjectType][iDirection][iStatus][iFrame].m_bypImage = new BYTE[fileSize];
BYTE* startBuffer = m_stSprite[iObjectType][iDirection][iStatus][iFrame].m_bypImage;
BYTE* cpyBuffer = new BYTE[fileSize];
BYTE* srcBuffer = cpyBuffer;
if (0 == fread(srcBuffer, 1, fileSize, filePtr))
{
MessageBox(nullptr, L"fread 오류", MB_OK, MB_OK);
}
//m_Buffer <--> srcBuffer (이미지파일을 거꾸로 담아오기)
//맨끝에서 한줄뺀만큼 부터 출발
srcBuffer = srcBuffer + ((__int64)fileSize - pitch);
for (int i = 0; i < bitmapInfoHeder.biHeight; ++i)
{
memcpy(m_stSprite[iObjectType][iDirection][iStatus][iFrame].m_bypImage, srcBuffer, pitch);
m_stSprite[iObjectType][iDirection][iStatus][iFrame].m_bypImage += pitch;
srcBuffer -= pitch;
}
delete[] cpyBuffer;
m_stSprite[iObjectType][iDirection][iStatus][iFrame].m_bypImage = startBuffer;
fclose(filePtr);
return true;
}
CSpriteManager::stSprite* CSpriteManager::GetSprite(__int32 iObjectType, __int32 iDirection, __int32 iStatus, __int32 iFrame)
{
return &m_stSprite[iObjectType][iDirection][iStatus][iFrame];
}
CSpriteManager::stAnimationStatus* CSpriteManager::GetAnimationStatus(__int32 iObjectType, __int32 iStatus)
{
return &m_stAnimationStatus[iObjectType][iStatus];
}
void CSpriteManager::SetAnimationStatus(__int32 iObjectType, __int32 iStatus, __int32 iDelay, __int32 iFrameMax)
{
m_stAnimationStatus[iObjectType][iStatus].m_iDelay = iDelay;
m_stAnimationStatus[iObjectType][iStatus].m_iFrameMax = iFrameMax;
}
|
b85d512dbbfb13f18de0f1af8290607ea2247f78 | d9039054754abafeec2ff70a096d9ddcf51223c8 | /SYCL/Config/config.cpp | d66e0392c67f7dd1ed055f56f2dbfa8734fcb381 | [
"NCSA",
"LLVM-exception",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | hanzhan1/llvm-test-suite | 09dbb69662cf072656541f34efbc6e308feff627 | e23c7ebaa9c043f9f42277112205ba8a0d5e83a3 | refs/heads/intel | 2023-04-29T15:00:46.291096 | 2021-01-25T19:08:14 | 2021-01-25T19:08:14 | 323,266,562 | 0 | 0 | Apache-2.0 | 2021-01-14T08:11:19 | 2020-12-21T07:49:07 | Logos | UTF-8 | C++ | false | false | 856 | cpp | config.cpp | //==---- config.cpp --------------------------------------------------------==//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// RUN: %clangxx -g -O0 -fsycl %s -o %t.out
// RUN: echo "SYCL_PRINT_EXECUTION_GRAPH=always" > %t.cfg
// RUN: env SYCL_CONFIG_FILE_NAME=%t.cfg %t.out
// RUN: ls | grep dot
// RUN: rm *.dot
// RUN: env SYCL_PRINT_EXECUTION_GRAPH=always %t.out
// RUN: ls | grep dot
// RUN: rm *.dot
// RUN: %t.out
// RUN: ls | not grep dot
#include <CL/sycl.hpp>
using namespace cl;
int main() {
sycl::buffer<int, 1> Buf(sycl::range<1>{1});
auto Acc = Buf.get_access<sycl::access::mode::read>();
}
|
cebfaae4730613eb7829295eeb98b71f55d8d68a | 111063199c8d3a61ae22a0c1753b6565e802d516 | /shopping mall/projevol2/Component.h | 58ed9fad04f0c13ada1e41fb7ac58d014097128f | [] | no_license | imperio/ShoppingMall | 20d274ca8ef24255a4d363590fe51e900f4b1c3f | 061a822f6cc20d6f33e84e3e134c62f453f85f8d | refs/heads/master | 2021-01-22T21:00:14.639989 | 2013-07-14T23:57:08 | 2013-07-14T23:57:08 | null | 0 | 0 | null | null | null | null | ISO-8859-9 | C++ | false | false | 251 | h | Component.h | #pragma once
#include <iostream>
using namespace std;
//bu class composite patterin component base classıdır
class Component{
public:
//virtual ~Component()=0;
virtual void add()=0;
virtual void remove()=0;
virtual void printProperties()=0;
}; |
d423dccabe7e277478587105de88c289e0141aa3 | 2247c82425b89d0131d63254063564810d4c7cef | /GroupFolder.cpp | 9f8608d1581659afba36a700af4ebd3c19f4e79f | [] | no_license | Fizers/Laba_31 | 90a4be1b467bf81ff7202d10362af3b1b2abdcf7 | b763f081d7195999a18365016d554aada281cc41 | refs/heads/main | 2023-04-26T16:41:49.885187 | 2021-05-23T18:35:32 | 2021-05-23T18:35:32 | 370,127,955 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,855 | cpp | GroupFolder.cpp | #include "GroupFolder.h"
#include "Size.h"
qint64 getDirSize(const QString& path)
{
qint64 AllSize = 0;
QDir myDir(path);
for (const auto s : myDir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot , QDir::Name | QDir::Type))
AllSize += s.size();
return AllSize;
}
QMap<QString, qint64> GroupFolder::getFolderSize(const QString& path) const
{
QFileInfo folder(path);
QMap<QString, qint64> FolderList;
auto thisDirPath = folder.absoluteFilePath();
FolderList.insert(thisDirPath, getDirSize(thisDirPath));
for (auto x : QDir(path).entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden, QDir::Name | QDir::Type))
{
auto TotalPath = x.absoluteFilePath();
FolderList.insert(TotalPath, Total::getAllSize(TotalPath));
}
return FolderList;
}
QMap<QString, double> GroupFolder::getPercentFolder(qint64& AllSize, QMap<QString, qint64>& FolderList) const
{
QMap<QString, double> FolderListPercent;
for (auto s = FolderList.begin(); s != FolderList.end(); ++s)
{
auto percent = double(s.value() * 100) / AllSize;
if (percent < 0.01)
percent = -percent;
FolderListPercent.insert(s.key(), percent);
}
return FolderListPercent;
}
QList<QPair<double, QString>> sortPercent(const QMap<QString, double>& FolderPercent)
{
QList<QPair<double, QString>> sortList;
for (auto x : FolderPercent.keys())
{
sortList.append(QPair<double, QString>(FolderPercent[x], x));
}
std::sort(sortList.begin() + 1, sortList.end(), std::greater<QPair<double, QString>>());
return sortList;
}
void GroupFolder::PrintFolderAllInf(const QMap<QString, qint64>& FolderType, const QList<QPair<double, QString> >& FolderPercent) const
{QTextStream cout(stdout);
for (auto x : FolderPercent)
{
cout << qSetFieldWidth(28) << Qt::left << x.second << qSetFieldWidth(10) << FolderType.value(x.second) / 1073741824
<< qSetFieldWidth(10)<< " GB";
if (x.first < 0 || x.first == 0) {
cout << qSetFieldWidth(8) << "< 0.01 %\n";
}
else
cout << qSetFieldWidth(8) << QString::number(x.first, 'f', 2).append(" %") << "\n";
}
}
void GroupFolder::browser(const QString& path)
{QTextStream cout(stdout);
QFileInfo folder(path);
if (!folder.exists() && !folder.isReadable())
{
cout << "Error!Luke I'm not your papka(" << "\n";
return;
}
auto FolderList = getFolderSize(path);
auto AllSize = Total::GiveSize(FolderList);
auto FolderPercent = getPercentFolder(AllSize, FolderList);
auto sortFolderPercent = sortPercent(FolderPercent);
PrintFolderAllInf(FolderList, sortFolderPercent);
}
|
7a0a763f7911a85d7ad790a6f3bf6ffcae5f4a39 | e9fbeea8dbff32eed2fa1f688c410f534790419b | /language/examples/pennant.cc | b6c9929986782712883258844f5eaa43f85edd16 | [
"Apache-2.0"
] | permissive | laristra/legion | 1edee820513015ce31b10497a58a3afc5f0882b0 | b372a5a9022421113b98f2f8920b062f3a7c5b88 | refs/heads/master | 2020-05-07T20:40:20.800254 | 2019-04-10T02:39:06 | 2019-04-10T02:39:06 | 180,869,362 | 1 | 1 | null | 2019-04-11T20:05:47 | 2019-04-11T20:05:47 | null | UTF-8 | C++ | false | false | 50,063 | cc | pennant.cc | /* Copyright 2019 Stanford University
*
* 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 "pennant.h"
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstring>
#include <map>
#include <vector>
#include "mappers/default_mapper.h"
#include <sys/time.h>
#include <sys/resource.h>
void print_rusage(const char *message)
{
struct rusage usage;
if (getrusage(RUSAGE_SELF, &usage) != 0) return;
printf("%s: %ld MB\n", message, usage.ru_maxrss / 1024);
}
using namespace Legion;
using namespace Legion::Mapping;
struct config {
int64_t np;
int64_t nz;
int64_t nzx;
int64_t nzy;
double lenx;
double leny;
int64_t numpcx;
int64_t numpcy;
int64_t npieces;
int64_t meshtype;
bool compact;
int64_t stripsize;
int64_t spansize;
};
enum {
MESH_PIE = 0,
MESH_RECT = 1,
MESH_HEX = 2,
};
///
/// Mesh Generator
///
/*
* Some portions of the following code are derived from the
* open-source release of PENNANT:
*
* https://github.com/losalamos/PENNANT
*/
static void generate_mesh_rect(config &conf,
std::vector<double> &pointpos_x,
std::vector<double> &pointpos_y,
std::vector<int64_t> &pointcolors,
std::map<int64_t, std::vector<int64_t> > &pointmcolors,
std::vector<int64_t> &zonestart,
std::vector<int64_t> &zonesize,
std::vector<int64_t> &zonepoints,
std::vector<int64_t> &zonecolors,
std::vector<int64_t> &zxbounds,
std::vector<int64_t> &zybounds)
{
int64_t &nz = conf.nz;
int64_t &np = conf.np;
nz = conf.nzx * conf.nzy;
const int npx = conf.nzx + 1;
const int npy = conf.nzy + 1;
np = npx * npy;
// generate point coordinates
pointpos_x.reserve(np);
pointpos_y.reserve(np);
double dx = conf.lenx / (double) conf.nzx;
double dy = conf.leny / (double) conf.nzy;
int pcy = 0;
for (int j = 0; j < npy; ++j) {
if (j >= zybounds[pcy+1]) pcy += 1;
double y = dy * (double) j;
int pcx = 0;
for (int i = 0; i < npx; ++i) {
if (i >= zxbounds[pcx+1]) pcx += 1;
double x = dx * (double) i;
pointpos_x.push_back(x);
pointpos_y.push_back(y);
int c = pcy * conf.numpcx + pcx;
if (i != zxbounds[pcx] && j != zybounds[pcy])
pointcolors.push_back(c);
else {
int p = pointpos_x.size() - 1;
pointcolors.push_back(MULTICOLOR);
std::vector<int64_t> &pmc = pointmcolors[p];
if (i == zxbounds[pcx] && j == zybounds[pcy])
pmc.push_back(c - conf.numpcx - 1);
if (j == zybounds[pcy]) pmc.push_back(c - conf.numpcx);
if (i == zxbounds[pcx]) pmc.push_back(c - 1);
pmc.push_back(c);
}
}
}
// generate zone adjacency lists
zonestart.reserve(nz);
zonesize.reserve(nz);
zonepoints.reserve(4 * nz);
zonecolors.reserve(nz);
pcy = 0;
for (int j = 0; j < conf.nzy; ++j) {
if (j >= zybounds[pcy+1]) pcy += 1;
int pcx = 0;
for (int i = 0; i < conf.nzx; ++i) {
if (i >= zxbounds[pcx+1]) pcx += 1;
zonestart.push_back(zonepoints.size());
zonesize.push_back(4);
int p0 = j * npx + i;
zonepoints.push_back(p0);
zonepoints.push_back(p0 + 1);
zonepoints.push_back(p0 + npx + 1);
zonepoints.push_back(p0 + npx);
zonecolors.push_back(pcy * conf.numpcx + pcx);
}
}
}
static void generate_mesh_pie(config &conf,
std::vector<double> &pointpos_x,
std::vector<double> &pointpos_y,
std::vector<int64_t> &pointcolors,
std::map<int64_t, std::vector<int64_t> > &pointmcolors,
std::vector<int64_t> &zonestart,
std::vector<int64_t> &zonesize,
std::vector<int64_t> &zonepoints,
std::vector<int64_t> &zonecolors,
std::vector<int64_t> &zxbounds,
std::vector<int64_t> &zybounds)
{
int64_t &nz = conf.nz;
int64_t &np = conf.np;
nz = conf.nzx * conf.nzy;
const int npx = conf.nzx + 1;
const int npy = conf.nzy + 1;
np = npx * (npy - 1) + 1;
// generate point coordinates
pointpos_x.reserve(np);
pointpos_y.reserve(np);
double dth = conf.lenx / (double) conf.nzx;
double dr = conf.leny / (double) conf.nzy;
int pcy = 0;
for (int j = 0; j < npy; ++j) {
if (j >= zybounds[pcy+1]) pcy += 1;
if (j == 0) {
// special case: "row" at origin only contains
// one point, shared by all pieces in row
pointpos_x.push_back(0.);
pointpos_y.push_back(0.);
if (conf.numpcx == 1)
pointcolors.push_back(0);
else {
pointcolors.push_back(MULTICOLOR);
std::vector<int64_t> &pmc = pointmcolors[0];
for (int c = 0; c < conf.numpcx; ++c)
pmc.push_back(c);
}
continue;
}
double r = dr * (double) j;
int pcx = 0;
for (int i = 0; i < npx; ++i) {
if (i >= zxbounds[pcx+1]) pcx += 1;
double th = dth * (double) (conf.nzx - i);
double x = r * cos(th);
double y = r * sin(th);
pointpos_x.push_back(x);
pointpos_y.push_back(y);
int c = pcy * conf.numpcx + pcx;
if (i != zxbounds[pcx] && j != zybounds[pcy])
pointcolors.push_back(c);
else {
int p = pointpos_x.size() - 1;
pointcolors.push_back(MULTICOLOR);
std::vector<int64_t> &pmc = pointmcolors[p];
if (i == zxbounds[pcx] && j == zybounds[pcy])
pmc.push_back(c - conf.numpcx - 1);
if (j == zybounds[pcy]) pmc.push_back(c - conf.numpcx);
if (i == zxbounds[pcx]) pmc.push_back(c - 1);
pmc.push_back(c);
}
}
}
// generate zone adjacency lists
zonestart.reserve(nz);
zonesize.reserve(nz);
zonepoints.reserve(4 * nz);
zonecolors.reserve(nz);
pcy = 0;
for (int j = 0; j < conf.nzy; ++j) {
if (j >= zybounds[pcy+1]) pcy += 1;
int pcx = 0;
for (int i = 0; i < conf.nzx; ++i) {
if (i >= zxbounds[pcx+1]) pcx += 1;
zonestart.push_back(zonepoints.size());
int p0 = j * npx + i - (npx - 1);
if (j == 0) {
zonesize.push_back(3);
zonepoints.push_back(0);
}
else {
zonesize.push_back(4);
zonepoints.push_back(p0);
zonepoints.push_back(p0 + 1);
}
zonepoints.push_back(p0 + npx + 1);
zonepoints.push_back(p0 + npx);
zonecolors.push_back(pcy * conf.numpcx + pcx);
}
}
}
static void generate_mesh_hex(config &conf,
std::vector<double> &pointpos_x,
std::vector<double> &pointpos_y,
std::vector<int64_t> &pointcolors,
std::map<int64_t, std::vector<int64_t> > &pointmcolors,
std::vector<int64_t> &zonestart,
std::vector<int64_t> &zonesize,
std::vector<int64_t> &zonepoints,
std::vector<int64_t> &zonecolors,
std::vector<int64_t> &zxbounds,
std::vector<int64_t> &zybounds)
{
int64_t &nz = conf.nz;
int64_t &np = conf.np;
nz = conf.nzx * conf.nzy;
const int npx = conf.nzx + 1;
const int npy = conf.nzy + 1;
// generate point coordinates
pointpos_x.resize(2 * npx * npy); // upper bound
pointpos_y.resize(2 * npx * npy); // upper bound
double dx = conf.lenx / (double) (conf.nzx - 1);
double dy = conf.leny / (double) (conf.nzy - 1);
std::vector<int64_t> pbase(npy);
int p = 0;
int pcy = 0;
for (int j = 0; j < npy; ++j) {
if (j >= zybounds[pcy+1]) pcy += 1;
pbase[j] = p;
double y = dy * ((double) j - 0.5);
y = std::max(0., std::min(conf.leny, y));
int pcx = 0;
for (int i = 0; i < npx; ++i) {
if (i >= zxbounds[pcx+1]) pcx += 1;
double x = dx * ((double) i - 0.5);
x = std::max(0., std::min(conf.lenx, x));
int c = pcy * conf.numpcx + pcx;
if (i == 0 || i == conf.nzx || j == 0 || j == conf.nzy) {
pointpos_x[p] = x;
pointpos_y[p++] = y;
if (i != zxbounds[pcx] && j != zybounds[pcy])
pointcolors.push_back(c);
else {
int p1 = p - 1;
pointcolors.push_back(MULTICOLOR);
std::vector<int64_t> &pmc = pointmcolors[p1];
if (j == zybounds[pcy]) pmc.push_back(c - conf.numpcx);
if (i == zxbounds[pcx]) pmc.push_back(c - 1);
pmc.push_back(c);
}
}
else {
pointpos_x[p] = x - dx / 6.;
pointpos_y[p++] = y + dy / 6.;
pointpos_x[p] = x + dx / 6.;
pointpos_y[p++] = y - dy / 6.;
if (i != zxbounds[pcx] && j != zybounds[pcy]) {
pointcolors.push_back(c);
pointcolors.push_back(c);
}
else {
int p1 = p - 2;
int p2 = p - 1;
pointcolors.push_back(MULTICOLOR);
pointcolors.push_back(MULTICOLOR);
std::vector<int64_t> &pmc1 = pointmcolors[p1];
std::vector<int64_t> &pmc2 = pointmcolors[p2];
if (i == zxbounds[pcx] && j == zybounds[pcy]) {
pmc1.push_back(c - conf.numpcx - 1);
pmc2.push_back(c - conf.numpcx - 1);
pmc1.push_back(c - 1);
pmc2.push_back(c - conf.numpcx);
}
else if (j == zybounds[pcy]) {
pmc1.push_back(c - conf.numpcx);
pmc2.push_back(c - conf.numpcx);
}
else { // i == zxbounds[pcx]
pmc1.push_back(c - 1);
pmc2.push_back(c - 1);
}
pmc1.push_back(c);
pmc2.push_back(c);
}
}
} // for i
} // for j
np = p;
pointpos_x.resize(np);
pointpos_y.resize(np);
// generate zone adjacency lists
zonestart.resize(nz);
zonesize.resize(nz);
zonepoints.reserve(6 * nz); // upper bound
zonecolors.reserve(nz);
pcy = 0;
for (int j = 0; j < conf.nzy; ++j) {
if (j >= zybounds[pcy+1]) pcy += 1;
int pbasel = pbase[j];
int pbaseh = pbase[j+1];
int pcx = 0;
for (int i = 0; i < conf.nzx; ++i) {
if (i >= zxbounds[pcx+1]) pcx += 1;
int z = j * conf.nzx + i;
std::vector<int64_t> v(6);
v[1] = pbasel + 2 * i;
v[0] = v[1] - 1;
v[2] = v[1] + 1;
v[5] = pbaseh + 2 * i;
v[4] = v[5] + 1;
v[3] = v[4] + 1;
if (j == 0) {
v[0] = pbasel + i;
v[2] = v[0] + 1;
if (i == conf.nzx - 1) v.erase(v.begin()+3);
v.erase(v.begin()+1);
} // if j
else if (j == conf.nzy - 1) {
v[5] = pbaseh + i;
v[3] = v[5] + 1;
v.erase(v.begin()+4);
if (i == 0) v.erase(v.begin()+0);
} // else if j
else if (i == 0)
v.erase(v.begin()+0);
else if (i == conf.nzx - 1)
v.erase(v.begin()+3);
zonestart[z] = zonepoints.size();
zonesize[z] = v.size();
zonepoints.insert(zonepoints.end(), v.begin(), v.end());
zonecolors.push_back(pcy * conf.numpcx + pcx);
} // for i
} // for j
}
static void calc_mesh_num_pieces(config &conf)
{
// pick numpcx, numpcy such that pieces are as close to square
// as possible
// we would like: nzx / numpcx == nzy / numpcy,
// where numpcx * numpcy = npieces (total number of pieces)
// this solves to: numpcx = sqrt(npieces * nzx / nzy)
// we compute this, assuming nzx <= nzy (swap if necessary)
double nx = static_cast<double>(conf.nzx);
double ny = static_cast<double>(conf.nzy);
bool swapflag = (nx > ny);
if (swapflag) std::swap(nx, ny);
double n = sqrt(conf.npieces * nx / ny);
// need to constrain n to be an integer with npieces % n == 0
// try rounding n both up and down
int n1 = floor(n + 1.e-12);
n1 = std::max(n1, 1);
while (conf.npieces % n1 != 0) --n1;
int n2 = ceil(n - 1.e-12);
while (conf.npieces % n2 != 0) ++n2;
// pick whichever of n1 and n2 gives blocks closest to square,
// i.e. gives the shortest long side
double longside1 = std::max(nx / n1, ny / (conf.npieces/n1));
double longside2 = std::max(nx / n2, ny / (conf.npieces/n2));
conf.numpcx = (longside1 <= longside2 ? n1 : n2);
conf.numpcy = conf.npieces / conf.numpcx;
if (swapflag) std::swap(conf.numpcx, conf.numpcy);
}
static void generate_mesh(config &conf,
std::vector<double> &pointpos_x,
std::vector<double> &pointpos_y,
std::vector<int64_t> &pointcolors,
std::map<int64_t, std::vector<int64_t> > &pointmcolors,
std::vector<int64_t> &zonestart,
std::vector<int64_t> &zonesize,
std::vector<int64_t> &zonepoints,
std::vector<int64_t> &zonecolors)
{
// Do calculations common to all mesh types:
std::vector<int64_t> zxbounds;
std::vector<int64_t> zybounds;
if (conf.numpcx <= 0 || conf.numpcy <= 0) {
calc_mesh_num_pieces(conf);
}
zxbounds.push_back(-1);
for (int pcx = 1; pcx < conf.numpcx; ++pcx)
zxbounds.push_back(pcx * conf.nzx / conf.numpcx);
zxbounds.push_back(conf.nzx + 1);
zybounds.push_back(-1);
for (int pcy = 1; pcy < conf.numpcy; ++pcy)
zybounds.push_back(pcy * conf.nzy / conf.numpcy);
zybounds.push_back(0x7FFFFFFF);
// Mesh type-specific calculations:
if (conf.meshtype == MESH_PIE) {
generate_mesh_pie(conf, pointpos_x, pointpos_y, pointcolors, pointmcolors,
zonestart, zonesize, zonepoints, zonecolors,
zxbounds, zybounds);
} else if (conf.meshtype == MESH_RECT) {
generate_mesh_rect(conf, pointpos_x, pointpos_y, pointcolors, pointmcolors,
zonestart, zonesize, zonepoints, zonecolors,
zxbounds, zybounds);
} else if (conf.meshtype == MESH_HEX) {
generate_mesh_hex(conf, pointpos_x, pointpos_y, pointcolors, pointmcolors,
zonestart, zonesize, zonepoints, zonecolors,
zxbounds, zybounds);
}
}
static void sort_zones_by_color(const config &conf,
const std::vector<int64_t> &zonecolors,
std::vector<int64_t> &zones_inverse_map,
std::vector<int64_t> &zones_map)
{
// Sort zones by color.
assert(int64_t(zonecolors.size()) == conf.nz);
std::map<int64_t, std::vector<int64_t> > zones_by_color;
for (int64_t z = 0; z < conf.nz; z++) {
zones_by_color[zonecolors[z]].push_back(z);
}
for (int64_t c = 0; c < conf.npieces; c++) {
std::vector<int64_t> &zones = zones_by_color[c];
for (std::vector<int64_t>::iterator zt = zones.begin(), ze = zones.end();
zt != ze; ++zt) {
int64_t z = *zt;
assert(zones_map[z] == -1ll);
zones_map[z] = zones_inverse_map.size();
zones_inverse_map.push_back(z);
}
}
}
static std::set<int64_t> zone_point_set(
int64_t z,
const std::vector<int64_t> &zonestart,
const std::vector<int64_t> &zonesize,
const std::vector<int64_t> &zonepoints)
{
std::set<int64_t> points;
for (int64_t z_start = zonestart[z], z_size = zonesize[z],
z_point = z_start; z_point < z_start + z_size; z_point++) {
points.insert(zonepoints[z_point]);
}
return points;
}
static void sort_zones_by_color_strip(const config &conf,
const std::vector<double> &pointpos_x,
const std::vector<double> &pointpos_y,
const std::vector<int64_t> &zonestart,
const std::vector<int64_t> &zonesize,
const std::vector<int64_t> &zonepoints,
const std::vector<int64_t> &zonecolors,
std::vector<int64_t> &zones_inverse_map,
std::vector<int64_t> &zones_map)
{
int64_t stripsize = conf.stripsize;
// Sort zones by color. Within each color, make strips of zones of
// size stripsize.
std::vector<std::vector<int64_t> > strips;
assert(int64_t(zonecolors.size()) == conf.nz);
for (int64_t c = 0; c < conf.npieces; c++) {
strips.assign(strips.size(), std::vector<int64_t>());
int64_t z_start = -1ll;
std::set<int64_t> z_start_points;
for (int64_t z = 0; z < conf.nz; z++) {
if (zonecolors[z] == c) {
if (z_start >= 0) {
if (z > z_start + 1) {
bool intersect = false;
for (int64_t z_start = zonestart[z], z_size = zonesize[z],
z_point = z_start; z_point < z_start + z_size; z_point++) {
if (z_start_points.count(zonepoints[z_point])) {
intersect = true;
break;
}
}
if (intersect) {
z_start = z;
z_start_points =
zone_point_set(z_start, zonestart, zonesize, zonepoints);
}
}
} else {
z_start = z;
z_start_points =
zone_point_set(z_start, zonestart, zonesize, zonepoints);
}
int64_t strip = (z - z_start)/stripsize;
if (strip + 1 > int64_t(strips.size())) {
strips.resize(strip+1);
}
strips[strip].push_back(z);
}
}
for (std::vector<std::vector<int64_t> >::iterator st = strips.begin(),
se = strips.end(); st != se; ++st) {
for (std::vector<int64_t>::iterator zt = st->begin(), ze = st->end();
zt != ze; ++zt) {
int64_t z = *zt;
assert(zones_map[z] == -1ll);
zones_map[z] = zones_inverse_map.size();
zones_inverse_map.push_back(z);
}
}
}
}
static void sort_points_by_color(
const config &conf,
const std::vector<int64_t> &pointcolors,
std::map<int64_t, std::vector<int64_t> > &pointmcolors,
std::vector<int64_t> &points_inverse_map,
std::vector<int64_t> &points_map)
{
// Sort points by color; sort multi-color points by first color.
assert(int64_t(pointcolors.size()) == conf.np);
std::map<int64_t, std::vector<int64_t> > points_by_color;
std::map<int64_t, std::vector<int64_t> > points_by_multicolor;
for (int64_t p = 0; p < conf.np; p++) {
if (pointcolors[p] == MULTICOLOR) {
points_by_multicolor[pointmcolors[p][0]].push_back(p);
} else {
points_by_color[pointcolors[p]].push_back(p);
}
}
for (int64_t c = 0; c < conf.npieces; c++) {
std::vector<int64_t> &points = points_by_multicolor[c];
for (std::vector<int64_t>::iterator pt = points.begin(), pe = points.end();
pt != pe; ++pt) {
int64_t p = *pt;
assert(points_map[p] == -1ll);
points_map[p] = points_inverse_map.size();
points_inverse_map.push_back(p);
}
}
for (int64_t c = 0; c < conf.npieces; c++) {
std::vector<int64_t> &points = points_by_color[c];
for (std::vector<int64_t>::iterator pt = points.begin(), pe = points.end();
pt != pe; ++pt) {
int64_t p = *pt;
assert(points_map[p] == -1ll);
points_map[p] = points_inverse_map.size();
points_inverse_map.push_back(p);
}
}
}
static void compact_mesh(const config &conf,
std::vector<double> &pointpos_x,
std::vector<double> &pointpos_y,
std::vector<int64_t> &pointcolors,
std::map<int64_t, std::vector<int64_t> > &pointmcolors,
std::vector<int64_t> &zonestart,
std::vector<int64_t> &zonesize,
std::vector<int64_t> &zonepoints,
std::vector<int64_t> &zonecolors)
{
// This stage is responsible for compacting the mesh so that each of
// the pieces is dense (in the global coordinate space). This
// involves sorting the various elements by color and then rewriting
// the various pointers to be internally consistent again.
// Sort zones by color.
std::vector<int64_t> zones_inverse_map;
std::vector<int64_t> zones_map(conf.nz, -1ll);
if (conf.stripsize > 0) {
sort_zones_by_color_strip(conf, pointpos_x, pointpos_y,
zonestart, zonesize, zonepoints, zonecolors,
zones_inverse_map, zones_map);
} else {
sort_zones_by_color(conf, zonecolors, zones_inverse_map, zones_map);
}
assert(int64_t(zones_inverse_map.size()) == conf.nz);
// Sort points by color; sort multi-color points by first color.
std::vector<int64_t> points_inverse_map;
std::vector<int64_t> points_map(conf.np, -1ll);
sort_points_by_color(conf, pointcolors, pointmcolors,
points_inverse_map, points_map);
assert(int64_t(points_inverse_map.size()) == conf.np);
// Various sanity checks.
#if 0
for (int64_t z = 0; z < conf.nz; z++) {
printf("zone old %ld new %ld color %ld\n", z, zones_map[z], zonecolors[z]);
}
printf("\n");
for (int64_t newz = 0; newz < conf.nz; newz++) {
int64_t oldz = zones_inverse_map[newz];
printf("zone new %ld old %ld color %ld\n", newz, oldz, zonecolors[oldz]);
}
printf("\n");
for (int64_t p = 0; p < conf.np; p++) {
printf("point old %ld new %ld color %ld\n", p, points_map[p], pointcolors[p]);
}
printf("\n");
for (int64_t newp = 0; newp < conf.np; newp++) {
int64_t oldp = points_inverse_map[newp];
printf("point new %ld old %ld color %ld\n", newp, oldp, pointcolors[oldp]);
}
#endif
// Project zones through the zones map.
{
std::vector<int64_t> old_zonestart = zonestart;
for (int64_t newz = 0; newz < conf.nz; newz++) {
int64_t oldz = zones_inverse_map[newz];
zonestart[newz] = old_zonestart[oldz];
}
}
{
std::vector<int64_t> old_zonesize = zonesize;
for (int64_t newz = 0; newz < conf.nz; newz++) {
int64_t oldz = zones_inverse_map[newz];
zonesize[newz] = old_zonesize[oldz];
}
}
{
std::vector<int64_t> old_zonepoints = zonepoints;
int64_t nzp = zonepoints.size();
for (int64_t zp = 0; zp < nzp; zp++) {
zonepoints[zp] = points_map[old_zonepoints[zp]];
}
}
{
std::vector<int64_t> old_zonecolors = zonecolors;
for (int64_t newz = 0; newz < conf.nz; newz++) {
int64_t oldz = zones_inverse_map[newz];
zonecolors[newz] = old_zonecolors[oldz];
}
}
// Project points through the points map.
{
std::vector<double> old_pointpos_x = pointpos_x;
for (int64_t newp = 0; newp < conf.np; newp++) {
int64_t oldp = points_inverse_map[newp];
pointpos_x[newp] = old_pointpos_x[oldp];
}
}
{
std::vector<double> old_pointpos_y = pointpos_y;
for (int64_t newp = 0; newp < conf.np; newp++) {
int64_t oldp = points_inverse_map[newp];
pointpos_y[newp] = old_pointpos_y[oldp];
}
}
{
std::vector<int64_t> old_pointcolors = pointcolors;
for (int64_t newp = 0; newp < conf.np; newp++) {
int64_t oldp = points_inverse_map[newp];
pointcolors[newp] = old_pointcolors[oldp];
}
}
{
std::map<int64_t, std::vector<int64_t> > old_pointmcolors = pointmcolors;
for (int64_t newp = 0; newp < conf.np; newp++) {
int64_t oldp = points_inverse_map[newp];
pointmcolors[newp] = old_pointmcolors[oldp];
}
}
}
static void
color_spans(const config &conf,
const std::vector<double> &pointpos_x,
const std::vector<double> &pointpos_y,
const std::vector<int64_t> &pointcolors,
std::map<int64_t, std::vector<int64_t> > &pointmcolors,
const std::vector<int64_t> &zonestart,
const std::vector<int64_t> &zonesize,
const std::vector<int64_t> &zonepoints,
const std::vector<int64_t> &zonecolors,
std::vector<int64_t> &zonespancolors_vec,
std::vector<int64_t> &pointspancolors_vec,
int64_t &nspans_zones,
int64_t &nspans_points)
{
{
// Compute zone spans.
std::vector<std::vector<std::vector<int64_t> > > spans(conf.npieces);
std::vector<int64_t> span_size(conf.npieces, conf.spansize);
for (int64_t z = 0; z < conf.nz; z++) {
int64_t c = zonecolors[z];
if (span_size[c] + zonesize[c] > conf.spansize) {
spans[c].resize(spans[c].size() + 1);
span_size[c] = 0;
}
spans[c][spans[c].size() - 1].push_back(z);
span_size[c] += zonesize[z];
}
// Color zones by span.
nspans_zones = 0;
zonespancolors_vec.assign(conf.nz, -1ll);
for (int64_t c = 0; c < conf.npieces; c++) {
std::vector<std::vector<int64_t> > &color_spans = spans[c];
int64_t nspans = color_spans.size();
nspans_zones = std::max(nspans_zones, nspans);
for (int64_t ispan = 0; ispan < nspans; ispan++) {
std::vector<int64_t> &span = color_spans[ispan];
for (std::vector<int64_t>::iterator zt = span.begin(), ze = span.end();
zt != ze; ++zt) {
int64_t z = *zt;
zonespancolors_vec[z] = ispan;
}
}
}
for (int64_t z = 0; z < conf.nz; z++) {
assert(zonespancolors_vec[z] != -1ll);
}
}
{
// Compute point spans.
std::vector<std::vector<std::vector<int64_t> > > spans(conf.npieces);
std::vector<std::vector<std::vector<int64_t> > > mspans(conf.npieces);
std::vector<int64_t> span_size(conf.npieces, conf.spansize);
std::vector<int64_t> mspan_size(conf.npieces, conf.spansize);
for (int64_t p = 0; p < conf.np; p++) {
int64_t c = pointcolors[p];
if (c != MULTICOLOR) {
if (span_size[c] >= conf.spansize) {
spans[c].resize(spans[c].size() + 1);
span_size[c] = 0;
}
spans[c][spans[c].size() - 1].push_back(p);
span_size[c]++;
} else {
c = pointmcolors[p][0];
if (mspan_size[c] >= conf.spansize) {
mspans[c].resize(mspans[c].size() + 1);
mspan_size[c] = 0;
}
mspans[c][mspans[c].size() - 1].push_back(p);
mspan_size[c]++;
}
}
// Color points by span.
nspans_points = 0;
pointspancolors_vec.assign(conf.np, -1ll);
for (int64_t c = 0; c < conf.npieces; c++) {
std::vector<std::vector<int64_t> > &color_spans = spans[c];
int64_t nspans = color_spans.size();
nspans_points = std::max(nspans_points, nspans);
for (int64_t ispan = 0; ispan < nspans; ispan++) {
std::vector<int64_t> &span = color_spans[ispan];
for (std::vector<int64_t>::iterator pt = span.begin(), pe = span.end();
pt != pe; ++pt) {
int64_t p = *pt;
pointspancolors_vec[p] = ispan;
}
}
}
for (int64_t c = 0; c < conf.npieces; c++) {
std::vector<std::vector<int64_t> > &color_spans = mspans[c];
int64_t nspans = color_spans.size();
nspans_points = std::max(nspans_points, nspans);
for (int64_t ispan = 0; ispan < nspans; ispan++) {
std::vector<int64_t> &span = color_spans[ispan];
for (std::vector<int64_t>::iterator pt = span.begin(), pe = span.end();
pt != pe; ++pt) {
int64_t p = *pt;
pointspancolors_vec[p] = ispan;
}
}
}
for (int64_t p = 0; p < conf.np; p++) {
assert(pointspancolors_vec[p] != -1ll);
}
}
}
void generate_mesh_raw(
int64_t conf_np,
int64_t conf_nz,
int64_t conf_nzx,
int64_t conf_nzy,
double conf_lenx,
double conf_leny,
int64_t conf_numpcx,
int64_t conf_numpcy,
int64_t conf_npieces,
int64_t conf_meshtype,
bool conf_compact,
int64_t conf_stripsize,
int64_t conf_spansize,
double *pointpos_x, size_t *pointpos_x_size,
double *pointpos_y, size_t *pointpos_y_size,
int64_t *pointcolors, size_t *pointcolors_size,
uint64_t *pointmcolors, size_t *pointmcolors_size,
int64_t *pointspancolors, size_t *pointspancolors_size,
int64_t *zonestart, size_t *zonestart_size,
int64_t *zonesize, size_t *zonesize_size,
int64_t *zonepoints, size_t *zonepoints_size,
int64_t *zonecolors, size_t *zonecolors_size,
int64_t *zonespancolors, size_t *zonespancolors_size,
int64_t *nspans_zones,
int64_t *nspans_points)
{
config conf;
conf.np = conf_np;
conf.nz = conf_nz;
conf.nzx = conf_nzx;
conf.nzy = conf_nzy;
conf.lenx = conf_lenx;
conf.leny = conf_leny;
conf.numpcx = conf_numpcx;
conf.numpcy = conf_numpcy;
conf.npieces = conf_npieces;
conf.meshtype = conf_meshtype;
conf.compact = conf_compact;
conf.stripsize = conf_stripsize;
conf.spansize = conf_spansize;
std::vector<double> pointpos_x_vec;
std::vector<double> pointpos_y_vec;
std::vector<int64_t> pointcolors_vec;
std::map<int64_t, std::vector<int64_t> > pointmcolors_map;
std::vector<int64_t> zonestart_vec;
std::vector<int64_t> zonesize_vec;
std::vector<int64_t> zonepoints_vec;
std::vector<int64_t> zonecolors_vec;
generate_mesh(conf,
pointpos_x_vec,
pointpos_y_vec,
pointcolors_vec,
pointmcolors_map,
zonestart_vec,
zonesize_vec,
zonepoints_vec,
zonecolors_vec);
if (conf.compact) {
compact_mesh(conf,
pointpos_x_vec,
pointpos_y_vec,
pointcolors_vec,
pointmcolors_map,
zonestart_vec,
zonesize_vec,
zonepoints_vec,
zonecolors_vec);
}
std::vector<int64_t> zonespancolors_vec;
std::vector<int64_t> pointspancolors_vec;
color_spans(conf,
pointpos_x_vec,
pointpos_y_vec,
pointcolors_vec,
pointmcolors_map,
zonestart_vec,
zonesize_vec,
zonepoints_vec,
zonecolors_vec,
zonespancolors_vec,
pointspancolors_vec,
*nspans_zones,
*nspans_points);
int64_t color_words = int64_t(ceil(conf_npieces/64.0));
assert(pointpos_x_vec.size() <= *pointpos_x_size);
assert(pointpos_y_vec.size() <= *pointpos_y_size);
assert(pointcolors_vec.size() <= *pointcolors_size);
assert(pointcolors_vec.size()*color_words <= *pointmcolors_size);
assert(pointspancolors_vec.size() <= *pointspancolors_size);
assert(zonestart_vec.size() <= *zonestart_size);
assert(zonesize_vec.size() <= *zonesize_size);
assert(zonepoints_vec.size() <= *zonepoints_size);
assert(zonecolors_vec.size() <= *zonecolors_size);
assert(zonespancolors_vec.size() <= *zonespancolors_size);
memcpy(pointpos_x, pointpos_x_vec.data(), pointpos_x_vec.size()*sizeof(double));
memcpy(pointpos_y, pointpos_y_vec.data(), pointpos_y_vec.size()*sizeof(double));
memcpy(pointcolors, pointcolors_vec.data(), pointcolors_vec.size()*sizeof(int64_t));
memcpy(pointspancolors, pointspancolors_vec.data(), pointspancolors_vec.size()*sizeof(int64_t));
memcpy(zonestart, zonestart_vec.data(), zonestart_vec.size()*sizeof(int64_t));
memcpy(zonesize, zonesize_vec.data(), zonesize_vec.size()*sizeof(int64_t));
memcpy(zonepoints, zonepoints_vec.data(), zonepoints_vec.size()*sizeof(int64_t));
memcpy(zonecolors, zonecolors_vec.data(), zonecolors_vec.size()*sizeof(int64_t));
memcpy(zonespancolors, zonespancolors_vec.data(), zonespancolors_vec.size()*sizeof(int64_t));
memset(pointmcolors, 0, (*pointmcolors_size)*sizeof(uint64_t));
for (std::map<int64_t, std::vector<int64_t> >::iterator it = pointmcolors_map.begin(),
ie = pointmcolors_map.end(); it != ie; ++it) {
int64_t p = it->first;
for (std::vector<int64_t>::iterator ct = it->second.begin(),
ce = it->second.end(); ct != ce; ++ct) {
int64_t word = (*ct) / 64.0;
int64_t bit = (*ct) % 64;
pointmcolors[p + word] |= (1 << bit);
}
}
*pointpos_x_size = pointpos_x_vec.size();
*pointpos_y_size = pointpos_y_vec.size();
*pointcolors_size = pointcolors_vec.size();
*pointmcolors_size = pointcolors_vec.size()*color_words;
*pointspancolors_size = pointspancolors_vec.size();
*zonestart_size = zonestart_vec.size();
*zonesize_size = zonesize_vec.size();
*zonepoints_size = zonepoints_vec.size();
*zonecolors_size = zonecolors_vec.size();
*zonespancolors_size = zonespancolors_vec.size();
}
///
/// Mapper
///
#define SPMD_SHARD_USE_IO_PROC 0
static LegionRuntime::Logger::Category log_pennant("pennant");
class PennantMapper : public DefaultMapper
{
public:
PennantMapper(MapperRuntime *rt, Machine machine, Processor local,
const char *mapper_name,
std::vector<Processor>* procs_list,
std::vector<Memory>* sysmems_list,
std::map<Memory, std::vector<Processor> >* sysmem_local_procs,
#if SPMD_SHARD_USE_IO_PROC
std::map<Memory, std::vector<Processor> >* sysmem_local_io_procs,
#endif
std::map<Processor, Memory>* proc_sysmems,
std::map<Processor, Memory>* proc_regmems);
virtual void default_policy_rank_processor_kinds(
MapperContext ctx, const Task &task,
std::vector<Processor::Kind> &ranking);
virtual Processor default_policy_select_initial_processor(
MapperContext ctx, const Task &task);
virtual void default_policy_select_target_processors(
MapperContext ctx,
const Task &task,
std::vector<Processor> &target_procs);
virtual LogicalRegion default_policy_select_instance_region(
MapperContext ctx, Memory target_memory,
const RegionRequirement &req,
const LayoutConstraintSet &constraints,
bool force_new_instances,
bool meets_constraints);
virtual void map_copy(const MapperContext ctx,
const Copy ©,
const MapCopyInput &input,
MapCopyOutput &output);
virtual void map_must_epoch(const MapperContext ctx,
const MapMustEpochInput& input,
MapMustEpochOutput& output);
template<bool IS_SRC>
void pennant_create_copy_instance(MapperContext ctx, const Copy ©,
const RegionRequirement &req, unsigned index,
std::vector<PhysicalInstance> &instances);
private:
std::vector<Processor>& procs_list;
std::vector<Memory>& sysmems_list;
std::map<Memory, std::vector<Processor> >& sysmem_local_procs;
#if SPMD_SHARD_USE_IO_PROC
std::map<Memory, std::vector<Processor> >& sysmem_local_io_procs;
#endif
std::map<Processor, Memory>& proc_sysmems;
// std::map<Processor, Memory>& proc_regmems;
};
PennantMapper::PennantMapper(MapperRuntime *rt, Machine machine, Processor local,
const char *mapper_name,
std::vector<Processor>* _procs_list,
std::vector<Memory>* _sysmems_list,
std::map<Memory, std::vector<Processor> >* _sysmem_local_procs,
#if SPMD_SHARD_USE_IO_PROC
std::map<Memory, std::vector<Processor> >* _sysmem_local_io_procs,
#endif
std::map<Processor, Memory>* _proc_sysmems,
std::map<Processor, Memory>* _proc_regmems)
: DefaultMapper(rt, machine, local, mapper_name),
procs_list(*_procs_list),
sysmems_list(*_sysmems_list),
sysmem_local_procs(*_sysmem_local_procs),
#if SPMD_SHARD_USE_IO_PROC
sysmem_local_io_procs(*_sysmem_local_io_procs),
#endif
proc_sysmems(*_proc_sysmems)// ,
// proc_regmems(*_proc_regmems)
{
}
void PennantMapper::default_policy_rank_processor_kinds(MapperContext ctx,
const Task &task, std::vector<Processor::Kind> &ranking)
{
#if SPMD_SHARD_USE_IO_PROC
const char* task_name = task.get_task_name();
const char* prefix = "shard_";
if (strncmp(task_name, prefix, strlen(prefix)) == 0) {
// Put shard tasks on IO processors.
ranking.resize(4);
ranking[0] = Processor::TOC_PROC;
ranking[1] = Processor::PROC_SET;
ranking[2] = Processor::IO_PROC;
ranking[3] = Processor::LOC_PROC;
} else {
#endif
ranking.resize(4);
ranking[0] = Processor::TOC_PROC;
ranking[1] = Processor::PROC_SET;
ranking[2] = Processor::LOC_PROC;
ranking[3] = Processor::IO_PROC;
#if SPMD_SHARD_USE_IO_PROC
}
#endif
}
Processor PennantMapper::default_policy_select_initial_processor(
MapperContext ctx, const Task &task)
{
if (!task.regions.empty()) {
if (task.regions[0].handle_type == SINGULAR) {
Color index = runtime->get_logical_region_color(ctx, task.regions[0].region);
#define NO_SPMD 0
#if NO_SPMD
return procs_list[index % procs_list.size()];
#else
std::vector<Processor> &local_procs =
sysmem_local_procs[proc_sysmems[local_proc]];
if (local_procs.size() > 1) {
#define SPMD_RESERVE_SHARD_PROC 0
#if SPMD_RESERVE_SHARD_PROC
return local_procs[(index % (local_procs.size() - 1)) + 1];
#else
return local_procs[index % local_procs.size()];
#endif
} else {
return local_procs[0];
}
#endif
}
}
return DefaultMapper::default_policy_select_initial_processor(ctx, task);
}
void PennantMapper::default_policy_select_target_processors(
MapperContext ctx,
const Task &task,
std::vector<Processor> &target_procs)
{
target_procs.push_back(task.target_proc);
}
LogicalRegion PennantMapper::default_policy_select_instance_region(
MapperContext ctx, Memory target_memory,
const RegionRequirement &req,
const LayoutConstraintSet &layout_constraints,
bool force_new_instances,
bool meets_constraints)
{
return req.region;
}
//--------------------------------------------------------------------------
template<bool IS_SRC>
void PennantMapper::pennant_create_copy_instance(MapperContext ctx,
const Copy ©, const RegionRequirement &req,
unsigned idx, std::vector<PhysicalInstance> &instances)
//--------------------------------------------------------------------------
{
// This method is identical to the default version except that it
// chooses an intelligent memory based on the destination of the
// copy.
// See if we have all the fields covered
std::set<FieldID> missing_fields = req.privilege_fields;
for (std::vector<PhysicalInstance>::const_iterator it =
instances.begin(); it != instances.end(); it++)
{
it->remove_space_fields(missing_fields);
if (missing_fields.empty())
break;
}
if (missing_fields.empty())
return;
// If we still have fields, we need to make an instance
// We clearly need to take a guess, let's see if we can find
// one of our instances to use.
// ELLIOTT: Get the remote node here.
Color index = runtime->get_logical_region_color(ctx, copy.src_requirements[idx].region);
// #if SPMD_RESERVE_SHARD_PROC
// size_t sysmem_index = index / (std::max(sysmem_local_procs.begin()->second.size() - 1, (size_t)1));
// #else
// size_t sysmem_index = index / sysmem_local_procs.begin()->second.size();
// #endif
// assert(sysmem_index < sysmems_list.size());
// Memory target_memory = sysmems_list[sysmem_index];
Memory target_memory = default_policy_select_target_memory(ctx,
procs_list[index % procs_list.size()],
req);
log_pennant.spew("Building instance for copy of a region with index %u to be in memory %llx",
index, target_memory.id);
bool force_new_instances = false;
LayoutConstraintID our_layout_id =
default_policy_select_layout_constraints(ctx, target_memory,
req, COPY_MAPPING,
true/*needs check*/,
force_new_instances);
LayoutConstraintSet creation_constraints =
runtime->find_layout_constraints(ctx, our_layout_id);
creation_constraints.add_constraint(
FieldConstraint(missing_fields,
false/*contig*/, false/*inorder*/));
instances.resize(instances.size() + 1);
if (!default_make_instance(ctx, target_memory,
creation_constraints, instances.back(),
COPY_MAPPING, force_new_instances, true/*meets*/, req))
{
// If we failed to make it that is bad
log_pennant.error("Pennant mapper failed allocation for "
"%s region requirement %d of explicit "
"region-to-region copy operation in task %s "
"(ID %lld) in memory " IDFMT " for processor "
IDFMT ". This means the working set of your "
"application is too big for the allotted "
"capacity of the given memory under the default "
"mapper's mapping scheme. You have three "
"choices: ask Realm to allocate more memory, "
"write a custom mapper to better manage working "
"sets, or find a bigger machine. Good luck!",
IS_SRC ? "source" : "destination", idx,
copy.parent_task->get_task_name(),
copy.parent_task->get_unique_id(),
target_memory.id,
copy.parent_task->current_proc.id);
assert(false);
}
}
void PennantMapper::map_copy(const MapperContext ctx,
const Copy ©,
const MapCopyInput &input,
MapCopyOutput &output)
{
log_pennant.spew("Pennant mapper map_copy");
for (unsigned idx = 0; idx < copy.src_requirements.size(); idx++)
{
// Use a virtual instance for the source unless source is
// restricted or we'd applying a reduction.
output.src_instances[idx].clear();
if (copy.src_requirements[idx].is_restricted()) {
// If it's restricted, just take the instance. This will only
// happen inside the shard task.
output.src_instances[idx] = input.src_instances[idx];
if (!output.src_instances[idx].empty())
runtime->acquire_and_filter_instances(ctx,
output.src_instances[idx]);
} else if (copy.dst_requirements[idx].privilege == REDUCE) {
// Use the default here. This will place the instance on the
// current node.
default_create_copy_instance<true/*is src*/>(ctx, copy,
copy.src_requirements[idx], idx, output.src_instances[idx]);
} else {
output.src_instances[idx].push_back(
PhysicalInstance::get_virtual_instance());
}
// Place the destination instance on the remote node.
output.dst_instances[idx].clear();
if (!copy.dst_requirements[idx].is_restricted()) {
// Call a customized method to create an instance on the desired node.
pennant_create_copy_instance<false/*is src*/>(ctx, copy,
copy.dst_requirements[idx], idx, output.dst_instances[idx]);
} else {
// If it's restricted, just take the instance. This will only
// happen inside the shard task.
output.dst_instances[idx] = input.dst_instances[idx];
if (!output.dst_instances[idx].empty())
runtime->acquire_and_filter_instances(ctx,
output.dst_instances[idx]);
}
}
}
void PennantMapper::map_must_epoch(const MapperContext ctx,
const MapMustEpochInput& input,
MapMustEpochOutput& output)
{
size_t num_nodes = sysmems_list.size();
size_t num_tasks = input.tasks.size();
size_t num_shards_per_node =
num_nodes < input.tasks.size() ? (num_tasks + num_nodes - 1) / num_nodes : 1;
std::map<const Task*, size_t> task_indices;
for (size_t idx = 0; idx < num_tasks; ++idx) {
size_t node_idx = idx / num_shards_per_node;
size_t proc_idx = idx % num_shards_per_node;
assert(node_idx < sysmems_list.size());
#if SPMD_SHARD_USE_IO_PROC
assert(proc_idx < sysmem_local_io_procs[sysmems_list[node_idx]].size());
output.task_processors[idx] = sysmem_local_io_procs[sysmems_list[node_idx]][proc_idx];
#else
assert(proc_idx < sysmem_local_procs[sysmems_list[node_idx]].size());
output.task_processors[idx] = sysmem_local_procs[sysmems_list[node_idx]][proc_idx];
#endif
task_indices[input.tasks[idx]] = node_idx;
}
for (size_t idx = 0; idx < input.constraints.size(); ++idx) {
const MappingConstraint& constraint = input.constraints[idx];
int owner_id = -1;
for (unsigned i = 0; i < constraint.constrained_tasks.size(); ++i) {
const RegionRequirement& req =
constraint.constrained_tasks[i]->regions[
constraint.requirement_indexes[i]];
if (req.is_no_access()) continue;
assert(owner_id == -1);
owner_id = static_cast<int>(i);
}
assert(owner_id != -1);
const Task* task = constraint.constrained_tasks[owner_id];
const RegionRequirement& req =
task->regions[constraint.requirement_indexes[owner_id]];
Memory target_memory = sysmems_list[task_indices[task]];
LayoutConstraintSet layout_constraints;
default_policy_select_constraints(ctx, layout_constraints, target_memory, req);
layout_constraints.add_constraint(
FieldConstraint(req.privilege_fields, false /*!contiguous*/));
PhysicalInstance inst;
bool created;
bool ok = runtime->find_or_create_physical_instance(ctx, target_memory,
layout_constraints, std::vector<LogicalRegion>(1, req.region),
inst, created, true /*acquire*/);
assert(ok);
output.constraint_mappings[idx].push_back(inst);
}
}
static void create_mappers(Machine machine, HighLevelRuntime *runtime, const std::set<Processor> &local_procs)
{
std::vector<Processor>* procs_list = new std::vector<Processor>();
std::vector<Memory>* sysmems_list = new std::vector<Memory>();
std::map<Memory, std::vector<Processor> >* sysmem_local_procs =
new std::map<Memory, std::vector<Processor> >();
#if SPMD_SHARD_USE_IO_PROC
std::map<Memory, std::vector<Processor> >* sysmem_local_io_procs =
new std::map<Memory, std::vector<Processor> >();
#endif
std::map<Processor, Memory>* proc_sysmems = new std::map<Processor, Memory>();
std::map<Processor, Memory>* proc_regmems = new std::map<Processor, Memory>();
std::vector<Machine::ProcessorMemoryAffinity> proc_mem_affinities;
machine.get_proc_mem_affinity(proc_mem_affinities);
for (unsigned idx = 0; idx < proc_mem_affinities.size(); ++idx) {
Machine::ProcessorMemoryAffinity& affinity = proc_mem_affinities[idx];
if (affinity.p.kind() == Processor::LOC_PROC ||
affinity.p.kind() == Processor::IO_PROC) {
if (affinity.m.kind() == Memory::SYSTEM_MEM) {
(*proc_sysmems)[affinity.p] = affinity.m;
if (proc_regmems->find(affinity.p) == proc_regmems->end())
(*proc_regmems)[affinity.p] = affinity.m;
}
else if (affinity.m.kind() == Memory::REGDMA_MEM)
(*proc_regmems)[affinity.p] = affinity.m;
}
}
for (std::map<Processor, Memory>::iterator it = proc_sysmems->begin();
it != proc_sysmems->end(); ++it) {
if (it->first.kind() == Processor::LOC_PROC) {
procs_list->push_back(it->first);
(*sysmem_local_procs)[it->second].push_back(it->first);
}
#if SPMD_SHARD_USE_IO_PROC
else if (it->first.kind() == Processor::IO_PROC) {
(*sysmem_local_io_procs)[it->second].push_back(it->first);
}
#endif
}
for (std::map<Memory, std::vector<Processor> >::iterator it =
sysmem_local_procs->begin(); it != sysmem_local_procs->end(); ++it)
sysmems_list->push_back(it->first);
for (std::set<Processor>::const_iterator it = local_procs.begin();
it != local_procs.end(); it++)
{
PennantMapper* mapper = new PennantMapper(runtime->get_mapper_runtime(),
machine, *it, "pennant_mapper",
procs_list,
sysmems_list,
sysmem_local_procs,
#if SPMD_SHARD_USE_IO_PROC
sysmem_local_io_procs,
#endif
proc_sysmems,
proc_regmems);
runtime->replace_default_mapper(mapper, *it);
}
}
void register_mappers()
{
HighLevelRuntime::add_registration_callback(create_mappers);
}
|
a4532d0f6d89261e2455144eddfc7e838c30f479 | beaef70fffb6668549da7191ebea16ab4e5ba4f0 | /Infoarena/infoarena turniri.cpp | ba4820f38b3597e5cc8f3bec1ffe19282eb462d7 | [] | no_license | QuickSorting/CompetitiveProgramming | fe57922f1ab3d8ee3e066ff8b68fd217eacf6f3c | 9120d7971425f263ba7bd2eb75f86c479a913839 | refs/heads/master | 2021-12-27T19:38:03.477901 | 2021-12-13T17:55:36 | 2021-12-13T17:55:36 | 202,154,323 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,878 | cpp | infoarena turniri.cpp | /*
-I use two stacks to find the first and second next bigger number for each index
-Then we have to consider a couple of cases inlcuding removing the first next bigger
number for a index, which means it will then be able to go until the second one
*/
#include <bits/stdc++.h>
using namespace std;
const int kN = 1e6 + 7;
int a[kN], n;
pair<int, int> bigger[kN];
int main(){
ios::sync_with_stdio(false);
cin.tie(NULL);
freopen("turnuri.in", "r", stdin);
freopen("turnuri.out", "w", stdout);
cin >> n;
for(int i = 0; i < n; ++i)
cin >> a[i];
stack<int> st1, st2, new2;
for(int i = n - 1; i >= 0; --i){
while(!st1.empty() && a[i] > a[st1.top()]){
bigger[st1.top()].first = i;
new2.push(st1.top());
st1.pop();
}
st1.push(i);
while(!st2.empty() && a[i] > a[st2.top()]){
bigger[st2.top()].second = i;
st2.pop();
}
while(!new2.empty()){
st2.push(new2.top());
new2.pop();
}
}
while(!st1.empty()){
bigger[st1.top()].first = -1;
bigger[st1.top()].second = -1;
st1.pop();
}
while(!st2.empty()){
bigger[st2.top()].second = -1;
st2.pop();
}
//for(int i = 0; i < n; ++i)
// cout << bigger[i].first << " " << bigger[i].second << endl;
long long ans_normal = 0;
for(int i = 0; i < n; ++i){
if(bigger[i].first == -1)
ans_normal += i;
else
ans_normal += i - bigger[i].first;
//cout << ans_normal << " add" << endl;
}
long long ans_new = (long long)n * ans_normal;
//cout << ans_normal << " " << ans_new << endl;
for(int i = 0; i < n; ++i){
if(bigger[i].first == -1)
ans_new -= i;
else
ans_new -= i - bigger[i].first;
if(bigger[i].first == -1){
ans_new -= i;
continue;
}
if(bigger[i].second == -1)
ans_new += (i) - 1;
else
ans_new += (i - bigger[i].second) - 1;
ans_new -= i - bigger[i].first ;
ans_new -= i - bigger[i].first - 1;
}
cout << ans_new << "\n";
} |
b9008b498dc6db8db2e3f54a77d9d3d582fa61f4 | d504e27023af330590befafd2d7f542eafdd0d50 | /HeatPump/Pump.h | 78d184c74eab4a4ddcbd33e4c4615b446bbbe334 | [] | no_license | igorgsh/HeatPump_old | d85028bc99b944cf5d1f7cf17abceaefc874933c | c63f17cefc0881d7a6e7673425c1c1c5bccbd5a2 | refs/heads/master | 2022-04-06T21:34:33.602034 | 2020-02-07T08:51:55 | 2020-02-07T08:51:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 285 | h | Pump.h | #pragma once
#include "Relay.h"
#include "OutputDevice.h"
class Pump :
public Relay
{
public:
Pump(String label, UnitType pumpType, int pin, bool on, unsigned long minTimeOn=0, unsigned long minTimeOff=0);
~Pump();
void begin();
void StopPump();
void StartPump();
private:
};
|
abb918fc0e69d4c60c3eae1df1537c9159eb653f | 9f171d8ffef98b78f6568692f05fec8c6ff3a6a9 | /Top_Interview/200_NumberOfIslands/200.cpp | 4de0152d8cce4c82c9e4ab350684e7f91562bc5b | [] | no_license | AnyaLeung/2019Summer | d28514f282b3767f4ff80f4cac57db694d793043 | ddba9bca0d20c2bfd5ca12654c86fc0009dfbe86 | refs/heads/master | 2020-06-13T21:56:11.544454 | 2019-09-03T12:56:22 | 2019-09-03T12:56:22 | 194,800,321 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 997 | cpp | 200.cpp | class Solution {
public:
//dfs
void setNum(vector<vector<char>>& grid, int row, int col){
int m = grid.size();
int n = grid[0].size();
if(row<0 || col<0 || row>=m || col>=n
|| grid[row][col]!='1' || grid[row][col]=='2'){
return ;
}
grid[row][col] = 2;
setNum(grid, row+1, col);
setNum(grid, row-1, col);
setNum(grid, row, col+1);
setNum(grid, row, col-1);
}
int numIslands(vector<vector<char>>& grid) {
if(grid.empty()){
return 0;
}
int mlen = grid.size();
int nlen = grid[0].size();
if(mlen==0 || nlen==0){
return 0;
}
int sum = 0;
for(int i=0; i<mlen; i++){
for(int j=0; j<nlen; j++){
if(grid[i][j]=='1'){ //is land
sum ++;
setNum(grid, i, j);
}
}
}
return sum;
}
};
|
0fcfc789066980f102b00fcd768367af73ea0380 | ead381c771918483369037e7a61b0967dc10d580 | /OFX Saturation debug.cpp | b920e8a17f8ec5cea546203a44b82c8d3160fe7a | [] | no_license | crabshank/OFX-plugins | 3004d31e6e3a8f2c80245f614809337f1467a282 | 3ba49a92be521c17abd89289ae43644f6d27e3df | refs/heads/main | 2023-02-28T15:40:09.178031 | 2021-02-07T11:31:55 | 2021-02-07T11:31:55 | 336,769,130 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,320 | cpp | OFX Saturation debug.cpp | /*
Software License :
Copyright (c) 2003, The Open Effects Association Ltd. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name The Open Effects Association Ltd, 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.
*/
#include <cstring>
#include <stdexcept>
#include <new>
#include <iostream>
#include "ofxImageEffect.h"
#include "ofxMemory.h"
#include "ofxMultiThread.h"
#include "ofxUtilities.H" // example support utils
#if defined __APPLE__ || defined linux || defined __FreeBSD__
# define EXPORT __attribute__((visibility("default")))
#elif defined _WIN32
# define EXPORT OfxExport
#else
# error Not building on your operating system quite yet
#endif
#define rcptwoFiveFive 1.0/255.0
template <class T> inline T Maximum(T a, T b) { return a > b ? a : b; }
template <class T> inline T Minimum(T a, T b) { return a < b ? a : b; }
// pointers64 to various bits of the host
OfxHost* gHost;
OfxImageEffectSuiteV1* gEffectHost = 0;
OfxPropertySuiteV1* gPropHost = 0;
OfxParameterSuiteV1* gParamHost = 0;
OfxMemorySuiteV1* gMemoryHost = 0;
OfxMultiThreadSuiteV1* gThreadHost = 0;
OfxMessageSuiteV1* gMessageSuite = 0;
OfxInteractSuiteV1* gInteractHost = 0;
// some flags about the host's behaviour
int gHostSupportsMultipleBitDepths = false;
// private instance data type
struct MyInstanceData {
// handles to the clips we deal with
OfxImageClipHandle sourceClip;
OfxImageClipHandle outputClip;
OfxParamHandle saturationParam;
};
/* mandatory function to set up the host structures */
// Convinience wrapper to get private data
static MyInstanceData*
getMyInstanceData(OfxImageEffectHandle effect)
{
MyInstanceData* myData = (MyInstanceData*)ofxuGetEffectInstanceData(effect);
return myData;
}
/** @brief Called at load */
// instance construction
static OfxStatus
createInstance(OfxImageEffectHandle effect)
{
// get a pointer to the effect properties
OfxPropertySetHandle effectProps;
gEffectHost->getPropertySet(effect, &effectProps);
// get a pointer to the effect's parameter set
OfxParamSetHandle paramSet;
gEffectHost->getParamSet(effect, ¶mSet);
// make my private instance data
MyInstanceData* myData = new MyInstanceData;
// cache away param handles
gParamHost->paramGetHandle(paramSet, "saturation", &myData->saturationParam, 0);
// cache away clip handles
gEffectHost->clipGetHandle(effect, kOfxImageEffectSimpleSourceClipName, &myData->sourceClip, 0);
gEffectHost->clipGetHandle(effect, kOfxImageEffectOutputClipName, &myData->outputClip, 0);
// set my private instance data
gPropHost->propSetPointer(effectProps, kOfxPropInstanceData, 0, (void*)myData);
return kOfxStatOK;
}
// instance destruction
static OfxStatus
destroyInstance(OfxImageEffectHandle effect)
{
// get my instance data
MyInstanceData* myData = getMyInstanceData(effect);
// and delete it
if (myData)
delete myData;
return kOfxStatOK;
}
////////////////////////////////////////////////////////////////////////////////
// rendering routines
// look up a pixel in the image, does bounds checking to see if it is in the image rectangle
template <class PIX> inline PIX*
pixelAddress(PIX* img, OfxRectI rect, int x, int y, int bytesPerLine)
{
if (x < rect.x1 || x >= rect.x2 || y < rect.y1 || y > rect.y2)
return 0;
PIX* pix = (PIX*)(((char*)img) + (y - rect.y1) * bytesPerLine);
pix += x - rect.x1;
return pix;
}
////////////////////////////////////////////////////////////////////////////////
// base class to process images with
class Processor {
protected:
OfxImageEffectHandle effect;
double saturation;
void* srcV, * dstV;
OfxRectI srcRect, dstRect;
OfxRectI window;
int srcBytesPerLine, dstBytesPerLine;
public:
Processor(OfxImageEffectHandle eff,
double sat,
void* src, OfxRectI sRect, int sBytesPerLine,
void* dst, OfxRectI dRect, int dBytesPerLine,
OfxRectI win)
: effect(eff)
, saturation(sat)
, srcV(src)
, dstV(dst)
, srcRect(sRect)
, dstRect(dRect)
, window(win)
, srcBytesPerLine(sBytesPerLine)
, dstBytesPerLine(dBytesPerLine)
{}
static void multiThreadProcessing(unsigned int threadId, unsigned int nThreads, void* arg);
virtual void doProcessing(OfxRectI window) = 0;
void process(void);
};
// function call once for each thread by the host
void
Processor::multiThreadProcessing(unsigned int threadId, unsigned int nThreads, void* arg)
{
Processor* proc = (Processor*)arg;
// slice the y range into the number of threads it has
unsigned int dy = proc->window.y2 - proc->window.y1;
unsigned int y1 = proc->window.y1 + threadId * dy / nThreads;
unsigned int y2 = proc->window.y1 + Minimum((threadId + 1) * dy / nThreads, dy);
OfxRectI win = proc->window;
win.y1 = y1; win.y2 = y2;
// and render that thread on each
proc->doProcessing(win);
}
// function to kick off rendering across multiple CPUs
void
Processor::process(void)
{
unsigned int nThreads;
gThreadHost->multiThreadNumCPUs(&nThreads);
gThreadHost->multiThread(multiThreadProcessing, nThreads, (void*)this);
}
// template to do the RGBA processing
template <class PIX, int max>
class ProcessRGBA : public Processor {
public:
ProcessRGBA(OfxImageEffectHandle eff,
double sat,
void* src, OfxRectI sRect, int sBytesPerLine,
void* dst, OfxRectI dRect, int dBytesPerLine,
OfxRectI win)
: Processor(eff,
sat,
src, sRect, sBytesPerLine,
dst, dRect, dBytesPerLine,
win)
{
}
void doProcessing(OfxRectI procWindow)
{
PIX* src = (PIX*)srcV;
PIX* dst = (PIX*)dstV;
for (int y = procWindow.y1; y < procWindow.y2; y++) {
if (gEffectHost->abort(effect)) break;
PIX* dstPix = pixelAddress(dst, dstRect, procWindow.x1, y, dstBytesPerLine);
for (int x = procWindow.x1; x < procWindow.x2; x++) {
PIX* srcPix = 0;
if (src)
srcPix = pixelAddress(src, srcRect, x, y, srcBytesPerLine);
double OG_RGB[3] = { (double)(srcPix->r) * rcptwoFiveFive,(double)(srcPix->g) * rcptwoFiveFive ,(double)(srcPix->b) * rcptwoFiveFive };
double mx = fmax(OG_RGB[0], fmax(OG_RGB[1], OG_RGB[2]));
double mn = fmin(OG_RGB[0], fmin(OG_RGB[1], OG_RGB[2]));
double sat = (mx==0)?0:(mx-mn)/mx;
dstPix->r =(sat<= saturation)?0:fmax(fmin(round(OG_RGB[0] * 255), 255), 0);
dstPix->g =(sat<= saturation)?0:fmax(fmin(round(OG_RGB[1] * 255), 255), 0);
dstPix->b =(sat<= saturation)?0:fmax(fmin(round(OG_RGB[2] * 255), 255), 0);
dstPix++;
}
}
}
};
// the process code that the host sees
static OfxStatus render(OfxImageEffectHandle effect,
OfxPropertySetHandle inArgs,
OfxPropertySetHandle outArgs)
{
// get the render window and the time from the inArgs
OfxTime time;
OfxRectI renderWindow;
OfxStatus status = kOfxStatOK;
gPropHost->propGetDouble(inArgs, kOfxPropTime, 0, &time);
gPropHost->propGetIntN(inArgs, kOfxImageEffectPropRenderWindow, 4, &renderWindow.x1);
// retrieve any instance data associated with this effect
MyInstanceData* myData = getMyInstanceData(effect);
// property handles and members of each image
// in reality, we would put this in a struct as the C++ support layer does
OfxPropertySetHandle sourceImg = NULL, outputImg = NULL;
int srcRowBytes = 0, srcBitDepth, dstRowBytes, dstBitDepth;
bool srcIsAlpha, dstIsAlpha;
OfxRectI dstRect, srcRect = { 0 };
void* src = NULL, * dst;
try {
outputImg = ofxuGetImage(myData->outputClip, time, dstRowBytes, dstBitDepth, dstIsAlpha, dstRect, dst);
if (outputImg == NULL) throw OfxuNoImageException();
sourceImg = ofxuGetImage(myData->sourceClip, time, srcRowBytes, srcBitDepth, srcIsAlpha, srcRect, src);
if (sourceImg == NULL) throw OfxuNoImageException();
// get the saturation of it
double saturation;
gParamHost->paramGetValueAtTime(myData->saturationParam, time, &saturation);
if ((srcBitDepth == 8) && (dstBitDepth == 8)) {
ProcessRGBA<OfxRGBAColourB, 255> fred(effect, saturation, // ProcessRGBA<OfxRGBAColourB, 255, 0> fred(effect, rectI, saturation, unpremultiplied,
src, srcRect, srcRowBytes,
dst, dstRect, dstRowBytes,
renderWindow);
fred.process();
}
// do the rendering
}
catch (OfxuNoImageException& ex) {
// if we were interrupted, the failed fetch is fine, just return kOfxStatOK
// otherwise, something wierd happened
if (!gEffectHost->abort(effect)) {
status = kOfxStatFailed;
}
}
// release the data pointers
if (sourceImg)
gEffectHost->clipReleaseImage(sourceImg);
if (outputImg)
gEffectHost->clipReleaseImage(outputImg);
return status;
}
// describe the plugin in context
static OfxStatus
describeInContext(OfxImageEffectHandle effect, OfxPropertySetHandle inArgs)
{
OfxPropertySetHandle clipProps;
gEffectHost->clipDefine(effect, kOfxImageEffectSimpleSourceClipName, &clipProps);
gPropHost->propSetString(clipProps, kOfxImageEffectPropSupportedComponents, 0, kOfxImageComponentRGBA);
gEffectHost->clipDefine(effect, kOfxImageEffectOutputClipName, &clipProps);
// set the component types we can handle on our main input
gPropHost->propSetString(clipProps, kOfxImageEffectPropSupportedComponents, 0, kOfxImageComponentRGBA);
////////////////////////////////////////////////////////////////////////////////
// define the parameters for this context
// get a pointer to the effect's parameter set
OfxParamSetHandle paramSet;
gEffectHost->getParamSet(effect, ¶mSet);
// our 2 corners are normalised spatial 2D doubles
OfxPropertySetHandle paramProps;
// make an rgba saturation parameter
gParamHost->paramDefine(paramSet, kOfxParamTypeDouble, "saturation", ¶mProps);
gPropHost->propSetDouble(paramProps, kOfxParamPropDefault, 0, 0.02);
gPropHost->propSetString(paramProps, kOfxParamPropHint, 0, "The saturation at which and below pixels will turn black");
gPropHost->propSetString(paramProps, kOfxParamPropScriptName, 0, "saturation");
gPropHost->propSetString(paramProps, kOfxPropLabel, 0, "Saturation");
return kOfxStatOK;
}
////////////////////////////////////////////////////////////////////////////////
// the plugin's description routine
static OfxStatus
describe(OfxImageEffectHandle effect)
{
// first fetch the host APIs, this cannot be done before this call
OfxStatus stat;
if ((stat = ofxuFetchHostSuites()) != kOfxStatOK)
return stat;
OfxPropertySetHandle effectProps;
gEffectHost->getPropertySet(effect, &effectProps);
// say we cannot support multiple pixel depths and let the clip preferences action deal with it all.
gPropHost->propSetInt(effectProps, kOfxImageEffectPropSupportsMultipleClipDepths, 0, 0);
// set the bit depths the plugin can handle
gPropHost->propSetString(effectProps, kOfxImageEffectPropSupportedPixelDepths, 0, kOfxBitDepthByte);
// set plugin label and the group it belongs to
gPropHost->propSetString(effectProps, kOfxPropLabel, 0, "Saturation debug");
gPropHost->propSetString(effectProps, kOfxImageEffectPluginPropGrouping, 0, "Saturation debug");
// define the contexts we can be used in
gPropHost->propSetString(effectProps, kOfxImageEffectPropSupportedContexts, 0, kOfxImageEffectContextFilter);
return kOfxStatOK;
}
////////////////////////////////////////////////////////////////////////////////
// The main function
static OfxStatus
pluginMain(const char* action, const void* handle, OfxPropertySetHandle inArgs, OfxPropertySetHandle outArgs)
{
try {
// cast to appropriate type
OfxImageEffectHandle effect = (OfxImageEffectHandle)handle;
if (strcmp(action, kOfxActionDescribe) == 0) {
return describe(effect);
}
else if (strcmp(action, kOfxImageEffectActionDescribeInContext) == 0) {
return describeInContext(effect, inArgs);
}
else if (strcmp(action, kOfxActionCreateInstance) == 0) {
return createInstance(effect);
}
else if (strcmp(action, kOfxActionDestroyInstance) == 0) {
return destroyInstance(effect);
}
else if (strcmp(action, kOfxImageEffectActionRender) == 0) {
return render(effect, inArgs, outArgs);
}
}
catch (std::bad_alloc) {
// catch memory
//std::cout << "OFX Plugin Memory error." << std::endl;
return kOfxStatErrMemory;
}
catch (const std::exception& e) {
// standard exceptions
//std::cout << "OFX Plugin error: " << e.what() << std::endl;
return kOfxStatErrUnknown;
}
catch (int err) {
// ho hum, gone wrong somehow
return err;
}
catch (...) {
// everything else
//std::cout << "OFX Plugin error" << std::endl;
return kOfxStatErrUnknown;
}
// other actions to take the default value
return kOfxStatReplyDefault;
}
// function to set the host structure
static void
setHostFunc(OfxHost* hostStruct)
{
gHost = hostStruct;
}
////////////////////////////////////////////////////////////////////////////////
// the plugin struct
static OfxPlugin basicPlugin =
{
kOfxImageEffectPluginApi,
1,
"uk.co.thefoundry.GeneratorExample",
1,
0,
setHostFunc,
pluginMain
};
// the two mandated functions
EXPORT OfxPlugin*
OfxGetPlugin(int nth)
{
if (nth == 0)
return &basicPlugin;
return 0;
}
EXPORT int
OfxGetNumberOfPlugins(void)
{
return 1;
}
|
3cc86dad3d88c893018cdbee1b2b58659728c826 | f753c6173870b72768fe106715b5cbe8496b9a89 | /private/inc/lib_mrp_daemon/IasLibMrpDaemon.hpp | 3dda9c70bfe9d22ab9f4a892255ce0fa654b083b | [
"BSL-1.0",
"BSD-3-Clause"
] | permissive | intel/AVBStreamHandler | 3615b97a799a544b2b3847ad9f5f69902fbcab6e | 45558f68e84cc85fa38c8314a513b876090943bd | refs/heads/master | 2023-09-02T13:13:49.643816 | 2022-08-04T22:47:26 | 2022-08-04T22:47:26 | 145,041,581 | 17 | 24 | NOASSERTION | 2019-04-11T23:04:57 | 2018-08-16T21:38:32 | C++ | UTF-8 | C++ | false | false | 1,411 | hpp | IasLibMrpDaemon.hpp | /*
* Copyright (C) 2018 Intel Corporation. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
/**
* @file IasLibMrpDaemon.hpp
* @brief Library class for the PTP daemon.
* @date 2013
*/
#ifndef IASLIBMRPDAEMON_HPP_
#define IASLIBMRPDAEMON_HPP_
#include "avb/ipcdef.hpp"
namespace IasMediaTransportAvb {
class /* IAS_DSO_PUBLIC */ IasLibMrpDaemon
{
public:
/**
* @brief Constructor.
*/
IasLibMrpDaemon();
/**
* @brief Destructor, virtual by default.
*/
virtual ~IasLibMrpDaemon();
/**
* @brief Allocate resources.
*/
IasAvbProcessingResult init();
/**
* @brief Cleanup allocated resources.
*/
void cleanUp();
/**
* @brief Get the maximum number of filter stages that can be used for
* each audio channel.
*
* @return The maximum number of filter stages.
*/
IasAvbProcessingResult getCurrentNetworkScalingFactors(gPtpTimeData* td);
private:
/**
* @brief Copy constructor, private unimplemented to prevent misuse.
*/
IasLibMrpDaemon(IasLibMrpDaemon const &other);
/**
* @brief Assignment operator, private unimplemented to prevent misuse.
*/
IasLibMrpDaemon& operator=(IasLibMrpDaemon const &other); //lint !e1704
}; // class IasLibMrpDaemon
} // namespace IasMediaTransport
#endif /* IASLIBMRPDAEMON_HPP_ */
|
a1813b1c02d6643935172be1fab4077031db072f | a87a5157d8620a887b8ac9e86d395913759e55cc | /data/data.cpp | ba83fbd7fb4cf724b7937359c6d5773fd81bc70e | [
"Apache-2.0"
] | permissive | gjlper/cluster | 65b55f60fdadb5c6eecc8c9c0a3bf67fc7403ddd | 534392ae4f0b2e94a4e44f51a9160693dd80300b | refs/heads/master | 2020-05-13T16:05:56.562406 | 2016-01-05T15:31:33 | 2016-01-05T15:31:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 703 | cpp | data.cpp | #include "data.h"
using std::vector;
using std::bad_alloc;
Matrix getData1(){
int size = 10;
int width = 2;
Matrix data1;
vector<HeaderItem> yHeader;
for(int i=0;i!=size;i++){
HeaderItem t;
t.setData(i, "2", -1);
yHeader.insert(yHeader.end(), t);
}
data1.y = yHeader;
data1.setD(width);
for(int i=0;i!=size;i++){
double *tmp;
try{
tmp = new double[width];
}catch(const bad_alloc&e){
cout<<"内存不足"<<endl;
return data1;
}
for(int j=0;j!=width;j++){
tmp[j] = rand()%100;
}
data1.m.push_back(tmp);
}
return data1;
}
|
373456b6f385fcf14a3b889a5861cf521f116f95 | ddc1bf673634e874fdd467bad44051daba1dfa76 | /include/core/renderer.h | b98181801e97ee1ff14a0f7bc876d331d8242351 | [] | no_license | Sirithang/PBREngine | 2c8c643c6d0103e5d89f65fe8e97889f80a4fb32 | 03cac7d69f66f021e558019066efc8efec1f6474 | refs/heads/master | 2016-09-11T13:20:49.393223 | 2013-08-07T07:57:39 | 2013-08-07T07:57:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 136 | h | renderer.h | #pragma once
#include <array.h>
namespace sigurd
{
class Renderer
{
protected:
public:
Renderer();
void renderFrame();
};
} |
a579b0dcf3f8ba6ed895f90c7c4e52953bb612e3 | fad91098672d8488c43a410dc82d1059ed4397f2 | /tools/tool/generate_infoFile.cpp | a1c977a2f2aff953c429bb5d9e3b7611669c4e08 | [] | no_license | golden1232004/use_opencv | a6418f04dae2a42373b602787d8361c1fcbaf1fd | 6c1bbb7f570d1f622d01e5c545baec00c753204a | refs/heads/master | 2020-12-29T02:38:48.469606 | 2017-03-22T06:01:12 | 2017-03-22T06:01:12 | 15,545,595 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,037 | cpp | generate_infoFile.cpp | #include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char* argv[])
{
char* listName = argv[1];
char* infoName = argv[2];
FILE* listFile = fopen(listName, "r");
if (NULL == listFile){
fprintf(stderr, "Error: load %s failed\n", listName);
return -1;
}
FILE* infoFile = fopen(infoName, "a");
if (NULL == infoFile){
fprintf(stderr, "Error: open %s failed\n", infoName);
return -1;
}
const int iBufLen = 1000;
char tmpName[iBufLen]={'\0'};
int cnt = 0;
while(!feof(listFile)){
cnt++;
if (fgets(tmpName, iBufLen, listFile)){
int len = strlen(tmpName);
if (!isprint(tmpName[len-1])){
tmpName[len-1] = '\0';
}
}
fprintf(infoFile, "%s ", tmpName);
const int count = 1;
fprintf(infoFile, "%d ", count);
int left = 0;
int top = 0;
int width = 24;
int height = 24;
fprintf(infoFile, "%d %d %d %d\n", left, top, width, height);
}
fclose(listFile);
fclose(infoFile);
return 1;
}
|
4e0bc24021c72228627d652b34e0122899d3dc7b | bb90ad20468f9fe2039b8c16858bd8eae8bbc050 | /src/kv/test/stub_consensus.h | 9786347419242f60ac43923e700018e5c3c5260d | [
"Apache-2.0"
] | permissive | microsoft/CCF | 0997fd81a924d36d775b219720b26b4ff196b18a | 2fbf87840b9e8334c141f4a9c9b25aae979b0540 | refs/heads/main | 2023-09-05T15:39:37.265089 | 2023-09-05T15:27:25 | 2023-09-05T15:27:25 | 180,112,558 | 687 | 229 | Apache-2.0 | 2023-09-14T14:28:39 | 2019-04-08T09:13:04 | C++ | UTF-8 | C++ | false | false | 6,063 | h | stub_consensus.h | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the Apache 2.0 License.
#pragma once
#include "ccf/crypto/symmetric_key.h"
#include "consensus/aft/impl/state.h"
#include "kv/kv_types.h"
#include <algorithm>
#include <iostream>
namespace kv::test
{
static NodeId PrimaryNodeId = std::string("PrimaryNodeId");
static NodeId FirstBackupNodeId = std::string("FirstBackupNodeId");
static NodeId SecondBackupNodeId = std::string("SecondBackupNodeId");
static NodeId ThirdBackupNodeId = std::string("ThirdBackupNodeId");
static NodeId FourthBackupNodeId = std::string("FourthBackupNodeId");
class StubConsensus : public Consensus
{
public:
std::vector<BatchVector::value_type> replica;
ccf::TxID committed_txid = {};
ccf::View current_view = 0;
ccf::SeqNo last_signature = 0;
aft::ViewHistory view_history;
enum State
{
Primary,
Backup,
Candidate
};
State state;
NodeId local_id;
StubConsensus() : replica(), state(Backup), local_id(PrimaryNodeId) {}
virtual NodeId id() override
{
return local_id;
}
virtual bool is_primary() override
{
return state == Primary;
}
virtual bool is_candidate() override
{
return state == Candidate;
}
virtual bool can_replicate() override
{
return state == Primary;
}
virtual Consensus::SignatureDisposition get_signature_disposition() override
{
if (state == Primary)
{
return Consensus::SignatureDisposition::CAN_SIGN;
}
else
{
return Consensus::SignatureDisposition::CANT_REPLICATE;
}
}
virtual bool is_backup() override
{
return state == Backup;
}
virtual void force_become_primary() override
{
state = Primary;
}
virtual void force_become_primary(
ccf::SeqNo,
ccf::View,
const std::vector<ccf::SeqNo>&,
ccf::SeqNo) override
{
state = Primary;
}
virtual void init_as_backup(
ccf::SeqNo,
ccf::View,
const std::vector<ccf::SeqNo>&,
ccf::SeqNo) override
{
state = Backup;
}
bool replicate(const BatchVector& entries, ccf::View view) override
{
for (const auto& entry : entries)
{
replica.push_back(entry);
const auto& [v, data, committable, hooks] = entry;
// Simplification: all entries are replicated in the same term
view_history.update(v, view);
if (committable)
{
// All committable indices are instantly committed
committed_txid = {view, v};
}
}
current_view = view;
return true;
}
std::optional<std::vector<uint8_t>> get_latest_data()
{
if (!replica.empty())
{
return *std::get<1>(replica.back());
}
else
{
return std::nullopt;
}
}
std::optional<BatchVector::value_type> pop_oldest_entry()
{
if (!replica.empty())
{
auto entry = replica.front();
replica.erase(replica.begin());
return entry;
}
else
{
return std::nullopt;
}
}
size_t number_of_replicas()
{
return replica.size();
}
void flush()
{
replica.clear();
}
std::pair<ccf::View, ccf::SeqNo> get_committed_txid() override
{
return {committed_txid.view, committed_txid.seqno};
}
ccf::SeqNo get_previous_committable_seqno() override
{
// Since we commit instantly in this stub, we do not distinguish
// committable from committed. The last committable thing we saw was
// immediately committed, and we store it in committed_txid.
return committed_txid.seqno;
}
ccf::SeqNo get_committed_seqno() override
{
return committed_txid.seqno;
}
std::optional<NodeId> primary() override
{
return PrimaryNodeId;
}
ccf::View get_view(ccf::SeqNo seqno) override
{
return view_history.view_at(seqno);
}
ccf::View get_view() override
{
return current_view;
}
std::vector<ccf::SeqNo> get_view_history(ccf::SeqNo seqno) override
{
return view_history.get_history_until(seqno);
}
std::vector<ccf::SeqNo> get_view_history_since(ccf::SeqNo seqno) override
{
return view_history.get_history_since(seqno);
}
void recv_message(
const NodeId& from, const uint8_t* data, size_t size) override
{}
void add_configuration(
ccf::SeqNo seqno,
const Configuration::Nodes& conf,
const std::unordered_set<NodeId>& learners = {},
const std::unordered_set<NodeId>& retired_nodes = {}) override
{}
Configuration::Nodes get_latest_configuration_unsafe() const override
{
return {};
}
Configuration::Nodes get_latest_configuration() override
{
return {};
}
ConsensusDetails get_details() override
{
return ConsensusDetails{{}, {}, MembershipState::Active};
}
void set_last_signature_at(ccf::SeqNo seqno)
{
last_signature = seqno;
}
};
class BackupStubConsensus : public StubConsensus
{
public:
BackupStubConsensus() : StubConsensus() {}
bool is_primary() override
{
return false;
}
bool replicate(const BatchVector& entries, ccf::View view) override
{
return false;
}
bool can_replicate() override
{
return false;
}
Consensus::SignatureDisposition get_signature_disposition() override
{
return Consensus::SignatureDisposition::CANT_REPLICATE;
}
};
class PrimaryStubConsensus : public StubConsensus
{
public:
PrimaryStubConsensus() : StubConsensus() {}
bool is_primary() override
{
return true;
}
bool can_replicate() override
{
return true;
}
Consensus::SignatureDisposition get_signature_disposition() override
{
return Consensus::SignatureDisposition::CAN_SIGN;
}
};
}
|
70769ae2310745fac22f9f410fecf635d9d26ca9 | b5bc696868bf5cf07c20bb0c1c94606947675d3b | /src/include/zombye/rendering/directional_light_component.hpp | a021aa5035a86d6cd263dd00a49e31ddf931a79e | [
"MIT"
] | permissive | atomicptr/project-zombye | 199240c0e085b87a5355b41954e6786dbe213901 | 30d3dc0b7e6a929162fa0ddfb77dd10bc9bf4f05 | refs/heads/master | 2021-01-15T14:47:14.727586 | 2015-09-01T00:38:13 | 2015-09-01T00:38:13 | 25,641,920 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,232 | hpp | directional_light_component.hpp | #ifndef __ZOMBYE_DIRECTIONAL_LIGHT_COMPONENT_HPP__
#define __ZOMBYE_DIRECTIONAL_LIGHT_COMPONENT_HPP__
#include <glm/glm.hpp>
#include <zombye/ecs/component.hpp>
#include <zombye/ecs/reflective.hpp>
namespace zombye {
class entity;
class game;
}
namespace zombye {
class directional_light_component : public reflective<directional_light_component, component> {
friend class reflective<directional_light_component, component>;
glm::vec4 direction_;
glm::vec3 color_;
float energy_;
public:
directional_light_component(game& game, entity& owner, const glm::vec3& color, float energy) noexcept;
~directional_light_component() noexcept;
auto& color() const noexcept {
return color_;
}
void color(const glm::vec3& value) noexcept {
color_ = value;
}
auto& energy() const noexcept {
return energy_;
}
void energy(float value) {
energy_ = value;
}
static void register_at_script_engine(game& game);
private:
directional_light_component(game& game, entity& owner) noexcept;
static void register_reflection();
};
}
#endif
|
0bc685ce655427fd7012651ea22a190bb025ea40 | 627751e288735adca64a1544a30c64f2957256f5 | /src/Log.h | e34a1a5564b91fa130a846de719f45ef683264cb | [] | no_license | lvyanxuan/OmniCopter | 86d15ca9103a4275fdf93a42e08ccd8c48b8a3a9 | 62aed53dde85835ebb2460a02f5820c7d3827639 | refs/heads/master | 2021-01-12T10:32:20.885766 | 2017-03-08T15:59:42 | 2017-03-08T15:59:42 | 81,799,535 | 1 | 0 | null | 2017-02-13T07:57:58 | 2017-02-13T07:57:58 | null | UTF-8 | C++ | false | false | 1,049 | h | Log.h | /*
* Log.h
*
* Created on: 2017年2月12日
* Author: jiawei
*/
#ifndef LIBRARIES_OMNICOPTER_LOG_H_
#define LIBRARIES_OMNICOPTER_LOG_H_
#include <OmniCopter.h>
class Log
{
public:
void log(char* message,double value); //控制台输出信息,包括键值对:信息和值(double型)
void setDebugMode(bool mode); //设置调试模式(true为开启调试模式)
void setFreq(int freq); //设置输出频率(隔多少次开始输出)
void showRcInput(OmniCopter omniCopter); //输出rcinput的值
void showSensor(OmniCopter omniCopter); //输出传感器的值
void showEscOutput(OmniCopter omniCopter); //输出控制电调的pwm脉宽
void showForce(OmniCopter omniCopter); //输出控制力和力矩
void showFreq(OmniCopter omniCopter); //输出外环控制频率
void init();
void oneLoop(); //记录一次循环的状态
private:
bool debugEnable=false;
bool showEnable=false;
int showTime=0;
int showF=10;
unsigned long int lastTime=0;
};
#endif /* LIBRARIES_OMNICOPTER_LOG_H_ */
|
b60bf7186d44b7be578e8d6f3268b45e07dec7a4 | 22e7f5ba3cf9b003593e7cf4ce2f14c40032e0ef | /main.cpp | 75c80bfeb6f27c1eb5895df84b2924ed600191a1 | [] | no_license | ksophocleous/cpplibuv | 409c8fcf805119280aa4afd4d744c1573cb402b2 | 9f75c81c6f89ed884873a9c31f2061eb4bda7878 | refs/heads/master | 2016-09-05T10:15:06.278658 | 2013-10-06T21:45:49 | 2013-10-06T21:45:49 | 13,344,491 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,042 | cpp | main.cpp | #include <cstdio>
#include <sstream>
#include <iostream>
#include <functional>
#include <string>
#include <cstdint>
#include <vector>
#include <uv.h>
class UVException
{
public:
UVException(std::string msg) : m_msg(std::move(msg))
{
}
friend std::ostream& operator<< (std::ostream& out, const UVException &e)
{
out << e.m_msg;
return out;
}
private:
std::string m_msg;
};
class IUVLoop
{
public:
virtual ~IUVLoop() { }
virtual void Loop() = 0;
virtual void Shutdown() = 0;
};
class IUVHandle
{
public:
virtual ~IUVHandle();
};
class UVTimer
{
public:
typedef std::function<void (UVTimer&)> TimerCallback;
static void timer_cb(uv_timer_t* handle, int status)
{
if (status < 0)
throw UVException("UVTimer callback received status (below zero)");
UVTimer *pTimer = reinterpret_cast<UVTimer *>(handle->data);
if (pTimer != nullptr)
pTimer->m_customcb(*pTimer);
}
UVTimer(uv_loop_t *owningLooper, uint64_t firstInterval, uint64_t loopInterval, TimerCallback customcb) :
m_customcb(customcb)
{
m_timer.data = this;
if (m_customcb == nullptr)
throw UVException("Timer without a callback is not allowed");
if (uv_timer_init(owningLooper, &m_timer) == -1)
throw UVException("uv_timer_init failed");
if (uv_timer_start(&m_timer, timer_cb, firstInterval, loopInterval) == -1)
throw UVException("uv_timer_start failed");
}
UVTimer(UVTimer&& moved) : m_customcb(std::move(moved.m_customcb))
{
memcpy(&m_timer, &moved.m_timer, sizeof(m_timer));
m_timer.data = this;
moved.m_timer.data = nullptr;
std::cout << "moving from object " << &moved << " to this " << this;
}
~UVTimer()
{
uv_timer_stop(&m_timer);
}
private:
UVTimer(const UVTimer&);
UVTimer& operator=(const UVTimer&);
uv_timer_t m_timer;
TimerCallback m_customcb;
};
namespace NetProtocol
{
enum Enum
{
Tcp,
Udp
};
};
class UVAddress4Resolve
{
public:
typedef std::function<void (UVAddress4Resolve &resolver, const std::string &ip, int status)> AddressResolvedCb;
UVAddress4Resolve(uv_loop_t* loop, std::string hostname, uint16_t port, AddressResolvedCb cb, NetProtocol::Enum protocol = NetProtocol::Tcp) :
m_cb(cb), m_port(port), m_hostname(std::move(hostname))
{
std::cout << "Resolver :: IN" << std::endl;
m_addrInfo.data = this;
struct addrinfo hints;
if (protocol == NetProtocol::Tcp)
{
hints.ai_family = PF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = 0;
}
std::ostringstream oss; oss << port;
int r = uv_getaddrinfo(loop, &m_addrInfo, dns_cb, m_hostname.c_str(), oss.str().c_str(), &hints);
if (r != 0)
throw UVException("uv_getaddrinfo: something went wrong");
}
uint16_t GetPort() const { return m_port; }
std::string GetHostname() const { return m_hostname; }
~UVAddress4Resolve()
{
std::cout << "Resolver :: OUT" << std::endl;
}
private:
static void dns_cb(uv_getaddrinfo_t* req, int status, struct addrinfo* res)
{
UVAddress4Resolve *pAddr = reinterpret_cast<UVAddress4Resolve *>(req->data);
if (pAddr)
{
AddressResolvedCb cb = pAddr->m_cb;
if (status < 0)
throw UVException("Resolve address X failed with status negative");
char addr[17] = {'\0'};
uv_ip4_name((struct sockaddr_in*) res->ai_addr, addr, 16);
if (cb)
cb(*pAddr, addr, status);
}
uv_freeaddrinfo(res);
}
std::string m_hostname;
uint16_t m_port;
uv_getaddrinfo_t m_addrInfo;
AddressResolvedCb m_cb;
};
class UVLoop : public IUVLoop
{
public:
UVLoop()
{
m_loop = uv_loop_new();
if (m_loop == nullptr)
throw UVException("uv_loop_new failed");
}
~UVLoop()
{
uv_loop_delete(m_loop);
}
void Loop()
{
uv_run(m_loop, UV_RUN_DEFAULT);
}
void Shutdown()
{
uv_stop(m_loop);
}
UVAddress4Resolve &ResolveAddress(std::string hostname, uint16_t port, std::function<void (UVAddress4Resolve &resolver, const std::string &ip, int status)> funcCb, NetProtocol::Enum protocol = NetProtocol::Tcp)
{
if (funcCb == nullptr)
throw UVException("Resolving address with no callback - waste of time: consider removing it");
auto intermediate = [this, funcCb] (UVAddress4Resolve &resolver, const std::string &ip, int status)
{
try
{
if (status < 0)
funcCb(resolver, "", status);
else
funcCb(resolver, ip, status);
}
catch (UVException e)
{
std::cerr << "UVLoop::ResolveAddress(): " << e;
}
UVAddress4Resolve *pResolver = &resolver;
delete pResolver;
};
return *(new UVAddress4Resolve(m_loop, std::move(hostname), port, intermediate, protocol));
}
UVTimer& NewTimer(uint64_t firstInterval, uint64_t loopInterval, std::function<bool ()> customcb)
{
if (customcb == nullptr)
throw UVException("NewTimer must have a custom callback");
auto intermediate = [this, customcb, loopInterval] (UVTimer &timer)
{
try
{
if (loopInterval != 0 && customcb() == true)
return;
}
catch (UVException e)
{
std::cerr << e;
}
StopTimer(timer);
};
return *(new UVTimer(m_loop, firstInterval, loopInterval, intermediate));
}
void StopTimer(UVTimer& ptr)
{
UVTimer *pTimer = &ptr;
delete pTimer;
}
protected:
uv_loop_t *m_loop;
};
int main(int argc, char *argv[])
{
std::cout << "testing" << std::endl;
UVLoop looper;
/////////////////////////////////////////////
uint32_t timerCount = 0;
looper.NewTimer(2000, 100,
[&timerCount] () -> bool
{
std::cout << "timer exec" << std::endl;
timerCount++;
return (timerCount < 10);
});
/////////////////////////////////////////////
looper.ResolveAddress("www.google.com", 80,
[] (UVAddress4Resolve &resolver, const std::string &ip, int status)
{
std::cout << "Host " << resolver.GetHostname() << " resolved at ip " << ip << std::endl;
});
/////////////////////////////////////////////
looper.Loop();
return 0;
}
|
13cb6e63d60c84635593b89d487ea15f01230d7f | 51033cc8a6469aa304ecf58844e050ad469d72cd | /structures/structures/more.cpp | 7508ae78ce046e7c51b1bb47856f797a231c9adb | [] | no_license | lukeplaisance/IntroToCpp | 3528e94fc2a1044587ee8ddbb7b95656953dac44 | fb05a234fcf1dd6fdaba48fabe7c414c46a83f4f | refs/heads/master | 2021-07-09T01:50:16.214657 | 2017-09-27T17:48:55 | 2017-09-27T17:48:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,122 | cpp | more.cpp | #include <iostream>
struct Vehicle
{
int mNumTires;
int mNumSeats;
char mMakerName[255];
char mModelName[255];
int mModelYear;
};
//create a function that prints vehicle infomration
Vehicle CarInfo(Vehicle vehicle)
{
//std::cout << "Maker :" << vehicle.mMakerName << std::endl;
//std::cout << "Model Name :" << vehicle.mModelName << std::endl;
//std::cout << "Model Year :" << vehicle.mModelYear << std::endl;
//std::cout << "Number Tires :" << vehicle.mNumTires << std::endl;
//std::cout << "Number Seats :" << vehicle.mNumSeats << std::endl;
}
int main()
{
//Vehicle MatthewCar = { 4, 2, "Nissan", "Frontier", 2001 };
//Vehicle LukeCar = { 4, 2, "Suabru", "BRZ", 2014 };
//Vehicle StevenCar = { 2, 1, "Mongoose", "Legion L40", 2017 };
Vehicle ebayAutomotive[15];
ebayAutomotive[0] = { 2, 4, "Porshe", "911", 2016 };
ebayAutomotive[1] = { 2, 4, "McLaren", "720s", 2018 };
ebayAutomotive[2] = { 4, 4, "Honda", "Civic", 2017 };
ebayAutomotive[3] = { 4,4,"Nissan", "Sentra", 2012 };
ebayAutomotive[4] = { 2,4, "Ford", "Mustang", 1965 };
ebayAutomotive[5] = { 2, 4, "Audi", "S8", 2017 };
ebayAutomotive[6] = { 2, 2, "Ford", "GT", 2017 };
ebayAutomotive[7] = { 2,4,"Toyota", "Supra", 1998 };
ebayAutomotive[8] = { 4,4,"Ford", "Fiesta", 2005 };
ebayAutomotive[9] = { 2, 1, "YuGiOh", "Duel Runner", 2025 };
ebayAutomotive[10] = { 2, 3, "UNSC", "Warthog", 2500 };
ebayAutomotive[11] = { 2, 1, "Moongoose", "Legion L40", 2017 };
ebayAutomotive[12] = { 2, 2, "Ferrari", "La Farrari", 2015 };
ebayAutomotive[13] = { 2, 2, "TVR", "Sergis", 2013 };
ebayAutomotive[14] = { 1, 0, "US Army", "M1 Abrams", 2018 };
//prompt the user to input a maker name. Then the application should display all vehicles with that maker
// modify your answer to allow the user to search for vehicles by year, name, and maker
char userInput[255];
std::cout << "Enter a vehicle maker.\n";
std::cin >> userInput;
bool carFound = false;
for (int i = 0; i < 15; i++)
{
if (strcmp(userInput, ebayAutomotive[i].mMakerName) == 0);
{
CarInfo(ebayAutomotive[i]);
std::cout << std::endl;
carFound = true;
}
}
if (carFound == false)
std::cout << "No results found." <<std::endl;
system("pause");
}
/*struct Item
{
char mName[255];
int mCost;
int mQuantity;
};
struct Shop
{
int mTotalGold;
Item mItems[5];
};
void PrintShopInventory(Shop shopData)
{
std:: cout << "Current shop funds:" << shopData.mTotalGold;
for (int i = 0; i < 5; i++)
{
std::cout <<"Item Name" << shopData.mItems[i].mName << std::endl;
std::cout << "Item Cost" << shopData.mItems[i].mCost << std::endl;
std::cout <<"Quantity" << shopData.mItems[i].mQuantity << std::endl;
int main()
{
{
Shop blacksmith = { 2000 };
blacksmith.mItems[0] = { "Stick", 1, 1 };
blacksmith.mItems[1] = { "Wand", 5, 1 };
blacksmith.mItems[2] = { "Knife", 15, 1 };
blacksmith.mItems[3] = { "Sword", 30, 1 };
blacksmith.mItems[4] = { "Excalibur", 1500, 1 };
PrintShopInventory(blacksmith);
std::cout << "Changing Prices" << std::endl;
system("pause");
PrintShopInventory(blacksmith);
system("pause")
}
}
*/ |
07b79ccd6baba83c98eb5bb33dd43e04bc27fc87 | 962b17d13edaf129b17694aae1d10e19815b9b57 | /Recursion and Backtracking/WordMatching.cpp | 418ab8567f5aa6fb6558ee3cdbae7307d896b1ac | [
"MIT"
] | permissive | Ankitlenka26/IP2021 | de1a37104f9b8d45bad88c06b5e343896a14ef50 | 99322c9c84a8a9c9178a505afbffdcebd312b059 | refs/heads/main | 2023-03-01T09:38:12.704657 | 2021-01-26T12:32:26 | 2021-01-26T12:32:26 | 315,255,897 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,645 | cpp | WordMatching.cpp | #include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
void solution(string str, string pattern, unordered_map<char, string> &m, string op)
{
// base case
if (pattern.size() == 0)
{
if (str.size() == 0)
{
// p -> graph, e -> trees, .
unordered_set<char> s;
for (int i = 0; i < op.size(); i++)
{
if (s.find(op[i]) == s.end())
{
cout << op[i] << " -> " << m[op[i]] << ", ";
}
s.insert(op[i]);
}
cout << ".";
cout << endl;
}
return;
}
char ch = pattern[0];
string rem = pattern.substr(1);
if (m.find(ch) != m.end())
{
string previousMapping = m[ch];
if (str.size() >= previousMapping.size())
{
string left = str.substr(0, previousMapping.size());
string right = str.substr(previousMapping.size());
if (left == previousMapping)
{
solution(right, rem, m, op);
}
}
}
else
{
for (int i = 0; i < str.size(); i++)
{
string left = str.substr(0, i + 1);
string right = str.substr(i + 1);
m[ch] = left;
solution(right, rem, m, op);
m.erase(ch);
}
}
return;
}
int main()
{
string str, pattern;
cin >> str >> pattern;
unordered_map<char, string> m;
solution(str, pattern, m, pattern);
return 0;
}
|
425cc34807c349ba97b68da1a4e295186c802733 | ee7f0fad5eccb34ab452dbc270a91ddcc2cf64c7 | /Incredible_Hulk.cpp | 3a0e359d2e9538758d9ef5b8b725aef9b814aeba | [] | no_license | Aerma7309/codingblocks | 553b1febccf025784c937d48a4dd6235f06c5fbc | f41dc62789b09df24a463c55e655fad4a8eac302 | refs/heads/master | 2023-05-24T13:29:20.606118 | 2021-06-21T19:13:01 | 2021-06-21T19:13:01 | 238,761,676 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 674 | cpp | Incredible_Hulk.cpp | #include <iostream>
using namespace std;
//normal approach
// int max_num(long n)
// {
// long d=1;
// for (int i = 0;n>=d ; i++) d*=2;
// return d/2;
// }
// int cal_step(long n)
// {
// if(n==0) return 0;
// int t = max_num(n);
// if(n==1||n==2|| n==t) return 1;
// return 1+cal_step(n-t);
// }
// using bitmasking
int cal_step(int n)
{
int count = 0;
while (n > 0)
{
if (n & 1)
{
count++;
}
n = n >> 1;
}
return count;
}
int main()
{
int t;
long num;
cin >> t;
while (t--)
{
cin >> num;
cout << cal_step(num) << "\n";
}
return 0;
}
|
f6ff4ba4a4e7e1fdffe98833d26174d9d6e90685 | 0d7b4718c4814ef0c16145277721e803986bdac3 | /glare/render/common.h | 29d1c7696ab1ab360fadf3a9518bc5a83ae75b25 | [
"MIT"
] | permissive | krovma/glare | 5b249b740c13657f37bab66b5547a4252590f13d | df1dda413d93d56b15ccac60123210505683f278 | refs/heads/master | 2020-12-02T19:04:07.567278 | 2020-04-02T19:16:13 | 2020-04-02T19:16:13 | 231,092,437 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,148 | h | common.h | #pragma once
#include "glare/core/common.h"
#include <d3d11.h>
#include <dxgi.h>
#include <dxgidebug.h>
#pragma comment(lib, "dxguid.lib")
#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "dxgi.lib")
namespace glare {
//#define GLARE_INDEX_T_UINT16
#define GLARE_INDEX_T_UINT32
#define GLARE_RENDERER_DEBUG_LEAK 1
#define GLARE_RENDERER_DEBUG_SHADER 10
#if defined(_DEBUG)
#define GLARE_RENDERER_DEBUG_LEVEL 999
#else
#define GLARE_RENDERER_DEBUG_LEVEL 0
#endif
#define DX_RELEASE(resource)\
{\
if (resource) {\
(resource)->Release();\
(resource) = nullptr;\
}\
}
using dx_device = ID3D11Device;
using dx_context = ID3D11DeviceContext;
using dx_resource = ID3D11Resource;
using dx_texture2d = ID3D11Texture2D;
using dx_rtv = ID3D11RenderTargetView;
using dx_srv = ID3D11ShaderResourceView;
using dx_swapchain = IDXGISwapChain;
using dx_debug = ID3D11Debug;
using dx_buffer = ID3D11Buffer;
using dx_bytecode = ID3D10Blob;
using dx_vs = ID3D11VertexShader;
using dx_ps = ID3D11PixelShader;
using dx_layout = ID3D11InputLayout;
using dx_state_depth_stencil = ID3D11DepthStencilState;
using dx_state_rasterizer = ID3D11RasterizerState;
using dx_state_blend = ID3D11BlendState;
using dx_sampler = ID3D11SamplerState;
using dx_format = DXGI_FORMAT;
enum e_render_buffer_usage
{
RENDER_BUFFER_VERTEX = D3D11_BIND_VERTEX_BUFFER,
RENDER_BUFFER_INDEX = D3D11_BIND_INDEX_BUFFER,
RENDER_BUFFER_CONSTANT = D3D11_BIND_CONSTANT_BUFFER,
};
enum e_gpu_memory_usage
{
GPU_MEMORY_GPU = D3D11_USAGE_DEFAULT,
GPU_MEMORY_IMMUTABLE = D3D11_USAGE_IMMUTABLE,
GPU_MEMORY_DYNAMIC = D3D11_USAGE_DYNAMIC,
GPU_MEMORY_STAGING = D3D11_USAGE_STAGING
};
enum e_texture_usage
{
TEXTURE_SHADER_RESOURCE = D3D11_BIND_SHADER_RESOURCE,
TEXTURE_RENDER_TARGET = D3D11_BIND_RENDER_TARGET,
TEXTURE_DEPTH_STENCIL = D3D11_BIND_DEPTH_STENCIL
};
enum e_texture_slot : uint32
{
TEXTURE_SLOT_DIFFUSE = 0,
TEXTURE_SLOT_NORMAL = 1,
TEXTURE_SLOT_EMMISIVE = 2,
TEXTURE_SLOT_SPECULAR = 3,
TEXTURE_SLOT_ROUGHNESS = 4,
TEXTURE_SLOT_METALLIC = 5
};
enum e_constant_buffer_id : uint32
{
CONSTANT_FRAME_BUFFER = 1,
CONSTANT_CAMERA_BUFFER = 2,
CONSTANT_MODEL_BUFFER = 3,
CONSTANT_LIGHT_BUFFER = 4,
CONSTANT_EFFECT_BUFFER = 8,
};
enum e_blend_mode
{
BLEND_OPAQUE,
BLEND_ALPHA,
BLEND_ADDITIVE
};
enum e_texture_filter
{
MIN_POINT_MAG_POINT = D3D11_FILTER_MIN_MAG_MIP_POINT,
MIN_POINT_MAG_LINEAR = D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT,
MIN_LINEAR_MAG_POINT = D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT,
MIN_LINEAR_MAG_LINEAR = D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT
};
enum e_compare_operator
{
COMP_NEVER = D3D11_COMPARISON_NEVER,
COMP_ALWAYS = D3D11_COMPARISON_ALWAYS,
COMP_EQ = D3D11_COMPARISON_EQUAL,
COMP_NEQ = D3D11_COMPARISON_NOT_EQUAL,
COMP_LESS = D3D11_COMPARISON_LESS,
COMP_LESS_EQ = D3D11_COMPARISON_LESS_EQUAL,
COMP_GREATER = D3D11_COMPARISON_GREATER,
COMP_GREATER_EQ = D3D11_COMPARISON_GREATER_EQUAL
};
enum e_cull_mode
{
CULL_NONE = D3D11_CULL_NONE,
CULL_FRONT = D3D11_CULL_FRONT,
CULL_BACK = D3D11_CULL_BACK
};
enum e_fill_mode
{
FILL_WIRE = D3D11_FILL_WIREFRAME,
FILL_SOLID = D3D11_FILL_SOLID
};
}; |
c917e403d8417298678c2405ebbf0096a3903d11 | fb5b25b4fbe66c532672c14dacc520b96ff90a04 | /export/release/macos/obj/src/openfl/display/_internal/CanvasGraphics.cpp | 5e63dc265a5a63d0c18a0e64d5e88c922433be4b | [
"Apache-2.0"
] | permissive | Tyrcnex/tai-mod | c3849f817fe871004ed171245d63c5e447c4a9c3 | b83152693bb3139ee2ae73002623934f07d35baf | refs/heads/main | 2023-08-15T07:15:43.884068 | 2021-09-29T23:39:23 | 2021-09-29T23:39:23 | 383,313,424 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 27,262 | cpp | CanvasGraphics.cpp | // Generated by Haxe 4.1.5
#include <hxcpp.h>
#ifndef INCLUDED_95f339a1d026d52c
#define INCLUDED_95f339a1d026d52c
#include "hxMath.h"
#endif
#ifndef INCLUDED_openfl__Vector_FloatVector
#include <openfl/_Vector/FloatVector.h>
#endif
#ifndef INCLUDED_openfl__Vector_IVector
#include <openfl/_Vector/IVector.h>
#endif
#ifndef INCLUDED_openfl_display_BitmapData
#include <openfl/display/BitmapData.h>
#endif
#ifndef INCLUDED_openfl_display_CanvasRenderer
#include <openfl/display/CanvasRenderer.h>
#endif
#ifndef INCLUDED_openfl_display_DisplayObjectRenderer
#include <openfl/display/DisplayObjectRenderer.h>
#endif
#ifndef INCLUDED_openfl_display_Graphics
#include <openfl/display/Graphics.h>
#endif
#ifndef INCLUDED_openfl_display_IBitmapDrawable
#include <openfl/display/IBitmapDrawable.h>
#endif
#ifndef INCLUDED_openfl_display__internal_CanvasGraphics
#include <openfl/display/_internal/CanvasGraphics.h>
#endif
#ifndef INCLUDED_openfl_display__internal_DrawCommandBuffer
#include <openfl/display/_internal/DrawCommandBuffer.h>
#endif
#ifndef INCLUDED_openfl_events_EventDispatcher
#include <openfl/events/EventDispatcher.h>
#endif
#ifndef INCLUDED_openfl_events_IEventDispatcher
#include <openfl/events/IEventDispatcher.h>
#endif
#ifndef INCLUDED_openfl_geom_Matrix
#include <openfl/geom/Matrix.h>
#endif
#ifndef INCLUDED_openfl_geom_Rectangle
#include <openfl/geom/Rectangle.h>
#endif
HX_LOCAL_STACK_FRAME(_hx_pos_fd1c4d1c82edf2db_68_closePath,"openfl.display._internal.CanvasGraphics","closePath",0x4bc7f60e,"openfl.display._internal.CanvasGraphics.closePath","openfl/display/_internal/CanvasGraphics.hx",68,0x5a71bf7c)
HX_LOCAL_STACK_FRAME(_hx_pos_fd1c4d1c82edf2db_99_createBitmapFill,"openfl.display._internal.CanvasGraphics","createBitmapFill",0x4b43bfbd,"openfl.display._internal.CanvasGraphics.createBitmapFill","openfl/display/_internal/CanvasGraphics.hx",99,0x5a71bf7c)
HX_LOCAL_STACK_FRAME(_hx_pos_fd1c4d1c82edf2db_106_createGradientPattern,"openfl.display._internal.CanvasGraphics","createGradientPattern",0x550b94b5,"openfl.display._internal.CanvasGraphics.createGradientPattern","openfl/display/_internal/CanvasGraphics.hx",106,0x5a71bf7c)
HX_LOCAL_STACK_FRAME(_hx_pos_fd1c4d1c82edf2db_165_createTempPatternCanvas,"openfl.display._internal.CanvasGraphics","createTempPatternCanvas",0x6ada6549,"openfl.display._internal.CanvasGraphics.createTempPatternCanvas","openfl/display/_internal/CanvasGraphics.hx",165,0x5a71bf7c)
HX_LOCAL_STACK_FRAME(_hx_pos_fd1c4d1c82edf2db_189_drawRoundRect,"openfl.display._internal.CanvasGraphics","drawRoundRect",0xaa7470ff,"openfl.display._internal.CanvasGraphics.drawRoundRect","openfl/display/_internal/CanvasGraphics.hx",189,0x5a71bf7c)
HX_LOCAL_STACK_FRAME(_hx_pos_fd1c4d1c82edf2db_223_endFill,"openfl.display._internal.CanvasGraphics","endFill",0xd6b0224f,"openfl.display._internal.CanvasGraphics.endFill","openfl/display/_internal/CanvasGraphics.hx",223,0x5a71bf7c)
HX_LOCAL_STACK_FRAME(_hx_pos_fd1c4d1c82edf2db_232_endStroke,"openfl.display._internal.CanvasGraphics","endStroke",0x88be9284,"openfl.display._internal.CanvasGraphics.endStroke","openfl/display/_internal/CanvasGraphics.hx",232,0x5a71bf7c)
HX_LOCAL_STACK_FRAME(_hx_pos_fd1c4d1c82edf2db_457_hitTest,"openfl.display._internal.CanvasGraphics","hitTest",0x934efa96,"openfl.display._internal.CanvasGraphics.hitTest","openfl/display/_internal/CanvasGraphics.hx",457,0x5a71bf7c)
HX_LOCAL_STACK_FRAME(_hx_pos_fd1c4d1c82edf2db_462_isCCW,"openfl.display._internal.CanvasGraphics","isCCW",0x9437381e,"openfl.display._internal.CanvasGraphics.isCCW","openfl/display/_internal/CanvasGraphics.hx",462,0x5a71bf7c)
HX_LOCAL_STACK_FRAME(_hx_pos_fd1c4d1c82edf2db_466_normalizeUVT,"openfl.display._internal.CanvasGraphics","normalizeUVT",0xa0796975,"openfl.display._internal.CanvasGraphics.normalizeUVT","openfl/display/_internal/CanvasGraphics.hx",466,0x5a71bf7c)
HX_LOCAL_STACK_FRAME(_hx_pos_fd1c4d1c82edf2db_507_playCommands,"openfl.display._internal.CanvasGraphics","playCommands",0xa3390eeb,"openfl.display._internal.CanvasGraphics.playCommands","openfl/display/_internal/CanvasGraphics.hx",507,0x5a71bf7c)
HX_LOCAL_STACK_FRAME(_hx_pos_fd1c4d1c82edf2db_1142_render,"openfl.display._internal.CanvasGraphics","render",0xc2394625,"openfl.display._internal.CanvasGraphics.render","openfl/display/_internal/CanvasGraphics.hx",1142,0x5a71bf7c)
HX_LOCAL_STACK_FRAME(_hx_pos_fd1c4d1c82edf2db_1461_renderMask,"openfl.display._internal.CanvasGraphics","renderMask",0x605729b1,"openfl.display._internal.CanvasGraphics.renderMask","openfl/display/_internal/CanvasGraphics.hx",1461,0x5a71bf7c)
HX_LOCAL_STACK_FRAME(_hx_pos_fd1c4d1c82edf2db_1565_setSmoothing,"openfl.display._internal.CanvasGraphics","setSmoothing",0x137bf581,"openfl.display._internal.CanvasGraphics.setSmoothing","openfl/display/_internal/CanvasGraphics.hx",1565,0x5a71bf7c)
HX_LOCAL_STACK_FRAME(_hx_pos_fd1c4d1c82edf2db_34_boot,"openfl.display._internal.CanvasGraphics","boot",0x19dfbd41,"openfl.display._internal.CanvasGraphics.boot","openfl/display/_internal/CanvasGraphics.hx",34,0x5a71bf7c)
HX_LOCAL_STACK_FRAME(_hx_pos_fd1c4d1c82edf2db_36_boot,"openfl.display._internal.CanvasGraphics","boot",0x19dfbd41,"openfl.display._internal.CanvasGraphics.boot","openfl/display/_internal/CanvasGraphics.hx",36,0x5a71bf7c)
HX_LOCAL_STACK_FRAME(_hx_pos_fd1c4d1c82edf2db_37_boot,"openfl.display._internal.CanvasGraphics","boot",0x19dfbd41,"openfl.display._internal.CanvasGraphics.boot","openfl/display/_internal/CanvasGraphics.hx",37,0x5a71bf7c)
HX_LOCAL_STACK_FRAME(_hx_pos_fd1c4d1c82edf2db_43_boot,"openfl.display._internal.CanvasGraphics","boot",0x19dfbd41,"openfl.display._internal.CanvasGraphics.boot","openfl/display/_internal/CanvasGraphics.hx",43,0x5a71bf7c)
HX_LOCAL_STACK_FRAME(_hx_pos_fd1c4d1c82edf2db_50_boot,"openfl.display._internal.CanvasGraphics","boot",0x19dfbd41,"openfl.display._internal.CanvasGraphics.boot","openfl/display/_internal/CanvasGraphics.hx",50,0x5a71bf7c)
namespace openfl{
namespace display{
namespace _internal{
void CanvasGraphics_obj::__construct() { }
Dynamic CanvasGraphics_obj::__CreateEmpty() { return new CanvasGraphics_obj; }
void *CanvasGraphics_obj::_hx_vtable = 0;
Dynamic CanvasGraphics_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< CanvasGraphics_obj > _hx_result = new CanvasGraphics_obj();
_hx_result->__construct();
return _hx_result;
}
bool CanvasGraphics_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x1d4500f1;
}
Float CanvasGraphics_obj::SIN45;
Float CanvasGraphics_obj::TAN22;
bool CanvasGraphics_obj::allowSmoothing;
::openfl::display::BitmapData CanvasGraphics_obj::bitmapFill;
::openfl::display::BitmapData CanvasGraphics_obj::bitmapStroke;
bool CanvasGraphics_obj::bitmapRepeat;
::openfl::geom::Rectangle CanvasGraphics_obj::bounds;
::openfl::display::_internal::DrawCommandBuffer CanvasGraphics_obj::fillCommands;
::openfl::display::Graphics CanvasGraphics_obj::graphics;
bool CanvasGraphics_obj::hasFill;
bool CanvasGraphics_obj::hasStroke;
bool CanvasGraphics_obj::hitTesting;
::openfl::geom::Matrix CanvasGraphics_obj::inversePendingMatrix;
::openfl::geom::Matrix CanvasGraphics_obj::pendingMatrix;
::openfl::display::_internal::DrawCommandBuffer CanvasGraphics_obj::strokeCommands;
::Dynamic CanvasGraphics_obj::windingRule;
Float CanvasGraphics_obj::worldAlpha;
void CanvasGraphics_obj::closePath(::hx::Null< bool > __o_strokeBefore){
bool strokeBefore = __o_strokeBefore.Default(false);
HX_STACKFRAME(&_hx_pos_fd1c4d1c82edf2db_68_closePath)
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(CanvasGraphics_obj,closePath,(void))
::Dynamic CanvasGraphics_obj::createBitmapFill( ::openfl::display::BitmapData bitmap,bool bitmapRepeat,bool smooth){
HX_STACKFRAME(&_hx_pos_fd1c4d1c82edf2db_99_createBitmapFill)
HXDLIN( 99) return null();
}
STATIC_HX_DEFINE_DYNAMIC_FUNC3(CanvasGraphics_obj,createBitmapFill,return )
void CanvasGraphics_obj::createGradientPattern( ::Dynamic type,::cpp::VirtualArray colors,::cpp::VirtualArray alphas,::cpp::VirtualArray ratios, ::openfl::geom::Matrix matrix, ::Dynamic spreadMethod, ::Dynamic interpolationMethod,Float focalPointRatio){
HX_STACKFRAME(&_hx_pos_fd1c4d1c82edf2db_106_createGradientPattern)
}
STATIC_HX_DEFINE_DYNAMIC_FUNC8(CanvasGraphics_obj,createGradientPattern,(void))
void CanvasGraphics_obj::createTempPatternCanvas( ::openfl::display::BitmapData bitmap,bool repeat,int width,int height){
HX_STACKFRAME(&_hx_pos_fd1c4d1c82edf2db_165_createTempPatternCanvas)
}
STATIC_HX_DEFINE_DYNAMIC_FUNC4(CanvasGraphics_obj,createTempPatternCanvas,(void))
void CanvasGraphics_obj::drawRoundRect(Float x,Float y,Float width,Float height,Float ellipseWidth, ::Dynamic ellipseHeight){
HX_STACKFRAME(&_hx_pos_fd1c4d1c82edf2db_189_drawRoundRect)
}
STATIC_HX_DEFINE_DYNAMIC_FUNC6(CanvasGraphics_obj,drawRoundRect,(void))
void CanvasGraphics_obj::endFill(){
HX_STACKFRAME(&_hx_pos_fd1c4d1c82edf2db_223_endFill)
}
STATIC_HX_DEFINE_DYNAMIC_FUNC0(CanvasGraphics_obj,endFill,(void))
void CanvasGraphics_obj::endStroke(){
HX_STACKFRAME(&_hx_pos_fd1c4d1c82edf2db_232_endStroke)
}
STATIC_HX_DEFINE_DYNAMIC_FUNC0(CanvasGraphics_obj,endStroke,(void))
bool CanvasGraphics_obj::hitTest( ::openfl::display::Graphics graphics,Float x,Float y){
HX_STACKFRAME(&_hx_pos_fd1c4d1c82edf2db_457_hitTest)
HXDLIN( 457) return false;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC3(CanvasGraphics_obj,hitTest,return )
bool CanvasGraphics_obj::isCCW(Float x1,Float y1,Float x2,Float y2,Float x3,Float y3){
HX_STACKFRAME(&_hx_pos_fd1c4d1c82edf2db_462_isCCW)
HXDLIN( 462) return ((((x2 - x1) * (y3 - y1)) - ((y2 - y1) * (x3 - x1))) < 0);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC6(CanvasGraphics_obj,isCCW,return )
::Dynamic CanvasGraphics_obj::normalizeUVT( ::openfl::_Vector::FloatVector uvt,::hx::Null< bool > __o_skipT){
bool skipT = __o_skipT.Default(false);
HX_GC_STACKFRAME(&_hx_pos_fd1c4d1c82edf2db_466_normalizeUVT)
HXLINE( 467) Float max = ::Math_obj::NEGATIVE_INFINITY;
HXLINE( 468) Float tmp = ::Math_obj::NEGATIVE_INFINITY;
HXLINE( 469) int len = uvt->get_length();
HXLINE( 471) {
HXLINE( 471) int _g = 1;
HXDLIN( 471) int _g1 = (len + 1);
HXDLIN( 471) while((_g < _g1)){
HXLINE( 471) _g = (_g + 1);
HXDLIN( 471) int t = (_g - 1);
HXLINE( 473) bool _hx_tmp;
HXDLIN( 473) if (skipT) {
HXLINE( 473) _hx_tmp = (::hx::Mod(t,3) == 0);
}
else {
HXLINE( 473) _hx_tmp = false;
}
HXDLIN( 473) if (_hx_tmp) {
HXLINE( 475) continue;
}
HXLINE( 478) tmp = uvt->get((t - 1));
HXLINE( 480) if ((max < tmp)) {
HXLINE( 482) max = tmp;
}
}
}
HXLINE( 486) if (!(skipT)) {
HXLINE( 488) return ::Dynamic(::hx::Anon_obj::Create(2)
->setFixed(0,HX_("max",a4,0a,53,00),max)
->setFixed(1,HX_("uvt",f3,2e,59,00),uvt));
}
HXLINE( 491) int length = null();
HXDLIN( 491) bool fixed = null();
HXDLIN( 491) ::Array< Float > array = null();
HXDLIN( 491) ::openfl::_Vector::FloatVector result = ::openfl::_Vector::FloatVector_obj::__alloc( HX_CTX ,length,fixed,array,true);
HXLINE( 493) {
HXLINE( 493) int _g2 = 1;
HXDLIN( 493) int _g3 = (len + 1);
HXDLIN( 493) while((_g2 < _g3)){
HXLINE( 493) _g2 = (_g2 + 1);
HXDLIN( 493) int t = (_g2 - 1);
HXLINE( 495) bool _hx_tmp;
HXDLIN( 495) if (skipT) {
HXLINE( 495) _hx_tmp = (::hx::Mod(t,3) == 0);
}
else {
HXLINE( 495) _hx_tmp = false;
}
HXDLIN( 495) if (_hx_tmp) {
HXLINE( 497) continue;
}
HXLINE( 500) result->push(uvt->get((t - 1)));
}
}
HXLINE( 503) return ::Dynamic(::hx::Anon_obj::Create(2)
->setFixed(0,HX_("max",a4,0a,53,00),max)
->setFixed(1,HX_("uvt",f3,2e,59,00),result));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(CanvasGraphics_obj,normalizeUVT,return )
void CanvasGraphics_obj::playCommands( ::openfl::display::_internal::DrawCommandBuffer commands,::hx::Null< bool > __o_stroke){
bool stroke = __o_stroke.Default(false);
HX_STACKFRAME(&_hx_pos_fd1c4d1c82edf2db_507_playCommands)
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(CanvasGraphics_obj,playCommands,(void))
void CanvasGraphics_obj::render( ::openfl::display::Graphics graphics, ::openfl::display::CanvasRenderer renderer){
HX_STACKFRAME(&_hx_pos_fd1c4d1c82edf2db_1142_render)
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(CanvasGraphics_obj,render,(void))
void CanvasGraphics_obj::renderMask( ::openfl::display::Graphics graphics, ::openfl::display::CanvasRenderer renderer){
HX_STACKFRAME(&_hx_pos_fd1c4d1c82edf2db_1461_renderMask)
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(CanvasGraphics_obj,renderMask,(void))
void CanvasGraphics_obj::setSmoothing(bool smooth){
HX_STACKFRAME(&_hx_pos_fd1c4d1c82edf2db_1565_setSmoothing)
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(CanvasGraphics_obj,setSmoothing,(void))
CanvasGraphics_obj::CanvasGraphics_obj()
{
}
bool CanvasGraphics_obj::__GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 5:
if (HX_FIELD_EQ(inName,"isCCW") ) { outValue = isCCW_dyn(); return true; }
break;
case 6:
if (HX_FIELD_EQ(inName,"bounds") ) { outValue = ( bounds ); return true; }
if (HX_FIELD_EQ(inName,"render") ) { outValue = render_dyn(); return true; }
break;
case 7:
if (HX_FIELD_EQ(inName,"hasFill") ) { outValue = ( hasFill ); return true; }
if (HX_FIELD_EQ(inName,"endFill") ) { outValue = endFill_dyn(); return true; }
if (HX_FIELD_EQ(inName,"hitTest") ) { outValue = hitTest_dyn(); return true; }
break;
case 8:
if (HX_FIELD_EQ(inName,"graphics") ) { outValue = ( graphics ); return true; }
break;
case 9:
if (HX_FIELD_EQ(inName,"hasStroke") ) { outValue = ( hasStroke ); return true; }
if (HX_FIELD_EQ(inName,"closePath") ) { outValue = closePath_dyn(); return true; }
if (HX_FIELD_EQ(inName,"endStroke") ) { outValue = endStroke_dyn(); return true; }
break;
case 10:
if (HX_FIELD_EQ(inName,"bitmapFill") ) { outValue = ( bitmapFill ); return true; }
if (HX_FIELD_EQ(inName,"hitTesting") ) { outValue = ( hitTesting ); return true; }
if (HX_FIELD_EQ(inName,"worldAlpha") ) { outValue = ( worldAlpha ); return true; }
if (HX_FIELD_EQ(inName,"renderMask") ) { outValue = renderMask_dyn(); return true; }
break;
case 11:
if (HX_FIELD_EQ(inName,"windingRule") ) { outValue = ( windingRule ); return true; }
break;
case 12:
if (HX_FIELD_EQ(inName,"bitmapStroke") ) { outValue = ( bitmapStroke ); return true; }
if (HX_FIELD_EQ(inName,"bitmapRepeat") ) { outValue = ( bitmapRepeat ); return true; }
if (HX_FIELD_EQ(inName,"fillCommands") ) { outValue = ( fillCommands ); return true; }
if (HX_FIELD_EQ(inName,"normalizeUVT") ) { outValue = normalizeUVT_dyn(); return true; }
if (HX_FIELD_EQ(inName,"playCommands") ) { outValue = playCommands_dyn(); return true; }
if (HX_FIELD_EQ(inName,"setSmoothing") ) { outValue = setSmoothing_dyn(); return true; }
break;
case 13:
if (HX_FIELD_EQ(inName,"pendingMatrix") ) { outValue = ( pendingMatrix ); return true; }
if (HX_FIELD_EQ(inName,"drawRoundRect") ) { outValue = drawRoundRect_dyn(); return true; }
break;
case 14:
if (HX_FIELD_EQ(inName,"allowSmoothing") ) { outValue = ( allowSmoothing ); return true; }
if (HX_FIELD_EQ(inName,"strokeCommands") ) { outValue = ( strokeCommands ); return true; }
break;
case 16:
if (HX_FIELD_EQ(inName,"createBitmapFill") ) { outValue = createBitmapFill_dyn(); return true; }
break;
case 20:
if (HX_FIELD_EQ(inName,"inversePendingMatrix") ) { outValue = ( inversePendingMatrix ); return true; }
break;
case 21:
if (HX_FIELD_EQ(inName,"createGradientPattern") ) { outValue = createGradientPattern_dyn(); return true; }
break;
case 23:
if (HX_FIELD_EQ(inName,"createTempPatternCanvas") ) { outValue = createTempPatternCanvas_dyn(); return true; }
}
return false;
}
bool CanvasGraphics_obj::__SetStatic(const ::String &inName,Dynamic &ioValue,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 6:
if (HX_FIELD_EQ(inName,"bounds") ) { bounds=ioValue.Cast< ::openfl::geom::Rectangle >(); return true; }
break;
case 7:
if (HX_FIELD_EQ(inName,"hasFill") ) { hasFill=ioValue.Cast< bool >(); return true; }
break;
case 8:
if (HX_FIELD_EQ(inName,"graphics") ) { graphics=ioValue.Cast< ::openfl::display::Graphics >(); return true; }
break;
case 9:
if (HX_FIELD_EQ(inName,"hasStroke") ) { hasStroke=ioValue.Cast< bool >(); return true; }
break;
case 10:
if (HX_FIELD_EQ(inName,"bitmapFill") ) { bitmapFill=ioValue.Cast< ::openfl::display::BitmapData >(); return true; }
if (HX_FIELD_EQ(inName,"hitTesting") ) { hitTesting=ioValue.Cast< bool >(); return true; }
if (HX_FIELD_EQ(inName,"worldAlpha") ) { worldAlpha=ioValue.Cast< Float >(); return true; }
break;
case 11:
if (HX_FIELD_EQ(inName,"windingRule") ) { windingRule=ioValue.Cast< ::Dynamic >(); return true; }
break;
case 12:
if (HX_FIELD_EQ(inName,"bitmapStroke") ) { bitmapStroke=ioValue.Cast< ::openfl::display::BitmapData >(); return true; }
if (HX_FIELD_EQ(inName,"bitmapRepeat") ) { bitmapRepeat=ioValue.Cast< bool >(); return true; }
if (HX_FIELD_EQ(inName,"fillCommands") ) { fillCommands=ioValue.Cast< ::openfl::display::_internal::DrawCommandBuffer >(); return true; }
break;
case 13:
if (HX_FIELD_EQ(inName,"pendingMatrix") ) { pendingMatrix=ioValue.Cast< ::openfl::geom::Matrix >(); return true; }
break;
case 14:
if (HX_FIELD_EQ(inName,"allowSmoothing") ) { allowSmoothing=ioValue.Cast< bool >(); return true; }
if (HX_FIELD_EQ(inName,"strokeCommands") ) { strokeCommands=ioValue.Cast< ::openfl::display::_internal::DrawCommandBuffer >(); return true; }
break;
case 20:
if (HX_FIELD_EQ(inName,"inversePendingMatrix") ) { inversePendingMatrix=ioValue.Cast< ::openfl::geom::Matrix >(); return true; }
}
return false;
}
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo *CanvasGraphics_obj_sMemberStorageInfo = 0;
static ::hx::StaticInfo CanvasGraphics_obj_sStaticStorageInfo[] = {
{::hx::fsFloat,(void *) &CanvasGraphics_obj::SIN45,HX_("SIN45",79,16,be,fa)},
{::hx::fsFloat,(void *) &CanvasGraphics_obj::TAN22,HX_("TAN22",41,f4,da,88)},
{::hx::fsBool,(void *) &CanvasGraphics_obj::allowSmoothing,HX_("allowSmoothing",ab,b7,66,68)},
{::hx::fsObject /* ::openfl::display::BitmapData */ ,(void *) &CanvasGraphics_obj::bitmapFill,HX_("bitmapFill",12,2e,19,35)},
{::hx::fsObject /* ::openfl::display::BitmapData */ ,(void *) &CanvasGraphics_obj::bitmapStroke,HX_("bitmapStroke",07,55,54,1c)},
{::hx::fsBool,(void *) &CanvasGraphics_obj::bitmapRepeat,HX_("bitmapRepeat",aa,38,9c,11)},
{::hx::fsObject /* ::openfl::geom::Rectangle */ ,(void *) &CanvasGraphics_obj::bounds,HX_("bounds",75,86,1d,66)},
{::hx::fsObject /* ::openfl::display::_internal::DrawCommandBuffer */ ,(void *) &CanvasGraphics_obj::fillCommands,HX_("fillCommands",6b,f6,c9,c2)},
{::hx::fsObject /* ::openfl::display::Graphics */ ,(void *) &CanvasGraphics_obj::graphics,HX_("graphics",cb,f8,67,12)},
{::hx::fsBool,(void *) &CanvasGraphics_obj::hasFill,HX_("hasFill",fd,ee,ff,12)},
{::hx::fsBool,(void *) &CanvasGraphics_obj::hasStroke,HX_("hasStroke",b2,66,1d,52)},
{::hx::fsBool,(void *) &CanvasGraphics_obj::hitTesting,HX_("hitTesting",bd,65,48,19)},
{::hx::fsObject /* ::openfl::geom::Matrix */ ,(void *) &CanvasGraphics_obj::inversePendingMatrix,HX_("inversePendingMatrix",28,14,8c,bb)},
{::hx::fsObject /* ::openfl::geom::Matrix */ ,(void *) &CanvasGraphics_obj::pendingMatrix,HX_("pendingMatrix",f8,9d,96,b5)},
{::hx::fsObject /* ::openfl::display::_internal::DrawCommandBuffer */ ,(void *) &CanvasGraphics_obj::strokeCommands,HX_("strokeCommands",a0,98,2a,67)},
{::hx::fsObject /* ::Dynamic */ ,(void *) &CanvasGraphics_obj::windingRule,HX_("windingRule",36,83,c0,4f)},
{::hx::fsFloat,(void *) &CanvasGraphics_obj::worldAlpha,HX_("worldAlpha",ac,57,43,8d)},
{ ::hx::fsUnknown, 0, null()}
};
#endif
static void CanvasGraphics_obj_sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(CanvasGraphics_obj::SIN45,"SIN45");
HX_MARK_MEMBER_NAME(CanvasGraphics_obj::TAN22,"TAN22");
HX_MARK_MEMBER_NAME(CanvasGraphics_obj::allowSmoothing,"allowSmoothing");
HX_MARK_MEMBER_NAME(CanvasGraphics_obj::bitmapFill,"bitmapFill");
HX_MARK_MEMBER_NAME(CanvasGraphics_obj::bitmapStroke,"bitmapStroke");
HX_MARK_MEMBER_NAME(CanvasGraphics_obj::bitmapRepeat,"bitmapRepeat");
HX_MARK_MEMBER_NAME(CanvasGraphics_obj::bounds,"bounds");
HX_MARK_MEMBER_NAME(CanvasGraphics_obj::fillCommands,"fillCommands");
HX_MARK_MEMBER_NAME(CanvasGraphics_obj::graphics,"graphics");
HX_MARK_MEMBER_NAME(CanvasGraphics_obj::hasFill,"hasFill");
HX_MARK_MEMBER_NAME(CanvasGraphics_obj::hasStroke,"hasStroke");
HX_MARK_MEMBER_NAME(CanvasGraphics_obj::hitTesting,"hitTesting");
HX_MARK_MEMBER_NAME(CanvasGraphics_obj::inversePendingMatrix,"inversePendingMatrix");
HX_MARK_MEMBER_NAME(CanvasGraphics_obj::pendingMatrix,"pendingMatrix");
HX_MARK_MEMBER_NAME(CanvasGraphics_obj::strokeCommands,"strokeCommands");
HX_MARK_MEMBER_NAME(CanvasGraphics_obj::windingRule,"windingRule");
HX_MARK_MEMBER_NAME(CanvasGraphics_obj::worldAlpha,"worldAlpha");
};
#ifdef HXCPP_VISIT_ALLOCS
static void CanvasGraphics_obj_sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(CanvasGraphics_obj::SIN45,"SIN45");
HX_VISIT_MEMBER_NAME(CanvasGraphics_obj::TAN22,"TAN22");
HX_VISIT_MEMBER_NAME(CanvasGraphics_obj::allowSmoothing,"allowSmoothing");
HX_VISIT_MEMBER_NAME(CanvasGraphics_obj::bitmapFill,"bitmapFill");
HX_VISIT_MEMBER_NAME(CanvasGraphics_obj::bitmapStroke,"bitmapStroke");
HX_VISIT_MEMBER_NAME(CanvasGraphics_obj::bitmapRepeat,"bitmapRepeat");
HX_VISIT_MEMBER_NAME(CanvasGraphics_obj::bounds,"bounds");
HX_VISIT_MEMBER_NAME(CanvasGraphics_obj::fillCommands,"fillCommands");
HX_VISIT_MEMBER_NAME(CanvasGraphics_obj::graphics,"graphics");
HX_VISIT_MEMBER_NAME(CanvasGraphics_obj::hasFill,"hasFill");
HX_VISIT_MEMBER_NAME(CanvasGraphics_obj::hasStroke,"hasStroke");
HX_VISIT_MEMBER_NAME(CanvasGraphics_obj::hitTesting,"hitTesting");
HX_VISIT_MEMBER_NAME(CanvasGraphics_obj::inversePendingMatrix,"inversePendingMatrix");
HX_VISIT_MEMBER_NAME(CanvasGraphics_obj::pendingMatrix,"pendingMatrix");
HX_VISIT_MEMBER_NAME(CanvasGraphics_obj::strokeCommands,"strokeCommands");
HX_VISIT_MEMBER_NAME(CanvasGraphics_obj::windingRule,"windingRule");
HX_VISIT_MEMBER_NAME(CanvasGraphics_obj::worldAlpha,"worldAlpha");
};
#endif
::hx::Class CanvasGraphics_obj::__mClass;
static ::String CanvasGraphics_obj_sStaticFields[] = {
HX_("SIN45",79,16,be,fa),
HX_("TAN22",41,f4,da,88),
HX_("allowSmoothing",ab,b7,66,68),
HX_("bitmapFill",12,2e,19,35),
HX_("bitmapStroke",07,55,54,1c),
HX_("bitmapRepeat",aa,38,9c,11),
HX_("bounds",75,86,1d,66),
HX_("fillCommands",6b,f6,c9,c2),
HX_("graphics",cb,f8,67,12),
HX_("hasFill",fd,ee,ff,12),
HX_("hasStroke",b2,66,1d,52),
HX_("hitTesting",bd,65,48,19),
HX_("inversePendingMatrix",28,14,8c,bb),
HX_("pendingMatrix",f8,9d,96,b5),
HX_("strokeCommands",a0,98,2a,67),
HX_("windingRule",36,83,c0,4f),
HX_("worldAlpha",ac,57,43,8d),
HX_("closePath",7d,65,20,14),
HX_("createBitmapFill",2e,ac,46,6a),
HX_("createGradientPattern",a4,ee,44,f6),
HX_("createTempPatternCanvas",f8,58,91,d0),
HX_("drawRoundRect",ee,c3,aa,e2),
HX_("endFill",fe,87,e0,25),
HX_("endStroke",f3,01,17,51),
HX_("hitTest",45,60,7f,e2),
HX_("isCCW",0d,84,49,c1),
HX_("normalizeUVT",66,09,2f,47),
HX_("playCommands",dc,ae,ee,49),
HX_("render",56,6b,29,05),
HX_("renderMask",62,3b,60,e5),
HX_("setSmoothing",72,95,31,ba),
::String(null())
};
void CanvasGraphics_obj::__register()
{
CanvasGraphics_obj _hx_dummy;
CanvasGraphics_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("openfl.display._internal.CanvasGraphics",bf,c1,78,cf);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &CanvasGraphics_obj::__GetStatic;
__mClass->mSetStaticField = &CanvasGraphics_obj::__SetStatic;
__mClass->mMarkFunc = CanvasGraphics_obj_sMarkStatics;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(CanvasGraphics_obj_sStaticFields);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(0 /* sMemberFields */);
__mClass->mCanCast = ::hx::TCanCast< CanvasGraphics_obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = CanvasGraphics_obj_sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = CanvasGraphics_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = CanvasGraphics_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
void CanvasGraphics_obj::__boot()
{
{
HX_STACKFRAME(&_hx_pos_fd1c4d1c82edf2db_34_boot)
HXDLIN( 34) __mClass->__meta__ = ::Dynamic(::hx::Anon_obj::Create(2)
->setFixed(0,HX_("obj",f7,8f,54,00), ::Dynamic(::hx::Anon_obj::Create(1)
->setFixed(0,HX_("SuppressWarnings",0c,d3,d2,00),::cpp::VirtualArray_obj::__new(1)->init(0,HX_("checkstyle:FieldDocComment",70,56,1b,20)))))
->setFixed(1,HX_("statics",05,3c,65,36), ::Dynamic(::hx::Anon_obj::Create(3)
->setFixed(0,HX_("createGradientPattern",a4,ee,44,f6), ::Dynamic(::hx::Anon_obj::Create(1)
->setFixed(0,HX_("SuppressWarnings",0c,d3,d2,00),::cpp::VirtualArray_obj::__new(1)->init(0,HX_("checkstyle:Dynamic",ce,ea,47,3c)))))
->setFixed(1,HX_("windingRule",36,83,c0,4f), ::Dynamic(::hx::Anon_obj::Create(1)
->setFixed(0,HX_("SuppressWarnings",0c,d3,d2,00),::cpp::VirtualArray_obj::__new(1)->init(0,HX_("checkstyle:Dynamic",ce,ea,47,3c)))))
->setFixed(2,HX_("createBitmapFill",2e,ac,46,6a), ::Dynamic(::hx::Anon_obj::Create(1)
->setFixed(0,HX_("SuppressWarnings",0c,d3,d2,00),::cpp::VirtualArray_obj::__new(1)->init(0,HX_("checkstyle:Dynamic",ce,ea,47,3c))))))));
}
{
HX_STACKFRAME(&_hx_pos_fd1c4d1c82edf2db_36_boot)
HXDLIN( 36) SIN45 = ((Float)0.70710678118654752440084436210485);
}
{
HX_STACKFRAME(&_hx_pos_fd1c4d1c82edf2db_37_boot)
HXDLIN( 37) TAN22 = ((Float)0.4142135623730950488016887242097);
}
{
HX_GC_STACKFRAME(&_hx_pos_fd1c4d1c82edf2db_43_boot)
HXDLIN( 43) fillCommands = ::openfl::display::_internal::DrawCommandBuffer_obj::__alloc( HX_CTX );
}
{
HX_GC_STACKFRAME(&_hx_pos_fd1c4d1c82edf2db_50_boot)
HXDLIN( 50) strokeCommands = ::openfl::display::_internal::DrawCommandBuffer_obj::__alloc( HX_CTX );
}
}
} // end namespace openfl
} // end namespace display
} // end namespace _internal
|
6c5b6636e425f22a75e7f599f4f68a8acf86e6b8 | bacac8a191882ce7b6a44a3ea76fd5e7247c7645 | /Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiFitPeaks1D.h | 95046700d7d45d70350ff1cd6debb20cbb5a62ca | [] | no_license | tianhl/mantid | 63e322523384b17c00470ee54ee5b17e6eda1537 | 509ef7ebd2fb49c13dc2251c9ead1be8473bee74 | refs/heads/master | 2021-01-16T20:27:40.107265 | 2015-02-03T16:20:15 | 2015-02-03T16:20:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,266 | h | PoldiFitPeaks1D.h | #ifndef MANTID_SINQ_POLDIFITPEAKS1D_H_
#define MANTID_SINQ_POLDIFITPEAKS1D_H_
#include "MantidKernel/System.h"
#include "MantidAPI/Algorithm.h"
#include "MantidSINQ/DllConfig.h"
#include "MantidSINQ/PoldiUtilities/PoldiPeakCollection.h"
#include "MantidAPI/IPeakFunction.h"
#include "MantidDataObjects/Workspace2D.h"
#include "MantidDataObjects/TableWorkspace.h"
#include "MantidAPI/TableRow.h"
namespace Mantid {
namespace Poldi {
/** PoldiFitPeaks1D :
PoldiFitPeaks1D fits multiple peaks to POLDI auto-correlation data.
@author Michael Wedel, Paul Scherrer Institut - SINQ
@date 17/03/2014
Copyright © 2014 PSI-MSS
This file is part of Mantid.
Mantid 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.
Mantid 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/>.
File change history is stored at: <https://github.com/mantidproject/mantid>
Code Documentation is available at: <http://doxygen.mantidproject.org>
*/
class MANTID_SINQ_DLL PoldiFitPeaks1D : public API::Algorithm {
public:
PoldiFitPeaks1D();
virtual ~PoldiFitPeaks1D();
virtual const std::string name() const;
/// Summary of algorithms purpose
virtual const std::string summary() const {
return "PoldiPeakFit1D fits peak profiles to POLDI auto-correlation data.";
}
virtual int version() const;
virtual const std::string category() const;
protected:
void setPeakFunction(std::string peakFunction);
PoldiPeakCollection_sptr
getInitializedPeakCollection(DataObjects::TableWorkspace_sptr peakTable);
API::IFunction_sptr getPeakProfile(PoldiPeak_sptr poldiPeak);
void setValuesFromProfileFunction(PoldiPeak_sptr poldiPeak,
API::IFunction_sptr fittedFunction);
double getFwhmWidthRelation(API::IPeakFunction_sptr peakFunction);
API::IAlgorithm_sptr
getFitAlgorithm(DataObjects::Workspace2D_sptr dataWorkspace,
PoldiPeak_sptr peak, API::IFunction_sptr profile);
void addPeakFitCharacteristics(API::ITableWorkspace_sptr fitResult);
void initializeFitResultWorkspace(API::ITableWorkspace_sptr fitResult);
void initializePeakResultWorkspace(
DataObjects::TableWorkspace_sptr peakResultWorkspace);
void storePeakResult(API::TableRow tableRow, PoldiPeak_sptr peak);
DataObjects::TableWorkspace_sptr
generateResultTable(PoldiPeakCollection_sptr peaks);
PoldiPeakCollection_sptr m_peaks;
std::string m_profileTemplate;
API::IFunction_sptr m_backgroundTemplate;
std::string m_profileTies;
DataObjects::TableWorkspace_sptr m_fitCharacteristics;
DataObjects::TableWorkspace_sptr m_peakResultOutput;
double m_fwhmMultiples;
private:
void init();
void exec();
};
} // namespace Poldi
} // namespace Mantid
#endif /* MANTID_SINQ_POLDIFITPEAKS1D_H_ */
|
169fb878a9d697285e1065b22bac1666b9a000bc | e9a302f72cf8bb851a6322304813c7916564de8c | /StarsGameEngine/texture.cpp | 8f3506c6d207a205f43c80cadc08655623e3c0f2 | [] | no_license | adjs6157/StarsGameEngine | 76588b0200f6411e3b7a2a281d25669c4f91d0f6 | 4ee532f6f8e862022a8a6fd9f62ad7e6feae20e1 | refs/heads/master | 2022-01-31T06:01:14.246602 | 2019-06-06T01:33:20 | 2019-06-06T01:33:20 | 108,400,336 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 579 | cpp | texture.cpp | #include "texture.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
Texture::~Texture()
{
if (_data != nullptr)
{
stbi_image_free(_data);
_data = nullptr;
}
}
bool Texture::InitFromFile(const std::string & fname)
{
assert(_data == nullptr);
int w = 0, h = 0, channel = 0;
_data = stbi_load(fname.c_str(), &w, &h, &channel, 0);
if (_data != nullptr)
{
_w = static_cast<unsigned int>(w);
_h = static_cast<unsigned int> (h);
_channel = static_cast<unsigned int> (channel);
}
return _data != nullptr;
}
|
7a28412c843581e7139df94955b61fe62a307208 | 7aa20a8b3b037d9d0f2314327fe72e9d87780720 | /GameStructure/ComponentManager.cpp | 5cccda2840beaf8c11fa784903b464018d9b43be | [] | no_license | ramses2099/GamesStucture | 87af050dca695977efc5cc73e50989808b23e87e | 0510fcfbd28e1f18072846238a2a264df8088d7d | refs/heads/master | 2020-06-25T23:09:59.880759 | 2019-07-31T18:34:51 | 2019-07-31T18:34:51 | 199,449,841 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 377 | cpp | ComponentManager.cpp | #include "pch.h"
#include "ComponentManager.h"
jp::ComponentManager::ComponentManager()
{
}
//
jp::ComponentManager::~ComponentManager()
{
}
//
void jp::ComponentManager::AddComponent(std::string name, Component component)
{
this->_components[name] = component;
}
//
jp::Component & jp::ComponentManager::GetComponent(std::string name)
{
return this->_components.at(name);
}
|
9584c2426a6da624367836dafc4e3d7cbed78c2a | 7e0821a158498c86b2a1bd85c8cecde4b666e520 | /lab5_2/src/tree.h | b423bb28c1f266c72d812b2461973b4c6a8d0630 | [] | no_license | michelle19l/compiler | 5d7b6b4c383a53134e31ea100089b720f4332385 | 39d5009fe06b362cc6946bf31f0ecec38e3bd401 | refs/heads/master | 2023-02-10T04:03:36.015200 | 2021-01-08T11:42:49 | 2021-01-08T11:42:49 | 316,940,376 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,912 | h | tree.h | #ifndef TREE_H
#define TREE_H
#include "pch.h"
#include "type.h"
#include "field.h"
enum NodeType
{
NODE_CONST=1, //常量
NODE_VAR,//变量
NODE_EXPR,//表达式
NODE_TYPE,//类型
NODE_STMT,//语句
NODE_PROG,//程序
NODE_PARAM,//参数
};
enum ConstType//常量
{
CON_INT=1,
CON_CHAR,
CON_STRING,
};
enum OperatorType
{
//OP_ASIGN=1, // =
OP_EQUAL,//==
OP_GREAT,
OP_LESS,
OP_GREAT_EQ,
OP_LESS_EQ,
OP_NOT_EQ,
OP_ADD,//+
OP_SUB,
OP_MUL,
OP_DIV,
OP_MOD,
OP_NEG,//负号
OP_POS,//正号
OP_AND,
OP_OR,
OP_NOT,
OP_ADDR,//&
OP_VAL,//*
};
enum StmtType {
STMT_SKIP=1,//空语句
STMT_DEFINE,//定义语句
STMT_ASSIGN,
STMT_DECL,//声明
STMT_WHILE,
STMT_FOR,
STMT_RET,
STMT_PRT,//printf
STMT_SCF,//scanf
STMT_FUNC_DECL,
STMT_FUNC_DEF,
STMT_FUNC_USE,
STMT_ADD_ASSIGN,
STMT_SUB_ASSIGN,
STMT_MUL_ASSIGN,
STMT_DIV_ASSIGN,
STMT_MOD_ASSIGN,
STMT_SELF_INC_R,
STMT_SELF_INC_L,
STMT_SELF_DEC_R,
STMT_SELF_DEC_L,
STMT_IF_ELSE,//if语句
STMT_IF,
STMT_ELSE,
STMT_BLOCK,//语句块
};
struct TreeNode {
public:
int nodeID; // 用于作业的序号输出
int lineno;//行号
NodeType nodeType;//结点类型
TreeNode* child = nullptr;
TreeNode* sibling = nullptr;
//TreeNode* father=nullptr;
void addChild(TreeNode*);
void addSibling(TreeNode*);
void printNodeInfo();
void printChildrenId();
void printAST(); // 先输出自己 + 孩子们的id;再依次让每个孩子输出AST。
void printSpecialInfo();
void genNodeId();
public:
ConstType contype;
OperatorType optype; // 如果是表达式
Type* type; // 变量、类型、表达式结点,有类型。
StmtType stype;
int int_val;//整型
string int_val_;//整型的字符串
char ch_val;//字符
bool b_val;//布尔
string str_val;
string var_name;
int lex;//符号表结点指针
string workfield;//变量作用域
table* scope;//所属作用域
static int current_node_id;
public:
string nodeType2String ();//结点基本类型
// static string opType2String (OperatorType type);
string sType2String ();//语句类型
string tType2String ();//int bool
string cType2String();//常量
string opType2String();//表达式
string varName2String();//变量名
string getfield();//作用域
public:
TreeNode(int lineno, NodeType type);
//TreeNode(){}
};
#endif
void insertID(TreeNode* root,table* scope);//向当前作用域插入IDint
//static int checkID(string yytext,table*scope);//在当前作用域查找是否存在该ID
void getBlock(TreeNode* root,table* scope);//根据ast得到作用域树
void getVarField(TreeNode* root,table*scope);//为变量分配作用域 |
dfa4134346970459203ce1414de4f8bf454b7928 | b6bf909e10eb5acf34b7b23f1eb2d390f972a77e | /BK_GPU_HYBRID/src/Host/BKInstance.h | 867b71cccf47941a17b3dfcfcbbb614f8a88c81d | [] | no_license | deepai/BK_GPU | 428ed6ce9028b6ce8cafa2ba5960834970836cb9 | 66fb61fabaaf372226d69aade547decf7b57a155 | refs/heads/master | 2020-04-11T10:48:50.170006 | 2015-11-12T14:17:25 | 2015-11-12T14:17:25 | 42,102,718 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,321 | h | BKInstance.h | /*
* BKInstance.h
*
* Created on: 06-Oct-2015
* Author: debarshi
*/
#ifndef BKINSTANCE_H_
#define BKINSTANCE_H_
#include "../Device/GPUCSR.h"
#include "../Device/NeighbourGraph.h"
#include "../Device/GPUStack.h"
#include "../utilities.h"
#include "../cub/cub.cuh"
#include "../moderngpu/moderngpu.cuh"
#include "../Device/RecursionStack.h"
#include "BKInstanceTest.h"
namespace BK_GPU {
class BKInstance {
public:
int maxCliqueSizeObtained;
//Auxiliary memory required for Sorting,InclusiveSum
BK_GPU::GPU_CSR *gpuGraph;
BK_GPU::NeighbourGraph *Ng;
BK_GPU::GPU_Stack *stack;
BK_GPU::StackElement topElement;
BK_GPU::StackElement secondElement;
BK_GPU::RecursionStack *tracker;
mgpu::ContextPtr *Context;
Graph *host_graph;
cudaStream_t *Stream;
mgpu::ContextPtr *Contextptr;
int MaxThreads;
BKInstanceTest *testInstance;
BKInstance(Graph *host_graph,BK_GPU::GPU_CSR *gpuGraph,BK_GPU::NeighbourGraph *Ng,BK_GPU::GPU_Stack *stack,cudaStream_t &stream,mgpu::ContextPtr *context,int numThreads);
~BKInstance();
void RunCliqueFinder(int CliqueId);
int processPivot(BK_GPU::StackElement &element);
void printClique(int CliqueSize,int beginClique);
void moveToX(int pivot);
void moveFromXtoP();
void nextNonPivot(int pivot);
};
} /* namespace BK_GPU */
#endif /* BKINSTANCE_H_ */
|
bea676f9ed8835795be82eaa12dfdacdb6234d41 | 0c223a66cadf2d4488a6678a8f5578c39990aaec | /CF:540:B/a.cpp | 96971f935c6f76293803970b9e6e8555722bcd9b | [] | no_license | prajogotio/upsolving | b71a1803b372960eec65c6effef2934065d36786 | 51078bf1118acd97af75683a53104bd59311686c | refs/heads/master | 2021-01-10T01:00:18.757460 | 2015-07-21T18:48:02 | 2015-07-21T18:48:02 | 28,124,346 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 660 | cpp | a.cpp | #include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
int n, k, p, x, y;
int main(){
scanf("%d%d%d%d%d",&n,&k,&p,&x,&y);
int v;
int lo, hi;
lo = hi = 0;
int sum = 0;
for(int i=0;i<k;++i){
scanf("%d",&v);
sum += v;
if(v < y) lo++;
else hi++;
}
int rem = x - sum;
if (rem < n-k) {
printf("-1\n");
return 0;
}
vector<int> st;
for(int i=0;i<n-k;++i){
if(rem - y >= n-k-i-1) {
st.push_back(y);
++hi;
rem -= y;
}else {
st.push_back(1);
++lo;
rem -= 1;
}
}
if(hi > lo) {
for(int i = 0; i < n-k; ++i){
printf("%d ", st[i]);
}
printf("\n");
} else {
printf("-1\n");
}
return 0;
} |
e30c5b92e96f9882bd247f26fd7b1552aa413eaf | 532f7b18ae8170a5f7c723a2fef3a245fb7cd766 | /B.Sc/1O-YEARS PART 2/31.cpp | dd1bf4faf4bdeae392b394534f94f7b60f0c86ef | [] | no_license | HomeVampire/C-Programming | 6db31aecce9746ea1c2e842b143950255ec2c24c | 98076d5e641e3bfd308af5d4565fc85579714e63 | refs/heads/main | 2023-02-05T10:08:05.917823 | 2020-12-12T17:25:11 | 2020-12-12T17:27:26 | 320,881,279 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 643 | cpp | 31.cpp | #include<stdio.h>
#include<process.h>
int main()
{
FILE *fp1,*fp2;
char a[100],b[100];
int n,i;
fp1=fopen("country.txt","w");
fp2=fopen("capital.txt","w");
printf("Enter total number of country: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter country and corrosponding ");
fflush(stdin);
gets(a);
fprintf(fp1,"%s\n",a);
fflush(stdin);
gets(b);
fprintf(fp2,"%s\n",b);
}
fclose(fp1);
fclose(fp2);
fp1=fopen("country.txt","r");
fp2=fopen("capital.txt","r");
for(i=0;i<n;i++)
{
fscanf(fp1,"%s",a);
fscanf(fp2,"%s",b);
printf("The capital of %s is %s\n",a,b);
}
fclose(fp1);
fclose(fp2);
return(0);
}
|
83afd437386493432ca618c1037b49fd02c96473 | 992cf827f336d53df721b62f3a317e56cdf1fa06 | /openGlab/openGlabView.h | ae95ce0b0354d869a5bf82260b8084204b2f8627 | [] | no_license | MasaDjordjevic/OpenGL-lab | a2e5c42463bc3ace76f22f717c64b47579149219 | 3d6e95d37be77a937cef4de8bd1ee48db6721f54 | refs/heads/master | 2021-01-13T14:48:50.499962 | 2016-12-21T22:18:44 | 2016-12-21T22:18:44 | 76,556,819 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,413 | h | openGlabView.h |
// openGlabView.h : interface of the CopenGlabView class
//
#pragma once
#include "Renderer.h"
class CopenGlabView : public CView
{
protected:
Renderer renderer;
protected: // create from serialization only
CopenGlabView();
DECLARE_DYNCREATE(CopenGlabView)
// Attributes
public:
CopenGlabDoc* GetDocument() const;
// Operations
public:
// Overrides
public:
virtual void OnDraw(CDC* pDC); // overridden to draw this view
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:
virtual BOOL OnPreparePrinting(CPrintInfo* pInfo);
virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo);
virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo);
void OnInitialUpdate();
// Implementation
public:
virtual ~CopenGlabView();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
DECLARE_MESSAGE_MAP()
public:
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnDestroy();
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
afx_msg BOOL OnMouseWheel(UINT nFlags, short zDelta, CPoint pt);
};
#ifndef _DEBUG // debug version in openGlabView.cpp
inline CopenGlabDoc* CopenGlabView::GetDocument() const
{ return reinterpret_cast<CopenGlabDoc*>(m_pDocument); }
#endif
|
457d550212474a950ffb30ec616059fb0af326c0 | 5712a01bc06416cf32fb637e10b21b34b938961c | /AtCoder/Beginner Contest 166/A.cpp | c40b016a3a4ecd4fe320526352cb5fb44c42224b | [] | no_license | WenShihKen/uva | 654a9f5f3e56935625e061795f152609899b79e5 | 03a3d603941dd9b9ec13e76fb99d24da6749a81b | refs/heads/master | 2021-01-10T14:34:29.580527 | 2020-06-25T15:34:23 | 2020-06-25T15:34:23 | 48,536,090 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 574 | cpp | A.cpp | /**
* @judge Atcoder
* @id A
* @name A?C
* @contest Beginner Contest 166
*
* @tag ad-hoc
*/
#include <algorithm>
#include <map>
#include <iostream>
#include <string>
#include <set>
#include <queue>
#include <cmath>
#include <iterator>
#include <array>
typedef long long int ll;
using namespace std;
#define maxN 200005
#define mod 1000000007
string s;
void solve()
{
cin >> s;
if (s == "ABC")
{
cout << "ARC\n";
}
else
{
cout << "ABC\n";
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
solve();
}
|
0b01f6fecfa1df04c7ff8643ace4de8f5910cd0d | 988e0a3e05ca7298452dbb754bf73c4de4f0acf7 | /1072.cpp | 138639f613b4034491fe95f61891e25965ba7542 | [] | no_license | matheusrodrisantos/URI_EXERCICIOS | c5970d0fc53ebc2e91941e51bcd85c6491dd82d5 | e24f3b2af862bea012c22efa9660e5e280138ada | refs/heads/master | 2020-08-04T18:11:17.776952 | 2020-02-20T16:08:14 | 2020-02-20T16:08:14 | 212,233,178 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 328 | cpp | 1072.cpp | #include <iostream>
using namespace std;
int main()
{
int n,n1,in,out;
in=0;out=0;
cin>>n;
while (n--)
{
cin>>n1;
if((n1>=10)and (n1<=20))
{
in++;
}else
{
out++;
}
}
cout<<in<<" in\n";
cout<<out<<" out\n";
return 0;
} |
341f2ec4f215ab6877820e9256783139e523a947 | 202b5d48806e6ea71130f6828b0266d7a481acb2 | /TLBB3_DLL/TabSheet.cpp | d53c950e7980908b7f9681c2f36b66918de98706 | [] | no_license | rogeecn/WG_Injector | c2a723bffdd4c0faf4dd0feea1a40940e011e438 | 3488788b377402740d2cca7898aefee394342025 | refs/heads/master | 2016-09-16T01:37:26.038771 | 2015-05-20T04:39:48 | 2015-05-20T04:39:48 | 35,926,068 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,595 | cpp | TabSheet.cpp | // TabSheet.cpp : implementation file
//
#include "stdafx.h"
#include "TabSheet.h"
// CTabSheet
IMPLEMENT_DYNAMIC(CTabSheet, CTabCtrl)
CTabSheet::CTabSheet()
{
m_nNumOfPages = 0;
m_nCurrentPage = 0;
}
CTabSheet::~CTabSheet()
{
}
BEGIN_MESSAGE_MAP(CTabSheet, CTabCtrl)
ON_NOTIFY_REFLECT(TCN_SELCHANGE, &CTabSheet::OnTcnSelchange)
END_MESSAGE_MAP()
// CTabSheet message handlers
BOOL CTabSheet::AddPage(CString szTitle, CDialog * pDialog, UINT ID)
{
if (MAX_PAGES == m_nNumOfPages){
return FALSE;
}
m_pPages[m_nNumOfPages] = pDialog;
m_IDD[m_nNumOfPages] = ID;
m_Title[m_nNumOfPages] = szTitle;
InsertItem(m_nNumOfPages, szTitle);
CRect innerRect = GetInnerRect();
m_pPages[m_nNumOfPages]->Create(ID, this);
m_pPages[m_nNumOfPages]->SetParent(this);
m_pPages[m_nNumOfPages]->MoveWindow(&innerRect);
if (m_nCurrentPage ==0 && m_nNumOfPages == 0) {
m_pPages[m_nNumOfPages]->ShowWindow(SW_NORMAL);
}else{
m_pPages[m_nNumOfPages]->ShowWindow(SW_HIDE);
}
m_nNumOfPages++;
return TRUE;
}
void CTabSheet::OnTcnSelchange(NMHDR *pNMHDR, LRESULT *pResult)
{
if (m_nCurrentPage != GetCurFocus()){
m_pPages[m_nCurrentPage]->ShowWindow(SW_HIDE);
m_nCurrentPage = GetCurFocus();
m_pPages[m_nCurrentPage]->ShowWindow(SW_SHOW);
}
*pResult = 0;
}
CRect CTabSheet::GetInnerRect(void)
{
CRect tabRect, itemRect;
int nX = 0, nY = 0, nXc = 0, nYc = 0;
UINT nCount = 0;
GetClientRect(&tabRect);
GetItemRect(0, &itemRect);
nX = itemRect.left;
nY = itemRect.bottom + 1;
nXc = tabRect.right - 3;
nYc = tabRect.bottom - 2;
return CRect(nX,nY,nXc,nYc);
}
|
005aadf17e2bb9f7945ee2c98447465c769174b7 | d96ebf4dac46404a46253afba5ba5fc985d5f6fc | /third_party/msgpack/include/msgpack/preprocessor/facilities/overload.hpp | cc3f4f2c6cc9082e3ab5875fa4281be5c400dd81 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | marco-c/gecko-dev-wordified-and-comments-removed | f9de100d716661bd67a3e7e3d4578df48c87733d | 74cb3d31740be3ea5aba5cb7b3f91244977ea350 | refs/heads/master | 2023-08-04T23:19:13.836981 | 2023-08-01T00:33:54 | 2023-08-01T00:33:54 | 211,297,165 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 391 | hpp | overload.hpp | #
#
#
#
#
ifndef
MSGPACK_PREPROCESSOR_FACILITIES_OVERLOAD_HPP
#
define
MSGPACK_PREPROCESSOR_FACILITIES_OVERLOAD_HPP
#
#
include
<
msgpack
/
preprocessor
/
cat
.
hpp
>
#
include
<
msgpack
/
preprocessor
/
variadic
/
size
.
hpp
>
#
#
#
#
if
MSGPACK_PP_VARIADICS
#
define
MSGPACK_PP_OVERLOAD
(
prefix
.
.
.
)
MSGPACK_PP_CAT
(
prefix
MSGPACK_PP_VARIADIC_SIZE
(
__VA_ARGS__
)
)
#
endif
#
#
endif
|
ae758b37c79d87522535454d24393c3a1f4c27a7 | b6ad4a5f91225b6b12299633f94ec3dc3a600a60 | /pokegearsolid/pokegearsolid/WinMain.cpp | e7dbd53f897764c717e7cdde5d0ebff071b17d38 | [] | no_license | Ishoa/EeveeHound2.0 | e9f33fe7340fc3bb22dfd82599b451f0d601f11f | 5188777579be895227c8bdff55171d7a13e4a00b | refs/heads/master | 2021-01-19T11:46:14.033821 | 2014-04-21T05:37:55 | 2014-04-21T05:37:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,503 | cpp | WinMain.cpp | #include <Windows.h>
#include "PokeGear.h"
//#define _CRTDBG_MAP_ALLOC
//fullscreen res
#define SCREEN_WIDTH 1920
#define SCREEN_HEIGHT 1080
//windowed res
#define W_SCREEN_WIDTH 800
#define W_SCREEN_HEIGHT 600
#define WINDOW_TITLE L"PokeGear Solid"
HWND g_hWnd; // Handle to the window
HINSTANCE g_hInstance; // Handle to the application instance
bool g_bWindowed; // Boolean for windowed or full-screen
// Entry point for the game or application.
int WINAPI wWinMain(HINSTANCE hInstance, // Handle to the application
HINSTANCE hPrevInstance, // Handle to the previous app
LPTSTR lpCmdLine, // Command line string
int lpCmdShow); // Show window value
LRESULT CALLBACK WndProc(HWND hWnd, // Handle to the window
UINT message, // Incoming Message
WPARAM wparam, // Message Info
LPARAM lparam); // Message Info
void InitWindow(void)
{
WNDCLASSEX wndClass;
ZeroMemory(&wndClass, sizeof(wndClass));
// set up the window
wndClass.cbSize = sizeof(WNDCLASSEX); // size of window structure
wndClass.lpfnWndProc = (WNDPROC)WndProc; // message callback
wndClass.lpszClassName = WINDOW_TITLE; // class name
wndClass.hInstance = g_hInstance; // handle to the application
wndClass.hCursor = LoadCursor(NULL, IDC_ARROW); // default cursor
//wndClass.hbrBackground = (HBRUSH)(COLOR_WINDOWFRAME); // background brush
// register a new type of window
RegisterClassEx(&wndClass);
DWORD style;
int height, width;
if(g_bWindowed)
{
style = WS_OVERLAPPEDWINDOW | WS_VISIBLE;
width = W_SCREEN_WIDTH;
height = W_SCREEN_HEIGHT;
}
else
{
style = WS_EX_TOPMOST | WS_POPUP;
width = SCREEN_WIDTH;
height = SCREEN_HEIGHT;
}
g_hWnd = CreateWindowEx(
NULL,
WINDOW_TITLE, WINDOW_TITLE, // window class name and title
style, // window style
CW_USEDEFAULT, CW_USEDEFAULT, // x and y coordinates
width, height, // width and height of window
NULL, NULL, // parent window and menu
g_hInstance, // handle to application
NULL);
// Display the window
ShowWindow(g_hWnd, SW_SHOW);
UpdateWindow(g_hWnd);
}
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )
{
g_hInstance = hInstance; // Store application handle
g_bWindowed = true; // Windowed mode or full-screen
bool push = false;
// Init the window
InitWindow();
MSG msg;
ZeroMemory(&msg, sizeof(msg));
PokeGear pokegear;
pokegear.init(g_hWnd,g_hInstance,g_bWindowed);
//Main Loop
while(msg.message != WM_QUIT)
{
if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
pokegear.update();
}
pokegear.shutdown();
// Unregister window
UnregisterClass(WINDOW_TITLE, g_hInstance);
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
_CrtDumpMemoryLeaks();
// Return successful
return 0;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wparam, LPARAM lparam)
{
// attempt to handle your messages
switch(message)
{
case (WM_PAINT):
{
InvalidateRect(hWnd,NULL,TRUE);
break;
}
case(WM_DESTROY):
{
PostQuitMessage(0);
break;
}
case(WM_KEYDOWN):
{
switch(wparam)
{
// Escape Key will close the application
// Remove/Modify this call when creating a real game with menus, etc.
//case VK_ESCAPE:
//{
//PostQuitMessage(0);
//break;
//}
}
}
}
// pass to default handler
return DefWindowProc(hWnd, message, wparam, lparam);
}
|
20780ec26063b52dfac33c762d63b769a05d2ac1 | 3fa05bd3be30fe7d8b7b7df08e49bbb87403c30b | /src/boundary/boundary.h | 5fbfc40acad1d9bbb0eb9ae4b5180783043a7f61 | [] | no_license | joebradly/kMC | e50aaa3a4183e88c1600c59b9780040c6bd077c5 | 3e7b138fc07bb36c6242cde1059bb1fa6f96743c | refs/heads/master | 2020-12-26T18:47:19.358359 | 2014-03-24T19:12:55 | 2014-03-24T19:12:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,611 | h | boundary.h |
#pragma once
#include <armadillo>
using namespace std;
using namespace arma;
namespace kMC
{
class KMCSolver;
class Site;
class Boundary
{
public:
Boundary(const uint dimension, const uint orientation, const uint type);
virtual ~Boundary();
const uint type;
virtual uint transformCoordinate(const int xi) const
{
return (((xi >= (int)span()) || (xi < 0)) ? BLOCKED_COORDINATE : xi);
}
virtual int getDistanceBetween(int x1, int x2)
{
return x1 - x2;
}
virtual void update() = 0;
virtual void initialize() = 0;
virtual void finalize() {}
void setupBoundarySites();
void distanceFromSite(const Site * site, int & dxi, bool abs = false);
static bool isBlocked(const uint xi)
{
return (xi == BLOCKED_COORDINATE);
}
static bool isBlocked(const uint xi, const uint yi, const uint zi)
{
return isBlocked(xi) || isBlocked(yi) || isBlocked(zi);
}
static bool isCompatible(const int type1, const int type2, bool reverse = true);
static umat allBoundariesAs(const int boundaryType)
{
return zeros<umat>(3, 2) + boundaryType;
}
static void setMainSolver(KMCSolver * m_solver);
static void clearAll()
{
m_currentBoundaries.clear();
m_solver = NULL;
}
enum BoundaryTypes
{
Periodic,
Edge,
Surface,
ConcentrationWall
};
const static uint & NX();
const static uint & NY();
const static uint & NZ();
static uint N(const uint i);
static void setupCurrentBoundaries(const uint x, const uint y, const uint z);
static const Boundary* currentBoundaries(const uint i)
{
return m_currentBoundaries.at(i);
}
const uint & orientation() const
{
return m_orientation;
}
private:
static uint BLOCKED_COORDINATE;
static KMCSolver * m_solver;
const uint m_dimension;
const uint m_orientation;
vector<Site*> m_boundarySites;
protected:
static KMCSolver * solver()
{
return m_solver;
}
static void setupLocations(const uint x, const uint y, const uint z, uvec3 &loc);
static vector<const Boundary*> m_currentBoundaries;
vector<Site*> & boundarySites()
{
return m_boundarySites;
}
uint span() const
{
return N(m_dimension);
}
const uint & dimension() const
{
return m_dimension;
}
enum Dimensions
{
X,
Y,
Z
};
enum Orientations
{
Near,
Far
};
};
}
|
26a298b84d266199161832df6b7fdecd8890582e | f5a3e2fcfe01bfe95d125a903c0af454c1b9cdd6 | /MyTableView.cpp | afb7f5f2fc212f3250337694f3cd7b75f8ec64e8 | [] | no_license | congchenutd/congchenmywords | 11418c97d3d260d35766cdfbb9968a54f569fad7 | 29fd31f7e7a99b17fe789e9d97879728ea9dbb80 | refs/heads/master | 2021-01-02T09:08:59.667661 | 2011-02-21T02:05:05 | 2011-02-21T02:05:05 | 32,358,808 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,418 | cpp | MyTableView.cpp | #include <QtSql/QSqlQuery>
#include <QtGui>
#include "MyTableView.h"
MyTableView::MyTableView(QWidget *parent) : QTableView(parent) {}
MyTableView::~MyTableView() {
saveSectionSizes();
}
void MyTableView::loadSectionSizes()
{
QSqlQuery query;
query.exec(tr("SELECT section, size FROM SectionSizes WHERE tableName = \'%1\'")
.arg(tableName));
while(query.next())
sizes[query.value(0).toInt()] = query.value(1).toDouble();
}
void MyTableView::saveSectionSizes()
{
if(horizontalHeader()->count() == 0)
return;
QSqlQuery query;
query.exec(tr("DELETE FROM SectionSizes WHERE tableName = \'%1\'").arg(tableName));
for(int i=0; i<horizontalHeader()->count(); ++i)
query.exec(tr("INSERT INTO SectionSizes VALUES(\'%1\', %2, %3)")
.arg(tableName)
.arg(i)
.arg((float)horizontalHeader()->sectionSize(i) / width()));
}
void MyTableView::slotSetSectionSizes(int section, int /*oldSize*/, int newSize) {
sizes[section] = (float)newSize / width();
}
void MyTableView::setTableName(const QString& table)
{
if(!tableName.isEmpty() && table != tableName)
saveSectionSizes(); // save last table
tableName = table;
loadSectionSizes();
slotResizeSections();
}
void MyTableView::slotResizeSections()
{
disconnect(horizontalHeader(), SIGNAL(sectionResized(int, int, int)),
this, SLOT(slotSetSectionSizes(int, int, int)));
resizeSections(sizes);
connect(horizontalHeader(), SIGNAL(sectionResized(int, int, int)),
this, SLOT(slotSetSectionSizes(int, int, int)));
}
void MyTableView::resizeSections(Map& map)
{
// goes wrong when the program is still loading
if(map.size() < 7) // very ugly, temporary solution
return;
int lastNoneZero;
for(lastNoneZero=map.size()-1; lastNoneZero>=0 && map[lastNoneZero]==0; --lastNoneZero)
;
for(size_t section=0; section<map.size(); ++section)
{
if(map[section] == 0)
hideColumn(section);
else
{
showColumn(section);
if(section != lastNoneZero) // ignore last non-0 section
setColumnWidth(section, map[section] * width());
}
}
}
void MyTableView::resizeEvent(QResizeEvent* event)
{
slotResizeSections();
QTableView::resizeEvent(event);
}
void MyTableView::mousePressEvent(QMouseEvent* event)
{
QTableView::mousePressEvent(event);
if(event->button() == Qt::MidButton)
emit midClicked();
}
|
b1211c7223705f3b6367eca584ca421602ee3f3e | 57eda1247d0165ac9a542b083a48f1d4fde47d1d | /Detours/XFileMonitor/XFileMonitor.Hook/XFileMonitor.Hook.cpp | e4110f016ed4605007527de0dad87edf2af3e534 | [] | no_license | DjPasco/Mag | 44604299a1245ec6f650cd25eaabc1659b3de33c | ba2ed7b1b2b72695a79281777e44eb0f7fa9c973 | refs/heads/master | 2021-08-16T10:08:00.512458 | 2020-03-04T12:43:29 | 2020-03-04T12:43:29 | 552,892 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,780 | cpp | XFileMonitor.Hook.cpp | #include "stdafx.h"
#include "XFileMonitor.Hook.h"
#include "..\detours\detours.h" // Detours header
#include <map> // std::map
#include <atlstr.h> // for CString
using namespace std;
// Just a way for us to track what the client did, eg open/close/write to a file
enum FileAction
{
File_Unknown = 0,
File_CreateAlways,
File_CreateNew,
File_OpenAlways,
File_OpenExisting,
File_TruncateExisting,
File_Write,
File_Read,
File_Close
};
// Just a way for us to track which API was called..
enum Win32API
{
API_CreateFile = 1,
API_WriteFile,
API_ReadFile,
API_CloseHandle
};
// This is the structure we'll send over to the GUI via WM_COPYDATA
struct FILECONTEXT
{
HANDLE File;
__int32 OriginalAPI;
};
map<HANDLE, CString> g_openFiles;
CRITICAL_SECTION g_CritSec; // Guards access to the collection (thread synch)
HINSTANCE g_hInstance = NULL; // This instance
// Function pointer to the original (undetoured) WriteFile API.
HANDLE (WINAPI * Real_CreateFile)
(LPCWSTR lpFileName,DWORD dwDesiredAcces, DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,HANDLE hTemplateFile) = CreateFileW;
// Function pointer to the original (undetoured) WriteFile API.
BOOL (WINAPI * Real_WriteFile)
(HANDLE hFile,LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite,
LPDWORD lpNumberOfBytesWritten,LPOVERLAPPED lpOverlapped) = WriteFile;
// Function pointer to the original (undetoured) ReadFile API.
BOOL (WINAPI *Real_ReadFile)
(HANDLE hFile,LPVOID lpBuffer,DWORD nNumberOfBytesToRead,
LPDWORD lpNumberOfBytesRead,LPOVERLAPPED lpOverlapped) = ReadFile;
// Function pointer to the original (undetoured) CloseHandle API.
BOOL (WINAPI * Real_CloseHandle)(HANDLE hObject) = CloseHandle;
// Transfer some textual data over to the GUI
void Transmit(FileAction action, Win32API sourceAPI, HANDLE hFile, LPCWSTR text)
{
HWND hWnd = ::FindWindow(NULL, L"Coding the Wheel - XFileMonitor v1.0");
if (!hWnd)
return;
COPYDATASTRUCT cds;
::ZeroMemory(&cds, sizeof(COPYDATASTRUCT));
cds.dwData = action;
cds.cbData = sizeof(FILECONTEXT) + ((wcslen(text)+1) * 2);
// Allocate the outgoing array
LPBYTE pOutData = new BYTE[cds.cbData];
// Place a HANDLEANDTEXT structure at the front of the array
FILECONTEXT ht;
ht.File = hFile;
ht.OriginalAPI = sourceAPI;
memcpy(pOutData, &ht, sizeof(FILECONTEXT));
// Place the text immediately following the structure
wcscpy((LPWSTR)(pOutData + sizeof(FILECONTEXT)), text);
// Send it off
cds.lpData = pOutData;
::SendMessage(hWnd, WM_COPYDATA, (WPARAM)::GetDesktopWindow(), (LPARAM)&cds);
delete [] pOutData;
}
// Check the first N bytes of data to see if they fall within printable ranges
// for Unicode character data. Quick and dirty and needs work.
bool IsUnicodeText(LPCWSTR buffer, int testLength)
{
int validChars = 0;
for (int index = 0; index < testLength; index++)
{
wchar_t c = buffer[index];
if (c < 0 || !(iswprint(c) || iswspace(c)))
return false;
}
return true;
}
// Check the first N bytes of data to see if they fall within printable ranges
// for ASCII/MBCS character data. Quick and dirty.
bool IsAsciiText(LPCSTR buffer, int testLength)
{
int validChars = 0;
for (int index = 0; index < testLength; index++)
{
char c = buffer[index];
if (c < 0 || !(isprint(c) || isspace(c)))
return false;
}
return true;
}
// Figure out if this is a binary file based on some common binary file extensions
// Quick and dirty.
bool IsBinaryFile(CString& file)
{
int indexOfExtension = file.ReverseFind(L'.');
if (indexOfExtension > -1)
{
CString sExt = file.Mid(indexOfExtension);
return (sExt == L".dll" || sExt == L".exe" || sExt == L".bmp" ||
sExt == L".png" || sExt == L".gif" || sExt == L".ico" ||
sExt == L".jpg" || sExt == L".jpeg" || sExt == L".mp3" ||
sExt == L".drv" || sExt == L".wmp" || sExt == L".ra");
}
return false;
}
// Our custom version of the CreateFile Windows API.
// http://msdn.microsoft.com/en-us/library/aa363858.aspx
HANDLE WINAPI Mine_CreateFile(LPCWSTR lpFileName,DWORD dwDesiredAccess,
DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecAttr,
DWORD dwCreateDisp, DWORD dwFlagsAttr,HANDLE hTemplate)
{
// First, all the original CreateFile provided by the operating system.
HANDLE hFile = Real_CreateFile(lpFileName,dwDesiredAccess,dwShareMode,lpSecAttr,
dwCreateDisp,dwFlagsAttr,hTemplate);
if (lpFileName && hFile)
{
CString sFileName = lpFileName;
if (!sFileName.IsEmpty())
{
// Store the handle/filename...
::EnterCriticalSection(&g_CritSec);
g_openFiles.insert(pair<HANDLE, CString>(hFile, sFileName));
::LeaveCriticalSection(&g_CritSec);
// Convert from creation disposition to our enumeration vals
FileAction fa;
switch(dwCreateDisp)
{
case CREATE_ALWAYS: fa = File_CreateAlways; break;
case CREATE_NEW: fa = File_CreateNew; break;
case OPEN_ALWAYS: fa = File_OpenAlways; break;
case OPEN_EXISTING: fa = File_OpenExisting; break;
case TRUNCATE_EXISTING: fa = File_TruncateExisting; break;
default: fa = File_Unknown; break;
}
// Send a notification off to the GUI
Transmit(fa, API_CreateFile, hFile, lpFileName);
}
}
return hFile;
}
// Our ReadFile and WriteFile detours both call this function to handle the buffer data
// and transmit it off to the GUI.
void ReadOrWriteFile(HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytes, bool isRead)
{
if (!hFile || !lpBuffer || !nNumberOfBytes)
return;
::EnterCriticalSection(&g_CritSec);
// Does the file being written to/read from exist in our map?
map<HANDLE, CString>::const_iterator iter = g_openFiles.find(hFile);
if (iter != g_openFiles.end())
{
CString msg, strFileName;
strFileName = (*iter).second;
strFileName.MakeLower();
// Check the file extension
if (IsBinaryFile(strFileName))
{
msg.Format(L"Target %s %d bytes %s '%s'\nBINARY\n\n", isRead ? L"read" : L"wrote",
nNumberOfBytes, isRead ? L"from" : L"to", (*iter).second);
}
// Check for ASCII text first..
else if (IsAsciiText((LPSTR)lpBuffer, min(100, nNumberOfBytes)))
{
// Convert from ASCII to Unicode text
LPWSTR lpTempBuffer = new WCHAR[nNumberOfBytes+1];
::ZeroMemory(lpTempBuffer, (nNumberOfBytes+1) * 2);
MultiByteToWideChar(CP_ACP, 0, (LPCSTR)lpBuffer, nNumberOfBytes, lpTempBuffer, nNumberOfBytes+1);
msg.Format(L"Target %s %d bytes %s '%s'\n%s\n\n", isRead ? L"read" : L"wrote",
nNumberOfBytes, isRead ? L"from" : L"to", (*iter).second, lpTempBuffer);
delete [] lpTempBuffer;
}
// If not ASCII, maybe it's Unicode?
else if (IsUnicodeText((LPWSTR)lpBuffer, min(100, nNumberOfBytes / 2)))
{
msg.Format(L"Target %s %d bytes %s '%s'\n", isRead ? L"read" : L"wrote",
nNumberOfBytes, isRead ? L"from" : L"to", (*iter).second);
msg.Append((LPWSTR)lpBuffer, nNumberOfBytes/2);
msg.Append(L"\n\n");
}
// Nope. Binary.
else
{
msg.Format(L"Target %s %d bytes %s '%s'\nBINARY\n\n", isRead ? L"read" : L"wrote",
nNumberOfBytes, isRead ? L"from" : L"to", (*iter).second);
}
// Notify the GUI.
Transmit(isRead ? File_Read : File_Write, isRead ? API_ReadFile : API_WriteFile, hFile, msg);
}
::LeaveCriticalSection(&g_CritSec);
}
// Our custom version of the WriteFile Windows API.
// http://msdn.microsoft.com/en-us/library/aa365747(VS.85).aspx
BOOL WINAPI Mine_WriteFile(HANDLE hFile,LPCVOID lpBuffer,DWORD nNumberOfBytesToWrite,LPDWORD lpNumberOfBytesWritten,LPOVERLAPPED lpOverlapped)
{
BOOL bSuccess = Real_WriteFile( hFile, lpBuffer, nNumberOfBytesToWrite, lpNumberOfBytesWritten, lpOverlapped);
ReadOrWriteFile(hFile, lpBuffer, nNumberOfBytesToWrite, false);
return bSuccess;
}
// Our custom version of the WriteFile Windows API.
// http://msdn.microsoft.com/en-us/library/aa365747(VS.85).aspx
BOOL WINAPI Mine_ReadFile(HANDLE hFile,LPVOID lpBuffer,DWORD nNumberOfBytesToRead,
LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped)
{
BOOL bSuccess = Real_ReadFile(hFile, lpBuffer, nNumberOfBytesToRead,lpNumberOfBytesRead, lpOverlapped);
ReadOrWriteFile(hFile, lpBuffer, *lpNumberOfBytesRead, true);
return bSuccess;
}
// Our custom version of the CloseHandle Windows API.
// http://msdn.microsoft.com/en-us/library/ms724211(VS.85).aspx
BOOL WINAPI Mine_CloseHandle(HANDLE hObject)
{
BOOL bSuccess = Real_CloseHandle(hObject);
::EnterCriticalSection(&g_CritSec);
map<HANDLE, CString>::iterator iter = g_openFiles.find(hObject);
if (iter != g_openFiles.end())
{
Transmit(File_Close, API_CloseHandle, hObject, L"");
g_openFiles.erase(iter);
}
::LeaveCriticalSection(&g_CritSec);
return bSuccess;
}
// DLL Entry Point. This DLL will be loaded in two places on any given run:
// in the XFileMonitor.Gui.EXE application, and in the target application's
// address space.
BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
if (::GetModuleHandle(L"XFILEMONITOR.GUI.EXE") == NULL)
{
InitializeCriticalSection(&g_CritSec);
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(PVOID&)Real_CreateFile, Mine_CreateFile);
DetourAttach(&(PVOID&)Real_CloseHandle, Mine_CloseHandle);
DetourAttach(&(PVOID&)Real_WriteFile, Mine_WriteFile);
DetourAttach(&(PVOID&)Real_ReadFile, Mine_ReadFile);
DetourTransactionCommit();
}
break;
case DLL_THREAD_ATTACH: break;
case DLL_THREAD_DETACH: break;
case DLL_PROCESS_DETACH:
if (::GetModuleHandle(L"XFILEMONITOR.GUI.EXE") == NULL)
{
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourDetach(&(PVOID&)Real_CreateFile, Mine_CreateFile);
DetourDetach(&(PVOID&)Real_CloseHandle, Mine_CloseHandle);
DetourDetach(&(PVOID&)Real_WriteFile, Mine_WriteFile);
DetourDetach(&(PVOID&)Real_ReadFile, Mine_ReadFile);
DetourTransactionCommit();
}
break;
}
return TRUE;
}
// Install the global window procedure hook, causing this DLL to be mapped
// into the address space of every process on the machine.
bool XFILEMONITORHOOK_API InstallHook(LPCWSTR targetExePath)
{
// Initialize some data structures...
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
ZeroMemory(&pi, sizeof(pi));
si.cb = sizeof(si);
// The following call loads the target executable with our DLL attached
BOOL bSuccess = DetourCreateProcessWithDll( targetExePath, NULL, NULL, NULL, TRUE,
CREATE_DEFAULT_ERROR_MODE | CREATE_SUSPENDED, NULL, NULL,
&si, &pi, "detoured.dll", "XFileMonitor.Hook.dll", NULL);
if (bSuccess)
ResumeThread(pi.hThread);
return TRUE == bSuccess;
}
|
b37ff489adc5238fa51358e2578ef2a86acd7d21 | a6b94244f9f9dee2a39536b12c7ef697dc9a81e7 | /src/hvpp/hvpp/lib/mm/win32/physical_memory_descriptor.cpp | 4218b359dd470bc4e0739406ceb8e79a570a965f | [
"BSD-2-Clause",
"LicenseRef-scancode-free-unknown",
"MIT"
] | permissive | can1357/hvpp | 7034c9b1a6460526ea3a4fe1e59b33c1debdec92 | 5994b48b4ae6fd0a8a31298265f1faab520cb581 | refs/heads/master | 2023-03-22T05:58:39.072516 | 2021-03-18T10:47:11 | 2021-03-18T10:47:11 | 347,962,044 | 3 | 2 | MIT | 2021-03-15T12:33:21 | 2021-03-15T12:33:21 | null | UTF-8 | C++ | false | false | 676 | cpp | physical_memory_descriptor.cpp | #include "hvpp/ia32/memory.h"
#include <ntddk.h>
using namespace ia32;
namespace mm::detail
{
void check_physical_memory(physical_memory_range* range_list, int range_list_size, int& count) noexcept
{
auto physical_memory_ranges = MmGetPhysicalMemoryRanges();
count = 0;
do
{
pa_t address = physical_memory_ranges[count].BaseAddress.QuadPart;
size_t size = physical_memory_ranges[count].NumberOfBytes.QuadPart;
if (!address && !size)
{
break;
}
range_list[count] = physical_memory_range(address, address + size);
} while (++count < range_list_size);
ExFreePool(physical_memory_ranges);
}
}
|
20503601a741d6856309a5219a5976bdcd4ad9a7 | 2a642208008c1ce2000431bea29f087d81d62abf | /Sanitizers/heap_buffer_overflow/heap_buffer_overflow_case.cpp | 1751fc1a689dff2854e162c1792e0ba47adfc6dc | [
"Apache-2.0"
] | permissive | anastasiak2512/basicDemo | 563308f7a012623f832caa9cfad59854e68164b5 | d43b16f79d5212eb60f1be8f7c16a86471d0da2f | refs/heads/main | 2023-08-07T17:38:28.408710 | 2023-07-28T07:14:09 | 2023-07-28T07:14:09 | 72,375,534 | 10 | 16 | NOASSERTION | 2023-07-28T07:14:10 | 2016-10-30T21:06:28 | C++ | UTF-8 | C++ | false | false | 163 | cpp | heap_buffer_overflow_case.cpp | int main(int argc, char **argv) {
int *array = new int[100];
array[0] = 0;
int res = array[argc + 100]; // BOOM
delete [] array;
return res;
} |
d1210b8ecdd7838a5ff1b881f0d14ab793a265ae | 7df3c0ab727c202af4d3a41658729382a37543a1 | /Asteroids/Display.h | a1eb24d0d63045a66b1e68869ae111fee46507d6 | [] | no_license | Fulten/Asteroids | 78d56bc38a6fffe876a0bfe7fdbd86d670fcef4c | 8376f5fab29abdf44c5b0bb6b5363b796fcd66c1 | refs/heads/main | 2023-08-17T00:30:39.702260 | 2021-09-30T00:26:54 | 2021-09-30T00:26:54 | 411,853,546 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,496 | h | Display.h | #pragma once
#include <Windows.h>
#include <windowsx.h>
#include <d3d9.h>
#include <d3dx9.h>
#include <vector>
#include "Draw.h"
#pragma comment (lib, "d3d9.lib")
#pragma comment (lib, "d3dx9.lib")
#pragma comment (lib, "Winmm.lib")
class Display : public Draw
{
private:
int triCount, drawSize;
void InitTextures();
std::vector<CUSTOMVERTEX> vertices;//utilize a vector to allow the creation of dynamic objects
std::vector<int> textures;
protected:
LPDIRECT3D9 d3d;
LPDIRECT3DDEVICE9 d3ddev;
LPDIRECT3DVERTEXBUFFER9 v_buffer = NULL; // buffer for writing to graphics card
std::vector<LPDIRECT3DTEXTURE9> textureList; // texture list stores currently used textures
// draws a textured square with given parameters and assigns it to certices
void dTexSquare(float x1, float y1, float x2, float y2, bool reverse);
void dTexTile(float x, float y, float width, float hight);
void cleanD3D(); // clears out memeory for the deconstructor
public:
Display(HWND& hWnd, int dSize); // constructor initilizes direct 3d devices
~Display(); // deconstructor
void addTex(float x1, float y1, float width1, float hight1, int texture1); // adds a new textured square to the pipeline
void VecDraw(); // renders a target scene using colored vectors
void VecBuild(); // uses defined vertices to render a target scene
void TexDraw(); // renders our target scene
void TexBuild(); // using created vertices, loads them into graphics memory
};
|
7e518fe70b52b51dda2b13c776ad771df0307142 | b9687a5da36555d4f0868e6557311b2d84c3520e | /code/src/UIGraphic/BSplineBltProvider.h | 745b3b71314fb6a862f6e4b62c2be1ad6cec8776 | [] | no_license | zleesz/ui-with-lua | 7defbe35f740790270ab867bf96df72564a1db08 | df37ab532073f9cda29d2352f7068ea049a37f43 | refs/heads/master | 2016-09-05T13:53:22.076409 | 2014-08-23T08:44:56 | 2014-08-23T08:44:56 | 32,198,624 | 1 | 1 | null | null | null | null | GB18030 | C++ | false | false | 891 | h | BSplineBltProvider.h |
/********************************************************************
*
* Description : B-Spline的算法实现.
*
********************************************************************/
#ifndef _BSPLINE_BLT_PROVIDER_H_
#define _BSPLINE_BLT_PROVIDER_H_
#include "./BltProvider.h"
namespace Graphic
{
class BSplineBltProvider : public IBltProvider
{
public:
BSplineBltProvider();
virtual ~BSplineBltProvider();
public:
//拉伸
virtual Bitmap* Stretch(Bitmap& src,long newWidth,long newHeight);
virtual void Stretch(Bitmap& src,Bitmap& dest);
protected:
static float BSpline(const float x);
protected:
BSplineBltProvider(const BSplineBltProvider& rhs) {return;}
BSplineBltProvider& operator=(const BSplineBltProvider& rhs) {return *this;}
};
}//namespace BaseGraphic
#endif //_BSPLINE_BLT_PROVIDER_H_ |
b583a95eee2366fe3f81804b5a3c88fedf847614 | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/a5/612738047ff3a5/main.cpp | 4dc36ff6fa12e197c014c4b3af8e77c3ecf22cd0 | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 212 | cpp | main.cpp | #include <functional>
#include <iostream>
#include <memory>
class A {};
class B : public A{};
int main (){
B b;
if (std::is_base_of<A,decltype(b)>::value){
std::cout<<"b can be up-cast to A*";
}
return 0;
}
|
4e2c8b8aeb98db57ce1563c356efb0e3a4146abe | 3fdfbf165b679784edad2d1097a32f7acc610b14 | /AdditionalApps/BlinkToRadio/BlinkToRadio.cpp | f4d755ff6d19ea04a58eddeef0e1cfa4a790ed79 | [
"MIT"
] | permissive | mdsaifalam96/Edu-hoc | 5f46a04eb03c1aa4384cd07ac36976dae9c269c2 | c5eda698adf66d7572a1a34a50c6216ecc944a10 | refs/heads/master | 2020-07-05T13:30:11.600462 | 2017-10-11T12:24:25 | 2017-10-11T12:24:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,478 | cpp | BlinkToRadio.cpp | #include <Arduino.h>
#include "RF12.h"
#include "RadioUtils.h"
#include "SerialUtils.h"
#include <EEPROM.h>
#include "../common.h"
const byte RF12_NORMAL_SENDWAIT = 0;
RadioUtils ru = RadioUtils();
SerialUtils su = SerialUtils(SERIAL_FREQUENCY);
long counter; //
int msgCounter = 0;
int nodeID = 0;
int groupID = 0;
int parentID = 0;
char payload[MAX_MESSAGE_LENGTH] = "";
String message = "";
boolean even = false;
void setup() {
Serial.begin(SERIAL_FREQUENCY);
nodeID = EEPROM.read(NODE_ID_LOCATION);
groupID = EEPROM.read(GROUP_ID_LOCATION);
parentID = EEPROM.read(PARENT_ID_LOCATION);
rf12_initialize( nodeID , FREQUENCY, groupID);
// initialize digital pin 13 as an output.
pinMode(9, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
if(counter % 10 == 0){
byte hdr = 0;
//counter to message
//sprintf(payload, "%d", counter);
//send counter broadcast
ru.setBroadcast(&hdr);
ru.resetAck(&hdr);
rf12_sendNow(0, &counter, sizeof counter);
rf12_sendWait(RF12_NORMAL_SENDWAIT);
su.print("new message send: ", debug);
su.println(counter, debug);
}
//increment counter
counter++;
if (rf12_recvDone()) {
if(even){
digitalWrite(9, HIGH); // turn the LED on (HIGH is the voltage level)
} else {
digitalWrite(9, LOW); // turn the LED off by making the voltage LOW
}
even = !even;
rf12_recvDone();
}
delay(10);
} |
c1e786cce0637f1c4758df179e72d4fd0d2e8537 | 56f2101e44cc4145761ca9e8fcebc8a931aae04e | /20-Inserting-a-Node-Into-a-Sorted-Doubly-Linked-List.cpp | d1a64719cbd141e9baeee364d3b9460bf9c8f5cf | [] | no_license | dvernon5/HackerRank-Data-Structures-Solutions | 492f8aac3cdf51903511f2bf189e60e1691bd865 | 348396d15c56984eac44246e4c0cc41cde975f78 | refs/heads/main | 2023-07-08T23:12:37.104948 | 2023-06-30T04:43:27 | 2023-06-30T04:43:27 | 306,916,698 | 1 | 0 | null | 2020-10-24T15:48:55 | 2020-10-24T15:46:48 | null | UTF-8 | C++ | false | false | 1,878 | cpp | 20-Inserting-a-Node-Into-a-Sorted-Doubly-Linked-List.cpp | /*
* Complete the 'sortedInsert' function below.
*
* The function is expected to return an INTEGER_DOUBLY_LINKED_LIST.
* The function accepts following parameters:
* 1. INTEGER_DOUBLY_LINKED_LIST llist
* 2. INTEGER data
*/
/*
* For your reference:
*
* DoublyLinkedListNode {
* int data;
* DoublyLinkedListNode* next;
* DoublyLinkedListNode* prev;
* };
*
*/
DoublyLinkedListNode* sortedInsert(DoublyLinkedList* llist, int data) {
DoublyLinkedListNode* headNode = llist
DoublyLinkedListNode* newNode = nullptr;
if (llist == nullptr)
{
newNode = (DoublyLinkedListNode*)calloc(0, sizeof(DoublyLinkedListNode));
newNode->data = data;
newNode->prev = nullptr;
newNode->next = nullptr;
headNode = newNode;
} else if (llist != nullptr) {
while (llist->data < data && llist->next != nullptr)
{
llist = llist->next;
}
if (llist == headNode)
{
newNode = (DoublyLinkedListNode*)calloc(0, sizeof(DoublyLinkedList));
newNode->data = data;
newNode->prev = nullptr;
newNode->next = llist;
llist->prev = newNode;
headNode = newNode;
} else if (data < llist->data) {
llist = llist->prev;
newNode = (DoublyLinkedListNode*)calloc(0, sizeof(DoublyLinkedList));
newNode->data = data;
newNode->prev = llist->prev;
newNode->next = llist;
llist->next->prev = newNode;
llist->next = newNode;
} else {
newNode = (DoublyLinkedListNode*)calloc(0, sizeof(DoublyLinkedListNode));
newNode->data = data;
newNode->prev = llist;
newNode->next = llist->next;
llist->next = newNode;
}
}
return headNode;
}
|
ef24f4862d972aeaf3b50d24209d45341c2bd8ac | b15ab3ad3d39756f53e82fea9efd406ff9ac8cfd | /TheGame/Resource/GoldResource.cpp | 70055d552455759e2f3adb8f73fefa898f3c8f3a | [] | no_license | Memhao/ProjectCPP | 6ed8728c3e7f7291a9c957c8d5d3757bb8f1eba7 | 17b93b5a4062a2bbf52743bd60365a7f86b0ec15 | refs/heads/master | 2021-01-11T02:31:31.431044 | 2016-10-14T20:06:43 | 2016-10-14T20:06:43 | 70,926,237 | 1 | 0 | null | 2016-10-14T20:06:44 | 2016-10-14T16:06:55 | C++ | UTF-8 | C++ | false | false | 220 | cpp | GoldResource.cpp | /*
* GoldResource.cpp
*
* Created on: Oct 14, 2016
* Author: xander
*/
#include "GoldResource.hpp"
GoldResource::GoldResource(unsigned short amount):IResource(amount)
{
}
GoldResource::~GoldResource()
{
}
|
2e4c6b173213b8deb2af69968956d04010ebc6a2 | c5a03277204cfb9f73023c371d74e145649f5eb9 | /code/pp.cpp | e8f64de6feeca72efbd3c3d5603ac79eac4748cf | [] | no_license | manishkeltton/newrepo | 093cdc1375c08844cb240d29027a3f365ed49c9b | 5f43934505869ad77781f63df64b8f5983a9ef20 | refs/heads/master | 2022-12-30T05:07:05.442018 | 2020-10-14T13:52:57 | 2020-10-14T13:52:57 | 285,295,105 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 935 | cpp | pp.cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
int T;
cin>>T;
while(T--){
int i,N;
cin>>N;
int ar[N];
for(i=0;i<N;i++)
cin>>ar[i];
int count=1;
if(N<6){
int p=ar[N-1];
int x=0;
sort(ar,ar+N-1);
/*for(i=0;i<N;i++)
{
if(p>=ar[i])
{
x=0;
break;
}
else{
x=1;
}
}*/
if(ar[0]>ar[N-1]){
count++;
}
}
else{
int Q=N-5;
int a=0;
int b=5;
while(Q--){
int p=ar[b];
int x=0;
for(i=a;i<a+5;i++){
if(p>ar[i]){
x=0;
break;
}
else{
x=1;
}
}
a++;
b++;
if(x==1)
count++;
}
}
cout<<count<<endl;
}
return 0;
}
|
de1360e9e4e9103d450c1d04c63a52918af80886 | 65b4c2de9b7887cd45af33824054ac722f23237d | /OAST/Simulation.cpp | 52bfba5d49a099be266102b1c8ace02d035180a1 | [] | no_license | Niveri/OAST | 4d5c352d5a64f55ad6305da859c6e9a285753ec2 | 3a0ef98b2fabb3bca6d5dbc700c9e2d258e259c7 | refs/heads/master | 2023-02-06T05:50:34.288910 | 2020-12-19T02:55:54 | 2020-12-19T02:55:54 | 310,021,729 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,713 | cpp | Simulation.cpp | #include "Simulation.h"
#include <random>
#include <iostream>
#include <math.h>
Simulation::Simulation(double lambda, int simulationTime, float ro) {
time = simulationTime;
currentTime = 0;
averageEventsNumber = lambda * simulationTime;
mi = lambda / ro;
this-> server = std::make_unique<Server>();
Events_list = StartEvents(lambda);
this->Imaginary_Events_list = std::make_shared<Events_List>();
}
std::shared_ptr<Events_List> Simulation::StartEvents(double lambda) {
std::vector<std::shared_ptr<Events>> IncomingEvents;
std::vector<std::shared_ptr<Events>> PastEvents;
std::random_device rd;
std::mt19937 gen(rd()); //uniform distrib
std::poisson_distribution<> p_distr(averageEventsNumber);
auto random_events_number = p_distr(gen);
std::exponential_distribution<> exp_dist(lambda);
std::uniform_real_distribution<double> unif(0, 1);
auto temp_arrival_time = 0;
for (int i = 0; i < random_events_number; i++) {
/*auto w = 1 - unif(gen);
auto expo = -log(w) / lambda;*/
auto rng = exp_dist(gen);
auto arrival_time = temp_arrival_time + rng;
temp_arrival_time = arrival_time;
IncomingEvents.push_back(std::make_shared<Events>(arrival_time, Events::EventType::Arrival, -1));
}
std::sort(IncomingEvents.begin(), IncomingEvents.end(),
[](std::shared_ptr<Events> const& a, std::shared_ptr<Events> const& b) -> bool
{return a->event_time > b->event_time; });
return std::make_unique<Events_List>(IncomingEvents, PastEvents);
}
std::vector<std::shared_ptr<Events>> Simulation::Simulate() {
while (!Events_list->getEventsList().empty()) {
eventHandler(Events_list->get());
}
return Events_list->getPastEventsList();
}
std::vector<std::shared_ptr<Events>> Simulation::SimulateContinousService() {
while (!Events_list->getEventsList().empty()) {
eventHandlerContinousService(Events_list->getContinousService(currentTime));
}
return Events_list->getPastEventsList();
}
void Simulation::eventHandler(std::shared_ptr<Events> event) {
switch (event->event_type) {
case Events::EventType::Arrival:
handleArrivalEvent(event);
break;
case Events::EventType::Departure:
currentTime = event->getTime();
handleDepartureEvent(event);
break;
}
}
void Simulation::eventHandlerContinousService(std::shared_ptr<Events> event) {
switch (event->event_type) {
case Events::EventType::Arrival:
handleArrivalEvent(event);
break;
case Events::EventType::Departure:
currentTime = event->getTime();
handleDepartureEvent(event);
break;
case Events::EventType::ImaginaryArrival:
handleImaginaryArrival(event);
break;
case Events::EventType::ImaginaryDeparture:
currentTime = event->getTime();
handleImaginaryDepartureEvent(event);
break;
}
}
void Simulation::handleArrivalEvent(std::shared_ptr<Events> event) {
//std::cout << "handle Arrival " << currentTime <<std::endl;
double serviceTime;
std::random_device rd;
std::mt19937 gen(rd()); //uniform distrib
std::exponential_distribution<> exp_dist(mi);
serviceTime = exp_dist(gen);
if (server->getNumberoFClients() == 0) {
server->addClient();
event->setClient(server->getMaxClients());
if (currentTime > event->getTime()) {
Events_list->put(std::make_shared<Events>(currentTime + serviceTime, Events::EventType::Departure, event->getClient()));
}
else {
Events_list->put(std::make_shared<Events>(event->getTime() + serviceTime, Events::EventType::Departure, event->getClient()));
}
}
else {
server->addClient();
event->setClient(server->getMaxClients());
}
}
void Simulation::handleImaginaryArrival(std::shared_ptr<Events> event) {
double serviceTime;
std::random_device rd;
std::mt19937 gen(rd());
std::exponential_distribution<> exp_dist(mi);
serviceTime = exp_dist(gen);
server->addClient();
event->setClient(server->getMaxClients());
std::shared_ptr<Events> ImaginaryEventDeparture = std::make_shared<Events>(currentTime + serviceTime, Events::EventType::ImaginaryDeparture, server->getMaxClients());
Imaginary_Events_list->putImaginary(ImaginaryEventDeparture);
Events_list->put(ImaginaryEventDeparture);
}
void Simulation::AddImaginaryEvent() {
std::shared_ptr<Events> ImaginaryEventArrival = std::make_shared<Events>(currentTime, Events::EventType::ImaginaryArrival, -1);
Imaginary_Events_list->putImaginary(ImaginaryEventArrival);
Events_list->put(ImaginaryEventArrival);
}
void Simulation::handleDepartureEvent(std::shared_ptr<Events> event) {
//std::cout << "handle Departure " << currentTime<< std::endl;
server->removeClient();
}
void Simulation::handleImaginaryDepartureEvent(std::shared_ptr<Events> event) {
//std::cout << "handle Departure " << currentTime<< std::endl;
server->removeClient();
}
|
784948505fd48442ccb0338e00503b0c0b3e85e1 | 161e93e6fbda56dae7c5dff7a1d186f06f02e084 | /chapter12/include/fcpp/macros.h | e50b1cfd28d103b3785f16b15594507ab8ed5ba2 | [
"BSD-3-Clause"
] | permissive | aharrison24/functional_cpp | 5f0a322d0e4e9656174b3467df43d9672ab1bf6f | 3e7087be82a854d05a7c6c4b25c4a511b65ce979 | refs/heads/master | 2020-05-14T14:47:30.152897 | 2019-08-13T19:27:31 | 2019-08-23T18:21:20 | 181,839,830 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 387 | h | macros.h | #pragma once
#define FWD(x) std::forward<decltype(x)>(x)
#define OVERLOAD_SET(f) \
[](auto&&... args) noexcept(noexcept(f(FWD(args)...))) \
->decltype(f(FWD(args)...)) { \
return f(FWD(args)...); \
}
|
8d91e7712c5efb7cf9187c5e75d907be45172d8f | efe30ed419e0cf1b16f43797cace46a68b6ce75f | /SOURCE/1bfs.cpp | 25cd8de84b2cae01a905c04a9cae0c5248858249 | [] | no_license | r03er7/algorithms | f64e0d9e1fc6dc6458edc4144ff251afd3502061 | e38a519ea81a8c92092c998c9959a356b044ca0e | refs/heads/master | 2020-03-27T03:39:13.239842 | 2018-08-23T18:55:06 | 2018-08-23T18:55:06 | 145,878,849 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,508 | cpp | 1bfs.cpp | #include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <set>
#include <list>
#include <stack>
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
typedef vector<int> VI;
typedef long long LL;
#define FOR(x, b, e) for(int x = b; x <= (e); ++x)
#define FORD(x, b, e) for(int x = b; x >= (e); --x)
#define REP(x, n) for(int x = 0; x < (n); ++x)
#define VAR(v, n) __typeof(n) v = (n)
#define ALL(c) (c).begin(), (c).end()
#define SIZE(x) ((int)(x).size())
#define FOREACH(i, c) for(VAR(i, (c).begin()); i != (c).end(); ++i)
#define PB push_back
#define ST first
#define ND second
int const M=8;//131072;
#define INF 1000000000 //nieskończoność
#define MAX 100000 //maksymalna liczba wierzchołków
using namespace std;
vector <int> V[MAX];
int s[MAX],t[MAX]; //t[]-odległość, s[]-przodek
int a,b,n,m; //n-wierzchołków, m-krawędzi
void BFS(int vs){
REP(i,n) s[i]=t[i]=-1;//FOREACH(it,V) t[*it]=-1;
t[vs]=0;
int qu[n],b,e;//FIFO SIZE(G)
qu[b=e=0]=vs;
while(b<=e){
vs=qu[b++];
FOREACH(it,V[vs]) if(t[*it]==-1){
t[qu[++e]=*it]=t[vs]+1;
s[*it]=vs;
}
}
}
void buildV(){
scanf("%d %d",&n,&m);
REP(i,m){
scanf("%d %d",&a,&b);
V[a].PB(b);
V[b].PB(a); //graf nieskierowany
}
}
void VVrite(){
REP(i,n)
if(t[i]==-1) printf("%d. brak ścieżki\n",i);
else printf("%d. %d %d\n",i,t[i],s[i]);
}
int main(){
buildV();
BFS(1);
VVrite();
return 0;
}
|
6265c59d39e3c7a02162a48786c4e0dd002ff618 | 86f8019eabea54665bf709725aaf7b2967206058 | /engine/calculators/source/PacificationCalculator.cpp | 5d6b4249ded19a0a51964b27f1bea6103d5bf25f | [
"MIT",
"Zlib"
] | permissive | cleancoindev/shadow-of-the-wyrm | ca5d21a0d412de88804467b92ec46b78fb1e3ef0 | 51b23e98285ecb8336324bfd41ebf00f67b30389 | refs/heads/master | 2022-07-13T22:03:50.687853 | 2020-02-16T14:39:43 | 2020-02-16T14:39:43 | 264,385,732 | 1 | 0 | MIT | 2020-05-16T07:45:16 | 2020-05-16T07:45:15 | null | UTF-8 | C++ | false | false | 2,239 | cpp | PacificationCalculator.cpp | #include "PacificationCalculator.hpp"
const int PacificationCalculator::MAX_PCT_CHANCE_PACIFY_MUSIC = 90;
const int PacificationCalculator::CHARMS_BONUS = 25;
// The chance to pacify musically is:
//
// The musician's music score
// + half the musician's level
// + half the musician's charisma
// - the opponent's music score
// - half the opponent's level
// - half the opponent's willpower
// + charms bonus, if specified
// + applicable item status bonus or penalty
int PacificationCalculator::calculate_pct_chance_pacify_music(CreaturePtr music_creature, CreaturePtr fov_creature, bool charms_creature, const ItemStatus item_status) const
{
int pct_chance_pacify = 0;
if (music_creature != nullptr && fov_creature != nullptr)
{
int music_val = music_creature->get_skills().get_value(SkillType::SKILL_GENERAL_MUSIC);
int music_lvl = music_creature->get_level().get_current() / 2;
int music_cha = music_creature->get_charisma().get_current() / 2;
int opp_music = fov_creature->get_skills().get_value(SkillType::SKILL_GENERAL_MUSIC);
int opp_lvl = fov_creature->get_level().get_current() / 2;
int opp_will = fov_creature->get_willpower().get_current() / 2;
int charms = charms_creature ? CHARMS_BONUS : 0;
int status = get_item_status_bonus(item_status);
pct_chance_pacify = music_val
+ music_lvl
+ music_cha
- opp_music
- opp_lvl
- opp_will
+ charms
+ status;
}
pct_chance_pacify = std::max<int>(pct_chance_pacify, 0);
return std::min<int>(pct_chance_pacify, MAX_PCT_CHANCE_PACIFY_MUSIC);
}
int PacificationCalculator::get_item_status_bonus(const ItemStatus status) const
{
int bonus = 0;
switch (status)
{
case ItemStatus::ITEM_STATUS_CURSED:
bonus = -20;
break;
case ItemStatus::ITEM_STATUS_BLESSED:
bonus = 20;
break;
case ItemStatus::ITEM_STATUS_UNCURSED:
default:
bonus = 0;
break;
}
return bonus;
}
#ifdef UNIT_TESTS
#include "unit_tests/PacificationCalculator_test.cpp"
#endif
|
8b6eb6f16045cb9ffb64109f5e43ad27e76070f9 | df170b3b6de7d7291c141d13c40dc91116d1f24e | /include/PurplePiece.h | d94453a10c4ff590947a080f179f07e99bf016eb | [
"MIT"
] | permissive | naidzim/Camelot-Jr-solver | 50e40da24065cceeeecb041c61656d7488aecb85 | 51dc44268aac48956cf3c2d444067b623ec3166d | refs/heads/main | 2023-03-04T02:53:58.890377 | 2021-02-05T11:46:58 | 2021-02-05T11:46:58 | 300,652,489 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 247 | h | PurplePiece.h |
#ifndef PURPLE_PIECE
#define PURPLE_PIECE
#include "Piece.h"
using namespace std;
class PurplePiece : public Piece {
public:
PurplePiece();
PurplePiece(std::string name,int rotation,int ligne,int colonne);
};
#endif // PURPLE_PIECE
|
3ce2b1df7590991582c933d2d24beda6f3198f3e | 8a2fb4d3076f008db245efae540041fc3eace4d6 | /HawkUtil/HawkProtocolListener.h | ce0134d9bd978811d10c23b6d110ad3146103590 | [] | no_license | hawkproject/hawkproject | f536953ef6df199b2b93cee5672fa4a4cca23c36 | e781fd463f24e5a4c54cbd8c2bf34f4d36906ae4 | refs/heads/master | 2021-01-22T09:26:32.063606 | 2014-07-23T10:22:43 | 2014-07-23T10:22:43 | 13,612,604 | 6 | 5 | null | null | null | null | GB18030 | C++ | false | false | 885 | h | HawkProtocolListener.h | #ifndef HAWK_PROTOCOLLISTENER_H
#define HAWK_PROTOCOLLISTENER_H
#include "HawkProtocol.h"
namespace Hawk
{
/************************************************************************/
/* 消息监听器 */
/************************************************************************/
class UTIL_API HawkProtocolListener
{
public:
//构造
HawkProtocolListener();
//析构
virtual ~HawkProtocolListener();
//消息注册表
typedef map<ProtoType, ProtoType> ProtoTypeMap;
public:
//注册消息监听
virtual Bool MonitorProto(ProtoType iType);
//消息处理
virtual Bool OnProtocol(HawkProtocol* pProto);
//移除消息监听(参数为0表示移除所有)
virtual Bool AbandonProto(ProtoType iType = 0);
protected:
//注册的消息映射
ProtoTypeMap m_mProtoType;
};
}
#endif
|
38e75fa5022230e7ef27ca37e58a2ef7f418457e | 85ddc694b14538d3e2215c347b05b85d10bb145e | /Tax.h | a19efc84d9bd398665e96fd9c7442a9152c751e5 | [] | no_license | Equadex/Monopoly-game | 86b9857e91eb1aae4509245c5958010ca7a719b2 | 870d743f013607b461f84c1d72a9949c4e0ac378 | refs/heads/master | 2021-01-19T00:08:36.362993 | 2014-04-03T18:15:03 | 2014-04-03T18:15:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 822 | h | Tax.h | #include "Property.h"
#include "Street.h"
#include "Player.h"
#include "Question.h"
#include "Button.h"
#ifndef TAX_H
#define TAX_H
class Tax : public Property{
public:
Tax(int pos_x_1, int pos_x_2, int pos_y_1, int pos_y_2, int pos_ruta, std::string namn, int typ, int fee);
void pay(Player* visitor){ //Pay standrad fee
if(!visitor->pay(fee)) //Player pays, if player cannot, player is defeated
visitor->defeated(NULL, fee);
}
void create_income_tax_question(int pos_x_in, int pos_y_in, ALLEGRO_BITMAP* button, ALLEGRO_BITMAP* question);
Question* get_question() const{
return choose;
}
void set_question_active(bool active){
choose->set_active(active);
}
void pay_fee(Player* visitor, Property** tomter); //Pay income tax 10 %
private:
int fee;
Question* choose;
Button** temp_buttons;
};
#endif |
e87a912e5c0bd4079a89cca39fe3aa4e874a0ae1 | 5138837a0034d705693f86debb3c4d069e09d48c | /HW2A/solution/Large.h | 6751773330d2969a588553a16d11bcaee284420d | [] | no_license | mv123453715/CCU_2019_Object-oriented_Programming | f45bc68e929bb2fa6570086a50ca382ad553bba1 | 5e538db26a2aa0d2640e969f1eba5576100764ac | refs/heads/master | 2022-11-11T19:20:54.194984 | 2020-07-01T03:33:33 | 2020-07-01T03:33:33 | 276,267,301 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 342 | h | Large.h |
#ifndef Large_h
#define Large_h
#include <bits/stdc++.h>
using namespace std;
int Large( vector<int> &A){
int Large_num,i;
Large_num = A.at(0);
//find Large num
for (i = 1; i<A.size();i++){
if ( A.at(i) >Large_num )
Large_num = A.at(i);
}//for
return Large_num;
}//Large
#endif /* Large_h */ |
5863f2a2642c1bf2a860b953eb804f806d87ef2d | 9e91a22165d17ce25232700802abad9c666a612c | /Client/Codes/Blood.cpp | de4531d68cb5acc3d921d0ced71e9ae27ffcddd6 | [] | no_license | cezyr0511/Bless_DirectX | b3ad7937fb02da75dfd841fa91c714f4d4b1d035 | b65e334da590f73b0e8982abc469065e2e6226a0 | refs/heads/main | 2023-03-20T20:44:52.431038 | 2021-03-16T12:48:15 | 2021-03-16T12:48:15 | 348,341,647 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 3,974 | cpp | Blood.cpp | #include "stdafx.h"
#include "Blood.h"
#include "Export_Engine.h"
CBlood::CBlood(LPDIRECT3DDEVICE9 pGraphicDev)
: CEffect(pGraphicDev)
, m_pRendererCom(NULL)
, m_pTransformCom(NULL)
, m_pTextureCom(NULL)
, m_pBufferCom(NULL)
, m_pShaderCom(NULL)
, m_fFrame(0.f)
{
}
CBlood::~CBlood(void)
{
}
HRESULT CBlood::Ready_GameObject(_vec3 vPos)
{
if(FAILED(Ready_Component()))
return E_FAIL;
m_pTransformCom->Set_Infomation(Engine::CTransform::INFO_POSITION, vPos.x, vPos.y, vPos.z);
m_pTransformCom->Set_Infomation(Engine::CTransform::INFO_SCALE, 0.1f, 0.1f, 0.1f);
return S_OK;
}
_int CBlood::Update_GameObject(const _float& fTimeDelta)
{
Engine::CGameObject::Update_GameObject(fTimeDelta);
m_fFrame += 17.f * fTimeDelta;
if(m_fFrame > 17.f)
return -1;
m_pRendererCom->Add_RenderList(Engine::CRenderer::RENDER_ALPHA, this);
Engine::_matrix matView;
D3DXMatrixIdentity(&matView);
m_pGraphicDev->GetTransform(D3DTS_VIEW, &matView);
// 뷰행렬을 받아옴
memset(&matView._41,0,sizeof(_vec3));
// 이동값 빼구
D3DXMatrixInverse(&matView, NULL, &matView);
// 역행렬
memcpy(&matView._41, m_pTransformCom->Get_vPos(), sizeof(_vec3));
float fScale[3];
fScale[0] = 0.1f;
fScale[1] = 0.1f;
fScale[2] = 0.1f;
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 4; ++j)
matView(i, j) *= fScale[i];
}
m_pTransformCom->Set_WorldMatrix(&matView, true);
return 0;
}
void CBlood::Render_GameObject(void)
{
LPD3DXEFFECT pEffect = m_pShaderCom->Get_EffectHandle();
if(NULL == pEffect)
return;
pEffect->AddRef();
_uint iNumPass = 0;
m_pTransformCom->SetUp_OnShader(pEffect, "g_matWorld");
_matrix matView, matProj;
m_pGraphicDev->GetTransform(D3DTS_VIEW, &matView);
m_pGraphicDev->GetTransform(D3DTS_PROJECTION, &matProj);
pEffect->SetMatrix("g_matView", &matView);
pEffect->SetMatrix("g_matProj", &matProj);
m_pTextureCom->SetUp_OnShader(pEffect, "g_BaseTexture", m_fFrame);
pEffect->Begin(&iNumPass, 0);
pEffect->BeginPass(1);
m_pBufferCom->Render_Buffer();
pEffect->EndPass();
pEffect->End();
Engine::Safe_Release(pEffect);
}
HRESULT CBlood::Ready_Component(void)
{
m_pRendererCom = (Engine::CRenderer*)Engine::Clone_Component(SCENE_STATIC, L"Component_Renderer");
if(NULL == m_pRendererCom)
return E_FAIL;
if(FAILED(Add_Component(Engine::CGameObject::TYPE_STATIC, L"Com_Renderer", m_pRendererCom)))
return E_FAIL;
m_pTransformCom = (Engine::CTransform*)Engine::Clone_Component(SCENE_STATIC, L"Component_Transform");
if(NULL == m_pTransformCom)
return E_FAIL;
if(FAILED(Add_Component(Engine::CGameObject::TYPE_DYNAMIC, L"Com_Transform", m_pTransformCom)))
return E_FAIL;
m_pTextureCom = (Engine::CTexture*)Engine::Clone_Component(SCENE_STAGE, L"Component_Texture_Blood01");
if(NULL == m_pTextureCom)
return E_FAIL;
if(FAILED(Add_Component(Engine::CGameObject::TYPE_STATIC, L"Com_Texture", m_pTextureCom)))
return E_FAIL;
m_pBufferCom = (Engine::CRect_Texture*)Engine::Clone_Component(SCENE_STATIC, L"Component_Buffer_RectTexture");
if(NULL == m_pBufferCom)
return E_FAIL;
if(FAILED(Add_Component(Engine::CGameObject::TYPE_STATIC, L"Com_Buffer", m_pBufferCom)))
return E_FAIL;
m_pShaderCom = (Engine::CShader*)Engine::Clone_Component(SCENE_STAGE, L"Component_Shader_Effect");
if(NULL == m_pShaderCom)
return E_FAIL;
if(FAILED(Add_Component(Engine::CGameObject::TYPE_STATIC, L"Com_Shader", m_pShaderCom)))
return E_FAIL;
return S_OK;
}
CBlood* CBlood::Create(LPDIRECT3DDEVICE9 pGraphicDev, _vec3 vPos)
{
CBlood* pInstance = new CBlood(pGraphicDev);
if(FAILED(pInstance->Ready_GameObject(vPos)))
{
MSG_BOX("CBlood Created Failed");
::Safe_Release(pInstance);
}
return pInstance;
}
void CBlood::Free(void)
{
Engine::Safe_Release(m_pRendererCom);
Engine::Safe_Release(m_pTransformCom);
Engine::Safe_Release(m_pTextureCom);
Engine::Safe_Release(m_pBufferCom);
Engine::Safe_Release(m_pShaderCom);
Engine::CGameObject::Free();
}
|
2d9af5600f87c20a9ed95ec8f39022ea556b9b39 | 2340859cdfd21ecf9bf5dd3d4dc3304b89ebf115 | /dogpack-developer/lib/4d/cart/DogStateCart4.h | 365f4ba2ee3da03e1e9564246e2ba56e2a1b2717 | [] | no_license | smoe1/ThesisCode | 56c97c440f7f8182f5be7dba76848741dcf9a9d6 | bd535bc99d0add16787524bd2ac5c4a53f2d86ee | refs/heads/master | 2021-01-24T07:18:55.455846 | 2017-06-07T02:15:40 | 2017-06-07T02:15:40 | 93,338,238 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,117 | h | DogStateCart4.h | #ifndef DogStateCart4_h
#define DogStateCart4_h
#include "DogState.h"
class dTensorBC4;
class dTensorBC5;
class dTensorBC6;
class DogSolverCart4;
struct DogStateCart4: public DogStateTB
{
private:
dTensorBC6* q;
dTensorBC6* aux;
private:
void init(int mx, int my, int mz, int mw);
DogStateCart4& operator=(const DogStateCart4& in); // disabled
DogSolverCart4& fetch_solver(){return (DogSolverCart4&) DogState::get_solver();}
protected:
virtual const char* get_classname(){return (const char*) "DogStateCart4";}
DogStateCart4(const DogStateCart4&in, CopyMode::Enum copyMode=CopyMode::DEEP);
public:
// Default constructor:
DogStateCart4(): q(NULL), aux(NULL) {};
// Destructor:
~DogStateCart4();
virtual DogState* clone(CopyMode::Enum copyMode)const
{ return new DogStateCart4(*this, copyMode); }
virtual void init();
virtual void copyfrom(const DogStateCart4& in);
virtual bool check_valid_state() const;
// Reverting to top level debug_check_condition().
// It looks like this was used once to check the posititivy of the
// function, which I beleive is now being checked elsewhere.
// (-DS, 3/27/2013).
// virtual bool debug_check_condition() const;
virtual void init_coarser_state(const DogStateCart4& in, int mx, int my, int mz, int mw);
// write restart frame and movie frames
virtual void write_output(int noutput) const;
virtual void write_frame(int nframe, const char* outputdir) const;
// read (restart) frame
virtual void read_frame(int nframe);
// accessors (fetch means write-access, get means read-access)
//
const dTensorBC6& get_q() const{return *q; }
const dTensorBC6& get_aux() const{return *aux;}
dTensorBC6& fetch_q() {return *q; }
dTensorBC6& fetch_aux() {return *aux;}
const DogStateCart4& get_solver()const
{return (DogStateCart4&) DogState::get_solver();}
// -- user "callbacks" -- //
//
// class methods with the virtual keyword have subclasses that can override
// these methods. In other words, EVERY subclass of this class will have
// these functions, and can override them.
// This function projects initial conditions onto aux and q.
virtual void InitState();
virtual void AfterInitState();
virtual void BeforeStage(double dt);
virtual void SetBndValues();
virtual void ConstructL();
virtual void ApplyLimiter();
virtual void AfterStage(double dt);
virtual void AfterReject(double dt);
virtual void AfterFullTimeStep(double dt);
virtual void ReportAfterStep() const;
};
// low-level methods to write and read state arrays
void WriteStateArray(const char* framedir, const char* varname,
const dTensorBC6& q, double t, int nframe);
double ReadStateArray(const char* dir, const char* varname,
dTensorBC6& q, int nstart);
#endif
|
5998171f18c04d4ecefe692705d30a1750a51aef | 4e9aa6d8635d6bfcbaeecbb9420ebdc4c4489fba | /QtTest/Dialog/Dialog/decision.h | 04895605bdc4795f49c86a2fdb639388e8d8c0d2 | [] | no_license | softwarekid/myexercise | 4daf73591917c8ba96f81e620fd2c353323a1ae5 | 7bea007029c4c656c49490a69062648797084117 | refs/heads/master | 2021-01-22T11:47:01.421922 | 2014-03-15T09:47:41 | 2014-03-15T09:47:41 | 18,024,710 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,224 | h | decision.h | #ifndef DECISION_H
#define DECISION_H
#include <cmath>
#include <qstring.h>
#include <QApplication>
#include <QObject>
#include <QtSql>
const double t=25;
const double Ctan=0.0002;
const double K_CH4 = 1.5;
const double kongqi_rho = 1.2;
const double ksai_on = 1;
const double ksai_jo = 0.025;
const double wz_Value_L = 10;
class Decision
{
public:
Decision();
virtual ~Decision();
double feliang_Q();
double chen_Q();
double wa_Q();
double xu_Q();
double hunhe_Q();
double yansuan_Q();
double fengzu_R();
QString display();
double Caculate();
double fengtongxishu();
double loufeng_P();
double fengjiQH();
void fengjixuanxing();
void WriteData(QString stl);
QString chouchuDisplay(QString strDisplay);
QString yaruDisplay(QString strDisplay);
QString hangdaoDisplay(QString strDisplay);
//private:
double zhayaoliang_Value_A;
double CO_Value_b;
double are_Value_S;
double lenth_Value_L;
double Yloufengxishu_Value_P;
double Cloufengxishu_Value_P;
double Yfengliang_Value_Q;
double Cfengliang_Value_Q;
double xu_Value_Q;
double wa_Value_Q;
double chen_Value_Q;
double Yfengzu_Value_R;
double Cfengzu_Value_R;
double Yzhijing_Value_D;
double Czhijing_Value_D;
double wasiyongchu_Value;
//double C_jin_CH4;
//double C_CH4;
double chanchen_G;
double zuigao_G;
double ji_G;
double Ybanjing_alpha;
double Cbanjing_alpha;
double Cksai_be;
double Yksai_be;
double ksai_in;
double Ybeita;
double Cbeita;
double YfengtongLth;
double YfengtongArea;
double Yfengtongjieshu_n;
double Yfengtong_K;
double Yfengtong_enta;
double Yevery_Value_R;
QString Ystlfengtongleixing;
QString YstljiekouMethod;
QString Ystlfengjileixing;
QString Yfengji;
double CfengtongLth;
double CfengtongArea;
double Cfengtongjieshu_n;
double Cfengtong_K;
double Cfengtong_enta;
double Cevery_Value_R;
QString stldriveMethod;
QString tongfengMethod;
QString Cstlfengtongleixing;
QString Cstlrukouyuanjiao;
QString CstljiekouMethod;
QString Cstlfengjileixing;
QString Cfengji;
private:
double Cfengji_Value_Q;
double Cfengji_Value_H;
double Yfengji_Value_Q;
double Yfengji_Value_H;
int fengtongleixingFlag;
double Yju_Value_L;
double Cju_Value_L;
//QString strDisplay;
};
#endif |
7bd561a8924f8e99d372365e1747d0203116b52c | 1f14b072bd1ed2d481b59a6b23cfa070ee194554 | /PinYinComboBox.cpp | 8d7365e9904e67ff4ae42fc65d4dec11d88ac505 | [] | no_license | congchenutd/congchencombobox | a305cc210b9af690746f48bb31de13e506a15011 | 69767939ddccd2c4c40615256d111fb453c8e9df | refs/heads/master | 2020-03-26T15:01:38.980505 | 2011-01-26T00:44:49 | 2011-01-26T00:44:49 | 32,358,805 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,653 | cpp | PinYinComboBox.cpp | #include "PinYinComboBox.h"
#include "GetPinYin.h"
#include <QKeyEvent>
#include <QSqlQuery>
PinYinComboBox::PinYinComboBox(QWidget *parent) : SetTextComboBox(parent)
{
setView(listView = new MyListView(this));
}
void PinYinComboBox::keyPressEvent(QKeyEvent* event)
{
showPopup();
setCurrentIndex(listView->search(event->text().at(0).toAscii()));
QComboBox::keyPressEvent(event);
}
void PinYinComboBox::loadFromTable(const QString& tableName, int column /*= 0*/)
{
clear();
QSqlQuery query;
query.exec("select * from " + tableName);
while(query.next())
addItem(query.value(column).toString());
}
void PinYinComboBox::sort()
{
QStringList strings;
for(int i=0; i<count(); ++i)
strings << itemText(i);
clear();
addItems(sortedChineseList(strings));
}
MyListView::MyListView(QWidget* parent) : QListView(parent)
{
lastChar = '\0';
current = -1;
}
void MyListView::keyPressEvent(QKeyEvent* event)
{
QAbstractItemModel* m = model();
QChar ch = event->text().at(0);
int row = search(ch.toAscii());
scrollTo(m->index(row, 0));
selectionModel()->select(m->index(0, 0), QItemSelectionModel::Clear);
selectionModel()->select(m->index(row, 0), QItemSelectionModel::Select |
QItemSelectionModel::Rows);
}
int MyListView::search(char ch)
{
if(ch != lastChar) // new search
{
results.clear();
lastChar = ch;
current = 0;
QAbstractItemModel* m = model();
for(int i=0; i<m->rowCount(); ++i)
if(getFirstPinYin(m->data(m->index(i, 0)).toString()) == ch)
results.push_back(i);
}
return results.empty() ? 0 : results[current++ % results.size()];
} |
f84f7d9b3d1a5dead22a39915e378c3667ee9f1d | 8d06e3dffd528788bcc09bc58fb790cb3f13196c | /Pxl/interface/pxl/core/FileFactory.hh | cda969731b03612458938c64920b5c84a25b1ae3 | [] | no_license | matt-komm/Pxl | ef29c13d0c0f3449a80cb1873c32cb586e848b36 | 4ad674a1965f368b7fb6b53d81bde50445507e08 | refs/heads/master | 2021-01-17T08:11:48.328055 | 2016-06-17T07:36:42 | 2016-06-17T07:36:42 | 32,524,457 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,457 | hh | FileFactory.hh | //-------------------------------------------
// Project: Physics eXtension Library (PXL) -
// http://vispa.physik.rwth-aachen.de/ -
// Copyright (C) 2009-2012 Martin Erdmann -
// RWTH Aachen, Germany -
// Licensed under a LGPL-2 or later license -
//-------------------------------------------
#ifndef PXL_FILE_FACTORY_HH
#define PXL_FILE_FACTORY_HH
#include "Pxl/Pxl/interface/pxl/core/macros.hh"
#include <map>
#include "Pxl/Pxl/interface/pxl/core/Id.hh"
#include "Pxl/Pxl/interface/pxl/core/File.hh"
namespace pxl
{
class FileProducerInterface;
class PXL_DLL_EXPORT FileFactory
{
private:
FileFactory();
std::map<std::string, const FileProducerInterface *> _Producers;
public:
static FileFactory& instance();
FileImpl *create(const std::string& id);
void registerProducer(const std::string& id,
const FileProducerInterface* producer);
void unregisterProducer(const FileProducerInterface* producer);
};
class FileProducerInterface
{
public:
virtual ~FileProducerInterface()
{
}
virtual FileImpl *create() const = 0;
};
template<class T>
class FileProducerTemplate: public FileProducerInterface
{
public:
void initialize(const std::string &schema)
{
FileFactory::instance().registerProducer(schema, this);
}
void shutdown()
{
FileFactory::instance().unregisterProducer(this);
}
FileImpl *create() const
{
return new T();
}
};
} // namespace pxl
#endif // PXL_IO_OBJECT_FACTORY_HH
|
535eb0070f31865aadd12a98711a73d3b590d718 | 5d7c35840914b45e13ee8a98e72ebe514e4a93a3 | /CS435-pa4-yangxqiao/src/FileReader.cpp | f0b8fad9a2be415cbe7d61e9489affa06ff2153e | [] | no_license | yangxqiao/CourseWork | 3388c74b2e4bdc2e236e07d717000af204cbb975 | 737f3c058080e525511aebc0601ee5e261ccf4c8 | refs/heads/master | 2020-12-04T19:54:04.283212 | 2020-01-05T09:21:35 | 2020-01-05T09:21:35 | 231,884,697 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,178 | cpp | FileReader.cpp | //
// FileReader.cpp
// pa3
//
// Created by Chelseaqiao on 10/20/19.
//
#include "FileReader.h"
#include <string>
#include <fstream>
#include <iostream>
FileReader::FileReader(std::string source){
std::ifstream::pos_type size;
// Open the file for input, in binary mode, and start ATE (at the end)
std::ifstream tempfile(source, std::ios::in|std::ios::binary|std::ios::ate);
if (tempfile.is_open())
{
size = tempfile.tellg(); // Save the size of the file
mcontent.reserve(static_cast<unsigned int>(size));
tempfile.close();
}
std::ifstream file(source);
if(file.is_open())
{
std::string newline;
std::getline(file, newline, '>');
std::getline(file, mheader, '\n');
char c;
while(static_cast<bool>(file.get(c)))
{
if(c != '\n' && c != '\r' && c != '\xff')
{
mcontent += c;
}
}
}
else{
std::cout << "Cannot open the file!" << std::endl;
}
file.close();
}
std::string FileReader::getHeader()
{
return mheader;
}
std::string FileReader::getContent()
{
return mcontent;
}
|
732810a6d6a22c681c88e814709d2042bbaa6791 | 6a863bdbd15dd769584235f07abdad9f715f2018 | /SDLTest/SDLTest/Scene.cpp | ae2a5f15ae987ed5fe80f5e8b28592195faa6cb7 | [] | no_license | ouerkakaChango/GLSDL | 9cea6abd1a19175b9b26081a15bc5cf0de97b8fa | 3c2b0cfa9e89d558e93db78938226ae37620f0d6 | refs/heads/master | 2022-11-25T07:29:39.809754 | 2020-07-26T11:37:01 | 2020-07-26T11:37:01 | 261,687,027 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,832 | cpp | Scene.cpp | #include "Scene.h"
#include "Drawable.h"
#include "Timeline.h"
#include "ShowAction.h"
#include "EndAction.h"
#include "SoundAction.h"
#include "FuncAction.h"
#include "Effect.h"
#include "God.h"
#include "SceneShaderImage.h"
#include "Condition.h"
Scene::Scene()
{
timeline_ = new Timeline;
}
Scene::~Scene()
{
}
void Scene::AddDrawable(Drawable* drawable)
{
if (drawable != nullptr)
{
drawable->SetOwnerScene(this);;
drawables_.push_back(drawable);
}
}
void Scene::AddDrawable(Drawable* drawable, bool bActive)
{
if (drawable != nullptr)
{
drawable->SetOwnerScene(this);
drawable->SetActive(bActive);
drawables_.push_back(drawable);
}
}
void Scene::AddEffect(Effect* effect)
{
if (effect != nullptr)
{
effects_.push_back(effect);
}
}
void Scene::Update(float deltaTime)
{
timeline_->Update(deltaTime);
for (auto& effect : effects_)
{
if (effect->GetActive())
{
effect->Update(deltaTime);
}
}
//渲染更新 (deprecated)
Render();
}
void Scene::Render()
{
for (auto& drawable : drawables_)
{
drawable->Render();
}
}
void Scene::Show(Drawable* drawable, float time , Effect* effect )
{
if (sceneColorShaderImg_ != nullptr)
{
drawable->SetSceneRT(sceneColorShaderImg_->GetRT());
}
auto showAction = new ShowAction(this, drawable);
showAction->name_ = drawable->name_+" ShowAction";
if (effect!=nullptr)
{
showAction->SetEffect(effect);
}
timeline_->AddAction(time, showAction);
}
void Scene::SetActive(bool active)
{
Activeable::SetActive(active);
if (sceneColorShaderImg_ != nullptr)
{
sceneColorShaderImg_->SetActive(active);
}
if (!active)
{//save state when close scene
SaveDrawableState();
}
if (active)
{
if (bFirstActive_)
{
for (auto& drawable : drawables_)
{
drawable->SetActive(active);
}
bFirstActive_ = false;
}
else
{//restore state when reopen scene
RestoreDrawableState();
}
}
else
{
for (auto& drawable : drawables_)
{
drawable->SetActive(false);
}
}
//??? 忘了为啥要这样了
if (active)
{
timeline_->Reset();
}
}
void Scene::SetAutoEnd(float time)
{
auto endAction = new EndAction;
timeline_->AddAction(time, endAction);
}
void Scene::AddSound(SoundEffect* sound, float time)
{
auto soundAction = new SoundAction(sound);
timeline_->AddAction(time, soundAction);
}
void Scene::AddCustomAction(float time, Func func)
{
auto funcAction = new FuncAction(func);
timeline_->AddAction(time, funcAction);
}
void Scene::ConditionShow(Drawable* drawable, Condition* condition)
{
condition->AddFunc(
[&,drawable]() mutable
{
Show(drawable, 0);
});
}
void Scene::SaveDrawableState()
{
for (auto& i : drawables_)
{
drawableStates_[i] = i->GetActive();
}
}
void Scene::RestoreDrawableState()
{
for (auto& i : drawables_)
{
i->SetActive(drawableStates_[i]);
}
} |
0ff73a58836f255694fc5104a99c693e4be006a3 | db4c4cd622795e0ac054920771f399905e0a12e0 | /src/server/server.cpp | 086f41f90bacf476b827a23fbb96c98bba9f4f82 | [] | no_license | ATM006/NobCno | 5f9ca3ab04e077b60dc9cb923c054b4276b68076 | 9a19bfb62800f472e30df5b5d3e247c353e4ed41 | refs/heads/master | 2021-08-30T16:08:47.381955 | 2017-12-18T15:19:06 | 2017-12-18T15:19:06 | 98,647,073 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,740 | cpp | server.cpp | #include "server.h"
#include "article.h"
#include "../log/log.h"
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/epoll.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <cstring>
#include <stdlib.h>
int server::m_count = 0;
/*
int setnonblocking( int fd )
{
int old_option = fcntl( fd, F_GETFL );
int new_option = old_option | O_NONBLOCK;
fcntl( fd, F_SETFL, new_option );
return old_option;
}*/
void server::running()
{
struct epoll_event events[MAXSIZE];
int nready = 0;
while(1)
{
nready = epoll_wait(this->epfd,events,MAXSIZE,-1);
if(nready > 0)
{
int i;
for(i = 0;i<nready;i++)
{
int tmpfd = events[i].data.fd;
if(tmpfd == m_sfd)//监听
{
struct sockaddr_in clientaddr;
socklen_t c_len = sizeof(clientaddr);
int cfd = accept(tmpfd,(struct sockaddr*)&clientaddr,&c_len);
//setnonblocking(cfd);
struct epoll_event event;
event.events = EPOLLIN;
event.data.fd = cfd;
//join tree
server::m_count+=1;
epoll_ctl(this->epfd,EPOLL_CTL_ADD,cfd,&event);
}
else if(events[i].events && EPOLLIN)
{
char *buf = new char[1024];
//memset(buf,0,sizeof(buf));
//char buf[100] = {0};
int len = MyRecv(tmpfd,buf,1024);
//int len = recv(tmpfd,buf,1024,0);
if(len<0)
{
std::cout<<" <"<<__FILE__<<":"<<__LINE__<<"> "<<"MyRecv failed!"<<std::endl;
}else if(len==0)
{
return ;
}
//int read_size = (int)ntohl(*(int*)buf);
std::cout<<" <"<<__FILE__<<":"<<__LINE__<<"> "<<"int read_szie ="<<len<<"buf = :"<<buf<<std::endl;
Article art;
int op = -1;
art.un_package(buf,len,op);
log("un_packaged");
/*响应用户操作:op*/
switch(op)
{
case ADD:
art.add_article();
break;
case DEL:
break;
case MOD:
break;
case SEA:
break;
default:
break;
}
//len = MyRecv(tmpfd,buf,len);
//{
// std::cout<<" <"<<__FILE__<<":"<<__LINE__<<"> "<<"MyRecv failed!"<<std::endl;
//}
//buf[len]='\0';
//std::cout<<buf<<std::endl;
/*
for(int i=0;i<len;i++)
std::cout<<buf[i];*/
//memset(buf,0,sizeof(buf));
/* if(0 >= len)
{
epoll_ctl(this->epfd,EPOLL_CTL_DEL,tmpfd,NULL);
server::m_count -= 1;
if(server::m_count==0)
{
shutdown(tmpfd,SHUT_RDWR);
}
}*/
// MySend(tmpfd,buf,len);
}else
{
}
}
}
}
}
server::server(int port):m_port(port),m_sfd(-1)
{
//创建套接字
m_sfd = socket(AF_INET,SOCK_STREAM,0);
int ret = 0;
if(-1 == m_sfd)
{
throw "创建套接字\n";
}
//端口复用
int opt = 1;
setsockopt(m_sfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(m_port);
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
//绑定
ret = bind(m_sfd,(struct sockaddr*)&serveraddr,sizeof(serveraddr));
if(-1 == ret)
{
throw "绑定失败\n";
}
//监听
ret = listen(m_sfd,128);
if(-1 == ret)
{
throw "监听失败";
}
//创建树根
this->epfd = epoll_create(MAXSIZE);
if(-1 == this->epfd)
{
throw "epoll_create is wrong";
}
struct epoll_event event;
event.events = EPOLLIN;
event.data.fd = m_sfd;
//加入树中
epoll_ctl(this->epfd,EPOLLIN,m_sfd,&event);
}
server::~server()
{
shutdown(this->m_sfd, SHUT_RDWR);
}
int server::MySend(int iSock,char *pchBuf,size_t tLen)
{
// int n;
// n = send(iSock,pchBuf,tLen,0);
// return n;
int iThisSend;
unsigned int iSended = 0;
if(0 == tLen)
return 0;
while(iSended<tLen)
{
do{
iThisSend = send(iSock,pchBuf,tLen-iSended,0);
}while((iThisSend<0)&&(errno == EINTR));
if(iThisSend<0)
return iSended;
iSended += iThisSend;
pchBuf += iThisSend;
}
return tLen;
}
int server::MyRecv( int iSock,char *&pchBuf, size_t tCount){
int n ;
n = recv(iSock,pchBuf,tCount,0);
return n;
//return tCount;
/* size_t tBytesRead=0;
int iThisRead;
while(tBytesRead < tCount){
do{
iThisRead = read(iSock, pchBuf+tBytesRead, tCount-tBytesRead);
if(iThisRead==0)
break;
//std::cout<<pchBuf;
} while((iThisRead< 0) && (errno==EINTR));
if(iThisRead < 0){
return iThisRead;
}
else if (iThisRead == 0)
return tBytesRead;
tBytesRead += iThisRead;
pchBuf += iThisRead;
}
*/
}
|
acdfdbbc024b6454217449ac99fc43f4bdcbbc42 | 420595f54dafdce25b7473cbb2c7ddfd36c1c781 | /ButtonObject.cpp | 263c8dd06905b572adf07d9050db8ae2bb34c6fb | [] | no_license | DomonicX/framework | 9599e24b4497d46867056ace4d2ec44395fd063c | de793992507123be98052508a2d7eb6a1110a8c7 | refs/heads/main | 2023-07-07T04:34:30.347201 | 2021-07-28T05:50:23 | 2021-07-28T05:50:23 | 390,223,143 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 128 | cpp | ButtonObject.cpp | #include "ButtonObject.h"
ButtonObject::ButtonObject()
{
//ctor
}
ButtonObject::~ButtonObject()
{
//dtor
}
|
91dd895c53863d05138999b4fb99209c190ee042 | 32067615986dddecce488006b0633b02d6fd58ce | /main/KeyExpansion.cpp | b16519f0eb15f5d07bf6f4db99b4542d40a4df33 | [] | no_license | fourthcaponi/CUDA_AES | 939fd5bb4ac514c3bbcde69cbd0aec067b278d96 | 086ebce92e2097ab0c1911b75726c2185a7200b8 | refs/heads/master | 2021-01-19T14:49:28.584743 | 2017-05-02T13:23:39 | 2017-05-02T13:23:39 | 88,191,598 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,262 | cpp | KeyExpansion.cpp | // Filename: KeyExpansion.cpp
// SIUE CS490-005
// Spring 2017
// Authors: David Shimkus and Michael Caponi
//
// NOTE: Byte operations are performed on char arrays.
//
// Revisions:
// 04/26/2017 | DS | Creation.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cstring>
#include "State.h"
#include "Matrices.h"
using namespace std;
void RotWord(Word &word)
{
unsigned char tempBytes[4];
for (int i = 0; i < 4; i++)
{
//place the appropriate left shifted bytes into the temp variable
tempBytes[i] = word.bytes[(i + 1) % 4];
}
for (int k = 0; k < 4; k++)
{
//place the temp var's data into the original input word
word.bytes[k] = tempBytes[k];
}
}
void SubWord(Word &word)
{
for (int i = 0; i < 4; i++)
{
//get the ASCII value as well as its decimal value
int byteTemp = word.bytes[i];
//get the leftmost 4 bits aka the COLUMN
byteTemp = (byteTemp >> 4) & ((1 << 4) - 1); //leftmost 4 bits
int column = byteTemp;
//get the rightmost 4 bits aka the ROW
byteTemp = word.bytes[i];
byteTemp = (byteTemp >> 0) & ((1 << 4) - 1); //rightmost 4 bits
int row = byteTemp;
//set the original bytes on the passed in matrix to the new bytes
word.bytes[i] = Matrix_Rijndael[column][row];
}
} |
a7ebf0b66ea514ad5dca6e351bff65a870db3507 | 7511ba47689d3c570d805fb6eacfb3608eec9cab | /core/ShadertoyShader.cpp | c3b0339b417b9944ff1aa314971e3f27faeeed38 | [
"MIT"
] | permissive | defgsus/QShadertoy | c560da52338884802c14f651daf6c9136158a716 | e8453a17a170f071a12e591db26cbabeb93544e8 | refs/heads/master | 2021-01-10T23:32:00.024772 | 2016-10-25T14:55:05 | 2016-10-25T14:55:05 | 70,431,573 | 9 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,383 | cpp | ShadertoyShader.cpp | /** @file
@brief
<p>(c) 2016, stefan.berke@modular-audio-graphics.com</p>
<p>All rights reserved</p>
<p>created 5/30/2016</p>
*/
#include <QJsonArray>
#include <QTextStream>
#include "ShadertoyShader.h"
#include "log.h"
QString ShadertoyShaderInfo::getUrl() const
{
return QString("https://shadertoy.com/view/%1").arg(id);
}
ShadertoyShader::ShadertoyShader(const QString& id)
{
p_info_.id = id;
}
bool ShadertoyShader::setJsonData(const QJsonObject& o)
{
p_json = o;
p_passes_.clear();
p_error_.clear();
// --- read info field ---
auto inf = p_json.value("info").toObject();
if (inf.isEmpty())
{
p_error_ = ("missing info in json");
return false;
}
p_info_.id = inf.value("id").toString();
p_info_.views = inf.value("viewed").toInt();
p_info_.likes = inf.value("likes").toInt();
p_info_.published = inf.value("published").toInt();
p_info_.flags = inf.value("flags").toInt();
p_info_.hasliked = inf.value("hasliked").toInt();
p_info_.name = inf.value("name").toString();
p_info_.username = inf.value("username").toString();
p_info_.description = inf.value("description").toString();
{ auto secs = inf.value("date").toString().toLong();
p_info_.date = QDateTime(QDate(1970, 1, 1)).addSecs(secs); }
p_info_.tags.clear();
for (auto t : inf.value("tags").toArray())
p_info_.tags << t.toString();
p_info_.numChars = 0; // will be counted below
p_info_.usesTextures = false;
p_info_.usesBuffers = false;
p_info_.usesMusic = false;
p_info_.usesVideo = false;
p_info_.usesCamera = false;
p_info_.usesMicrophone = false;
p_info_.usesKeyboard = false;
p_info_.hasSound = false;
// --- read render passes ---
auto rp = p_json.value("renderpass").toArray();
if (rp.isEmpty())
{
p_error_ = ("missing renderpass in json");
return false;
}
for (const QJsonValue& jpass : rp)
{
if (!jpass.isObject())
{
p_error_ = ("invalid renderpass in json");
return false;
}
ShadertoyRenderPass pass;
pass.setJsonData(jpass.toObject());
if (!pass.isValid())
{
p_error_ = ("invalid renderpass");
return false;
}
p_passes_.push_back(pass);
// -- update info --
p_info_.numChars += pass.fragmentSource().size();
/** @todo "iMouse" could be commented out */
if (pass.fragmentSource().contains("iMouse"))
p_info_.usesMouse = true;
if (pass.type() == ShadertoyRenderPass::T_SOUND)
p_info_.hasSound = true;
for (size_t i = 0; i < pass.numInputs(); ++i)
{
switch (pass.input(i).type())
{
case ShadertoyInput::T_KEYBOARD:
p_info_.usesKeyboard = true;
break;
case ShadertoyInput::T_MUSIC:
case ShadertoyInput::T_MUSICSTREAM:
p_info_.usesMusic = true;
break;
case ShadertoyInput::T_MICROPHONE:
p_info_.usesMicrophone = true;
break;
case ShadertoyInput::T_CAMERA:
p_info_.usesCamera = true;
break;
case ShadertoyInput::T_BUFFER:
p_info_.usesBuffers = true;
break;
case ShadertoyInput::T_VIDEO:
p_info_.usesVideo = true;
break;
case ShadertoyInput::T_TEXTURE:
case ShadertoyInput::T_CUBEMAP:
p_info_.usesTextures = true;
break;
case ShadertoyInput::T_NONE:
break;
}
}
}
return true;
}
QVector<ShadertoyRenderPass> ShadertoyShader::sortedRenderPasses() const
{
auto passes = p_passes_;
// sort for correct execution order
qSort(passes.begin(), passes.end(),
[](const ShadertoyRenderPass& l, const ShadertoyRenderPass& r)
{
// sorts "Buf X" alphabetically
if (l.type() == r.type())
return l.name() < r.name();
// otherwise by type
return l.type() < r.type();
});
return passes;
}
bool ShadertoyShader::containsString(const QString& s) const
{
if (p_info_.description.contains(s, Qt::CaseInsensitive)
|| p_info_.name.contains(s, Qt::CaseInsensitive)
|| p_info_.username.contains(s, Qt::CaseInsensitive)
|| p_info_.id.contains(s, Qt::CaseSensitive)
) return true;
for (const QString& tag : p_info_.tags)
if (tag.contains(s, Qt::CaseInsensitive))
return true;
for (const ShadertoyRenderPass& p : p_passes_)
if (p.fragmentSource().contains(s, Qt::CaseInsensitive))
return true;
return false;
}
void ShadertoyShader::setRenderPass(
size_t index, const ShadertoyRenderPass &pass)
{
auto rp = p_json.value("renderpass").toArray();
// XXX Todo: append or insert
if ((int)index >= rp.size())
{
ST_WARN("ShadertoyShader::setRenderPass("<<index<<") out of range");
return;
}
p_passes_.resize(std::max(p_passes_.size(), (int)index+1));
p_passes_[index] = pass;
rp[index] = pass.jsonData();
}
|
0afbf0bce8b50fc4f9b32da5bf700f31ce99d0d3 | a87ad3fcdd8c48d28b298944b34dbe327fab0684 | /include/time_step_sizers/TimeStepSizerConstant.h | 94672a978dae7abe042c223339846feb5a3a3f8d | [
"MIT"
] | permissive | joshuahansel/cl1de | e672844d28a4eb8cc32747f5e00154f74a47ee47 | a6e641f6f6ffaa477a3a82ef40e013100577b61f | refs/heads/master | 2021-06-12T11:37:23.030874 | 2021-04-24T02:16:22 | 2021-04-24T02:16:22 | 181,805,386 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 379 | h | TimeStepSizerConstant.h | #ifndef TimeStepSizerConstant_H
#define TimeStepSizerConstant_H
#include "TimeStepSizer.h"
class TimeStepSizerConstant : public TimeStepSizer
{
public:
TimeStepSizerConstant(const double & dt);
virtual double computeTimeStepSize(const double & max_wave_speed, const double & dx_min) const override;
protected:
const double _dt;
};
#endif /* TimeStepSizerConstant_H */
|
ec406ecb5c1af523decf3a0987dd9f8c12460449 | 360b66dbb902ef6d0590f0c29edde613ebb89e05 | /week1/4-6_최혜림_20210710.cpp | 7b5470df3e080f512c79cdc8e59c349ac001ad05 | [] | no_license | healim01/21_PPS | 62907e4063aff59ba4b81f9ab706d4897bfbc6ca | 9d918de3c5173619669db727f9d2ecfdbf716fcb | refs/heads/main | 2023-08-09T15:37:32.773936 | 2023-08-06T17:12:59 | 2023-08-06T17:12:59 | 383,125,938 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 433 | cpp | 4-6_최혜림_20210710.cpp | // 2021 07 10
#include <iostream>
using namespace std;
int addDigits(int num) {
int sum = 0;
while (1) {
while (1) {
sum += num%10;
if (num < 10) break;
num = num/10;
}
if (sum < 10) break;
else {
num = sum;
sum = 0;
}
}
return sum;
}
int main() {
int num = 138;
cout << addDigits(num) << endl;
}
|
e05d75b4148eebcad3711dae245f698c4651689e | 28a075502b7ee88ea58f639147b4064fa242014b | /Qt/include/cloud_viewer.h | 30d7e33b564c279ae3665c436e975ea07bb87b2f | [
"MIT"
] | permissive | leihui6/measurement_system_in_3d | 7da8c0e353716674ff87f8863d224226ef990268 | 8149f20c1af098dc3fe70769457908d0defa8931 | refs/heads/master | 2023-07-01T22:52:24.557084 | 2021-08-03T14:03:25 | 2021-08-03T14:03:25 | 255,170,435 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,815 | h | cloud_viewer.h | #ifndef CLOUD_VIEWER_H
#define CLOUD_VIEWER_H
#include <map>
#include "common_use.h"
#include "cloud_fitting.h"
#include "cloud_geometry.h"
#include "qviewerwidget.h"
/*
* list of point cloud
* - hover_point_cloud
* - picked_point_cloud
*
*/
// please use these name as a point cloud unique id
#define HOVER_POINT "hover_point_cloud"
#define PICKED_POINTS "picked_point_cloud"
#define POINT_CLOUD "point_cloud"
#define FITTING_CLOUD "fitting_point_cloud"
enum DETECT_TYPE
{
DT_POINT,
DT_LINE,
DT_PLANE,
DT_CYLINDER
};
class PickHandler;
/*
*
* cloud_viewer
*
*/
class cloud_viewer : public osgGA::GUIEventHandler
{
public:
cloud_viewer(osg::ref_ptr<osgViewer::Viewer> viewer);
~cloud_viewer();
public:
// add/remove by a name
size_t add_point_cloud(std::vector<point_3d> & points, const std::string & point_cloud_name, float w);
void remove_point_cloud(const std::string & point_cloud_name);
bool hide_point_cloud(const std::string & point_cloud_name);
void set_color(const std::string & point_cloud_name, float r, float g, float b, float w);
void set_color(const std::string & point_cloud_name, osg::Vec4 & color);
void set_point_size(const std::string & point_cloud_name, float point_size);
void set_background_color(float r, float g, float b, float w);
void set_background_color(osg::Vec4 & color);
void set_target_point_cloud(std::vector<point_3d> & points);
std::vector<point_3d> * get_target_point_cloud();
// default running
void add_pick_handler();
// in fact, it is a fake switch
void remove_pick_handler();
void clear_labeled_fitting();
void set_pick_handle(bool is_open);
bool get_pick_handle_status();
// get labeled points
std::map<std::string, std::vector<point_3d> > &get_labeled_points_map();
private:
bool is_pick_handler;
// initialize all node will be shown on screen
void initial_visualized_node();
// it will be called after adding/replacing with a new point cloud
void update(const std::string & point_cloud_name, osg::ref_ptr<osg::Node> node);
// initialized by constructor
osg::ref_ptr<osgViewer::Viewer> m_viewer;
std::shared_ptr<std::vector<point_3d>> m_target_point_cloud;
std::map<std::string, osg::ref_ptr<osg::Node>> m_node_map;
// normal point cloud properties
public:
void set_point_cloud_size(float size);
float get_point_cloud_size();
private:
float m_point_cloud_size;
osg::Vec4 m_point_cloud_color;
osg::Vec4 m_background_color;
// picked points properties
public:
float get_picking_range() const;
osg::Vec4 & get_picked_color();
float get_picked_size() const;
std::vector<point_3d> & get_picked_points();
void set_picked_color(const osg::Vec4 & c);
private:
float m_picked_size;
float m_picking_range;
osg::Vec4 m_picked_color;
std::vector<point_3d> m_picked_points;
osg::ref_ptr<PickHandler> m_pick_handler;
// picked points properties
public:
osg::Vec4 & get_hover_color();
void set_hover_color(const osg::Vec4 & c);
float get_hover_size() const;
private:
osg::Vec4 m_hover_color;
float m_hover_size;
// fitting
public:
void fit_picked_point_to_point();
void fit_picked_point_to_line();
void fit_picked_point_to_plane();
void fit_picked_point_cylinder();
void add_line_segment(const point_3d & beg_p, const point_3d & end_p, const std::string & line_name, float line_width);
void add_plane_square(std::vector<point_3d> & plane_square, const std::string plane_name);
void add_cylinder(cylinder_func &cf, Eigen::Vector3f & rotated_axis, float rotated_angle, const std::string cylinder_name);
void set_current_detection_type(DETECT_TYPE dt);
void record_labeled_points();
DETECT_TYPE get_current_detection_type();
void set_fitting_color(const osg::Vec4 & c);
private:
cloud_fitting m_cf;
DETECT_TYPE m_detection_type;
// will be increased automatically and work in current env
std::vector<std::vector<point_3d>> m_point_points;
std::vector<std::vector<point_3d>> m_line_points;
std::vector<std::vector<point_3d>> m_plane_points;
std::vector<std::vector<point_3d>> m_cylinder_points;
//osg::Vec4 m_line_color;
float m_line_width;
osg::Vec4 m_fitting_color;
std::map<std::string,std::vector<point_3d>> m_labeled_points_map;
};
/*
*
* PickHandler
*
*/
class PickHandler : public osgGA::GUIEventHandler
{
public:
PickHandler(cloud_viewer * cloud_viewer);
virtual ~PickHandler();
virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa);
private:
bool get_picked_point(osg::ref_ptr<osgViewer::Viewer> view, float x, float y, point_3d & picked_point);
bool add_point_to_picked_vector(const point_3d & p);
bool remove_point_from_picked_vector(const point_3d & p);
private:
cloud_viewer * m_cloud_viewer;
};
#endif // CLOUD_VIEWER_H
|
58303a7e3c135a039cc5042a368bef94170d351f | e2982d48d0743678885ca3358bb66d869275a8d6 | /include/Editor/CollidersEditActions.hpp | a0058c81fa477f6f99b35dab5402ad0e86f49d0c | [
"Zlib",
"Apache-2.0",
"MIT",
"BSD-2-Clause"
] | permissive | sreramk/ObEngine | 588a69c107166b731fc3c3c9fd915c166594cf45 | 36426bfe35098c6188fbb0633d3adeed0f687382 | refs/heads/master | 2021-01-20T04:55:30.599937 | 2017-08-24T19:51:24 | 2017-08-24T19:51:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 511 | hpp | CollidersEditActions.hpp | #pragma once
#include <Input/InputManager.hpp>
#include <Scene/Scene.hpp>
#include <System/Cursor.hpp>
namespace obe
{
namespace Editor
{
void connectCollidersActions(
Triggers::TriggerGroup* editorTriggers,
Input::InputManager& inputManager,
Scene::Scene& world,
System::Cursor& cursor,
int& colliderPtGrabbed,
Collision::PolygonalCollider*& selectedMasterCollider,
bool& masterColliderGrabbed);
}
}
|
b01a7fd921f8eaaeab7efa44a66b51a8226a3923 | d4ba636068fc2ffbb45f313012103afb9080c4e3 | /Other/N2F/Src/WinMoNative/trunk/solution/codebase/n2fcorelib/src/configurationstorage.cpp | c52324e1aa212940a769e566cf112a65e6c85c71 | [] | no_license | SHAREVIEW/GenXSource | 785ae187531e757860748a2e49d9b6a175c97402 | 5e5fe1d5816560ac41a117210fd40a314536f7a4 | refs/heads/master | 2020-07-20T22:05:24.794801 | 2019-09-06T05:00:39 | 2019-09-06T05:00:39 | 206,716,265 | 0 | 0 | null | 2019-09-06T05:00:12 | 2019-09-06T05:00:12 | null | UTF-8 | C++ | false | false | 2,056 | cpp | configurationstorage.cpp | #include "stdafx.h"
#include <configurationstorage.h>
#include <xmlparserwrapper.h>
#include <configurationstrings.h>
#include <configurationgraphics.h>
#include <configurationcolors.h>
N2FCORE_API ConfigutationStorageBase::ConfigutationStorageBase(TConfigStorageType type)
:iType(type)
{
}
N2FCORE_API ConfigutationStorageBase::~ConfigutationStorageBase()
{
}
N2FCORE_API bool ConfigutationStorageBase::LoadFromFile( CString& fileName )
{
this->ClearStorage();
if ( 0 == fileName.GetLength() )
return false;
XmlParserSimpleConfig *configParser = NULL;
XmlParserWrapper *xmlParser = new XmlParserWrapper;
if ( NULL == xmlParser )
return false;
bool result = false;
if ( true == xmlParser->Initialize() )
{
if ( true == this->CreateConfigParser(&configParser)
|| NULL != configParser )
{
result = xmlParser->ParseXmlFile(fileName, configParser);
}
}
if ( true == result )
{
SimpleConfigItemsList list = configParser->GetResultsList();
for ( int i = 0; i < list.GetSize(); ++i )
{
SimpleConfigItem *pItem = list[i];
this->AddToStorage(*pItem);
delete pItem;
list[i] = NULL;
}
}
delete xmlParser;
if ( NULL != configParser )
delete configParser;
return result;
}
N2FCORE_API void ConfigutationStorageBase::ReleaseStorage()
{
this->ClearStorage();
}
N2FCORE_API TConfigStorageType ConfigutationStorageBase::Type()
{
return iType;
}
N2FCORE_API ConfigutationStorageBase* ConfigutationStorageBase::CreateConfigurationStorage( TConfigStorageType type )
{
ConfigutationStorageBase *result = NULL;
if ( ECSTStrings == type )
{
result = new ConfigurationStrings;
}
else if ( ECSTGraphics == type )
{
result = new ConfigurationGraphics;
}
else if ( ECSTColors == type )
{
result = new ConfigurationColors;
}
else
{
// should be added implementation for all supported configuration storage types
ASSERT(FALSE);
}
ASSERT( NULL != result );
return result;
}
|
d5a8463893ff4942882a1a5d062eb396ebb72f20 | 1dcf36fd5f063395ee0ac2c56d1994045d9c2bb0 | /src/ui.cpp | 8afc7017085667d737639e34796acc6d175e15cc | [] | no_license | jpumc/Metropolia-ISD-ECG | f963cf7fae8741ef9abe50986954818620662b33 | af62cc6086e932473dd234f1232d833231c37213 | refs/heads/master | 2021-01-04T19:42:25.897484 | 2020-02-18T23:22:53 | 2020-02-18T23:22:53 | 240,731,309 | 0 | 2 | null | 2020-03-08T17:33:51 | 2020-02-15T14:55:23 | C++ | UTF-8 | C++ | false | false | 6,894 | cpp | ui.cpp |
#include "ui.h"
#include <Arduino.h>
#ifdef HAVE_SSD1306
#include <Adafruit_SSD1306.h>
#endif
#include "ecg_isd_config.h"
UIScreen::UIScreen(std::string title) : _title(title) {}
UIScreen::~UIScreen() {}
void UIScreen::set_title(std::string title) {
_title = title;
}
const std::string& UIScreen::title() {
return _title;
}
void UIScreen::on_enter() {}
void UIScreen::on_leave() {}
class UIMenuScreen : public UIScreen {
std::vector<std::pair<std::string, std::function<void(UI&)>>> _choices;
unsigned _index = 0;
public:
UIMenuScreen(
std::string title,
std::vector<std::pair<std::string, std::function<void(UI&)>>> choices)
: UIScreen(title), _choices(std::move(choices)) {}
bool on_event(UIEvent event, UI& ui) override {
switch (event) {
case UIEvent::UpClicked:
if (_index <= 0) {
_index = _choices.size() - 1;
} else {
_index--;
}
return true;
case UIEvent::DownClicked:
if (_index >= _choices.size() - 1) {
_index = 0;
} else {
_index++;
}
return true;
case UIEvent::OkClicked:
_choices.at(_index).second(ui);
return true;
default:
return false;
}
}
void draw(Adafruit_GFX& gfx) override {
int i = 0;
for (const auto& choice : _choices) {
if (i++ == _index) {
gfx.print("> ");
} else {
gfx.print("- ");
}
gfx.println(choice.first.data());
}
}
};
class UIWiFiApScreen : public UIScreen {
std::shared_ptr<SetupWiFi> _setup_wifi;
int _offset = 0;
public:
UIWiFiApScreen() : UIScreen("WiFi Access Point") {}
void set_setup_wifi(std::shared_ptr<SetupWiFi> setup_wifi) {
_setup_wifi = std::move(setup_wifi);
}
bool on_event(UIEvent event, UI& ui) override {
switch (event) {
case UIEvent::UpClicked:
if (_offset <= 0) {
_offset = 2;
} else {
_offset--;
}
return true;
case UIEvent::DownClicked:
if (_offset >= 2) {
_offset = 0;
} else {
_offset++;
}
return true;
case UIEvent::OkClicked:
if (_setup_wifi) {
_setup_wifi->set_ap_enabled(!_setup_wifi->is_ap_enabled());
}
return true;
default:
return false;
}
}
void draw(Adafruit_GFX& gfx) override {
if (!_setup_wifi) {
gfx.println("UI has no connection to WiFi");
return;
}
if (_offset <= 0) {
gfx.print("State: ");
if (_setup_wifi->is_ap_enabled()) {
gfx.println("Enabled");
} else {
gfx.println("Disabled");
}
}
if (_offset <= 1) {
gfx.println("Name:");
}
gfx.printf(" %s\n", _setup_wifi->get_ap_name());
gfx.printf("Password:\n %s\n", _setup_wifi->get_ap_password());
if (_offset >= 1) {
gfx.println("Address:");
}
if (_offset >= 2) {
gfx.print(" ");
gfx.println(_setup_wifi->get_ap_ip_address());
}
}
};
UI::UI(SPIClass& spi, std::mutex& spi_mutex)
: _spi(spi), _spi_mutex(spi_mutex)
#ifdef ARDUINO_NodeMCU_32S
,
_up_button(BTN_UP), _down_button(BTN_DOWN), _left_button(BTN_LEFT),
_right_button(BTN_RIGHT)
#endif
{
#ifdef HAVE_SSD1306
auto ssd1306 = std::make_unique<Adafruit_SSD1306>(
128, 64, &_spi, OLED_SA0, OLED_RST, OLED_CS);
{
std::lock_guard<std::mutex> lock(_spi_mutex);
if (ssd1306->begin(SSD1306_SWITCHCAPVCC)) {
ssd1306->clearDisplay();
ssd1306->display();
ssd1306->setTextSize(1);
ssd1306->setTextColor(SSD1306_WHITE);
ssd1306->cp437(true);
_gfx = std::move(ssd1306);
} else {
log_e("SSD1306 init failed");
}
}
#endif
std::vector<std::pair<std::string, std::function<void(UI&)>>> choices;
choices.push_back({
"WiFi Access Point",
[=](UI& ui) { ui.push(_wifi_menu); },
});
choices.push_back({
"Measurement",
[=](UI& ui) { ui.push(_measurement_menu); },
});
_main_menu =
std::make_shared<UIMenuScreen>(std::string("ECG ISD ESP32"), choices);
_wifi_menu = std::make_shared<UIWiFiApScreen>();
choices.clear();
choices.push_back({
"Start",
[=](UI& ui) { log_d("clicked: Start Measurement"); },
});
choices.push_back({
"Stop",
[=](UI& ui) { log_d("clicked: Stop Measurement"); },
});
_measurement_menu =
std::make_shared<UIMenuScreen>(std::string("Measurement"), choices);
reset(_main_menu);
}
UI::~UI() {}
void UI::set_setup_wifi(std::shared_ptr<SetupWiFi> setup_wifi) {
_setup_wifi = std::move(setup_wifi);
if (auto wifi_menu = std::static_pointer_cast<UIWiFiApScreen>(_wifi_menu)) {
wifi_menu->set_setup_wifi(_setup_wifi);
}
}
void UI::pop(unsigned num) {
for (int i = 0; i < _min((unsigned long) num, _stack.size() - 1); i++) {
_stack.back()->on_leave();
_stack.pop_back();
}
}
void UI::push(std::shared_ptr<UIScreen> screen) {
_stack.back()->on_leave();
_stack.push_back(screen);
_stack.back()->on_enter();
}
void UI::replace(std::shared_ptr<UIScreen> screen) {
if (_stack.size() == 0) {
push(screen);
} else {
_stack.back()->on_leave();
_stack.back() = screen;
_stack.back()->on_enter();
}
}
void UI::reset(std::shared_ptr<UIScreen> screen) {
for (int i = 0; i < _stack.size(); i++) {
_stack.back()->on_leave();
_stack.pop_back();
}
_stack.push_back(screen);
_stack.back()->on_enter();
}
void UI::loop() {
while (true) {
#ifdef ARDUINO_NodeMCU_32S
_up_button.update();
_down_button.update();
_left_button.update();
_right_button.update();
#endif
UIEvent event = UIEvent::None;
#ifdef ARDUINO_NodeMCU_32S
if (_up_button.clicked()) {
event = UIEvent::UpClicked;
}
if (_down_button.clicked()) {
event = UIEvent::DownClicked;
}
if (_left_button.clicked()) {
event = UIEvent::BackClicked;
}
if (_right_button.clicked()) {
event = UIEvent::OkClicked;
}
#endif
if (event != UIEvent::None) {
if (!_stack.empty()) {
if (!_stack.back()->on_event(event, *this)) {
switch (event) {
case UIEvent::BackClicked:
pop();
break;
default:
break;
}
}
_dirty = true;
}
}
if (_gfx && _dirty) {
std::unique_lock<std::mutex> lock(_spi_mutex, std::try_to_lock);
if (lock.owns_lock()) {
#ifdef HAVE_SSD1306
static_cast<Adafruit_SSD1306&>(*_gfx).clearDisplay();
#else
_gfx->fillScreen(0);
#endif
_gfx->setCursor(0, 10);
if (!_stack.empty()) {
_stack.back()->draw(*_gfx);
} else {
_gfx->println("No UIScreen");
}
// Header
_gfx->setCursor(1, 0);
if (_stack.size() > 1) {
_gfx->print("< ");
}
if (!_stack.empty()) {
_gfx->println(_stack.back()->title().data());
} else {
_gfx->println("!! ERROR !!");
}
_gfx->drawFastHLine(0, 8, 128, 1);
// Footer
int16_t footer_top = 64 - 7 - 2;
_gfx->drawFastHLine(0, footer_top, 128, 1);
_gfx->setCursor(1, footer_top + 2);
if (_stack.size() > 1) {
_gfx->print("Back");
}
_gfx->setCursor(128 - 6 * 2, footer_top + 2);
_gfx->print("OK");
#ifdef HAVE_SSD1306
static_cast<Adafruit_SSD1306&>(*_gfx).display();
#endif
_dirty = false;
}
}
delay(1000 / 60 * portTICK_PERIOD_MS);
}
}
|
0956a45448671866d45da73d09d0e1a6a5bf0766 | 49f93e9ca974840099ca3e3f6887a642223df76c | /TP/TP/Carro.cpp | ef3e6b90e4e1f6800de0f47f1c2cdf933ec316ac | [] | no_license | Strimblaster/POO1920 | 21a4f7fa7297a2183ed6bd59e678bf4751285a19 | 7f65324be5b1fe9f143d9449d57337d6fc7ada5d | refs/heads/master | 2022-03-25T14:11:24.612089 | 2020-01-07T14:47:12 | 2020-01-07T14:47:12 | 218,338,250 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 3,946 | cpp | Carro.cpp | #include <string>
#include <iostream>
#include <sstream>
#include "Carro.h"
#include "Piloto.h"
using namespace std;
Carro::Carro(string marca, int capacidadeMax, int energiaInicial, int velocidadeMax, string modelo):capacidadeMax(capacidadeMax), velocidadeMax(velocidadeMax) {
if (energiaInicial > capacidadeMax) throw string("A Energia Inicial do carro deve ser inferior à Capacidade Maxima");
this->marca = marca;
this->modelo = modelo;
if ('A' + this->contador > 'Z')
this->id = '?';
else
this->id = 'A' + this->contador++;
this->velocidade = 0;
this->energia = (float)energiaInicial;
sinalEmergencia = false;
estado = parado;
}
int Carro::acelerar(int n) {
if (estado == danificado || piloto == nullptr) throw string("O carro não tem piloto ou está danificado");
if (energia <= 0) {
if(velocidade > 0)
velocidade--;
if (velocidade == 0)
estado = parado;
return velocidade;
}
estado = movimento;
velocidade += n;
if (velocidade > velocidadeMax)
velocidade = velocidadeMax;
gastaEnergia();
return velocidade;
}
int Carro::travar() {
if (estado == danificado || piloto == nullptr) throw string("O carro não tem piloto ou está danificado");
if (energia <= 0 && velocidade > 0)
velocidade--;
if (velocidade > 0)
velocidade--;
if (velocidade == 0) estado = parado;
gastaEnergia();
return velocidade;
}
int Carro::manterVelocidade()
{
if (energia == 0)
velocidade--;
else
gastaEnergia();
return velocidade;
}
void Carro::gastaEnergia()
{
energia = energia - (float)(0.1 * velocidade);
if (energia < 0)
energia = 0;
}
void Carro::ativarSinalEmergencia()
{
sinalEmergencia = true;
}
void Carro::reset()
{
sinalEmergencia = false;
if (piloto != nullptr)
piloto->reset();
}
int Carro::getVelocidade()
{
return velocidade;
}
float Carro::getEnergia()
{
return energia;
}
bool Carro::getSinalEmergencia()
{
return sinalEmergencia;
}
int Carro::getEnergiaMax()
{
return capacidadeMax;
}
void Carro::entrarPiloto(Piloto* p) {
if (estado != parado) throw string("Erro: O carro tem que estar parado");
if(piloto != nullptr) throw string("Erro: O carro ja tem um condutor");
if(estado == danificado) throw string("Erro: O carro esta danificado");
piloto = p;
}
string Carro::toString() {
ostringstream o;
if (piloto != nullptr)
o << "ID: " << id << " Piloto: " << piloto->getNome();
else {
char idlower = tolower(id);
o << "ID: " << idlower;
}
o << " Marca: " << marca << " Modelo: " << modelo << " EnergiaMaxima:" << capacidadeMax << " VelMax:" << velocidadeMax;
if (estado == danificado)
o << " DANIFICADO";
o << endl;
return o.str();
}
string Carro::toStringBoard() {
ostringstream o;
o << "ID: " << id;
if (piloto != nullptr)
o << " Piloto: " << piloto->toString();
else {
char idlower = tolower(id);
o << "ID: " << idlower;
}
o << " Estado: ";
if (estado == parado)
o << "parado";
else if (estado == movimento)
o << "movimento";
else if (estado == danificado)
o << "danificado";
o << " Energia:" << energia << " Velocidade:" << velocidade << " VelMax:" << velocidadeMax << endl;
return o.str();
}
void Carro::sairPiloto()
{
if (estado == movimento)
throw string("O carro esta em movimento");
piloto = nullptr;
}
const char Carro::getid()
{
return id;
}
int Carro::contador = 0;
Piloto* Carro::getPiloto() {
return piloto;
}
void Carro::setVel(int v) {
velocidade = v;
if (v == 0) estado = parado;
else estado = movimento;
}
void Carro::carrega(int n)
{
if (estado == danificado) throw string("O carro está danificado!");
if (estado == movimento) throw string("O carro não está parado!");
energia += n;
if (energia > capacidadeMax)
energia = (float)capacidadeMax;
}
void Carro::carregaTudo() {
if (estado == danificado) return;
if (estado == movimento) return;
energia = (float)capacidadeMax;
}
void Carro::danificar()
{
estado = danificado;
velocidade = 0;
piloto = nullptr;
}
|
b07fdaaa3d17fe405b12913ee63c12103616bce9 | 0676032b18133a46adeace89196bc769a87500d1 | /2019-2020第二学期训练/Educational Codeforces Round 84/C. Game with Chips.cpp | 45e44cd9118f392a2ef03dc70c8264d7509f6da8 | [] | no_license | zhushaoben/training | ce47c19934f67fc21f4571f99973d16561ede195 | 530f2b5dc1a2d1e4a02c22f034e251160d0b42af | refs/heads/master | 2021-07-11T22:32:54.227626 | 2020-10-30T12:49:24 | 2020-10-30T12:49:24 | 213,320,465 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 604 | cpp | C. Game with Chips.cpp | #include<bits/stdc++.h>
using namespace std;
const int N=205;
int x[N],y[N];
char s[N*N*2];
int main(){
int n,m,k,ans=0,x1,y1;scanf("%d%d%d",&n,&m,&k);
for(int i=0;i<k;i++)scanf("%d%d",x+i,y+i);
for(int i=0;i<k;i++){
scanf("%d%d",&x1,&y1);
for(int j=0;j<ans;j++){
if(s[j]=='D'&&x[i]<n)x[i]++;
if(s[j]=='U'&&x[i]>1)x[i]--;
if(s[j]=='L'&&y[i]>1)y[i]--;
if(s[j]=='R'&&y[i]<m)y[i]++;
}
for(int j=x[i];j<x1;j++)s[ans++]='D';
for(int j=x[i];j>x1;j--)s[ans++]='U';
for(int j=y[i];j<y1;j++)s[ans++]='R';
for(int j=y[i];j>y1;j--)s[ans++]='L';
}
printf("%d\n%s",ans,s);
return 0;
}
|
08827b339c9a4dc53891ae128d40f53ad334caef | 1712f5a02cb995b21fe85ce2019e0893268c2149 | /Spolocnost_FRI/Spolocnost_FRI/Kamion.cpp | 91b8bca64882545a7ba64190aa90db36624b5c16 | [] | no_license | DejvIT/Udajovky-semestralky-C- | 3a43154770ecdc4a318cf15fa4e8092c979c4854 | 695eb321804a8132569e767eaa8ad2ae755f7320 | refs/heads/master | 2023-01-27T19:36:36.931723 | 2018-02-26T11:35:56 | 2018-02-26T11:35:56 | 122,960,793 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 68 | cpp | Kamion.cpp | #include "Kamion.h"
Kamion::Kamion()
{
}
Kamion::~Kamion()
{
}
|
9ed9794da86137a1072f51039558dabe7ddac22f | b5bc86dd7decfc6f1951c8f3a9bfa94e381a2f54 | /kernel/hw/pci.cpp | d25c55e53990f3823e2a863cfa52bc8a02e52889 | [] | no_license | mszoek/hydrogen | 0238fc5b123ed97f50d624177af5ab29fe2d6d09 | 61b14c7e91b6c093bb26eaf61f2af1ba66551e37 | refs/heads/master | 2021-03-17T07:18:14.841314 | 2020-03-13T03:06:57 | 2020-03-13T03:06:57 | 246,973,194 | 40 | 4 | null | 2020-03-13T02:48:14 | 2020-03-13T02:35:42 | C++ | UTF-8 | C++ | false | false | 4,953 | cpp | pci.cpp | /*
* H2 PCI Bus Driver
* Copyright (C) 2017-2019 Zoe Knox. All rights reserved.
*/
#include <kernel.h>
#include <hw/types.h>
#include <hw/port_io.h>
#include <hw/pci.h>
#include <hw/ata.h>
#include <hw/screen.h>
#include <kmem.h>
#include <kstdio.h>
PCIController::PCIController()
{
if(verbose)
kprintf("hw/PCIController: 0x%x\n", this);
g_controllers[CTRL_PCI] = (UInt64)this;
pciTableIndex = 0;
memset((char *)pciTable, 0, sizeof(pciTable));
}
PCIController::~PCIController()
{
g_controllers[CTRL_PCI] = 0;
}
UInt16 PCIController::pciReadCfgWord(UInt32 bus, UInt32 slot, UInt32 func, UInt32 offset)
{
return (UInt16)(pciReadCfgDWord(bus, slot, func, offset) >> ((offset & 2) * 8) & 0xffff);
}
UInt32 PCIController::pciReadCfgDWord(UInt32 bus, UInt32 slot, UInt32 func, UInt32 offset)
{
UInt32 address;
/*
31 30-24 23-16 15-11 10-8 7-0
Enable Reserved Bus # Device Func Reg Offset
*/
address = ((bus << 16) | (slot << 11) | (func << 8) | (offset & 0xfc) | 0x80000000);
portDWordOut(PCI_CFG_ADDR, address);
return portDWordIn(PCI_CFG_DATA);
}
void PCIController::pciCheckDevice(UInt32 bus, UInt32 slot)
{
UInt32 function;
UInt16 vendor, device, classcode, headertype;
vendor = pciReadCfgWord(bus, slot, 0, 0);
if(vendor == 0xFFFF) return;
for(function = 0; function < 8; function++)
{
vendor = pciReadCfgWord(bus, slot, function, 0);
if(vendor == 0xFFFF) continue;
device = pciReadCfgWord(bus, slot, function, 2);
classcode = pciReadCfgWord(bus, slot, function, 0x0a);
headertype = pciReadCfgWord(bus, slot, function, 0x0e);
pciTable[pciTableIndex].bus = bus;
pciTable[pciTableIndex].slot = slot;
pciTable[pciTableIndex].function = function;
pciTable[pciTableIndex].deviceID = device;
pciTable[pciTableIndex].vendorID = vendor;
pciTable[pciTableIndex].classCode = (classcode & 0xFF00) >> 8;
pciTable[pciTableIndex].subclassCode = classcode & 0xFF;
pciTable[pciTableIndex].headerType = headertype & 0x7f;
pciTable[pciTableIndex].BIST = (headertype & 0xFF00) >> 8;
UInt16 val = pciReadCfgWord(bus, slot, function, 0xc);
pciTable[pciTableIndex].latencyTimer = (val & 0xFF00) >> 8;
pciTable[pciTableIndex].cacheLineSize = val & 0xFF;
/* read 6 dwords for the BARs. Only header type 0x00 has all - the others have 2 or 0
so we will be stuffing other data in the BAR space. Can parse it later.
NOTE: the low bits of BARs need to be masked & 0xFC before using!! Kept
here so we can distinguish type: low 00 = mem addr, 01 = I/O addr */
for(int j = 0; j < 6; ++j)
{
UInt32 val32 = pciReadCfgDWord(bus, slot, function, 0x10+(4*j));
pciTable[pciTableIndex].baseAddrReg[j] = val32;
}
if(verbose || debug)
{
kprintf("%d/%d.%d %x:%x class %x type %x %s\n", bus, slot, function,
vendor, device, classcode /*& 0x7fff*/, headertype & 0x7f,
pciClassCodes[((classcode & 0xFF00) >> 8) % 13]);
if(debug)
{
for(int x = 0; x < 6; ++x)
kprintf("BAR%d=%x ", x, pciTable[pciTableIndex].baseAddrReg[x]);
kprintf("\n");
}
}
++pciTableIndex;
if(headertype & 0x80 == 0) break;
}
}
void PCIController::pciEnumBuses(void)
{
UInt32 bus, slot;
memset((char *)pciTable, 0xff, sizeof(pciTable));
if(verbose)
kprintf("PCI: Enumerating buses\n");
for(bus = 0; bus < 256; bus++)
{
for(slot = 0; slot < 32; slot++)
{
pciCheckDevice(bus, slot);
}
}
}
void PCIController::startDevices(void)
{
/* Call this only with interrupts enabled! The timer is required
to create delays after I/O during ATA init. */
for(int j = 0; j < 64; j++)
{
if(pciTable[j].bus == 0xFFFFFFFF)
break;
switch(pciTable[j].classCode)
{
case PCI_MASS_STORAGE_CTRL:
{
switch(pciTable[j].subclassCode)
{
case 0x6:
if(g_controllers[CTRL_AHCI] == 0)
{
UInt64 addr = vmm->remap(pciTable[j].baseAddrReg[5], 0x40);
new AHCIController((hbaMem *)(addr));
}
break;
}
break;
}
case PCI_DISPLAY_CTRL:
break;
default:
if(debug)
kprintf("PCI: Unsupported device: Vendor 0x%x Device 0x%x Class 0x%x.%x\n",
pciTable[j].vendorID, pciTable[j].deviceID, pciTable[j].classCode, pciTable[j].subclassCode);
}
}
} |
6502f50b287c82f2e7e5a5987ab5fe33d624d538 | 8b877fd49a93d461588b85918728114effe2a847 | /GUI/GUIwithconnections/Widgets Available/AttitudeMeter/AttitudeMeter widget fonctionnant seul/threadreadinput.cpp | 4c482a632a0747912a5f5be017c3dc11a3a17cd4 | [] | no_license | NaviPolytechnique/GUI | 301da3ef0ab9154a0853d058519b5abf6211d5ae | ae85f8bed7b815a7d2d3208ab561ceb22e7133aa | refs/heads/master | 2016-08-12T16:09:57.381982 | 2016-03-23T21:18:55 | 2016-03-23T21:18:55 | 44,568,567 | 3 | 1 | null | 2015-12-22T10:41:57 | 2015-10-19T22:47:53 | C++ | UTF-8 | C++ | false | false | 2,681 | cpp | threadreadinput.cpp | #include "threadreadinput.h"
//init Thread countainer
ThreadReadInput::ThreadReadInput(QString inputfile,QObject *parent) : QObject(parent),Tfile(inputfile),thread(new QThread(this))
{
}
//start thread
void ThreadReadInput::start(){
ReadInput* readinput=new ReadInput(Tfile);
connect(readinput,SIGNAL(signalNewLine(QString)),this,SLOT(onNewLine(QString)));
connect(readinput,SIGNAL(signalReadInputEnded()),this,SLOT(onReadInputEnded()));
readinput->moveToThread(thread);
QMetaObject::invokeMethod(readinput,"start");
thread->start();
}
//signal towards dronestatus
void ThreadReadInput::onNewLine(QString newline){
emit TonNewLine(newline);
}
//slot to end the run loop of this thread
void ThreadReadInput::onReadInputEnded(){
thread->exit();
}
//init worker "ReadInput"
ReadInput::ReadInput(QString inputfile,QObject *parent): QObject(parent),file(inputfile),newline(""),posRPY(0),lignelu(new QStringList())
{
}
//start worker "ReadInput"
void ReadInput::start()
{
int i=0;
while(i<10000){
QThread::msleep(10);
sendline();
i++;
}
emit signalReadInputEnded();
}
void ReadInput::sendline(){
QStringList list=readRPY();
lignelu->append(list.at(0));
lignelu->append(list.at(1));
newline=lignelu->join(",");
emit signalNewLine(newline);
lignelu->removeAt(1);
lignelu->removeAt(0);
}
QStringList ReadInput::readRPY(){
QFile fichier(file);
if(!fichier.exists()){
QMessageBox::information(0,"info","n'existe pas");
}
if(fichier.open(QIODevice::ReadOnly | QIODevice::Text)){
QTextStream flux(&fichier);
if(!flux.atEnd())
{
flux.seek(posRPY);
QString line = flux.readLine();
QStringList list=recuperationRPY(line);
posRPY=flux.pos();
fichier.close();
return list;
}
else{
fichier.close();
QMessageBox::information(0,"info","fichier fermé");
}
}
else{
QMessageBox::information(0,"info","ne peux pas ouvrir");
}
return QStringList();
}
QStringList ReadInput::recuperationRPY(QString s){
QStringList l;
int i = 0;
int j=s.size();
while(s[i]==' ')
{
i++;
}
for (int k=0;k<3;k++)
{
QString RorPorY;
while (s[i]!=' ' && i<j ){
RorPorY=RorPorY + s[i];
i++;
}
i++;
while (s[i]==' '&& i<j )
{
i++;
}
l << RorPorY;
}
return l;
}
|
e550fb714c39f671933c3c5dcd1d85b59f8ee1b4 | 7e68c3e0e86d1a1327026d189a613297b769c411 | /Lib/Src/Util/ListSelect.cpp | 61da896a80bb8393ea2234502560d776abac9068 | [] | no_license | staticlibs/Big-Numbers | bc08092e36c7c640dcf43d863448cd066abaebed | adbfa38cc2e3b8ef706a3ac8bbd3e398f741baf3 | refs/heads/master | 2023-03-16T20:25:08.699789 | 2020-12-20T20:50:25 | 2020-12-20T20:50:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 221 | cpp | ListSelect.cpp | #include "pch.h"
#include <LinkedList.h>
#include <Random.h>
void *ListImpl::select(RandomGenerator &rnd) const {
if(size() == 0) {
getError(__TFUNCTION__);
}
return findNode(randSizet(size(), rnd))->m_data;
}
|
804d13ca6ef6b9ff363cc8f4fef24d8dc3464728 | 8964e03e188440a997808eb11052c907b9ce8aa8 | /HDC1080.cpp | ae68fc9b8bb88395f8cbcc1f3adfc7b56958c68c | [] | no_license | paladin32776/HDC1080 | fdbf0cc1f5af7d06420ad5acf1da037c0814fb31 | 0439aa27134b1a2f45d60f3c37d18614fbc60041 | refs/heads/master | 2020-08-22T02:12:17.985494 | 2019-12-28T16:54:37 | 2019-12-28T16:54:37 | 216,296,971 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,551 | cpp | HDC1080.cpp | #include "HDC1080.h"
#define PRINTBIN(Num) for (uint32_t t = (1UL<< (sizeof(Num)*8)-1); t; t >>= 1) Serial.write(Num & t ? '1' : '0'); // Prints a binary number with leading zeros (Automatic Handling)
HDC1080::HDC1080()
{
Wire.begin(14,2);
addr = 64;
delay(20);
write_word(HDC_CONFIG, 0b0001000000000000);
}
unsigned char HDC1080::read_byte(unsigned char regbyte)
{
Wire.beginTransmission(addr);
Wire.write(byte(regbyte));
Wire.endTransmission(false);
Wire.requestFrom(addr, (byte)1);
unsigned char databyte = Wire.read();
return databyte;
}
unsigned int HDC1080::read_word(unsigned char regbyte)
{
Wire.beginTransmission(addr);
Wire.write(byte(regbyte));
Wire.endTransmission(false);
Wire.requestFrom(addr, (byte)2);
unsigned int dataword = 0;
while (Wire.available())
dataword = (dataword<<8)+Wire.read();
return dataword;
}
void HDC1080::write_regbyte(unsigned char regbyte)
{
Wire.beginTransmission(addr); // transmit to device #addr
Wire.write(byte(regbyte)); // sends instruction byte
Wire.endTransmission(); // stop transmitting
}
void HDC1080::write_byte(unsigned char regbyte, unsigned char databyte)
{
Wire.beginTransmission(addr); // transmit to device #addr
Wire.write(byte(regbyte)); // sends instruction byte
Wire.write(byte(databyte)); // sends value byte
Wire.endTransmission(); // stop transmitting
}
void HDC1080::write_word(unsigned char regbyte, unsigned int dataword)
{
Wire.beginTransmission(addr); // transmit to device #addr
Wire.write(byte(regbyte)); // sends instruction byte
Wire.write(byte(dataword>>8)); // sends upper byte
Wire.write(byte(dataword & 0xFF)); // sends lower byte
Wire.endTransmission(); // stop transmitting
}
void HDC1080::read(float* temperature, float* humidity)
{
write_regbyte(HDC_TEMPERATURE);
delay(15);
Wire.requestFrom(addr, (byte)4);
unsigned int TEMPERATURE = (Wire.read()<<8)+Wire.read();
unsigned int HUMIDITY = (Wire.read()<<8)+Wire.read();
*temperature = ((float)TEMPERATURE) / 65536.0 * 165.0 - 40.0;
*humidity = ((float)HUMIDITY) / 65536.0 * 100.0;
}
void HDC1080::get_serial_id(unsigned int* serial_id)
{
serial_id[0] = read_word(HDC_SERIALID1);
serial_id[1] = read_word(HDC_SERIALID2);
serial_id[2] = read_word(HDC_SERIALID3);
}
unsigned int HDC1080::get_mfg_id()
{
return read_word(HDC_MFGID);
}
unsigned int HDC1080::get_device_id()
{
return read_word(HDC_DEVICEID);
}
|
9e4f3f85f5050dea25299746275d93e1904f9f68 | 36c31b485a5906ab514c964491b8f001a70a67f5 | /Codeforces/CF 1600 - 1699/CF1686/CF1686D.cpp | a2eb913ee0ea62b9ee2b61af8a88c4b322f2a889 | [] | no_license | SMiles02/CompetitiveProgramming | 77926918d5512824900384639955b31b0d0a5841 | 035040538c7e2102a88a2e3587e1ca984a2d9568 | refs/heads/master | 2023-08-18T22:14:09.997704 | 2023-08-13T20:30:42 | 2023-08-13T20:30:42 | 277,504,801 | 25 | 5 | null | 2022-11-01T01:34:30 | 2020-07-06T09:54:44 | C++ | UTF-8 | C++ | false | false | 3,292 | cpp | CF1686D.cpp | #include <bits/stdc++.h>
using namespace std;
struct clean_set {
multiset<int> m;
void push(int x) {
if (x > 1)
m.insert(x);
}
void remove(int x) {
m.erase(m.find(x));
}
bool empty() {
return m.empty();
}
void clear() {
m.clear();
}
int big() {
return *(--m.end());
}
int smol() {
return *m.begin();
}
bool exists_at_least(int x) {
return m.lower_bound(x) != m.end();
}
int lower_bound(int x) {
return *m.lower_bound(x);
}
};
int f(int l, int r) {
return r - l + 1;
}
void solve() {
int n, a, b, c, d, x = 0, y = 0, cur = 0, p;
cin >> a >> b >> c >> d;
string s;
cin >> s;
n = s.size();
for (auto i : s) {
x += (i == 'A');
y += (i == 'B');
}
if (a + c + d != x || b + c + d != y) {
cout << "NO\n";
return;
}
clean_set ab, ba, aba, bab;
for (int i = 1; i < n; ++i)
if (s[i] == s[i - 1]) {
if (s[i - 1] == s[cur]) {
if (s[cur] == 'A')
aba.push(f(cur, i - 1));
else
bab.push(f(cur, i - 1));
}
else {
if (s[cur] == 'A')
ab.push(f(cur, i - 1));
else
ba.push(f(cur, i - 1));
}
cur = i;
}
if (cur != n) {
if (s[n - 1] == s[cur]) {
if (s[cur] == 'A')
aba.push(f(cur, n - 1));
else
bab.push(f(cur, n - 1));
}
else {
if (s[cur] == 'A')
ab.push(f(cur, n - 1));
else
ba.push(f(cur, n - 1));
}
}
while (c > 0) {
if (!ab.empty()) {
--c;
p = ab.smol();
ab.remove(p);
ab.push(p - 2);
}
else if (!aba.empty()) {
--c;
p = aba.smol();
aba.remove(p);
aba.push(p - 2);
}
else if (!bab.empty()) {
--c;
p = bab.smol();
bab.remove(p);
bab.push(p - 2);
}
else if (ba.exists_at_least(3)) {
--c;
p = ba.lower_bound(3);
ba.remove(p);
aba.push(p - 3);
}
else
break;
}
while (d > 0) {
if (!ba.empty()) {
--d;
p = ba.smol();
ba.remove(p);
ba.push(p - 2);
}
else if (!aba.empty()) {
--d;
p = aba.smol();
aba.remove(p);
aba.push(p - 2);
}
else if (!bab.empty()) {
--d;
p = bab.smol();
bab.remove(p);
bab.push(p - 2);
}
else if (ab.exists_at_least(3)) {
--d;
p = ab.lower_bound(3);
ab.remove(p);
bab.push(p - 3);
}
else
break;
}
if (c <= 0 && d <= 0) {
cout << "YES\n";
return;
}
cout << "NO\n";
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0);
int t;
cin >> t;
while (t--)
solve();
return 0;
} |
745c2238715ff8292b1b5ae4decb35fddd126b59 | 4a1bc929cddc55aa5ec73951209b8f7f5c9a3880 | /Pong/lib/Player.h | 726a521faa4cbbb206aac86ea196213d78aaaf7f | [] | no_license | kkafar/Pong | 6abab973fc81cf5a212015f589853393f59d31c2 | 9cf2492c380c02ec7ed52563f0ce9c5e1fcae9eb | refs/heads/master | 2021-01-02T19:45:54.928630 | 2020-02-11T13:55:39 | 2020-02-11T13:55:39 | 239,772,010 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,377 | h | Player.h | #ifndef __PLAYER_H_INCLUDED__
#define __PLAYER_H_INCLUDED__
#include "CollisionObject.h"
/// =============================================================================
enum MovementDirection {UP = 1, DOWN = 2, NONE = 3};
typedef MovementDirection MDIR;
/// =============================================================================
/// =============================================================================
class Player : public CollisionObject
{
private:
sf::Vector2f velocity;
MDIR dir;
int id;
public:
/*
\brief Constructor
\param paramPosition - starting position of player
\param ID - id number of player
*/
Player(sf::Vector2f paramPosition, int ID);
/*
/brief DEBUG destructor
*/
~Player();
/*
\brief Adds velocity vector to position vector
updates rect position
*/
void move();
/*
\brief sets velocity vector to appropriate value basing on 'direction' value
fixed velocity value UP/DOWN is -10/10 pixels per frame
\param direction - new direction of player
*/
void setVelocity(MDIR direction);
/*
\return value of id private member
*/
int getId();
};
/// =============================================================================
/* Bodies */
/// =============================================================================
Player::Player(sf::Vector2f paramPosition = {1000, 512}, int ID = 0)
{
position = paramPosition;
dimensions = {24, 100};
rect.setFillColor(sf::Color::Yellow);
rect.setPosition(position);
rect.setSize(dimensions);
dir = NONE;
id = ID;
}
Player::~Player()
{
std::cout << "DEBUG: DESTRUKTOR KLASY PLAYER\n";
}
int Player::getId()
{
return id;
}
void Player::move()
{
position = position + velocity;
rect.setPosition(position);
}
void Player::setVelocity(MDIR direction)
{
switch(direction)
{
case NONE:
velocity = {0, 0};
break;
case UP:
velocity = {0, -10};
break;
case DOWN:
velocity = {0, 10};
break;
default:
std::cout << "DEBUG: BLAD W SETVELOCITY(MDIR DIRECTION)\n";
}
}
/// =============================================================================
#endif |
d609fb704612cb2d4ac16651f25b2d1e850990cd | b31aa487eb865a6ed72d2f10e3970cc842b78438 | /ProjectEuler/LargestProductInASeries.cpp | 18da6c56af23802aeeb7f1a9f4f9aa942421f8cf | [] | no_license | hashmup/fun | 3f0e588a106a38b0d68cdcf5e0e6b96ae367323a | c6623d9a6adeae68f70eeb2eced52a890c330f06 | refs/heads/master | 2021-01-10T11:37:17.008816 | 2016-01-07T18:34:24 | 2016-01-07T18:34:24 | 49,222,789 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,380 | cpp | LargestProductInASeries.cpp | #include <iostream>
#include <algorithm>
#include <functional>
#include <string>
#include <cstdlib>
typedef long long ll;
using namespace std;
const int MAX = 1000;
ll dp[MAX];
int main(){
string str="7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
for(int i=0;i+12<1000;i++){
dp[i] = 1;
for(int j=0;j<13;j++){
dp[i] *= (str[i+j]-'0');
}
}
sort(dp,dp+MAX,greater<ll>());
cout << dp[0] << endl;
}
|
2f22bbc3c385ded79a33ad168eb874a3777414ff | cae63dae21561c4f39481278390f565ec5c419ec | /OpenCV/cap3-resize-crop.cpp | 12d788ff31d93d952a4cb788252431a7376e1fcd | [] | no_license | HRsniper/CPP | d48f16159c5439febbf3bce8eb1445320704b251 | 86e5928292a05df6c332558c0b8240a66ae3aeee | refs/heads/main | 2023-08-22T17:57:16.941360 | 2021-10-16T19:02:29 | 2021-10-16T19:02:29 | 308,703,801 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,053 | cpp | cap3-resize-crop.cpp | #include <iostream>
#include <string>
#include <opencv4/opencv2/highgui.hpp>
#include <opencv4/opencv2/imgcodecs.hpp>
#include <opencv4/opencv2/imgproc.hpp>
using namespace std;
using namespace cv;
int main(int argc, char const *argv[]) {
string image_path = "testopencvimage.bmp";
Mat img = imread(image_path);
Mat imgResize, imgResize_D, imgCrop;
// Redimensiona uma imagem. com uma escala definida
resize(img, imgResize, Size(500, 300));
// Redimensiona uma imagem. com uma escala dinâmica
resize(img, imgResize_D, Size(), 0.5, 0.5);
// Crop images
Rect roi(1, 1, 130, 100);
imgCrop = img(roi);
cout << "Original: " << img.size() << endl;
cout << "Resize: " << imgResize.size() << endl;
cout << "Resize Dynamic: " << imgResize_D.size() << endl;
cout << "Crop: " << imgCrop.size() << endl;
imshow("Image", img);
imshow("Image Resize", imgResize);
imshow("Image Resize Dynamic", imgResize_D);
imshow("Image Crop", imgCrop);
waitKey(0); // Aguardando ate pressionamento de tecla
return 0;
}
|
88727b6290ceed74b498bf1bde9f911944c30675 | 1174e8902323c4e114a3ef4440343cdfd736f306 | /core/CoreConfiguration.cpp | f069951dbd77ed938d3c1f423814912091d0a1e1 | [] | no_license | luogantt/helloworld-blockchain-cpp | 46aa3789557e9ba1eeeccdc6c82e1ec38677d5ff | 6d1cafa246ea6c3cffa0a68cd6df93ac041314ec | refs/heads/main | 2023-08-22T22:31:46.051626 | 2021-10-12T12:01:06 | 2021-10-12T12:01:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,111 | cpp | CoreConfiguration.cpp | //
// Created by 40906 on 2021/9/20.
//
#include "CoreConfiguration.h"
#include "../util/FileUtil.h"
#include "../util/ByteUtil.h"
#include "../util/KvDbUtil.h"
namespace core{
//配置数据库名字
const string CONFIGURATION_DATABASE_NAME = "ConfigurationDatabase";
//'矿工是否是激活状态'存入到数据库时的主键
const string MINE_OPTION_KEY = "IS_MINER_ACTIVE";
//'矿工可挖的最高区块高度'存入到数据库时的主键
const string MINER_MINE_MAX_BLOCK_HEIGHT_KEY = "MINER_MINE_MAX_BLOCK_HEIGHT";
//'矿工是否是激活状态'的默认值
const bool MINE_OPTION_DEFAULT_VALUE = false;
//这个时间间隔更新一次正在被挖矿的区块的交易。如果时间太长,可能导致新提交的交易延迟被确认。
const uint64_t MINE_TIMESTAMP_PER_ROUND = 1000 * 10;
string CoreConfiguration::getCorePath() {
return this->corePath;
}
bool CoreConfiguration::isMinerActive() {
vector<unsigned char> mineOption = getConfigurationValue(ByteUtil::stringToUtf8Bytes(MINE_OPTION_KEY));
if(mineOption.empty()){
return MINE_OPTION_DEFAULT_VALUE;
}
return ByteUtil::utf8BytesToBoolean(mineOption);
}
void CoreConfiguration::activeMiner() {
addOrUpdateConfiguration(ByteUtil::stringToUtf8Bytes(MINE_OPTION_KEY),ByteUtil::booleanToUtf8Bytes(true));
}
void CoreConfiguration::deactiveMiner() {
addOrUpdateConfiguration(ByteUtil::stringToUtf8Bytes(MINE_OPTION_KEY),ByteUtil::booleanToUtf8Bytes(false));
}
void CoreConfiguration::setMinerMineMaxBlockHeight(uint64_t maxHeight) {
addOrUpdateConfiguration(ByteUtil::stringToUtf8Bytes(MINER_MINE_MAX_BLOCK_HEIGHT_KEY),ByteUtil::uint64ToBytes(maxHeight));
}
uint64_t CoreConfiguration::getMinerMineMaxBlockHeight() {
vector<unsigned char> bytesMineMaxBlockHeight = getConfigurationValue(ByteUtil::stringToUtf8Bytes(MINER_MINE_MAX_BLOCK_HEIGHT_KEY));
if(bytesMineMaxBlockHeight.empty()){
//设置默认值,这是一个十分巨大的数字,矿工永远挖不到的高度
return 10000000000000000L;
}
return ByteUtil::bytesToUint64(bytesMineMaxBlockHeight);
}
uint64_t CoreConfiguration::getMinerMineTimeInterval() {
return MINE_TIMESTAMP_PER_ROUND;
}
string CoreConfiguration::getConfigurationDatabasePath(){
return FileUtil::newPath(corePath, CONFIGURATION_DATABASE_NAME);
}
vector<unsigned char> CoreConfiguration::getConfigurationValue(vector<unsigned char> configurationKey) {
return KvDbUtil::get(getConfigurationDatabasePath(), configurationKey);
}
void CoreConfiguration::addOrUpdateConfiguration(vector<unsigned char> configurationKey, vector<unsigned char> configurationValue) {
KvDbUtil::put(getConfigurationDatabasePath(), configurationKey, configurationValue);
}
CoreConfiguration::CoreConfiguration(string corePath) {
FileUtil::makeDirectory(corePath);
this->corePath = corePath;
}
} |
4437e1071d8139e356ce3211f0e3c32b7d9033e7 | 72b811259df144eeceeba2f45fc653f9baf315f5 | /Lab 3 Realistic Grade Predictor/main.cpp | de885bb099e437fe0d265d017ed026fcae45d858 | [] | no_license | ada-zhang-00/E115-Introduction-to-Programming | 34d5a1b8bfebe22ee6c86b77326cb75fe956eb34 | 7e47ff612c2e48cee5d6514f11f7c456c2cc474a | refs/heads/main | 2022-12-31T10:33:02.345644 | 2020-10-21T03:06:03 | 2020-10-21T03:06:03 | 305,891,285 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,589 | cpp | main.cpp | // main.cpp
// lab3-realistic grade predictor
//
// Created by Ada Zhang on 10/3/20.
//
//Create a grade predictor program for a hypothetical course that comprises the following elements:
//(i) six homework scores, (ii) two midterm scores, and (iii) one final.
//The following weightage is used to arrive at the final cumulative score:
//40% from homeworks, 40% from midterms and 20% from the final.
//A final letter grade is arrived at based on the following score range:
//(i) ‘A’ for scores 91--100, (ii) ‘B’ for 81--90, (iii) ‘C’ for 71--80 and D otherwise.
#include <iostream>
#include <string>
using namespace std;
int main() {
//6 homework scores
float hw1;
cout << "Homework 1 grade?\n";
cin>> hw1;
float hw2;
cout << "Homework 2 grade?\n";
cin>> hw2;
float hw3;
cout << "Homework 3 grade?\n";
cin>> hw3;
float hw4;
cout << "Homework 4 grade?\n";
cin>> hw4;
float hw5;
cout << "Homework 5 grade?\n";
cin>> hw5;
float hw6;
cout << "Homework 6 grade?\n";
cin>> hw6;
float hw_sum = hw1+hw2+hw3+hw4+hw5+hw6;
float hw_avg = hw_sum/6;
float hw_weight = hw_avg *0.4;
//cout << "Your homework weight is:" << hw_avg <<endl;
cout << "Your homework avg is:" << hw_avg <<endl;
cout << " \n";
//2 midterm
float midterm1;
cout << "Midterm 1 grade?\n";
cin>> midterm1;
float midterm2;
cout << "Miderem 2 grade?\n";
cin>> midterm2;
float midterm_sum = midterm1+midterm2;
float midterm_avg = midterm_sum/2;
float midterm_weight = midterm_avg *0.4;
//cout << "Your midterm weight is:" << midterm_weight <<endl;
cout << "Your midterm average is:" << midterm_avg <<endl;
cout << " \n";
//final
float final1;
cout << "Final 1 grade?\n";
cin>> final1;
float final_weight = final1 *0.2;
//cout << "Your final weight is:" << final_weight <<endl;
cout << "Your averaqge for the final is:" << final1 <<endl;
cout << " \n";
//course grade
float course_grade = hw_weight+midterm_weight+final_weight;
if (course_grade >= 91){
cout << "Congrats! You've recieved an A! \n";
}
else if (course_grade >= 81){
cout << "Not too bad! You've recieved a B. \n";
}
else if (course_grade >= 71){
cout << "Getting low. This is a C. \n";
}
else{
cout << "Unfortunately you get a D. \n";
}
cout << " \n";
return 0;
}
|
420fed689445d7fc06e401f4cd8c17df376ecc0e | 8d539ced39960119c418907075b631cec18ca399 | /ProjectEuler/208-PE72-CountingFractions.cpp | 6059da88a752feebe66ecbacfcc829ad405a0af0 | [
"MIT"
] | permissive | lucastarche/aotd | d27eed7414c11ce1a0a18c2459b800e9cdf91eef | e501a1f27fc48508d24eac461308aaa2e56a23cf | refs/heads/master | 2023-07-19T03:56:06.845259 | 2021-09-12T12:14:56 | 2021-09-12T12:14:56 | 294,989,043 | 3 | 1 | null | 2020-12-16T13:58:42 | 2020-09-12T17:06:06 | C++ | UTF-8 | C++ | false | false | 681 | cpp | 208-PE72-CountingFractions.cpp | //PE 72: Counting Fractions
//Problem: Count the number of irreducible proper fractions such that the denominator is under 1000000
//Solution: This is quite an easy problem, thanks to the fact that we coded the totient sieve earlier.
//It is just a matter of adding the euler totient of every number under the denominator bound.
//This is because there are phi(n) coprime to n, and less than n, which in fact is also what a proper irreducible fraction is.
//Runtime: O(n log n)
#include "EulerUtils.hpp"
long long solve() {
vector<long long> sieve = totient_sieve(1000000);
return accumulate(sieve.begin(), sieve.end(), 0LL);
}
int main() {
cout << solve() << '\n';
} |
dfe5ddebee0352afeea970237a84488343ff601a | e0a6fe38bc2164768b2272adac1984989024806e | /src/graphics/gfxdevice/opengl/OpenGLRenderer.cpp | e73bbb238d6bca402912e768c039908f1ddc7503 | [] | no_license | bfogerty/xdpixelengine | 802287559ff748eea3db6488338cfb5f39453ce2 | 240e1161b039a6a190473ef46b7e14bdea3b48bc | refs/heads/master | 2020-04-11T11:00:54.943741 | 2018-05-12T14:05:24 | 2018-05-12T14:05:24 | 10,495,378 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,287 | cpp | OpenGLRenderer.cpp | #include "core/platform.h"
#ifdef COMPILE_OPENGL_RENDERER
#include "graphics/gfxdevice/opengl/OpenGLRenderer.h"
#include "external/khronos/gl/glext.h"
#include "external/khronos/gl/wglext.h"
#include "graphics/Color.h"
#include "core/math/Vector3.h"
#include "core/mesh/Mesh.h"
#include "core/math/MathHelper.h"
#include "core/math/Matrix4x4.h"
#include <assert.h>
void Break(unsigned int glResult)
{
char buffer[1000];
//sprintf(buffer, "glGetError() = %d\n%s\n", glResult, gluErrorString(glResult));
OutputDebugString(buffer);
assert(glResult == GL_NO_ERROR);
}
#define GL_VERIFY(x) \
x;\
{\
unsigned int glResult = glGetError();\
if (glResult != GL_NO_ERROR) { \
Break(glResult);\
}\
}
LRESULT CALLBACK WindowProcedure(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case WM_KEYDOWN:
if (wParam == VK_ESCAPE) {
PostQuitMessage(0);
}
break;
case WM_CLOSE:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0; // message handled
}
ATOM registerClass(HINSTANCE hInstance) {
WNDCLASSEX wcex;
ZeroMemory(&wcex, sizeof(wcex));
wcex.cbSize = sizeof(wcex);
wcex.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wcex.lpfnWndProc = WindowProcedure;
wcex.hInstance = hInstance;
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.lpszClassName = "Core";
return RegisterClassEx(&wcex);
}
void OpenGLRenderer::SetupGLCore(HWND hWnd)
{
HINSTANCE hInstance = reinterpret_cast<HINSTANCE>(GetWindowLong(hWnd, GWL_HINSTANCE));
registerClass(hInstance);
HWND fakeWND = CreateWindow(
"Core", "Fake Window", // window class, title
WS_CLIPSIBLINGS | WS_CLIPCHILDREN, // style
0, 0, // position x, y
1, 1, // width, height
NULL, NULL, // parent window, menu
hInstance, NULL); // instance, param
HDC fakeDC = GetDC(fakeWND); // Device Context
PIXELFORMATDESCRIPTOR fakePFD;
ZeroMemory(&fakePFD, sizeof(fakePFD));
fakePFD.nSize = sizeof(fakePFD);
fakePFD.nVersion = 1;
fakePFD.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
fakePFD.iPixelType = PFD_TYPE_RGBA;
fakePFD.cColorBits = 32;
fakePFD.cAlphaBits = 8;
fakePFD.cDepthBits = 24;
int fakePFDID = ChoosePixelFormat(fakeDC, &fakePFD);
if (fakePFDID == 0) {
OutputDebugString("Error choosing pixel format.");
}
if (SetPixelFormat(fakeDC, fakePFDID, &fakePFD) == false) {
OutputDebugString("Error setting pixel format.");
}
HGLRC fakeRC = wglCreateContext(fakeDC); // Rendering Contex
if (fakeRC == 0) {
OutputDebugString("Error creating initial gl context.");
}
if (wglMakeCurrent(fakeDC, fakeRC) == false) {
OutputDebugString("Error setting initial gl context.");
}
const int pixelAttribs[] = {
WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
WGL_COLOR_BITS_ARB, 32,
WGL_ALPHA_BITS_ARB, 8,
WGL_DEPTH_BITS_ARB, 24,
WGL_STENCIL_BITS_ARB, 8,
WGL_SAMPLE_BUFFERS_ARB, GL_TRUE,
WGL_SAMPLES_ARB, 4,
0
};
PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = nullptr;
wglChoosePixelFormatARB = reinterpret_cast<PFNWGLCHOOSEPIXELFORMATARBPROC>(wglGetProcAddress("wglChoosePixelFormatARB"));
if (wglChoosePixelFormatARB == nullptr) {
}
PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = nullptr;
wglCreateContextAttribsARB = reinterpret_cast<PFNWGLCREATECONTEXTATTRIBSARBPROC>(wglGetProcAddress("wglCreateContextAttribsARB"));
if (wglCreateContextAttribsARB == nullptr) {
}
mHdc = GetDC(hWnd);
int pixelFormatID; UINT numFormats;
bool status = wglChoosePixelFormatARB(mHdc, pixelAttribs, NULL, 1, &pixelFormatID, &numFormats);
if (status == false || numFormats == 0) {
}
const int pixelAttribsModern[] = {
WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
WGL_COLOR_BITS_ARB, 32,
WGL_ALPHA_BITS_ARB, 8,
WGL_DEPTH_BITS_ARB, 24,
WGL_STENCIL_BITS_ARB, 8,
WGL_SAMPLE_BUFFERS_ARB, GL_TRUE,
WGL_SAMPLES_ARB, 4,
0
};
int pixelFormatIDModern; UINT numFormatsModern;
status = wglChoosePixelFormatARB(mHdc, pixelAttribsModern, NULL, 1, &pixelFormatIDModern, &numFormatsModern);
if (status == false || numFormats == 0) {
}
PIXELFORMATDESCRIPTOR PFD;
DescribePixelFormat(mHdc, pixelFormatID, sizeof(PFD), &PFD);
SetPixelFormat(mHdc, pixelFormatID, &PFD);
const int major_min = 4, minor_min = 5;
int contextAttribs[] = {
WGL_CONTEXT_MAJOR_VERSION_ARB, major_min,
WGL_CONTEXT_MINOR_VERSION_ARB, minor_min,
WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
0
};
HGLRC RC = wglCreateContextAttribsARB(mHdc, 0, contextAttribs);
if (RC == NULL) {
}
wglMakeCurrent(NULL, NULL);
wglDeleteContext(fakeRC);
ReleaseDC(fakeWND, fakeDC);
DestroyWindow(fakeWND);
if (!wglMakeCurrent(mHdc, RC)) {
}
gladLoadGL();
}
void OpenGLRenderer::SetupOldGL(HWND hWnd)
{
mHdc = GetDC(hWnd);
PIXELFORMATDESCRIPTOR pfd;
ZeroMemory(&pfd, sizeof(pfd));
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 24;
pfd.cDepthBits = 16;
pfd.iLayerType = PFD_MAIN_PLANE;
int iFormat = ChoosePixelFormat(mHdc, &pfd);
SetPixelFormat(mHdc, iFormat, &pfd);
mpDev = wglCreateContext(mHdc);
wglMakeCurrent(mHdc, mpDev);
gladLoadGL();
}
//-----------------------------------------------------------------------------------
OpenGLRenderer::OpenGLRenderer(RendererConfig config) : PlatformRenderer(config)
{
// Create Buffer Type Mappings
mBufferTypeMap[BT_COLOR] = GL_COLOR_BUFFER_BIT;
mBufferTypeMap[BT_DEPTH] = GL_DEPTH_BUFFER_BIT;
mBufferTypeMap[BT_STENCIL] = GL_STENCIL_BUFFER_BIT;
#ifdef WIN_RELEASE
InitializeForWindows(config);
#endif
glViewport(0, 0, (GLsizei)config.ScreenWidth, (GLsizei)config.ScreenHeight);
}
//-----------------------------------------------------------------------------------
#ifdef WIN_RELEASE
void OpenGLRenderer::InitializeForWindows( RendererConfig config )
{
HWND hWnd = (HWND)config.WindowHandle;
//SetupGLCore(hWnd);
SetupOldGL(hWnd);
}
#endif
//-----------------------------------------------------------------------------------
// This needs to be factored out.
void OpenGLRenderer::FakeSceneSetup(RendererConfig config)
{
}
//-----------------------------------------------------------------------------------
void OpenGLRenderer::SetVertexData(Mesh *pMesh)
{
for (unsigned int triangleIndex = 0; triangleIndex < pMesh->triangleData.size(); ++triangleIndex)
{
TriangleData triangle = *pMesh->triangleData[triangleIndex];
for (int i = 0; i < 3; ++i)
{
// Color must come before vertex,
// otherwise the color will not be assigned to the correct vertex.
(glColor4d((GLdouble)triangle.colors[i].r,
(GLdouble)triangle.colors[i].g,
(GLdouble)triangle.colors[i].b,
(GLdouble)triangle.colors[i].a));
(glTexCoord2d(triangle.uvs[i].x(), triangle.uvs[i].y()));
(glNormal3f(triangle.normals[i].x(), triangle.normals[i].y(), triangle.normals[i].z()));
(glVertex3f(triangle.verts[i].x(), triangle.verts[i].y(), triangle.verts[i].z()));
}
}
}
//-----------------------------------------------------------------------------------
void OpenGLRenderer::Clear( unsigned int buffers, Color c)
{
unsigned int FinalBuffers = 0;
FinalBuffers |= ( PlatformRenderer::BT_COLOR & buffers) != 0 ? mBufferTypeMap[BT_COLOR] : 0;
FinalBuffers |= ( PlatformRenderer::BT_DEPTH & buffers) != 0 ? mBufferTypeMap[BT_DEPTH] : 0;
FinalBuffers |= ( PlatformRenderer::BT_STENCIL & buffers) != 0 ? mBufferTypeMap[BT_STENCIL] : 0;
GL_VERIFY(glClear(FinalBuffers));
GL_VERIFY(glClearColor(c.r, c.g, c.b, c.a));
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}
//-----------------------------------------------------------------------------------
void OpenGLRenderer::UpdateMatricies()
{
GL_VERIFY(glMatrixMode(GL_PROJECTION));
GL_VERIFY(glLoadMatrixf(mMatProjection.mMatrix));
Matrix4x4 matModelView = mMatWorld * mMatView;
GL_VERIFY(glMatrixMode(GL_MODELVIEW));
GL_VERIFY(glLoadMatrixf(matModelView.mMatrix));
}
//-----------------------------------------------------------------------------------
void OpenGLRenderer::BeginScene()
{
/*
glEnable( GL_DEPTH_TEST );
glMatrixMode(GL_PROJECTION);
glLoadMatrixf(mMatProjection.mMatrix);
Matrix4x4 matModelView = mMatWorld * mMatView;
glMatrixMode(GL_MODELVIEW);
glLoadMatrixf(matModelView.mMatrix);
*/
(glBegin(GL_TRIANGLES));
}
//-----------------------------------------------------------------------------------
void OpenGLRenderer::CreateTexture(Texture2D &texture)
{
OpenGLTexture2D *pTexture = static_cast<OpenGLTexture2D*>(&texture);
int wrap = 1;
GL_VERIFY(glPixelStorei(GL_UNPACK_ALIGNMENT, 1));
GL_VERIFY(glGenTextures(1, (GLuint*)&pTexture->iTextureID));
GL_VERIFY(glBindTexture(GL_TEXTURE_2D, pTexture->iTextureID));
// Begin New
GL_VERIFY(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT));
GL_VERIFY(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT));
GL_VERIFY(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST));
GL_VERIFY(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_NEAREST));
GL_VERIFY(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, pTexture->Width,
pTexture->Height, 0, GL_RGB, GL_UNSIGNED_BYTE,
pTexture->data));
}
//-----------------------------------------------------------------------------------
void OpenGLRenderer::BindTexture( Texture2D *pTexture )
{
if( pTexture != 0 )
{
OpenGLTexture2D *pOpenGLTexture = static_cast<OpenGLTexture2D*>(pTexture);
GL_VERIFY(glEnable( GL_TEXTURE_2D ));
GL_VERIFY(glBindTexture( GL_TEXTURE_2D, pOpenGLTexture->iTextureID));
}
else
{
GL_VERIFY(glBindTexture( GL_TEXTURE_2D, 0 ));
GL_VERIFY(glDisable( GL_TEXTURE_2D ));
}
}
//-----------------------------------------------------------------------------------
void OpenGLRenderer::EndScene()
{
GL_VERIFY(glEnd());
}
//-----------------------------------------------------------------------------------
void OpenGLRenderer::Present()
{
SwapBuffers(mHdc);
GL_VERIFY(glFlush());
}
//-----------------------------------------------------------------------------------
void OpenGLRenderer::DrawDebugLine(Vector3 *start, Vector3 *end, Color *color)
{
UpdateMatricies();
glLineWidth(2.0f);
glBegin(GL_LINES);
// Color must come before vertex,
// otherwise the color will not be assigned to the correct vertex.
glColor4d( (GLdouble)color->r,
(GLdouble)color->g,
(GLdouble)color->b,
(GLdouble)1.0f );
glVertex3f(start->x(),start->y(),start->z());
// Color must come before vertex,
// otherwise the color will not be assigned to the correct vertex.
glColor4d( (GLdouble)color->r,
(GLdouble)color->g,
(GLdouble)color->b,
(GLdouble)1.0f );
glVertex3f(end->x(),end->y(),end->z());
glEnd();
}
//-----------------------------------------------------------------------------------
OpenGLRenderer::~OpenGLRenderer()
{
}
#endif |
8ae646a296abbbc8c0a5263dca71a31a77242b45 | bae937802411ba1ed87c4b212dd3852782c20831 | /cparser/parser_expression.cpp | 15cfdad3214e28fbafe4541ae659da506c1f7927 | [] | no_license | yuyfbj/c_compiler | 398b576431514bbd874775da89a7899118c0d12a | 6618bc948a74439b82b51ea4809761310fae46fc | refs/heads/master | 2020-04-05T12:36:01.969540 | 2017-07-13T08:27:11 | 2017-07-13T08:27:11 | 95,176,106 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 31,091 | cpp | parser_expression.cpp |
#include "parser_expression.h"
#include "public_func.h"
#include "parser_declare.h"
namespace expr
{
using namespace pub_func;
using namespace decl;
item_assignment_operator* assignment_operator()
{
//每个函数只关注自己预期得到,若得不到就报错。说明有语法问题 。
//assignment_operator
// : '='
// | MUL_ASSIGN
// | DIV_ASSIGN
// | MOD_ASSIGN
// | ADD_ASSIGN
// | SUB_ASSIGN
// | LEFT_ASSIGN
// | RIGHT_ASSIGN
// | AND_ASSIGN
// | XOR_ASSIGN
// | OR_ASSIGN
// ;
//item_assignment_operator* item = new item_assignment_expression;
auto item = NewItem<item_assignment_operator>();
if (NULL == item)
return NULL;
std::string strval;
int token = pre_get_token_val(strval);
if ('=' == token
|| MUL_ASSIGN == token
|| DIV_ASSIGN == token
|| MOD_ASSIGN == token
|| ADD_ASSIGN == token
|| SUB_ASSIGN == token
|| LEFT_ASSIGN == token
|| RIGHT_ASSIGN == token
|| AND_ASSIGN == token
|| XOR_ASSIGN == token
|| OR_ASSIGN == token
)
{
pop_token();
item->op = token;
item->right = strval;
return item;
}
return ReleaseItem<item_assignment_operator>(item);
};
//unary_operator
item_unary_operator* unary_operator()
{
//unary_operator
//: '&'
//| '*'
//| '+'
//| '-'
//| '~'
//| '!'
//;
auto item = NewItem<item_unary_operator>();
if (NULL == item)
return NULL;
std::string val;
int token = pre_get_token_val(val);
if (
'&' == token
|| '*' == token
|| '+' == token
|| '-' == token
|| '~' == token
|| '!' == token
)
{
pop_token();
item->op = token;
item->right = val;
return item;
}
return ReleaseItem<item_unary_operator>(item);
};
item_type_name* type_name()
{
/*type_name
: type_specifier
| specifier_qualifier_list abstract_declarator
;
*/
auto item = NewItem<item_type_name>();
if (!item)
return NULL;
auto item1 = type_specifier();
if (item1)
{
item->right1 = item1;
return item;
}
auto item2 = specifier_qualifier_list();
if (item2)
{
item->right2 = item2;
auto item3 = abstract_declarator();
if (item3)
{
item->right3 = item3;
return item;
}
}
return ReleaseItem<item_type_name>(item);
}
item_cast_expression* cast_expression()
{
/* cast_expression
: unary_expression
| '(' type_name ')' cast_expression
;*/
auto item = NewItem<item_cast_expression>();
if (!item)
return NULL;
std::string val;
int token = pre_get_token_val(val);
if ('(' == token)
{//'(' type_name ')' cast_expression
pop_token();
item->op = token;
item->right = val;
auto item2 = type_name();
if (item2)
{
item->right2 = item2;
token = pre_get_token_val(val);
if (')' == token)
{
pop_token();
item->right += val;
auto item3 = cast_expression();
if (item3)
{
item->right3 = item3;
return item;
}
}
}
}
auto item1 = unary_expression();
if (item1)
{// unary_expression
item->right1 = item1;
return item;
}
return ReleaseItem<item_cast_expression>(item);
}
/*消除产生式中的直接左递归是比较容易的。例如假设非终结符P的规则为
P→Pα / β
其中,β是不以P开头的符号串。那么,我们可以把P的规则改写为如下的非直接左递归形式:
P→βP’
P’→αP’ / ε*/
item_multiplicative_expression_ex* multiplicative_expression_ex()
{
/*multiplicative_expression_ex
: '*' cast_expression multiplicative_expression_ex
| '/' cast_expression multiplicative_expression_ex
| '%' cast_expression multiplicative_expression_ex
;*/
auto item = NewItem<item_multiplicative_expression_ex>();
if (!item)
return NULL;
std::string val;
int token = pre_get_token_val(val);
if ('*' == token
|| '/' == token
|| '%' == token
)
{
pop_token();
item->op = token;
item->right = val;
auto item1 = cast_expression();
if (item1)
{
item->right1 = item1;
auto item2 = multiplicative_expression_ex();
if (item2)
item->right2 = item2;
return item;
}
}
return ReleaseItem<item_multiplicative_expression_ex>(item);
}
item_multiplicative_expression* multiplicative_expression()
{
/*multiplicative_expression
: cast_expression
| multiplicative_expression '*' cast_expression
| multiplicative_expression '/' cast_expression
| multiplicative_expression '%' cast_expression
;
multiplicative_expression
: cast_expression multiplicative_expression_ex
;
multiplicative_expression_ex
: '*' cast_expression multiplicative_expression_ex
| '/' cast_expression multiplicative_expression_ex
| '%' cast_expression multiplicative_expression_ex
;
*/
auto item = NewItem<item_multiplicative_expression>();
if (!item)
return NULL;
auto item1 = cast_expression();
if (item1)
{
item->right1 = item1;
auto item2 = multiplicative_expression_ex();
if (item2)
{
item->right2 = item2;
}
return item;
}
return ReleaseItem<item_multiplicative_expression>(item);
}
item_additive_expression_ex* additive_expression_ex()
{
/*additive_expression_ex
: '+' multiplicative_expression additive_expression_ex
| '-' multiplicative_expression additive_expression_ex
| EMPTY
;*/
auto item = NewItem<item_additive_expression_ex>();
if (!item)
return NULL;
std::string val;
int token = pre_get_token_val(val);
if (token == '+'
|| token == '-'
)
{
pop_token();
item->op = token;
item->right = val;
auto item1 = multiplicative_expression();
if (item1)
{
item->right1 = item1;
auto item2 = additive_expression_ex();
if (item2)
item->right2 = item2;
return item;
}
}
return ReleaseItem<item_additive_expression_ex>(item);
}
item_additive_expression* additive_expression()
{
/*additive_expression
: multiplicative_expression
| additive_expression '+' multiplicative_expression
| additive_expression '-' multiplicative_expression
;
additive_expression
: multiplicative_expression additive_expression_ex
;
additive_expression_ex
: '+' multiplicative_expression additive_expression_ex
| '-' multiplicative_expression additive_expression_ex
|EMPTY
;
*/
auto item = NewItem<item_additive_expression>();
if (!item)
return NULL;
auto item1 = multiplicative_expression();
if (item1)
{
item->right1 = item1;
auto item2 = additive_expression_ex();
if (item2)
item->right2 = item2;
return item;
}
return ReleaseItem<item_additive_expression>(item);
}
/*消除产生式中的直接左递归是比较容易的。例如假设非终结符P的规则为
P→Pα / β
其中,β是不以P开头的符号串。那么,我们可以把P的规则改写为如下的非直接左递归形式:
P→βP’
P’→αP’ / ε
shift_expression
: additive_expression P'
P':
LEFT_OP additive_expression P'
| empty
*/
item_shift_expression_ex* shift_expression_ex()
{
/*shift_expression_ex
: LEFT_OP additive_expression shift_expression_ex
| RIGHT_OP additive_expression shift_expression_ex
| EMPTY
;*/
auto item = NewItem<item_shift_expression_ex>();
if (!item)
return NULL;
std::string val;
int token = pre_get_token_val(val);
if (LEFT_OP == token
|| RIGHT_OP == token
)
{
pop_token();
item->op = token;
item->right = val;
auto item1 = additive_expression();
if (item1)
{
item->right1 = item1;
auto item2 = shift_expression_ex();
if (item2)
item->right2 = item2;
return item;
}
}
return ReleaseItem<item_shift_expression_ex>(item);
}
item_shift_expression* shift_expression()
{
/*shift_expression
: additive_expression
| shift_expression LEFT_OP additive_expression
| shift_expression RIGHT_OP additive_expression
;
shift_expression
: additive_expression shift_expression_ex
;
shift_expression_ex
: LEFT_OP additive_expression shift_expression_ex
| RIGHT_OP additive_expression shift_expression_ex
|EMPTY
;
*/
auto item = NewItem<item_shift_expression>();
if (!item)
return NULL;
auto item1 = additive_expression();
if (item1)
{
item->right1 = item1;
auto item2 = shift_expression_ex();
if (item2)
item->right2 = item2;
return item;
}
return ReleaseItem<item_shift_expression>(item);
}
item_relational_expression_ex* relational_expression_ex()
{
/*
relational_expression_ex
: '<' shift_expression relational_expression_ex
| '>' shift_expression relational_expression_ex
| LE_OP shift_expression relational_expression_ex
| GE_OP shift_expression relational_expression_ex
|EMPTY
;
*/
auto item = NewItem<item_relational_expression_ex>();
if (!item)
return NULL;
std::string val;
int token = pre_get_token_val(val);
if ('>' == token
|| '<' == token
|| LE_OP == token
|| GE_OP == token
)
{
pop_token();
item->op = token;
item->right = val;
auto item1 = shift_expression();
if (item1)
{
item->right1 = item1;
auto item2 = relational_expression_ex();
if (item2)
item->right2 = item2;
return item;
}
}
return ReleaseItem<item_relational_expression_ex>(item);
}
item_relational_expression* relational_expression()
{
/*relational_expression
: shift_expression
| relational_expression '<' shift_expression
| relational_expression '>' shift_expression
| relational_expression LE_OP shift_expression
| relational_expression GE_OP shift_expression
;
relational_expression
: shift_expression relational_expression_ex
;
relational_expression_ex
: '<' shift_expression relational_expression_ex
| '>' shift_expression relational_expression_ex
| LE_OP shift_expression relational_expression_ex
| GE_OP shift_expression relational_expression_ex
|EMPTY
;
*/
auto item = NewItem<item_relational_expression>();
if (!item)
return NULL;
auto item1 = shift_expression();
if (item1)
{
item->right1 = item1;
auto item2 = relational_expression_ex();
if (item2)
item->right2 = item2;
return item;
}
return ReleaseItem<item_relational_expression>(item);
}
item_equality_expression_ex* equality_expression_ex()
{
/*
equality_expression_ex
: EQ_OP relational_expression equality_expression_ex
| NE_OP relational_expression equality_expression_ex
| EMPTY
;
*/
auto item = NewItem<item_equality_expression_ex>();
if (!item)
return NULL;
std::string val;
int token = pre_get_token_val(val);
if (EQ_OP == token
|| NE_OP == token)
{
pop_token();
item->op = token;
item->right = val;
auto item1 = relational_expression();
if (item1)
{
return ReleaseItem<item_equality_expression_ex>(item);
}
item->right1 = item1;
auto item2 = equality_expression_ex();
if (item2)
item->right2 = item2;
}
return item;
}
item_equality_expression* equality_expression()
{
/*equality_expression
: relational_expression
//| equality_expression EQ_OP relational_expression
| relational_expression EQ_OP equality_expression
//| equality_expression NE_OP relational_expression
| relational_expression NE_OP equality_expression
;
equality_expression
: relational_expression equality_expression_ex
;
equality_expression_ex
: EQ_OP relational_expression equality_expression_ex
| NE_OP relational_expression equality_expression_ex
| EMPTY
;
*/
auto item = NewItem<item_equality_expression>();
if (!item)
return NULL;
auto item1 = relational_expression();
if (item1)
{
item->right1 = item1;
auto item2 = equality_expression_ex();
if (item2)
{
item->right2 = item2;
}
return item;
}
return ReleaseItem<item_equality_expression>(item);
}
item_and_expression_ex* and_expression_ex()
{
/*and_expression_ex
: '&' equality_expression and_expression_ex
| EMPTY*/
auto item = NewItem<item_and_expression_ex>();
if (!item)
return NULL;
std::string val;
int token = pre_get_token_val(val);
if ('&' == token)
{
pop_token();
item->op = token;
item->right = val;
auto item1 = equality_expression();
if (item1)
{
item->right1 = item1;
auto item2 = and_expression_ex();
if (item2)
item->right2 = item2;
return item;
}
}
return ReleaseItem<item_and_expression_ex>(item);
}
item_and_expression* and_expression()
{
/*and_expression
: equality_expression
//| and_expression '&' equality_expression
| equality_expression '&' and_expression
;
and_expression
: equality_expression and_expression_ex
;
and_expression_ex
: '&' equality_expression and_expression_ex
|EMPTY
*/
auto item = NewItem<item_and_expression>();
if (!item)
return NULL;
auto item1 = equality_expression();
if (item1)
{
item->right1 = item1;
auto item2 = and_expression_ex();
if (item2)
{
item->right2 = item2;
}
return item;
}
return ReleaseItem<item_and_expression>(item);
}
item_exclusive_or_expression_ex* exclusive_or_expression_ex()
{
/* exclusive_or_expression_ex
| '^' and_expression exclusive_or_expression_ex
|EMPTY
;
*/
auto item = NewItem<item_exclusive_or_expression_ex>();
if (!item)
return NULL;
std::string val;
int token = pre_get_token_val(val);
if ('^' == token)
{
pop_token();
item->op = token;
item->right = val;
auto item1 = and_expression();
if (item1)
{
item->right1 = item1;
auto item2 = exclusive_or_expression_ex();
if (item2)
item->right2 = item2;
return item;
}
}
return ReleaseItem<item_exclusive_or_expression_ex>(item);
}
item_exclusive_or_expression* exclusive_or_expression()
{
/*exclusive_or_expression
: and_expression
//| exclusive_or_expression '^' and_expression
| and_expression '^' exclusive_or_expression
;
exclusive_or_expression
: and_expression exclusive_or_expression_ex
;
exclusive_or_expression_ex
| '^' and_expression exclusive_or_expression_ex
|EMPTY
;
*/
auto item = NewItem<item_exclusive_or_expression>();
if (!item)
return NULL;
auto item1 = and_expression();
if (item1)
{
item->right1 = item1;
auto item2 = exclusive_or_expression_ex();
if (item2)
item->right2 = item2;
return item;
}
return ReleaseItem<item_exclusive_or_expression>(item);
}
item_inclusive_or_expression_ex* inclusive_or_expression_ex()
{
/* ;
inclusive_or_expression_ex
: '|' exclusive_or_expression inclusive_or_expression_ex
|EMPTY;
*/
auto item = NewItem<item_inclusive_or_expression_ex>();
if (!item)
return NULL;
std::string val;
int token = pre_get_token_val(val);
if ('|' == token)
{
pop_token();
item->op = token;
item->right = val;
auto item1 = exclusive_or_expression();
if (item1)
{
item->right1 = item1;
auto item2 = inclusive_or_expression_ex();
if (item2)
{
item->right2 = item2;
}
return item;
}
}
return ReleaseItem<item_inclusive_or_expression_ex>(item);
}
item_inclusive_or_expression* inclusive_or_expression()
{
/*inclusive_or_expression
: exclusive_or_expression
//| inclusive_or_expression '|' exclusive_or_expression
| exclusive_or_expression '|' inclusive_or_expression
;
inclusive_or_expression
: exclusive_or_expression inclusive_or_expression_ex
;
inclusive_or_expression_ex
: '|' exclusive_or_expression inclusive_or_expression_ex
|EMPTY;
*/
auto item = NewItem<item_inclusive_or_expression>();
if (!item)
return NULL;
auto item1 = exclusive_or_expression();
if (item1)
{
item->right1 = item1;
auto item2 = inclusive_or_expression_ex();
if (item2)
item->right2 = item2;
return item;
}
return ReleaseItem<item_inclusive_or_expression>(item);
}
item_logical_and_expression_ex* logical_and_expression_ex()
{
/*logical_and_expression_ex
: AND_OP inclusive_or_expression logical_and_expression_ex
| EMPTY
;*/
auto item = NewItem<item_logical_and_expression_ex>();
if (!item)
return NULL;
std::string val;
int token = pre_get_token_val(val);
if (AND_OP == token)
{
pop_token();
item->op = token;
item->right = val;
auto item1 = inclusive_or_expression();
if (item1)
{
item->right1 = item1;
auto item2 = logical_and_expression_ex();
if (item2)
item->right2 = item2;
return item;
}
}
return ReleaseItem<item_logical_and_expression_ex>(item);
}
item_logical_and_expression* logical_and_expression()
{
/*logical_and_expression
: inclusive_or_expression
//| logical_and_expression AND_OP inclusive_or_expression
| inclusive_or_expression AND_OP logical_and_expression
;
logical_and_expression
: inclusive_or_expression logical_and_expression_ex
;
logical_and_expression_ex
: AND_OP inclusive_or_expression logical_and_expression_ex
|EMPTY
;
*/
auto item = NewItem<item_logical_and_expression>();
if (!item)
return NULL;
auto item1 = inclusive_or_expression();
if (item1)
{
item->right1 = item1;
auto item2 = logical_and_expression_ex();
if (item2)
item->right2 = item2;
return item;
}
return ReleaseItem<item_logical_and_expression>(item);
}
item_logical_or_expression_ex* logical_or_expression_ex()
{
/*logical_or_expression_ex
: OR_OP logical_and_expression logical_or_expression_ex
| EMPTY
;*/
auto item = NewItem<item_logical_or_expression_ex>();
if (!item)
return NULL;
std::string val;
int token = pre_get_token_val(val);
if (OR_OP == token)
{
pop_token();
item->op = token;
item->right = val;
auto item1 = logical_and_expression();
if (item1)
{
item->right1 = item1;
auto item2 = logical_or_expression_ex();
if (item2)
item->right2 = item2;
return item;
}
}
return ReleaseItem<item_logical_or_expression_ex>(item);
}
item_logical_or_expression* logical_or_expression()
{
//logical_or_expression
// : logical_and_expression
// | logical_or_expression OR_OP logical_and_expression
// ;
/*
logical_or_expression
: logical_and_expression logical_or_expression_ex
;
logical_or_expression_ex
: OR_OP logical_and_expression logical_or_expression_ex
|EMPTY
;
*/
auto item = NewItem<item_logical_or_expression>();
if (!item)
return NULL;
auto item1 = logical_and_expression();
if (item1)
{
item->right1 = item1;
auto item2 = logical_or_expression_ex();
if (item2)
item->right2 = item2;
return item;
}
return ReleaseItem<item_logical_or_expression>(item);
}
item_conditional_expression* conditional_expression()
{
/*conditional_expression
: logical_or_expression
| logical_or_expression '?' expression ':' conditional_expression
;*/
auto item = NewItem<item_conditional_expression>();
if (NULL == item)
return NULL;
auto item1 = logical_or_expression();
if (item1)
{
item->right1 = item1;
std::string val;
int token = pre_get_token_val(val);
if ('?' == token)
{
pop_token();
item->op = token;
item->right = val;
auto item2 = expression();
if (item2)
{
item->right2 = item2;
token = pre_get_token_val(val);
if (':' == token)
{
pop_token();
auto item3 = conditional_expression();
if (item3)
{
item->right3 = item3;
return item;
}
}
}
}
return item;
}
return ReleaseItem<item_conditional_expression>(item);
};
//======================================================
item_argument_expression_list_ex* argument_expression_list_ex()
{
auto item = NewItem<item_argument_expression_list_ex>();
if (!item)
return NULL;
/*
argument_expression_list_ex
: ',' assignment_expression argument_expression_list_ex
|EMPTY
;
*/
std::string val;
int token = pre_get_token_val(val);
if (',' == token)
{
pop_token();
item->op = token;
item->right = val;
auto item1 = assignment_expression();
if (item1)
{
item->right1 = item1;
auto item2 = argument_expression_list_ex();
if (item2)
item->right2 = item2;
return item;
}
}
return ReleaseItem<item_argument_expression_list_ex>(item);
}
item_argument_expression_list* argument_expression_list()
{
auto item = NewItem<item_argument_expression_list>();
if (!item)
return NULL;
/*argument_expression_list
: assignment_expression
| argument_expression_list ',' assignment_expression
;
argument_expression_list
: assignment_expression argument_expression_list_ex
;
argument_expression_list_ex
: ',' assignment_expression argument_expression_list_ex
|EMPTY
;
*/
auto item1 = assignment_expression();
if (item1)
{
auto item2 = argument_expression_list_ex();
if (item2)
item->right2 = item2;
return item;
}
return ReleaseItem<item_argument_expression_list>(item);
}
item_postfix_expression_ex* postfix_expression_ex()
{
/*
postfix_expression_ex
: '[' expression ']' postfix_expression_ex
| '(' ')' postfix_expression_ex
| '(' argument_expression_list ')' postfix_expression_ex
| '.' IDENTIFIER postfix_expression_ex
| PTR_OP IDENTIFIER postfix_expression_ex
| INC_OP postfix_expression_ex
| DEC_OP postfix_expression_ex
| EMPTY
;
*/
auto item = NewItem<item_postfix_expression_ex>();
if (!item)
return NULL;
std::string val;
int token = pre_get_token_val(val);
if ('.' == token
|| PTR_OP == token
)
{
//| '.' IDENTIFIER postfix_expression_ex
//| PTR_OP IDENTIFIER postfix_expression_ex
pop_token();
item->op = token;
item->right = val;
token = pre_get_token_val(val);
if (IDENTIFIER == token)
{
pop_token();
auto item3 = NewItem<item_identifier>();
if (item3)
{
item3->op = token;
item3->right = val;
item->right3 = item3;
auto item2 = postfix_expression_ex();
if (item2)
item->right2 = item2;
return item;
}
}
}
else if ('[' == token)
{
//: '[' expression ']' postfix_expression_ex
pop_token();
item->op = token;
item->right = val;
auto item1 = expression();
if (item1)
{
item->right1 = item1;
token = pre_get_token_val(val);
if (']' == token)
{
pop_token();
item->right += val;
auto item2 = postfix_expression_ex();
if (item2)
item->right2 = item2;
return item;
}
}
}
else if ('(' == token)
{
//| '(' ')' postfix_expression_ex
//| '(' argument_expression_list ')' postfix_expression_ex
pop_token();
item->op = token;
token = pre_get_token_val(val);
if (')' == token)
{
pop_token();
item->right += val;
auto item2 = postfix_expression_ex();
if (item2)
item->right2 = item2;
return item;
}
auto item4 = argument_expression_list();
if (item4)
{
item->right4 = item4;
token = pre_get_token_val(val);
if (')' == token)
{
pop_token();
item->right += val;
auto item2 = postfix_expression_ex();
if (item2)
item->right2 = item2;
return item;
}
}
}
else if (INC_OP == token
|| DEC_OP == token
)
{//| INC_OP postfix_expression_ex
//| DEC_OP postfix_expression_ex
pop_token();
item->op = token;
item->right = val;
auto item2 = postfix_expression_ex();
if (item2)
item->right2 = item2;
return item;
}
return ReleaseItem<item_postfix_expression_ex>(item);
}
item_postfix_expression* postfix_expression()
{
//postfix_expression
// : primary_expression
// | postfix_expression '[' expression ']'
// | postfix_expression '(' ')'
// | postfix_expression '(' argument_expression_list ')'
// | postfix_expression '.' IDENTIFIER
// | postfix_expression PTR_OP IDENTIFIER
// | postfix_expression INC_OP
// | postfix_expression DEC_OP
// ;
/*消除左递归后
postfix_expression
: primary_expression postfix_expression_ex
;
postfix_expression_ex
: '[' expression ']' postfix_expression_ex
| '(' ')' postfix_expression_ex
| '(' argument_expression_list ')' postfix_expression_ex
| '.' IDENTIFIER postfix_expression_ex
| PTR_OP IDENTIFIER postfix_expression_ex
| INC_OP postfix_expression_ex
| DEC_OP postfix_expression_ex
| EMPTY
*/
auto item = NewItem<item_postfix_expression>();
if (!item)
return NULL;
auto item1 = primary_expression();
if (item1)
{
item->right1 = item1;
auto item2 = postfix_expression_ex();
if (item2)
item->right2 = item2;
return item;
}
return ReleaseItem<item_postfix_expression>(item);
}
//unary_expression
item_unary_expression * unary_expression()
{
/*unary_expression
: postfix_expression
| INC_OP unary_expression
| DEC_OP unary_expression
| unary_operator cast_expression
| SIZEOF unary_expression
| SIZEOF '(' type_name ')'*/
auto item = NewItem<item_unary_expression>();
if (!item)
return NULL;
std::string val;
int token = pre_get_token_val(val);
if (INC_OP == token
|| DEC_OP == token
)
{//| INC_OP unary_expression
//| DEC_OP unary_expression
pop_token();
item->op = token;
item->right = val;
auto item2 = unary_expression();
if (item2)
{
item->right2 = item2;
return item;
}
}
if (SIZEOF == token)
{//| SIZEOF unary_expression
//| SIZEOF '(' type_name ')'
pop_token();
item->op = token;
item->right = val;
token = pre_get_token_val(val);
if ('(' == token)
{
auto item4 = type_name();
if (item4)
{
item->right4 = item4;
token = pre_get_token_val(val);
if (')' == token)
{
pop_token();
return item;
}
}
}
}
auto item_op = unary_operator();
if (item_op)
{
item->op = item_op->op;
auto item3 = cast_expression();
if (item3)
{
item->right3 = item3;
return item;
}
}
auto item1 = postfix_expression();
if (item1)
{
item->right1 = item1;
return item;
}
return ReleaseItem<item_unary_expression>(item);
};
//assignment_expression
item_assignment_expression* assignment_expression()
{
/*assignment_expression
: conditional_expression
| unary_expression assignment_operator assignment_expression
;*/
auto item = NewItem<item_assignment_expression>();
if (!item)
return NULL;
auto item1 = conditional_expression();
if (item1)
{//conditional_expression
item->right1 = item1;
return item;
}
auto item2 = unary_expression();
if (item2)
{
// unary_expression assignment_operator assignment_expression
item->gen_index = 1;
item->right2 = item2;
auto item3 = assignment_operator();
if (item3)
{
item->right3 = item3;
auto item4 = assignment_expression();
if (item4)
{
item->right4 = item4;
return item;
}
}
}
return ReleaseItem<item_assignment_expression>(item);
};
item_expression_ex* expression_ex()
{
/*expression_ex
: ',' assignment_expression expression_ex
| EMPTY*/
auto item = NewItem<item_expression_ex>();
if (!item)
return NULL;
std::string val;
int token = pre_get_token_val(val);
if (token == ',')
{
pop_token();
item->op = token;
item->right = val;
auto item1 = assignment_expression();
if (item1)
{
item->right1 = item1;
auto item2 = expression_ex();
if (item2)
item->right2 = item2;
return item;
}
}
return ReleaseItem<item_expression_ex>(item);
}
item_expression* expression()
{
/*expression
: assignment_expression
| expression ',' assignment_expression
;
//消除左递归。
expression
: assignment_expression expression_ex
expression_ex
: ',' assignment_expression expression_ex
| EMPTY
*/
auto item = NewItem<item_expression>();
if (!item)
return NULL;
auto item1 = assignment_expression();
if (item1)
{
item->right1 = item1;
auto item2 = expression_ex();
if (item2)
item->right2 = item2;
return item;
}
return ReleaseItem<item_expression>(item);
};
item_primary_expression* primary_expression()
{
///*primary_expression
// : IDENTIFIER
// | CONSTANT
//|F_CONSTANT
//|I_CONSTANT
// | STRING_LITERAL
// | '(' expression ')'
// ;*/
auto item = NewItem<item_primary_expression>();
if (!item)
return NULL;
std::string val;
int token = pre_get_token_val(val);
if (IDENTIFIER == token
|| CONSTANT == token
|| F_CONSTANT == token
|| I_CONSTANT == token
|| STRING_LITERAL == token
)
{
pop_token();
item->op = token;
item->right = val;
return item;
}
else if ('(' == token)
{
pop_token();
item->op = token;
item->right = val;
auto item1 = expression();
if (item1)
{
item->right1 = item1;
token = pre_get_token_val(val);
if (')' == token)
{
pop_token();
item->right += val;
return item;
}
}
}
return ReleaseItem<item_primary_expression>(item);
}
/*constant_expression
: conditional_expression
;*/
item_constant_expression* constant_expression()
{
/*constant_expression
: conditional_expression
;*/
auto item = NewItem<item_constant_expression>();
if (!item)
return NULL;
auto item1 = conditional_expression();
if (item1)
{
item->right1 = item1;
return item;
}
return ReleaseItem<item_constant_expression>(item);
}
//----------------------------------------------
item_expression* g_root = NULL;
bool main_parse()
{
auto item = expression();
g_root = item;
return true;
};
}
|
76c4067b270c01a295a43888659ead1703391ba0 | 826f33b5a00269bde164410bc5145eeefc47b3b5 | /include/KalmanDetection.h | 64b6c584dc830362fe6ee9b77ae84829565c96b2 | [] | no_license | larics/pointcloud_filter | d3fb88ccb3e9f4c523db8286b2bb4db1fd83afe1 | 0d8a787160e8921e620001b7404af67ede96b037 | refs/heads/master | 2020-09-09T09:44:57.059154 | 2020-04-21T10:24:15 | 2020-04-21T10:24:15 | 221,414,767 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,233 | h | KalmanDetection.h | #ifndef KALMAN_DETECTION_H
#define KALMAN_DETECTION_H
#include "KalmanFilter.h"
#include <pointcloud_filter/BrickDistanceParametersConfig.h>
#include <ros/ros.h>
#include <dynamic_reconfigure/server.h>
#include <std_msgs/Float32.h>
#define NO_DISTANCE_DETECTED -1
#define MAX_INVALID_TIME 2
typedef pointcloud_filter::BrickDistanceParametersConfig bdist_cfg;
class KalmanDetection
{
public:
KalmanDetection(std::string ns):
_bdistServer {_bdistMutex, ros::NodeHandle("kalman_ns/" + ns + "_config")},
_kalmanFilter {new KalmanFilter},
_kalmanInitialized {false},
_filteredDistance (NO_DISTANCE_DETECTED),
_filteredDistanceVel (0),
_timeInvalid (0),
_ns (ns)
{
}
~KalmanDetection()
{
}
void initializeParameters(ros::NodeHandle& nh)
{
ROS_WARN("KalmanDetection::initializeParameters()");
// Setup dynamic reconfigure server
double kalmanNoiseMv;
double kalmanNoisePos;
double kalmanNoiseVel;
bool initialized =
nh.getParam(_ns + "/kalman/noise_mv", kalmanNoiseMv) &&
nh.getParam(_ns + "/kalman/noise_pos", kalmanNoisePos) &&
nh.getParam(_ns + "/kalman/noise_vel", kalmanNoiseVel);
_kalmanFilter->setMeasureNoise(kalmanNoiseMv);
_kalmanFilter->setPositionNoise(kalmanNoisePos);
_kalmanFilter->setVelocityNoise(kalmanNoiseVel);
ROS_INFO_STREAM(*_kalmanFilter);
if (!initialized)
{
ROS_FATAL("KalmanDetection::initializeParameters() - parameter initialization failed.");
throw std::invalid_argument("KalmanDetection parameters not properly set.");
}
bdist_cfg cfg;
cfg.noise_mv = kalmanNoiseMv;
cfg.noise_pos = kalmanNoisePos;
cfg.noise_vel = kalmanNoiseVel;
_bdistServer.updateConfig(cfg);
_bdistParamCb = boost::bind(
&KalmanDetection::parametersCallback, this, _1, _2);
_bdistServer.setCallback(_bdistParamCb);
// Initialize publisher
_filtDistPub = nh.advertise<std_msgs::Float32>("kalman/" + _ns + "/filtered", 1);
_filtDistVelPub = nh.advertise<std_msgs::Float32>("kalman/" + _ns + "/filtered_vel", 1);
}
void parametersCallback(
bdist_cfg& configMsg,
uint32_t level)
{
ROS_DEBUG("KalmanDetection::parametersCallback");
_kalmanFilter->setMeasureNoise(configMsg.noise_mv);
_kalmanFilter->setPositionNoise(configMsg.noise_pos);
_kalmanFilter->setVelocityNoise(configMsg.noise_vel);
ROS_INFO_STREAM(*_kalmanFilter);
}
void filterCurrentDistance(double dt, double currDistance, bool newMeasurementFlag)
{
// Reset filtered distance if filter is not initialized
if (!_kalmanInitialized)
{
resetState();
}
// Check if initialization failed
if (!_kalmanInitialized && currDistance == NO_DISTANCE_DETECTED)
{
ROS_WARN_THROTTLE(5.0, "KalmanFilter - Failed to initialize");
return;
}
// Check if initialization should take place
if (!_kalmanInitialized && currDistance != NO_DISTANCE_DETECTED)
{
_kalmanInitialized = true;
_kalmanFilter->initializePosition(currDistance);
ROS_WARN("KalmanFilter - Initialized.");
}
// Do model update
_kalmanFilter->modelUpdate(dt);
// Do measure update if everything is valid
if (newMeasurementFlag &&currDistance != NO_DISTANCE_DETECTED)
{
// ROS_INFO("KalmanFilter - New measurement! update called");
_kalmanFilter->measureUpdate(currDistance);
_timeInvalid = 0;
}
else
{
// Increase time invalid
// ROS_WARN("KalmanFilter - doing only model update");
_timeInvalid += dt;
}
// Check if invalid time reached maximum
if (_timeInvalid > MAX_INVALID_TIME)
{
resetState();
ROS_FATAL("KalmanFilter - Max invalid time reached.");
return;
}
// Get kalman filter position and velocity
_filteredDistance = _kalmanFilter->getPosition();
_filteredDistanceVel = _kalmanFilter->getVelocity();
}
void publish()
{
std_msgs::Float32 distMsg;
distMsg.data = _filteredDistance;
_filtDistPub.publish(distMsg);
std_msgs::Float32 velMsg;
velMsg.data = _filteredDistanceVel;
_filtDistVelPub.publish(velMsg);
}
void resetState()
{
_kalmanInitialized = false;
_timeInvalid = 0;
_filteredDistance = NO_DISTANCE_DETECTED;
_filteredDistanceVel = 0;
}
double getState()
{
return _filteredDistance;
}
double getStateVel()
{
return _filteredDistanceVel;
}
private:
/** Define Dynamic Reconfigure parameters **/
boost::recursive_mutex _bdistMutex;
dynamic_reconfigure::Server<bdist_cfg> _bdistServer;
dynamic_reconfigure::Server<bdist_cfg>::CallbackType _bdistParamCb;
/** Kalman filter object */
std::unique_ptr<KalmanFilter> _kalmanFilter;
ros::Publisher _filtDistPub;
ros::Publisher _filtDistVelPub;
/** Flag signaling that kalman filter is initialized. */
bool _kalmanInitialized;
/** Filtered distance - Kalman Filter output */
double _filteredDistance;
/** Filtered distance velocity - Kalman Filter output */
double _filteredDistanceVel;
/** Time passed while measurements are invalid. */
double _timeInvalid;
const std::string _ns;
};
#endif /* KALMAN_DETECTION_H */ |
c601f4d28fb2e262647992d6ddc5fe14d289d706 | f99c0194278639456604ebf76443b65bf1c6ed04 | /blockcypher/include/blockcypher/TxResult.hpp | 42b7d5ff5262f60891159f794744a9e6aa3691b2 | [] | no_license | RdeWilde/JoyStream | e4ed42ff61af1f348cb49469caa8e30ccf3f8a52 | 95c2b6fc50251fbe4730b19d47c18bec86e18bf4 | refs/heads/master | 2021-06-11T20:26:46.682624 | 2016-05-10T08:27:05 | 2016-05-10T08:27:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 950 | hpp | TxResult.hpp | /**
* Copyright (C) JoyStream - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
* Written by Bedeho Mender <bedeho.mender@gmail.com>, February 11 2016
*/
#ifndef BLOCKCYPHER_TXRESULT_H
#define BLOCKCYPHER_TXRESULT_H
#include <blockcypher/UTXO.hpp>
#include <set>
namespace BlockCypher {
class TxResult {
public:
void confirmations(const uint32_t & conf) { _confirmations = conf; }
uint32_t confirmations() const { return _confirmations; }
void creates(const UTXO & utxo) { _creationSet.insert(utxo); }
std::set<UTXO> creates() const { return _creationSet; }
void destroys(const UTXO & utxo) { _destructionSet.insert(utxo); }
std::set<UTXO> destroys() const { return _destructionSet; }
private:
uint32_t _confirmations;
std::set<UTXO> _creationSet;
std::set<UTXO> _destructionSet;
};
}
#endif // BLOCKCYPHER_TXRESULT_H
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.