hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
8e7954158da411790676266ca929404d39018dc9
293
cpp
C++
Contest 1007/A.cpp
PC-DOS/SEUCPP-OJ-KEYS
073f97fb29a659abd25554330382f0a7149c2511
[ "MIT" ]
null
null
null
Contest 1007/A.cpp
PC-DOS/SEUCPP-OJ-KEYS
073f97fb29a659abd25554330382f0a7149c2511
[ "MIT" ]
null
null
null
Contest 1007/A.cpp
PC-DOS/SEUCPP-OJ-KEYS
073f97fb29a659abd25554330382f0a7149c2511
[ "MIT" ]
null
null
null
#include <iostream> #include <iomanip> #include <cmath> #include <string> #include <cstring> using namespace std; double squaresum(double a,double b){ return a*a+b*b; } int main(){ double a, b; cin >> a >> b; cout << squaresum(a,b); //system("pause > nul"); return 0; }
18.3125
36
0.614334
PC-DOS
8e7db9402c2b8958cd30d426a4d8167e7003406d
2,143
cpp
C++
Source/Samples/62_FlappyUrho/barrier.cpp
elix22/Urho3D
99902ae2a867be0d6dbe4c575f9c8c318805ec64
[ "MIT" ]
20
2019-04-18T07:37:34.000Z
2022-02-02T21:43:47.000Z
Source/Samples/74_Admob/barrier.cpp
elix22/Urho3D
99902ae2a867be0d6dbe4c575f9c8c318805ec64
[ "MIT" ]
11
2019-10-21T13:39:41.000Z
2021-11-05T08:11:54.000Z
Source/Samples/74_Admob/barrier.cpp
elix22/Urho3D
99902ae2a867be0d6dbe4c575f9c8c318805ec64
[ "MIT" ]
1
2021-12-03T18:11:36.000Z
2021-12-03T18:11:36.000Z
#include "barrier.h" #include "crown.h" StaticModelGroup* Barrier::netGroup_{}; Barrier::Barrier(Context* context) : LogicComponent(context) { SetUpdateEventMask(USE_UPDATE); } void Barrier::RegisterObject(Context* context) { context->RegisterFactory<Barrier>(); } void Barrier::OnNodeSet(Node *node) { (void)node; GetNode()->SetRotation(Quaternion(Random(2) ? 180.0f : 0.0f, Random(2) ? 180.0f + Random(-5.0f, 5.0f) : 0.0f + Random(-5.0f, 5.0f) , Random(2) ? 180.0f + Random(-5.0f, 5.0f) : 0.0f + Random(-5.0f, 5.0f) )); GetNode()->CreateComponent<RigidBody>(); CollisionShape* shape{GetNode()->CreateComponent<CollisionShape>()}; shape->SetShapeType(SHAPE_BOX); shape->SetSize(Vector3(1.0f, BAR_GAP, 7.8f)); Node* netNode{GetNode()->CreateChild("Net")}; if (!netGroup_) { netGroup_ = node_->GetScene()->CreateComponent<StaticModelGroup>(); netGroup_->SetModel(CACHE->GetResource<Model>("Models/Net.mdl")); netGroup_->SetCastShadows(true); netGroup_->ApplyMaterialList(); } netGroup_->AddInstanceNode(netNode); for (float y : {15.0f, -15.0f}){ netNode->CreateComponent<RigidBody>(); CollisionShape* shape{netNode->CreateComponent<CollisionShape>()}; shape->SetShapeType(SHAPE_BOX); shape->SetSize(Vector3(0.23f, 30.0f, 64.0f)); shape->SetPosition(Vector3(0.0f, y + Sign(y)*(BAR_GAP / 2), 0.0f)); } } void Barrier::Update(float timeStep) { if (GLOBAL->gameState_ != GS_PLAY) return; Vector3 pos{node_->GetPosition()}; pos += Vector3::LEFT * timeStep * BAR_SPEED; if (pos.x_ < -BAR_OUTSIDE_X) { pos.x_ += NUM_BARRIERS * BAR_INTERVAL; pos.y_ = BAR_RANDOM_Y; node_->SetRotation(Quaternion(Random(2) ? 180.0f : 0.0f, Random(2) ? 180.0f + Random(-5.0f, 5.0f) : 0.0f + Random(-5.0f, 5.0f) , Random(2) ? 180.0f + Random(-5.0f, 5.0f) : 0.0f + Random(-5.0f, 5.0f) )); } node_->SetPosition(pos); }
31.514706
111
0.588427
elix22
8e7f38aa75184e3dda5ed678021fd12077976f11
521
cpp
C++
tests/fusion/materials.cpp
technobaboo/libstardust
743acc7c300a4ff5c60934c226b98c0b60ad28fe
[ "MIT" ]
null
null
null
tests/fusion/materials.cpp
technobaboo/libstardust
743acc7c300a4ff5c60934c226b98c0b60ad28fe
[ "MIT" ]
null
null
null
tests/fusion/materials.cpp
technobaboo/libstardust
743acc7c300a4ff5c60934c226b98c0b60ad28fe
[ "MIT" ]
null
null
null
#include <cmath> #include "fusion/fusion.hpp" #include "fusion/types/drawable/model.hpp" using namespace StardustXRFusion; double elapsed = 0.0f; int main(int, char *[]) { StardustXRFusion::Setup(); Model model(nullptr, "../../res/gyro_gem.glb"); OnLogicStep([&](double delta, double) { elapsed += delta; Color gemColor = Color::FromHSVA( (float) (int(elapsed * 180) % 360), 1, 1, abs(sinf(elapsed)) ); model.setMaterialProperty(0, "color", gemColor); }); StardustXRFusion::RunEventLoop(); }
20.84
50
0.669866
technobaboo
8e7ff2e3a0b4fd3aecea12e25be5246b3d913a25
2,290
cc
C++
CPP/2017-07/task1.cc
valkirilov/fmi-di
a3062e6b2b293a6e9c480a7fc5023d71ce41f543
[ "MIT" ]
null
null
null
CPP/2017-07/task1.cc
valkirilov/fmi-di
a3062e6b2b293a6e9c480a7fc5023d71ce41f543
[ "MIT" ]
null
null
null
CPP/2017-07/task1.cc
valkirilov/fmi-di
a3062e6b2b293a6e9c480a7fc5023d71ce41f543
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; const int MAX_SIZE = 100; const char RIVER = 'R'; const char ROCK = 'S'; const char FOREST_1 = '1'; const char FOREST_2 = '2'; const char FOREST_3 = '3'; const char FOREST_4 = '4'; void print_map(char** map, int m, int n) { for (int i=0; i<m; ++i) { for (int j=0; j<n; ++j) { cout << map[i][j] << " "; } cout << endl; } cout << endl; } char** build_map(char input[4][6], int m, int n) { char** map; map = new char*[m]; for (int i=0; i<m; ++i) { map[i] = new char[n]; for (int j=0; j<n; ++j) { map[i][j] = input[i][j]; } } return map; } char mutate_field(char** map, int m, int n, int i, int j) { if (map[i][j] == RIVER || map[i][j] == ROCK) { return map[i][j]; } else if (map[i][j] == '1') { return '2'; } else if (map[i][j] == '2') { return '3'; } else if (map[i][j] == '3') { return '4'; } else if (map[i][j] == '4') { int forest4_neighbours = 0; for (int k=i-1; k<=i+1; ++k) { for (int l=j-1; l<=j+1; ++l) { if (k <= 0 || k >= m || l <= 0 || l >= n) { continue; } else if (k == i && l == j) { continue; } else if (map[k][l] == '4') { forest4_neighbours++; } } } return forest4_neighbours >= 3 ? '3' : '4'; } } char** mutate_map(char** map, int m, int n) { char** mutated_map; mutated_map = new char*[m]; for (int i=0; i<m; ++i) { mutated_map[i] = new char[n]; for (int j=0; j<n; ++j) { mutated_map[i][j] = mutate_field(map, m, n, i, j); } } return mutated_map; } int main(int argc, char** argv) { char input[4][6] = { { 'R', 'R', '1', '1', '2', '2' }, { '1', 'R', 'R', 'R', '1', '2' }, { 'S', '1', 'R', 'R', '2', '3' }, { '4', '4', 'S', 'S', 'R', 'R' }, }; char** map = build_map(input, 4, 6); print_map(map, 4, 6); for (int i=0; i<10; ++i) { map = mutate_map(map, 4, 6); print_map(map, 4, 6); } return 0; }
21.809524
62
0.398253
valkirilov
8e80f0a960fd22dfb349dc698c6d305b9c9ed955
27,062
cxx
C++
inetsrv/query/bigtable/conpt.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetsrv/query/bigtable/conpt.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetsrv/query/bigtable/conpt.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1994 - 1998. // // File: conpt.cxx // // Contents: connection point / notification code for cursors // // Classes: CConnectionPointBase, CConnectionPointContainer // // History: 7 Oct 1994 Dlee Created // 12 Feb 1998 AlanW Generalized // //-------------------------------------------------------------------------- #include "pch.cxx" #pragma hdrstop #include <conpt.hxx> #include "tabledbg.hxx" // Max. connections per connection point. Should be enough for any application! const maxConnections = 20; //+------------------------------------------------------------------------- // // Method: CConnectionPointBase::QueryInterface, public // // Synopsis: Invokes QueryInterface on container object // // Arguments: [riid] -- interface ID // [ppvObject] -- returned interface pointer // // Returns: SCODE // // History: 07-Oct-1994 dlee // //-------------------------------------------------------------------------- STDMETHODIMP CConnectionPointBase::QueryInterface( REFIID riid, void **ppvObject) { SCODE sc = S_OK; if ( 0 == ppvObject ) return E_INVALIDARG; *ppvObject = 0; if ( IID_IConnectionPoint == riid ) { *ppvObject = (void *) (IConnectionPoint *) this; } else if ( IID_IUnknown == riid ) { *ppvObject = (void *) (IUnknown *) this; } else { sc = E_NOINTERFACE; } if (SUCCEEDED(sc)) AddRef(); return sc; } //QueryInterface //+------------------------------------------------------------------------- // // Method: CConnectionPointBase::AddRef, public // // Synopsis: Increments ref. count, or delegates to containing object // // Returns: ULONG // // History: 17 Mar 1998 AlanW // //-------------------------------------------------------------------------- STDMETHODIMP_(ULONG) CConnectionPointBase::AddRef() { if (_pIContrUnk) return _pIContrUnk->AddRef( ); else { tbDebugOut(( DEB_NOTIFY, "conpt: addref\n" )); return InterlockedIncrement( (long *) &_cRefs ); } } //AddRef //+------------------------------------------------------------------------- // // Method: CConnectionPointBase::Release, public // // Synopsis: Decrements ref. count, or delegates to containing object // // Returns: ULONG // // History: 17 Mar 1998 AlanW // //-------------------------------------------------------------------------- STDMETHODIMP_(ULONG) CConnectionPointBase::Release() { if (_pIContrUnk) return _pIContrUnk->Release( ); else { long cRefs = InterlockedDecrement((long *) &_cRefs); tbDebugOut(( DEB_NOTIFY, "conpt: release, new crefs: %lx\n", _cRefs )); // If no references, make sure container doesn't know about me anymore if ( 0 == cRefs ) { Win4Assert( 0 == _pContainer ); #if 0 // Note: no sense trying to avoid an AV for bad client code if ( 0 != _pContainer ) { // need to have been disconnected; must be an excess release // from client Disconnect(); } #endif // 0 delete this; } return cRefs; } } //Release //+------------------------------------------------------------------------- // // Method: CConnectionPointBase::GetConnectionInterface, public // // Synopsis: returns the IID of the callback notification object // // Arguments: [piid] -- interface ID // // Returns: SCODE // // History: 07-Oct-1994 dlee // //-------------------------------------------------------------------------- STDMETHODIMP CConnectionPointBase::GetConnectionInterface(IID * piid) { if ( 0 == piid ) return E_POINTER; *piid = _iidSink; return S_OK; } //GetConnectionInterface //+------------------------------------------------------------------------- // // Method: CConnectionPointBase::GetConnectionPointContainer, public // // Synopsis: returns the container that spawned the connection point // // Arguments: [ppCPC] -- returns the container // // Returns: SCODE // // History: 07-Oct-1994 dlee // //-------------------------------------------------------------------------- STDMETHODIMP CConnectionPointBase::GetConnectionPointContainer( IConnectionPointContainer ** ppCPC) { if ( 0 == ppCPC ) return E_POINTER; *ppCPC = 0; // if disconnected from container, can't do it. if (0 == _pContainer) return E_UNEXPECTED; _pContainer->AddRef(); *ppCPC = _pContainer; return S_OK; } //GetConnectionPointContainer //+------------------------------------------------------------------------- // // Method: CConnectionPointBase::Advise, public // // Synopsis: Passes in the client's notification object // // Arguments: [pIUnk] -- client's notification object // [pdwCookie] -- returned pseudo-id for this advise // // Returns: SCODE // // Notes: // // History: 07-Oct-1994 dlee // //-------------------------------------------------------------------------- STDMETHODIMP CConnectionPointBase::Advise( IUnknown * piunkNotify, DWORD * pdwCookie) { SCODE sc = S_OK; if ( 0 != pdwCookie ) *pdwCookie = 0; if ( 0 == piunkNotify || 0 == pdwCookie ) return E_POINTER; XInterface<IUnknown> piSink; sc = piunkNotify->QueryInterface( _iidSink, piSink.GetQIPointer() ); if (! SUCCEEDED(sc)) return CONNECT_E_CANNOTCONNECT; // If disconnected from the container, can't call GetMutex. if (0 == _pContainer) return CONNECT_E_ADVISELIMIT; CLock lock( GetMutex() ); CConnectionContext * pConnCtx = LokFindConnection( 0 ); if (0 == pConnCtx && _xaConns.Count() < maxConnections) pConnCtx = &_xaConns[_xaConns.Count()]; if (0 == pConnCtx) sc = CONNECT_E_ADVISELIMIT; else { _dwCookieGen++; Win4Assert( 0 != _dwCookieGen && 0 == LokFindConnection( _dwCookieGen ) ); pConnCtx->Set( piSink.Acquire(), _dwCookieGen, _dwDefaultSpare ); if (_pAdviseHelper) (*_pAdviseHelper) (_pAdviseHelperContext, this, pConnCtx); *pdwCookie = _dwCookieGen; } return sc; } //Advise //+------------------------------------------------------------------------- // // Method: CConnectionPointBase::Unadvise, public // // Synopsis: Turns off an advise previously turned on with Advise() // // Arguments: [dwCookie] -- pseudo-id for this advise // // Returns: SCODE // // History: 07-Oct-1994 dlee // //-------------------------------------------------------------------------- STDMETHODIMP CConnectionPointBase::Unadvise( DWORD dwCookie) { SCODE sc = S_OK; CConnectionContext * pConnCtx = 0; CReleasableLock lock( GetMutex(), ( 0 != _pContainer ) ); pConnCtx = LokFindConnection( dwCookie ); if (pConnCtx) { if (_pUnadviseHelper) (*_pUnadviseHelper) ( _pUnadviseHelperContext, this, pConnCtx, lock ); pConnCtx->Release(); } if (0 == pConnCtx) { tbDebugOut(( DEB_WARN, "conpt: unknown advise cookie %x\n", dwCookie )); sc = CONNECT_E_NOCONNECTION; } return sc; } //Unadvise //+------------------------------------------------------------------------- // // Method: CConnectionPointBase::EnumConnections, public // // Synopsis: Returns an enumerator of advises open in this connection // // Arguments: [ppEnum] -- returned enumerator // // Returns: SCODE // // Notes: The spec permits E_NOTIMPL to be returned for this. If // we chose to implement it, it's a straightforward matter of // iterating over the _xaConns array. // // History: 07-Oct-1994 dlee // //-------------------------------------------------------------------------- STDMETHODIMP CConnectionPointBase::EnumConnections( IEnumConnections ** ppEnum) { if ( 0 == ppEnum ) return E_POINTER; *ppEnum = 0; return E_NOTIMPL; } //EnumConnections //+------------------------------------------------------------------------- // // Method: CConnectionPointBase::Disconnect, private // // Synopsis: Disconnect from the connection point container // // Arguments: [dwCookie] -- pseudo-id for this advise // // Returns: CConnectionContext* - a connection matching the [dwCookie] or 0 // // Notes: Should be called with the CPC lock held. Might be called // without the lock for an Unadvise after the CPC is diconnected. // // History: 30 Mar 1998 AlanW Created // //-------------------------------------------------------------------------- void CConnectionPointBase::Disconnect( ) { Win4Assert( 0 != _pContainer ); CLock lock(GetMutex()); _pContainer->RemoveConnectionPoint( this ); _pContainer = 0; } //+------------------------------------------------------------------------- // // Method: CConnectionPointBase::LokFindConnection, private // // Synopsis: Find a connection matching an advise cookie // // Arguments: [dwCookie] -- pseudo-id for this advise // // Returns: CConnectionContext* - a connection matching the [dwCookie] or 0 // // Notes: Should be called with the CPC lock held. Might be called // without the lock for an Unadvise after the CPC is diconnected. // // History: 10 Mar 1998 AlanW Created // //-------------------------------------------------------------------------- CConnectionPointBase::CConnectionContext * CConnectionPointBase::LokFindConnection( DWORD dwCookie ) { for (unsigned i=0; i<_xaConns.Count(); i++) { CConnectionContext & rConnCtx = _xaConns[i]; if (rConnCtx._dwAdviseCookie == dwCookie) return &rConnCtx; } return 0; } //+------------------------------------------------------------------------- // // Method: CConnectionPointBase::LokFindActiveConnection, private // // Synopsis: Find an active advise by indexing // // Arguments: [riConn] -- index into conn. context array, updated on return // // Returns: CConnectionContext* - pointer to an active connection context, // or NULL. // // Notes: Should be called with the CPC lock held. // // History: 10 Mar 1998 AlanW Created // //-------------------------------------------------------------------------- CConnectionPointBase::CConnectionContext * CConnectionPointBase::LokFindActiveConnection( unsigned & riConn ) { while (riConn < _xaConns.Count()) { CConnectionContext & rCtx = _xaConns[riConn]; if (rCtx._dwAdviseCookie != 0) return &rCtx; riConn++; } return 0; } ///////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////// //+------------------------------------------------------------------------- // // Method: CConnectionPointContainer::QueryInterface, public // // Synopsis: Invokes QueryInterface on cursor object // // Arguments: [riid] -- interface ID // [ppvObject] -- returned interface pointer // // Returns: SCODE // // History: 07-Oct-1994 dlee // //-------------------------------------------------------------------------- STDMETHODIMP CConnectionPointContainer::QueryInterface( REFIID riid, void **ppvObject) { if ( 0 == ppvObject ) return E_INVALIDARG; return _rControllingUnk.QueryInterface(riid, ppvObject); } //QueryInterface //+------------------------------------------------------------------------- // // Method: CConnectionPointContainer::AddRef, public // // Synopsis: Invokes AddRef on cursor object // // Returns: ULONG // // History: 07-Oct-1994 dlee // //-------------------------------------------------------------------------- STDMETHODIMP_(ULONG) CConnectionPointContainer::AddRef() { tbDebugOut(( DEB_NOTIFY, "conptcontainer: addref\n" )); return _rControllingUnk.AddRef(); } //AddRef //+------------------------------------------------------------------------- // // Method: CConnectionPointContainer::Release, public // // Synopsis: Invokes Release on cursor object // // Returns: ULONG // // History: 07-Oct-1994 dlee // //-------------------------------------------------------------------------- STDMETHODIMP_(ULONG) CConnectionPointContainer::Release() { tbDebugOut(( DEB_NOTIFY, "conptcontainer: release\n" )); return _rControllingUnk.Release(); } //Release //+------------------------------------------------------------------------- // // Method: CConnectionPointContainer::CConnectionPointContainer, public // // Synopsis: Constructor for connection point container class. // // Arguments: [maxConnPt] -- maximum number of connection points supported // [rUnknown] -- controlling unknown // [ErrorObject] -- reference to error object // // Notes: After construction, use AddConnectionPoint to add a connection // point into the container. // // History: 07-Oct-1994 dlee // //-------------------------------------------------------------------------- CConnectionPointContainer::CConnectionPointContainer( unsigned maxConnPt, IUnknown &rUnknown, CCIOleDBError & ErrorObject ) : _rControllingUnk(rUnknown), _ErrorObject( ErrorObject ), _cConnPt( 0 ) { Win4Assert( maxConnPt <= maxConnectionPoints ); } //CConnectionPointContainer //+------------------------------------------------------------------------- // // Method: CConnectionPointContainer::~CConnectionPointContainer, public // // Synopsis: Destructor for connection point container class. // // Notes: It is expected that all connection points are relased by this // time. // // History: 07-Oct-1994 dlee // //-------------------------------------------------------------------------- CConnectionPointContainer::~CConnectionPointContainer() { CLock lock( _mutex ); // // Release all connection points // for (unsigned i = 0; i < _cConnPt; i++) { IConnectionPoint * pIConnPt = _aConnPt[i]._pIConnPt; if ( 0 != pIConnPt ) { _aConnPt[i]._pIConnPt = 0; pIConnPt->Release(); } } } //~CConnectionPointContainer //+------------------------------------------------------------------------- // // Method: CConnectionPointContainer::FindConnectionPoint, public // // Synopsis: Finds a connection point object that supports the given // interface for callback to the client // // Arguments: [riid] -- interface ID for proposed callback // [ppPoint] -- returned connection interface pointer // // Returns: SCODE // // History: 07-Oct-1994 dlee // //-------------------------------------------------------------------------- STDMETHODIMP CConnectionPointContainer::FindConnectionPoint( REFIID riid, IConnectionPoint ** ppPoint) { _ErrorObject.ClearErrorInfo(); if ( 0 == ppPoint ) return E_POINTER; *ppPoint = 0; SCODE sc = S_OK; TRANSLATE_EXCEPTIONS; TRY { CLock lock( _mutex ); for (unsigned i = 0; i < _cConnPt; i++) { if ( riid == _aConnPt[i]._iidConnPt ) break; } if ( i<_cConnPt ) { Win4Assert(_aConnPt[i]._pIConnPt != 0); IConnectionPoint * pIConnPt = _aConnPt[i]._pIConnPt; *ppPoint = pIConnPt; pIConnPt->AddRef(); } else { sc = CONNECT_E_NOCONNECTION; } if (FAILED(sc)) _ErrorObject.PostHResult(sc, IID_IConnectionPointContainer); } CATCH(CException,e) { _ErrorObject.PostHResult(e.GetErrorCode(), IID_IConnectionPointContainer); sc = E_UNEXPECTED; } END_CATCH; UNTRANSLATE_EXCEPTIONS; return sc; } //FindConnectionPoint //+------------------------------------------------------------------------- // // Method: CConnectionPointContainer::EnumConnectionPoints, public // // Synopsis: Enumerates all connection points currently in use // // Arguments: [ppEnum] -- returned enumerator // // Returns: SCODE // // History: 09 Mar 1998 AlanW Created // //-------------------------------------------------------------------------- STDMETHODIMP CConnectionPointContainer::EnumConnectionPoints( IEnumConnectionPoints **ppEnum) { _ErrorObject.ClearErrorInfo(); if ( 0 == ppEnum ) return E_POINTER; *ppEnum = 0; SCODE sc = S_OK; TRANSLATE_EXCEPTIONS; TRY { CLock lock( _mutex ); XInterface<IEnumConnectionPoints> pEnumCp( new CEnumConnectionPoints( *this ) ); *ppEnum = pEnumCp.GetPointer(); pEnumCp.Acquire(); } CATCH(CException,e) { _ErrorObject.PostHResult(e.GetErrorCode(), IID_IConnectionPointContainer); sc = e.GetErrorCode(); } END_CATCH; UNTRANSLATE_EXCEPTIONS; return sc; } //EnumConnectionPoints //+------------------------------------------------------------------------- // // Method: CEnumConnectionPoints::QueryInterface, public // // Synopsis: Invokes QueryInterface on connection point enumerator object // // Arguments: [riid] -- interface ID // [ppvObject] -- returned interface pointer // // Returns: SCODE // // History: 10 Mar 1998 AlanW // //-------------------------------------------------------------------------- STDMETHODIMP CEnumConnectionPoints::QueryInterface( REFIID riid, void **ppvObject) { SCODE sc = S_OK; if ( 0 == ppvObject ) return E_INVALIDARG; *ppvObject = 0; if ( IID_IEnumConnectionPoints == riid ) { *ppvObject = (void *) (IEnumConnectionPoints *) this; } else if ( IID_IUnknown == riid ) { *ppvObject = (void *) (IUnknown *) this; } else { sc = E_NOINTERFACE; } if (SUCCEEDED(sc)) AddRef(); return sc; } //QueryInterface //+------------------------------------------------------------------------- // // Method: CEnumConnectionPoints::AddRef, public // // Synopsis: Invokes AddRef on container object // // Returns: ULONG // // History: 07-Oct-1994 dlee // //-------------------------------------------------------------------------- STDMETHODIMP_(ULONG) CEnumConnectionPoints::AddRef() { return InterlockedIncrement( (long *) &_cRefs ); } //AddRef //+------------------------------------------------------------------------- // // Method: CEnumConnectionPoints::Release, public // // Synopsis: Invokes Release on container object // // Returns: ULONG // // History: 07-Oct-1994 dlee // //-------------------------------------------------------------------------- STDMETHODIMP_(ULONG) CEnumConnectionPoints::Release() { long cRefs = InterlockedDecrement((long *) &_cRefs); tbDebugOut(( DEB_NOTIFY, "enumconpt: release, new crefs: %lx\n", _cRefs )); // If no references, delete. if ( 0 == cRefs ) { delete this; } return cRefs; } //Release //+------------------------------------------------------------------------- // // Method: CEnumConnectionPoints::Clone, public // // Synopsis: Clone a connection point enumerator // // Arguments: [ppEnum] -- returned enumerator // // Returns: SCODE // // History: 09 Mar 1998 AlanW Created // //-------------------------------------------------------------------------- STDMETHODIMP CEnumConnectionPoints::Clone ( IEnumConnectionPoints **ppEnum) { //_ErrorObject.ClearErrorInfo(); if ( 0 == ppEnum ) return E_POINTER; *ppEnum = 0; SCODE sc = S_OK; TRANSLATE_EXCEPTIONS; TRY { XInterface<CEnumConnectionPoints> pEnumCp( new CEnumConnectionPoints( _rContainer ) ); pEnumCp->_iConnPt = _iConnPt; *ppEnum = pEnumCp.GetPointer(); pEnumCp.Acquire(); } CATCH(CException,e) { sc = e.GetErrorCode(); } END_CATCH; UNTRANSLATE_EXCEPTIONS; return sc; } //Clone //+------------------------------------------------------------------------- // // Method: CEnumConnectionPoints::Reset, public // // Synopsis: Reset a connection point enumerator // // Arguments: -NONE- // // Returns: SCODE // // History: 09 Mar 1998 AlanW Created // //-------------------------------------------------------------------------- STDMETHODIMP CEnumConnectionPoints::Reset ( ) { _iConnPt = 0; return S_OK; } //Reset //+------------------------------------------------------------------------- // // Method: CEnumConnectionPoints::Skip, public // // Synopsis: Skip some connection points // // Arguments: [cConnections] - number of connection points to skip // // Returns: SCODE // // History: 09 Mar 1998 AlanW Created // //-------------------------------------------------------------------------- STDMETHODIMP CEnumConnectionPoints::Skip ( ULONG cConnections ) { SCODE sc = S_OK; if ( _iConnPt+cConnections < _rContainer._cConnPt ) _iConnPt += cConnections; else sc = S_FALSE; return sc; } //Skip //+------------------------------------------------------------------------- // // Method: CEnumConnectionPoints::Next, public // // Synopsis: Return some connection points // // Arguments: [cConnections] - number of connection points to return, at most // [rgpcm] - array of IConnectionPoint* to be returned // [pcFetched] - on return, number of connection points in [rgpcm] // // Returns: SCODE // // History: 09 Mar 1998 AlanW Created // //-------------------------------------------------------------------------- STDMETHODIMP CEnumConnectionPoints::Next ( ULONG cConnections, IConnectionPoint **rgpcm, ULONG * pcFetched ) { SCODE sc = S_OK; if ( 0 != pcFetched ) *pcFetched = 0; if ( 0 == rgpcm || 0 == pcFetched ) return E_POINTER; for (ULONG i=0; i<cConnections; i++) rgpcm[i] = 0; TRANSLATE_EXCEPTIONS; TRY { ULONG cRet = 0; CLock lock(_rContainer._mutex); // Note: There could be leakage of CP pointers if there are exceptions // generated by the code below. while ( _iConnPt < _rContainer._cConnPt && cRet < cConnections ) { XInterface<IConnectionPoint> xCP( _rContainer._aConnPt[_iConnPt]._pIConnPt ); xCP->AddRef(); rgpcm[cRet] = xCP.GetPointer(); cRet++; _iConnPt++; *pcFetched = cRet; xCP.Acquire(); } sc = (cConnections == cRet) ? S_OK : S_FALSE; } CATCH(CException,e) { sc = e.GetErrorCode(); } END_CATCH; UNTRANSLATE_EXCEPTIONS; return sc; } //Next //+------------------------------------------------------------------------- // // Method: CConnectionPointContainer::AddConnectionPoint, public // // Synopsis: Adds a connection point to the container. // Called by the connection point itself. // // Arguments: [riid] --- IID of notification interface for CP // [pConnPt] --- connection point to be removed // // Notes: The back pointer from the connection point to the connection // point container does not contribute to the container's ref. // count so that the CPC <-> CP structure is not self-referential // and can be deleted when no longer needed. // // History: 10 Mar 1998 AlanW // //-------------------------------------------------------------------------- void CConnectionPointContainer::AddConnectionPoint( REFIID riid, CConnectionPointBase *pConnPt) { Win4Assert( _cConnPt < maxConnectionPoints ); XInterface<IConnectionPoint> xConnPt; SCODE sc = pConnPt->QueryInterface( IID_IConnectionPoint, xConnPt.GetQIPointer()); if (!SUCCEEDED(sc)) THROW( CException(sc) ); CLock lock(_mutex); CConnectionPointContext * pConnPtCtx = &_aConnPt[_cConnPt]; pConnPtCtx->_pIConnPt = xConnPt.Acquire(); pConnPtCtx->_iidConnPt = riid; _cConnPt++; } //AddConnectionPoint //+------------------------------------------------------------------------- // // Method: CConnectionPointContainer::RemoveConnectionPoint, public // // Synopsis: Removes a connection point from the container. // Called by the connection point itself. // // Arguments: [pConnPt] --- connection point to be removed // // History: 07-Oct-1994 dlee // //-------------------------------------------------------------------------- void CConnectionPointContainer::RemoveConnectionPoint( IConnectionPoint *pConnPt) { CLock lock(_mutex); for (unsigned i = 0; i < _cConnPt; i++) { if ( _aConnPt[i]._pIConnPt == pConnPt ) { _aConnPt[i]._pIConnPt = 0; pConnPt->Release(); } } } //RemoveConnectionPoint
28.072614
95
0.482891
npocmaka
8e83a03ca069f2e1934d5464346eb101163cd3b8
56,637
cpp
C++
src/Gull.cpp
kazu-nanoha/NanohaM
412f95fdcbc1eb1e8aeb5a75872eba0e544a1675
[ "MIT" ]
null
null
null
src/Gull.cpp
kazu-nanoha/NanohaM
412f95fdcbc1eb1e8aeb5a75872eba0e544a1675
[ "MIT" ]
null
null
null
src/Gull.cpp
kazu-nanoha/NanohaM
412f95fdcbc1eb1e8aeb5a75872eba0e544a1675
[ "MIT" ]
null
null
null
///#define W32_BUILD ///#undef W32_BUILD #ifdef W32_BUILD #define NTDDI_VERSION 0x05010200 #define _WIN32_WINNT 0x0501 #endif ///#ifndef W32_BUILD ///#define HNI ///#undef HNI ///#endif #include <iostream> #include <cmath> #include <cinttypes> #include <thread> #include <mutex> #include <intrin.h> #include "setjmp.h" #include "windows.h" #include "types.h" #include "misc.h" #include "TT.h" #include "evaluate.h" #include "position.h" #include "uci.h" #include "genmove.h" #include "search.h" #include "thread.h" ///#define MP_NPS // --> search.cpp /////#undef MP_NPS ///#define TIME_TO_DEPTH /////#undef TIME_TO_DEPTH using namespace std; #if 0 // ToDo: DEL constexpr uint8_t UpdateCastling[64] = { 0xFF^CanCastle_OOO,0xFF,0xFF,0xFF,0xFF^(CanCastle_OO|CanCastle_OOO), 0xFF,0xFF,0xFF^CanCastle_OO, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF^CanCastle_ooo,0xFF,0xFF,0xFF,0xFF^(CanCastle_oo|CanCastle_ooo), 0xFF,0xFF,0xFF^CanCastle_oo }; #endif const uint64_t BMagic[64] = { 0x0048610528020080, 0x00c4100212410004, 0x0004180181002010, 0x0004040188108502, 0x0012021008003040, 0x0002900420228000, 0x0080808410c00100, 0x000600410c500622, 0x00c0056084140184, 0x0080608816830050, 0x00a010050200b0c0, 0x0000510400800181, 0x0000431040064009, 0x0000008820890a06, 0x0050028488184008, 0x00214a0104068200, 0x004090100c080081, 0x000a002014012604, 0x0020402409002200, 0x008400c240128100, 0x0001000820084200, 0x0024c02201101144, 0x002401008088a800, 0x0003001045009000, 0x0084200040981549, 0x0001188120080100, 0x0048050048044300, 0x0008080000820012, 0x0001001181004003, 0x0090038000445000, 0x0010820800a21000, 0x0044010108210110, 0x0090241008204e30, 0x000c04204004c305, 0x0080804303300400, 0x00a0020080080080, 0x0000408020220200, 0x0000c08200010100, 0x0010008102022104, 0x0008148118008140, 0x0008080414809028, 0x0005031010004318, 0x0000603048001008, 0x0008012018000100, 0x0000202028802901, 0x004011004b049180, 0x0022240b42081400, 0x00c4840c00400020, 0x0084009219204000, 0x000080c802104000, 0x0002602201100282, 0x0002040821880020, 0x0002014008320080, 0x0002082078208004, 0x0009094800840082, 0x0020080200b1a010, 0x0003440407051000, 0x000000220e100440, 0x00480220a4041204, 0x00c1800011084800, 0x000008021020a200, 0x0000414128092100, 0x0000042002024200, 0x0002081204004200 }; const uint64_t RMagic[64] = { 0x00800011400080a6, 0x004000100120004e, 0x0080100008600082, 0x0080080016500080, 0x0080040008000280, 0x0080020005040080, 0x0080108046000100, 0x0080010000204080, 0x0010800424400082, 0x00004002c8201000, 0x000c802000100080, 0x00810010002100b8, 0x00ca808014000800, 0x0002002884900200, 0x0042002148041200, 0x00010000c200a100, 0x00008580004002a0, 0x0020004001403008, 0x0000820020411600, 0x0002120021401a00, 0x0024808044010800, 0x0022008100040080, 0x00004400094a8810, 0x0000020002814c21, 0x0011400280082080, 0x004a050e002080c0, 0x00101103002002c0, 0x0025020900201000, 0x0001001100042800, 0x0002008080022400, 0x000830440021081a, 0x0080004200010084, 0x00008000c9002104, 0x0090400081002900, 0x0080220082004010, 0x0001100101000820, 0x0000080011001500, 0x0010020080800400, 0x0034010224009048, 0x0002208412000841, 0x000040008020800c, 0x001000c460094000, 0x0020006101330040, 0x0000a30010010028, 0x0004080004008080, 0x0024000201004040, 0x0000300802440041, 0x00120400c08a0011, 0x0080006085004100, 0x0028600040100040, 0x00a0082110018080, 0x0010184200221200, 0x0040080005001100, 0x0004200440104801, 0x0080800900220080, 0x000a01140081c200, 0x0080044180110021, 0x0008804001001225, 0x00a00c4020010011, 0x00001000a0050009, 0x0011001800021025, 0x00c9000400620811, 0x0032009001080224, 0x001400810044086a }; const int32_t BShift[64] = { 58, 59, 59, 59, 59, 59, 59, 58, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 57, 57, 57, 57, 59, 59, 59, 59, 57, 55, 55, 57, 59, 59, 59, 59, 57, 55, 55, 57, 59, 59, 59, 59, 57, 57, 57, 57, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 58, 59, 59, 59, 59, 59, 59, 58 }; const int32_t BOffset[64] = { 0, 64, 96, 128, 160, 192, 224, 256, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, 768, 896, 1024, 1152, 1184, 1216, 1248, 1280, 1408, 1920, 2432, 2560, 2592, 2624, 2656, 2688, 2816, 3328, 3840, 3968, 4000, 4032, 4064, 4096, 4224, 4352, 4480, 4608, 4640, 4672, 4704, 4736, 4768, 4800, 4832, 4864, 4896, 4928, 4992, 5024, 5056, 5088, 5120, 5152, 5184 }; const int32_t RShift[64] = { 52, 53, 53, 53, 53, 53, 53, 52, 53, 54, 54, 54, 54, 54, 54, 53, 53, 54, 54, 54, 54, 54, 54, 53, 53, 54, 54, 54, 54, 54, 54, 53, 53, 54, 54, 54, 54, 54, 54, 53, 53, 54, 54, 54, 54, 54, 54, 53, 53, 54, 54, 54, 54, 54, 54, 53, 52, 53, 53, 53, 53, 53, 53, 52 }; const int32_t ROffset[64] = { 5248, 9344, 11392, 13440, 15488, 17536, 19584, 21632, 25728, 27776, 28800, 29824, 30848, 31872, 32896, 33920, 35968, 38016, 39040, 40064, 41088, 42112, 43136, 44160, 46208, 48256, 49280, 50304, 51328, 52352, 53376, 54400, 56448, 58496, 59520, 60544, 61568, 62592, 63616, 64640, 66688, 68736, 69760, 70784, 71808, 72832, 73856, 74880, 76928, 78976, 80000, 81024, 82048, 83072, 84096, 85120, 87168, 91264, 93312, 95360, 97408, 99456, 101504, 103552 }; uint64_t * BOffsetPointer[64]; uint64_t * ROffsetPointer[64]; #define FlagUnusualMaterial (1 << 30) #if 0 // Memo const int MatCode[16] = {0,0,MatWP,MatBP,MatWN,MatBN,MatWL,MatBL,MatWD,MatBD,MatWR,MatBR,MatWQ,MatBQ,0,0}; const uint64_t File[8] = {FileA,FileA<<1,FileA<<2,FileA<<3,FileA<<4,FileA<<5,FileA<<6,FileA<<7}; const uint64_t Line[8] = {Line0,(Line0<<8),(Line0<<16),(Line0<<24),(Line0<<32),(Line0<<40),(Line0<<48),(Line0<<56)}; #endif /* general move: 0 - 11: from & to 12 - 15: flags 16 - 23: history 24 - 25: spectial moves: killers, refutations... 26 - 30: MvvLva delta move: 0 - 11: from & to 12 - 15: flags 16 - 31: int16_t delta + (int16_t)0x4000 */ ///const int MvvLvaVictim[16] = {0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3}; const int MvvLvaAttacker[16] = {0, 0, 5, 5, 4, 4, 3, 3, 3, 3, 2, 2, 1, 1, 6, 6}; const int MvvLvaAttackerKB[16] = {0, 0, 9, 9, 7, 7, 5, 5, 5, 5, 3, 3, 1, 1, 11, 11}; #define PawnCaptureMvvLva(attacker) (MvvLvaAttacker[attacker]) #define MaxPawnCaptureMvvLva (MvvLvaAttacker[15]) // 6 #define KnightCaptureMvvLva(attacker) (MaxPawnCaptureMvvLva + MvvLvaAttackerKB[attacker]) #define MaxKnightCaptureMvvLva (MaxPawnCaptureMvvLva + MvvLvaAttackerKB[15]) // 17 #define BishopCaptureMvvLva(attacker) (MaxPawnCaptureMvvLva + MvvLvaAttackerKB[attacker] + 1) #define MaxBishopCaptureMvvLva (MaxPawnCaptureMvvLva + MvvLvaAttackerKB[15] + 1) // 18 #define RookCaptureMvvLva(attacker) (MaxBishopCaptureMvvLva + MvvLvaAttacker[attacker]) #define MaxRookCaptureMvvLva (MaxBishopCaptureMvvLva + MvvLvaAttacker[15]) // 24 #define QueenCaptureMvvLva(attacker) (MaxRookCaptureMvvLva + MvvLvaAttacker[attacker]) ///#define MvvLvaPromotion (MvvLva[WhiteQueen][BlackQueen]) ///#define MvvLvaPromotionKnight (MvvLva[WhiteKnight][BlackKnight]) ///#define MvvLvaPromotionCap(capture) (MvvLva[((capture) < WhiteRook) ? WhiteRook : ((capture) >= WhiteQueen ? WhiteKing : WhiteKnight)][BlackQueen]) ///#define MvvLvaPromotionKnightCap(capture) (MvvLva[WhiteKing][capture]) ///#define MvvLvaXray (MvvLva[WhiteQueen][WhitePawn]) ///#define MvvLvaXrayCap(capture) (MvvLva[WhiteKing][capture]) ///#define RefOneScore ((0xFF << 16) | (3 << 24)) ///#define RefTwoScore ((0xFF << 16) | (2 << 24)) ///#define KillerOneScore ((0xFF << 16) | (1 << 24)) ///#define KillerTwoScore (0xFF << 16) ///#define halt_check if ((Current - Data) >= 126) {evaluate(); return Current->score;} \ /// if (Current->ply >= 100) return 0; \ /// for (i = 4; i <= Current->ply; i+= 2) if (Stack[sp-i] == Current->key) return 0 ///#define ExtFlag(ext) ((ext) << 16) ///#define Ext(flags) (((flags) >> 16) & 0xF) ///#define FlagHashCheck (1 << 20) // first 20 bits are reserved for the hash killer and extension ///#define FlagHaltCheck (1 << 21) ///#define FlagCallEvaluation (1 << 22) ///#define FlagDisableNull (1 << 23) ///#define FlagNeatSearch (FlagHashCheck | FlagHaltCheck | FlagCallEvaluation) ///#define FlagNoKillerUpdate (1 << 24) ///#define FlagReturnBestMove (1 << 25) ///#define MSBZ(x) ((x) ? msb(x) : 63) ///#define LSBZ(x) ((x) ? lsb(x) : 0) ///#define NB(me, x) ((me) ? msb(x) : lsb(x)) ///#define NBZ(me, x) ((me) ? MSBZ(x) : LSBZ(x)) alignas(64) GBoard Board[1]; uint64_t Stack[2048]; int sp, save_sp; uint64_t nodes, check_node, check_node_smp; ///GBoard SaveBoard[1]; ///struct GPosData { /// uint64_t key, pawn_key; /// uint16_t move; /// uint8_t turn, castle_flags, ply, ep_square, piece, capture; /// uint8_t square[64]; /// int pst, material; ///}; alignas(64) GData Data[128]; // [ToDo] 数値の意味を確認する. GData *Current = Data; ///#define FlagSort (1 << 0) ///#define FlagNoBcSort (1 << 1) ///GData SaveData[1]; ///enum { /// stage_search, s_hash_move, s_good_cap, s_special, s_quiet, s_bad_cap, s_none, /// stage_evasion, e_hash_move, e_ev, e_none, /// stage_razoring, r_hash_move, r_cap, r_checks, r_none ///}; ///#define StageNone ((1 << s_none) | (1 << e_none) | (1 << r_none)) int RootList[256]; ///#define prefetch(a,mode) _mm_prefetch(a,mode) uint64_t Forward[2][8]; uint64_t West[8]; uint64_t East[8]; uint64_t PIsolated[8]; uint64_t HLine[64]; uint64_t VLine[64]; uint64_t NDiag[64]; uint64_t SDiag[64]; uint64_t RMask[64]; uint64_t BMask[64]; uint64_t QMask[64]; uint64_t BMagicMask[64]; uint64_t RMagicMask[64]; uint64_t NAtt[64]; uint64_t SArea[64]; uint64_t DArea[64]; uint64_t NArea[64]; uint64_t BishopForward[2][64]; uint64_t PAtt[2][64]; uint64_t PMove[2][64]; uint64_t PWay[2][64]; uint64_t PSupport[2][64]; uint64_t Between[64][64]; uint64_t FullLine[64][64]; ///uint64_t * MagicAttacks; ///GMaterial * Material; uint64_t MagicAttacks[magic_size]; GMaterial Material[TotalMat]; ///#define FlagSingleBishop_w (1 << 0) ///#define FlagSingleBishop_b (1 << 1) ///#define FlagCallEvalEndgame_w (1 << 2) ///#define FlagCallEvalEndgame_b (1 << 3) uint64_t TurnKey; uint64_t PieceKey[16][64]; uint64_t CastleKey[16]; uint64_t EPKey[8]; uint16_t date; uint64_t Kpk[2][64][64]; #if 0 // ToDo: DEL int16_t History[16 * 64]; #define HistoryScore(piece,from,to) History[((piece) << 6) | (to)] #define HistoryP(piece,from,to) ((Convert(HistoryScore(piece,from,to) & 0xFF00,int)/Convert(HistoryScore(piece,from,to) & 0x00FF,int)) << 16) #define History(from,to) HistoryP(Square(from),from,to) #define HistoryM(move) HistoryScore(Square(From(move)),From(move),To(move)) #define HistoryInc(depth) Min(((depth) >> 1) * ((depth) >> 1), 64) #define HistoryGood(move) if ((HistoryM(move) & 0x00FF) >= 256 - HistoryInc(depth)) \ HistoryM(move) = ((HistoryM(move) & 0xFEFE) >> 1) + ((HistoryInc(depth) << 8) | HistoryInc(depth)); \ else HistoryM(move) += ((HistoryInc(depth) << 8) | HistoryInc(depth)) #define HistoryBad(move) if ((HistoryM(move) & 0x00FF) >= 256 - HistoryInc(depth)) \ HistoryM(move) = ((HistoryM(move) & 0xFEFE) >> 1) + HistoryInc(depth); else HistoryM(move) += HistoryInc(depth) #endif GRef Ref[16 * 64]; uint64_t seed = 1; uint8_t PieceFromChar[256]; uint16_t PV[128]; char info_string[1024]; char pv_string[1024]; char score_string[16]; char mstring[65536]; int MultiPV[256]; int pvp; int pv_length; int best_move, best_score; int TimeLimit1, TimeLimit2, Console, HardwarePopCnt; int DepthLimit, LastDepth, LastTime, LastValue, LastExactValue, PrevMove, InstCnt; int64_t LastSpeed; int PVN, Stop, Print, Input = 1, PVHashing = 1, Infinite, MoveTime, SearchMoves, SMPointer, Ponder, Searching, Previous; GSearchInfo CurrentSI[1], BaseSI[1]; int Aspiration = 1; #define TimeSingTwoMargin 20 #define TimeSingOneMargin 30 #define TimeNoPVSCOMargin 60 #define TimeNoChangeMargin 70 #define TimeRatio 120 #define PonderRatio 120 #define MovesTg 30 #define InfoLag 5000 #define InfoDelay 1000 int64_t StartTime, InfoTime, CurrTime; uint16_t SMoves[256]; jmp_buf Jump, ResetJump; HANDLE StreamHandle; ///#define ExclSingle(depth) 8 ///#define ExclDouble(depth) 16 ///#define ExclSinglePV(depth) 8 ///#define ExclDoublePV(depth) 16 // EVAL const int8_t DistC[8] = {3, 2, 1, 0, 0, 1, 2, 3}; const int8_t RankR[8] = {-3, -2, -1, 0, 1, 2, 3, 4}; ///const int SeeValue[16] = {0, 0, 90, 90, 325, 325, 325, 325, 325, 325, 510, 510, 975, 975, 30000, 30000}; const int PieceType[16] = {0, 0, 0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 4, 4, 5, 5}; #define V(x) (x) // EVAL WEIGHTS // tuner: start enum { // tuner: enum IMatLinear, IMatQuadMe = IMatLinear + 5, IMatQuadOpp = IMatQuadMe + 14, IBishopPairQuad = IMatQuadOpp + 10, IMatSpecial = IBishopPairQuad + 9, IPstQuadWeights = IMatSpecial + 20, IPstLinearWeights = IPstQuadWeights + 48, IPstQuadMixedWeights = IPstLinearWeights + 48, IMobilityLinear = IPstQuadMixedWeights + 24, IMobilityLog = IMobilityLinear + 8, IShelterValue = IMobilityLog + 8, IStormQuad = IShelterValue + 15, IStormLinear = IStormQuad + 5, IStormHof = IStormLinear + 5, IPasserQuad = IStormHof + 2, IPasserLinear = IPasserQuad + 18, IPasserAttDefQuad = IPasserLinear + 18, IPasserAttDefLinear = IPasserAttDefQuad + 4, IPasserSpecial = IPasserAttDefLinear + 4, IIsolated = IPasserSpecial + 4, IUnprotected = IIsolated + 10, IBackward = IUnprotected + 6, IDoubled = IBackward + 4, IRookSpecial = IDoubled + 4, ITactical = IRookSpecial + 20, IKingDefence = ITactical + 12, IPawnSpecial = IKingDefence + 8, IBishopSpecial = IPawnSpecial + 8, IKnightSpecial = IBishopSpecial + 4, IPin = IKnightSpecial + 10, IKingRay = IPin + 10, IKingAttackWeight = IKingRay + 6 }; const int Phase[5] = { 0, 325, 325, 510, 975 }; #define MaxPhase (16 * Phase[0] + 4 * Phase[1] + 4 * Phase[2] + 4 * Phase[3] + 2 * Phase[4]) #define PhaseMin (2 * Phase[3] + Phase[1] + Phase[2]) #define PhaseMax (MaxPhase - Phase[1] - Phase[2]) const int MatLinear[5] = { // tuner: type=array, var=50, active=0 3, 0, 3, 19, 0 }; // pawn, knight, bishop, rook, queen const int MatQuadMe[14] = { // tuner: type=array, var=1000, active=0 -33, 17, -23, -155, -247, 15, 296, -105, -83, -162, 327, 315, -861, -1013 }; const int MatQuadOpp[10] = { // tuner: type=array, var=1000, active=0 -14, 47, -20, -278, 35, 39, 49, 9, -2, 75 }; const int BishopPairQuad[9] = { // tuner: type=array, var=1000, active=0 -38, 164, 99, 246, -84, -57, -184, 88, -186 }; enum { MatRB, MatRN, MatQRR, MatQRB, MatQRN, MatQ3, MatBBR, MatBNR, MatNNR, MatM }; const int MatSpecial[20] = { // tuner: type=array, var=30, active=0 13, -13, 10, -9, 8, 12, 4, 6, 5, 9, -3, -8, -4, 7, 2, 0, 0, -6, 1, 3 }; // piece type (6) * direction (4: h center dist, v center dist, diag dist, rank) * phase (2) const int PstQuadWeights[48] = { // tuner: type=array, var=100, active=0 -15, -19, -70, -13, 33, -20, 0, 197, -36, -122, 0, -60, -8, -3, -17, -28, -27, -63, -17, -7, 14, 0, -24, -5, -64, -2, 0, -38, -8, 0, 77, 11, -67, 3, -4, -92, -2, 12, -13, -42, -62, -84, -175, -42, -2, -17, 40, -19 }; const int PstLinearWeights[48] = { // tuner: type=array, var=500, active=0 -107, 67, -115, 83, -55, 67, 92, 443, -177, 5, -82, -61, -106, -104, 273, 130, 0, -145, -105, -58, -99, -37, -133, 14, -185, -43, -67, -53, 53, -65, 174, 134, -129, 7, 98, -231, 107, -40, -27, 311, 256, -117, 813, -181, 2, -215, -44, 344 }; // piece type (6) * type (2: h * v, h * rank) * phase (2) const int PstQuadMixedWeights[24] = { // tuner: type=array, var=100, active=0 14, -6, 1, -4, -8, -2, 4, -4, 1, -7, -12, 0, -2, -1, -5, 4, 5, -10, 0, 4, -2, 5, 4, -2 }; // tuner: stop // END EVAL WEIGHTS // SMP int PrN = 1, CPUs = 1, HT = 0, parent = 1, child = 0, WinParId, Id = 0, ResetHash = 1, NewPrN = 0; HANDLE ChildPr[MaxPrN]; ///#define FlagClaimed (1 << 1) ///#define FlagFinished (1 << 2) ///GSMPI * Smpi; ///jmp_buf CheckJump; HANDLE SHARED = NULL, HASH = NULL; inline unsigned get_num_cpus(void) { return std::thread::hardware_concurrency(); } // END SMP int lsb(uint64_t x); int msb(uint64_t x); int popcnt(uint64_t x); int MinF(int x, int y); int MaxF(int x, int y); double MinF(double x, double y); double MaxF(double x, double y); template <bool HPopCnt> int popcount(uint64_t x); uint64_t BMagicAttacks(int i, uint64_t occ); uint64_t RMagicAttacks(int i, uint64_t occ); uint16_t rand16(); uint64_t rand64(); void init_pst(); void init(); ///void setup_board(); ///void get_board(const char fen[]); ///template <bool me, bool pv> int q_search(int alpha, int beta, int depth, int flags); ///template <bool me, bool pv> int q_evasion(int alpha, int beta, int depth, int flags); ///template <bool me, bool exclusion> int search(int beta, int depth, int flags); ///template <bool me, bool exclusion> int search_evasion(int beta, int depth, int flags); ///template <bool me, bool root> int pv_search(int alpha, int beta, int depth, int flags); ///template <bool me> void root(); ///template <bool me> int multipv(int depth); ///void send_multipv(int depth, int curr_number); ///void check_time(int searching); ///void check_time(int time, int searching); ///void check_state(); #ifndef W32_BUILD int lsb(uint64_t x) { #if defined(__GNUC__) unsigned int y; #else unsigned long y; #endif _BitScanForward64(&y, x); return y; } int msb(uint64_t x) { #if defined(__GNUC__) unsigned int y; #else unsigned long y; #endif _BitScanReverse64(&y, x); return y; } int popcnt(uint64_t x) { x = x - ((x >> 1) & 0x5555555555555555); x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333); x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f; return (x * 0x0101010101010101) >> 56; } template <bool HPopCnt> int popcount(uint64_t x) { return HPopCnt ? _mm_popcnt_u64(x) : popcnt(x); } template int popcount<true>(uint64_t x); #else __forceinline int lsb(uint64_t x) { _asm { mov eax, dword ptr x[0] test eax, eax jz l_high bsf eax, eax jmp l_ret l_high : bsf eax, dword ptr x[4] add eax, 20h l_ret : } } __forceinline int msb(uint64_t x) { _asm { mov eax, dword ptr x[4] test eax, eax jz l_low bsr eax, eax add eax, 20h jmp l_ret l_low : bsr eax, dword ptr x[0] l_ret : } } __forceinline int popcnt(uint64_t x) { unsigned int x1, x2; x1 = (unsigned int)(x & 0xFFFFFFFF); x1 -= (x1 >> 1) & 0x55555555; x1 = (x1 & 0x33333333) + ((x1 >> 2) & 0x33333333); x1 = (x1 + (x1 >> 4)) & 0x0F0F0F0F; x2 = (unsigned int)(x >> 32); x2 -= (x2 >> 1) & 0x55555555; x2 = (x2 & 0x33333333) + ((x2 >> 2) & 0x33333333); x2 = (x2 + (x2 >> 4)) & 0x0F0F0F0F; return ((x1 * 0x01010101) >> 24) + ((x2 * 0x01010101) >> 24); } template <bool HPopCnt> __forceinline int popcount(uint64_t x) { return HPopCnt ? (__popcnt((int)x) + __popcnt(x >> 32)) : popcnt(x); } #endif int MinF(int x, int y) { return Min(x, y); } int MaxF(int x, int y) { return Max(x, y); } double MinF(double x, double y) { return Min(x, y); } double MaxF(double x, double y) { return Max(x, y); } uint16_t rand16() { seed = (seed * Convert(6364136223846793005,uint64_t)) + Convert(1442695040888963407,uint64_t); return Convert((seed >> 32) & 0xFFFF,uint16_t); } uint64_t BMagicAttacks(int i, uint64_t occ) { uint64_t att = 0; for (uint64_t u = BMask[i]; T(u); Cut(u)) { if (F(Between[i][lsb(u)] & occ)) att |= Between[i][lsb(u)] | Bit(lsb(u)); } return att; } uint64_t RMagicAttacks(int i, uint64_t occ) { uint64_t att = 0; for (uint64_t u = RMask[i]; T(u); Cut(u)) { if (F(Between[i][lsb(u)] & occ)) att |= Between[i][lsb(u)] | Bit(lsb(u)); } return att; } uint64_t rand64() { uint64_t key = Convert(rand16(),uint64_t); key <<= 16; key |= Convert(rand16(),uint64_t); key <<= 16; key |= Convert(rand16(),uint64_t); key <<= 16; return key | Convert(rand16(),uint64_t); } void init_misc() { int i, j, k, l, n; uint64_t u; for (i = 0; i < 64; i++) { HLine[i] = VLine[i] = NDiag[i] = SDiag[i] = RMask[i] = BMask[i] = QMask[i] = 0; BMagicMask[i] = RMagicMask[i] = NAtt[i] = SArea[i] = DArea[i] = NArea[i] = 0; PAtt[0][i] = PAtt[1][i] = PMove[0][i] = PMove[1][i] = PWay[0][i] = PWay[1][i] = PSupport[0][i] = PSupport[1][i] = BishopForward[0][i] = BishopForward[1][i] = 0; for (j = 0; j < 64; j++) Between[i][j] = FullLine[i][j] = 0; } for (i = 0; i < 64; i++) for (j = 0; j < 64; j++) if (i != j) { u = Bit(j); if (File(i) == File(j)) VLine[i] |= u; if (Rank(i) == Rank(j)) HLine[i] |= u; if (NDiag(i) == NDiag(j)) NDiag[i] |= u; if (SDiag(i) == SDiag(j)) SDiag[i] |= u; if (Dist(i,j) <= 2) { DArea[i] |= u; if (Dist(i,j) <= 1) SArea[i] |= u; if (Abs(Rank(i)-Rank(j)) + Abs(File(i)-File(j)) == 3) NAtt[i] |= u; } if (j == i + 8) PMove[0][i] |= u; if (j == i - 8) PMove[1][i] |= u; if (Abs(File(i) - File(j)) == 1) { if (Rank(j) >= Rank(i)) { PSupport[1][i] |= u; if (Rank(j) - Rank(i) == 1) PAtt[0][i] |= u; } if (Rank(j) <= Rank(i)) { PSupport[0][i] |= u; if (Rank(i) - Rank(j) == 1) PAtt[1][i] |= u; } } else if (File(i) == File(j)) { if (Rank(j) > Rank(i)) PWay[0][i] |= u; else PWay[1][i] |= u; } } for (i = 0; i < 64; i++) { RMask[i] = HLine[i] | VLine[i]; BMask[i] = NDiag[i] | SDiag[i]; QMask[i] = RMask[i] | BMask[i]; BMagicMask[i] = BMask[i] & Interior; RMagicMask[i] = RMask[i]; if (File(i) > 0) RMagicMask[i] &= ~File[0]; if (Rank(i) > 0) RMagicMask[i] &= ~Line[0]; if (File(i) < 7) RMagicMask[i] &= ~File[7]; if (Rank(i) < 7) RMagicMask[i] &= ~Line[7]; for (j = 0; j < 64; j++) if (NAtt[i] & NAtt[j]) Add(NArea[i],j); } for (i = 0; i < 8; i++) { West[i] = 0; East[i] = 0; Forward[0][i] = Forward[1][i] = 0; PIsolated[i] = 0; for (j = 0; j < 8; j++) { if (i < j) Forward[0][i] |= Line[j]; else if (i > j) Forward[1][i] |= Line[j]; if (i < j) East[i] |= File[j]; else if (i > j) West[i] |= File[j]; } if (i > 0) PIsolated[i] |= File[i - 1]; if (i < 7) PIsolated[i] |= File[i + 1]; } for (i = 0; i < 64; i++) { for (u = QMask[i]; T(u); Cut(u)) { j = lsb(u); k = Sgn(Rank(j)-Rank(i)); l = Sgn(File(j)-File(i)); for (n = i + 8 * k + l; n != j; n += (8 * k + l)) Add(Between[i][j],n); } for (u = BMask[i]; T(u); Cut(u)) { j = lsb(u); FullLine[i][j] = BMask[i] & BMask[j]; } for (u = RMask[i]; T(u); Cut(u)) { j = lsb(u); FullLine[i][j] = RMask[i] & RMask[j]; } BishopForward[0][i] |= PWay[0][i]; BishopForward[1][i] |= PWay[1][i]; for (j = 0; j < 64; j++) { if ((PWay[1][j] | Bit(j)) & BMask[i] & Forward[0][Rank(i)]) BishopForward[0][i] |= Bit(j); if ((PWay[0][j] | Bit(j)) & BMask[i] & Forward[1][Rank(i)]) BishopForward[1][i] |= Bit(j); } } for (i = 0; i < 16; i++) for (j = 0; j < 16; j++) { if (j < WhitePawn) MvvLva[i][j] = 0; else if (j < WhiteKnight) MvvLva[i][j] = PawnCaptureMvvLva(i) << 26; else if (j < WhiteLight) MvvLva[i][j] = KnightCaptureMvvLva(i) << 26; else if (j < WhiteRook) MvvLva[i][j] = BishopCaptureMvvLva(i) << 26; else if (j < WhiteQueen) MvvLva[i][j] = RookCaptureMvvLva(i) << 26; else MvvLva[i][j] = QueenCaptureMvvLva(i) << 26; } for (i = 0; i < 256; i++) PieceFromChar[i] = 0; PieceFromChar[66] = 6; PieceFromChar[75] = 14; PieceFromChar[78] = 4; PieceFromChar[80] = 2; PieceFromChar[81] = 12; PieceFromChar[82] = 10; PieceFromChar[98] = 7; PieceFromChar[107] = 15; PieceFromChar[110] = 5; PieceFromChar[112] = 3; PieceFromChar[113] = 13; PieceFromChar[114] = 11; TurnKey = rand64(); for (i = 0; i < 8; i++) EPKey[i] = rand64(); for (i = 0; i < 16; i++) CastleKey[i] = rand64(); for (i = 0; i < 16; i++) for (j = 0; j < 64; j++) { if (i == 0) PieceKey[i][j] = 0; else PieceKey[i][j] = rand64(); } /// for (i = 0; i < 16; i++) LogDist[i] = (int)(10.0 * log(1.01 + (double)i)); } void init_magic() { int i; uint64_t j; int k, index, bits, bit_list[16]; uint64_t u; for (i = 0; i < 64; i++) { bits = 64 - BShift[i]; for (u = BMagicMask[i], j = 0; T(u); Cut(u), j++) bit_list[j] = lsb(u); for (j = 0; j < Bit(bits); j++) { u = 0; for (k = 0; k < bits; k++) if (Odd(j >> k)) Add(u,bit_list[k]); #ifndef HNI index = Convert(BOffset[i] + ((BMagic[i] * u) >> BShift[i]),int); #else index = Convert(BOffset[i] + _pext_u64(u,BMagicMask[i]),int); #endif MagicAttacks[index] = BMagicAttacks(i,u); } bits = 64 - RShift[i]; for (u = RMagicMask[i], j = 0; T(u); Cut(u), j++) bit_list[j] = lsb(u); for (j = 0; j < Bit(bits); j++) { u = 0; for (k = 0; k < bits; k++) if (Odd(j >> k)) Add(u,bit_list[k]); #ifndef HNI index = Convert(ROffset[i] + ((RMagic[i] * u) >> RShift[i]),int); #else index = Convert(ROffset[i] + _pext_u64(u,RMagicMask[i]),int); #endif MagicAttacks[index] = RMagicAttacks(i,u); } } } void gen_kpk() { int turn, wp, wk, bk, to, cnt, old_cnt, un; uint64_t bwp, bwk, bbk, u; uint8_t Kpk_gen[2][64][64][64]; memset(Kpk_gen, 0, 2 * 64 * 64 * 64); cnt = 0; old_cnt = 1; start: if (cnt == old_cnt) goto end; old_cnt = cnt; cnt = 0; for (turn = 0; turn < 2; turn++) { for (wp = 0; wp < 64; wp++) { for (wk = 0; wk < 64; wk++) { for (bk = 0; bk < 64; bk++) { if (Kpk_gen[turn][wp][wk][bk]) continue; cnt++; if (wp < 8 || wp >= 56) goto set_draw; if (wp == wk || wk == bk || bk == wp) goto set_draw; bwp = Bit(wp); bwk = Bit(wk); bbk = Bit(bk); if (PAtt[White][wp] & bbk) { if (turn == White) goto set_draw; else if (F(SArea[wk] & bwp)) goto set_draw; } un = 0; if (turn == Black) { u = SArea[bk] & (~(SArea[wk] | PAtt[White][wp])); if (F(u)) goto set_draw; for (; T(u); Cut(u)) { to = lsb(u); if (Kpk_gen[turn ^ 1][wp][wk][to] == 1) goto set_draw; else if (Kpk_gen[turn ^ 1][wp][wk][to] == 0) un++; } if (F(un)) goto set_win; } else { for (u = SArea[wk] & (~(SArea[bk] | bwp)); T(u); Cut(u)) { to = lsb(u); if (Kpk_gen[turn ^ 1][wp][to][bk] == 2) goto set_win; else if (Kpk_gen[turn ^ 1][wp][to][bk] == 0) un++; } to = wp + 8; if (to != wk && to != bk) { if (to >= 56) { if (F(SArea[to] & bbk)) goto set_win; if (SArea[to] & bwk) goto set_win; } else { if (Kpk_gen[turn ^ 1][to][wk][bk] == 2) goto set_win; else if (Kpk_gen[turn ^ 1][to][wk][bk] == 0) un++; if (to < 24) { to += 8; if (to != wk && to != bk) { if (Kpk_gen[turn ^ 1][to][wk][bk] == 2) goto set_win; else if (Kpk_gen[turn ^ 1][to][wk][bk] == 0) un++; } } } } if (F(un)) goto set_draw; } continue; set_draw: Kpk_gen[turn][wp][wk][bk] = 1; continue; set_win: Kpk_gen[turn][wp][wk][bk] = 2; continue; } } } } if (cnt) goto start; end: for (turn = 0; turn < 2; turn++) { for (wp = 0; wp < 64; wp++) { for (wk = 0; wk < 64; wk++) { Kpk[turn][wp][wk] = 0; for (bk = 0; bk < 64; bk++) { if (Kpk_gen[turn][wp][wk][bk] == 2) Kpk[turn][wp][wk] |= Bit(bk); } } } } } void init_pst() { /// ToDo: ここの処理. #if 0 int i, j, k, op, eg, index, r, f, d, e, distQ[4], distL[4], distM[2]; memset(Pst,0,16 * 64 * sizeof(int)); for (i = 0; i < 64; i++) { r = Rank(i); f = File(i); d = Abs(f - r); e = Abs(f + r - 7); distQ[0] = DistC[f] * DistC[f]; distL[0] = DistC[f]; distQ[1] = DistC[r] * DistC[r]; distL[1] = DistC[r]; distQ[2] = RankR[d] * RankR[d] + RankR[e] * RankR[e]; distL[2] = RankR[d] + RankR[e]; distQ[3] = RankR[r] * RankR[r]; distL[3] = RankR[r]; distM[0] = DistC[f] * DistC[r]; distM[1] = DistC[f] * RankR[r]; for (j = 2; j < 16; j += 2) { index = PieceType[j]; op = eg = 0; for (k = 0; k < 2; k++) { op += Av(PstQuadMixedWeights, 4, index, (k * 2)) * distM[k]; eg += Av(PstQuadMixedWeights, 4, index, (k * 2) + 1) * distM[k]; } for (k = 0; k < 4; k++) { op += Av(PstQuadWeights,8,index,(k * 2)) * distQ[k]; eg += Av(PstQuadWeights,8,index,(k * 2) + 1) * distQ[k]; op += Av(PstLinearWeights,8,index,(k * 2)) * distL[k]; eg += Av(PstLinearWeights,8,index,(k * 2) + 1) * distL[k]; } Pst(j,i) = Compose(op/64, eg/64); } } Pst(WhiteKnight,56) -= Compose(100, 0); Pst(WhiteKnight,63) -= Compose(100, 0); for (i = 0; i < 64; i++) { for (j = 3; j < 16; j+=2) { op = Opening(Pst(j-1,63-i)); eg = Endgame(Pst(j-1,63-i)); Pst(j,i) = Compose(-op,-eg); } } Current->pst = 0; for (i = 0; i < 64; i++) if (Square(i)) Current->pst += Pst(Square(i),i); #endif } void calc_material(int index) { int pawns[2], knights[2], light[2], dark[2], rooks[2], queens[2], bishops[2], major[2], minor[2], tot[2], mat[2], mul[2], quad[2], score, phase, me, i = index; queens[White] = i % 3; i /= 3; queens[Black] = i % 3; i /= 3; rooks[White] = i % 3; i /= 3; rooks[Black] = i % 3; i /= 3; light[White] = i % 2; i /= 2; light[Black] = i % 2; i /= 2; dark[White] = i % 2; i /= 2; dark[Black] = i % 2; i /= 2; knights[White] = i % 3; i /= 3; knights[Black] = i % 3; i /= 3; pawns[White] = i % 9; i /= 9; pawns[Black] = i % 9; for (me = 0; me < 2; me++) { bishops[me] = light[me] + dark[me]; major[me] = rooks[me] + queens[me]; minor[me] = bishops[me] + knights[me]; tot[me] = 3 * minor[me] + 5 * rooks[me] + 9 * queens[me]; mat[me] = mul[me] = 32; quad[me] = 0; } score = (SeeValue[WhitePawn] + Av(MatLinear, 0, 0, 0)) * (pawns[White] - pawns[Black]) + (SeeValue[WhiteKnight] + Av(MatLinear, 0, 0, 1)) * (knights[White] - knights[Black]) + (SeeValue[WhiteLight] + Av(MatLinear, 0, 0, 2)) * (bishops[White] - bishops[Black]) + (SeeValue[WhiteRook] + Av(MatLinear, 0, 0, 3)) * (rooks[White] - rooks[Black]) + (SeeValue[WhiteQueen] + Av(MatLinear, 0, 0, 4)) * (queens[White] - queens[Black]) + 50 * ((bishops[White] / 2) - (bishops[Black] / 2)); phase = Phase[PieceType[WhitePawn]] * (pawns[White] + pawns[Black]) + Phase[PieceType[WhiteKnight]] * (knights[White] + knights[Black]) + Phase[PieceType[WhiteLight]] * (bishops[White] + bishops[Black]) + Phase[PieceType[WhiteRook]] * (rooks[White] + rooks[Black]) + Phase[PieceType[WhiteQueen]] * (queens[White] + queens[Black]); Material[index].phase = Min((Max(phase - PhaseMin, 0) * 128) / (PhaseMax - PhaseMin), 128); int special = 0; for (me = 0; me < 2; me++) { const int opp = (1 ^ me); if (queens[me] == queens[opp]) { if (rooks[me] - rooks[opp] == 1) { if (knights[me] == knights[opp] && bishops[opp] - bishops[me] == 1) IncV(special, Ca(MatSpecial, MatRB)); else if (bishops[me] == bishops[opp] && knights[opp] - knights[me] == 1) IncV(special, Ca(MatSpecial, MatRN)); else if (knights[me] == knights[opp] && bishops[opp] - bishops[me] == 2) DecV(special, Ca(MatSpecial, MatBBR)); else if (bishops[me] == bishops[opp] && knights[opp] - knights[me] == 2) DecV(special, Ca(MatSpecial, MatNNR)); else if (bishops[opp] - bishops[me] == 1 && knights[opp] - knights[me] == 1) DecV(special, Ca(MatSpecial, MatBNR)); } else if (rooks[me] == rooks[opp] && minor[me] - minor[opp] == 1) IncV(special, Ca(MatSpecial, MatM)); } else if (queens[me] - queens[opp] == 1) { if (rooks[opp] - rooks[me] == 2 && minor[opp] - minor[me] == 0) IncV(special, Ca(MatSpecial, MatQRR)); else if (rooks[opp] - rooks[me] == 1 && knights[opp] == knights[me] && bishops[opp] - bishops[me] == 1) IncV(special, Ca(MatSpecial, MatQRB)); else if (rooks[opp] - rooks[me] == 1 && knights[opp] - knights[me] == 1 && bishops[opp] == bishops[me]) IncV(special, Ca(MatSpecial, MatQRN)); else if ((major[opp] + minor[opp]) - (major[me] + minor[me]) >= 2) IncV(special, Ca(MatSpecial, MatQ3)); } } score += (Opening(special) * Material[index].phase + Endgame(special) * (128 - (int)Material[index].phase)) / 128; for (me = 0; me < 2; me++) { const int opp = (1 ^ me); quad[me] += pawns[me] * (pawns[me] * TrAv(MatQuadMe, 5, 0, 0) + knights[me] * TrAv(MatQuadMe, 5, 0, 1) + bishops[me] * TrAv(MatQuadMe, 5, 0, 2) + rooks[me] * TrAv(MatQuadMe, 5, 0, 3) + queens[me] * TrAv(MatQuadMe, 5, 0, 4)); quad[me] += knights[me] * (knights[me] * TrAv(MatQuadMe, 5, 1, 0) + bishops[me] * TrAv(MatQuadMe, 5, 1, 1) + rooks[me] * TrAv(MatQuadMe, 5, 1, 2) + queens[me] * TrAv(MatQuadMe, 5, 1, 3)); quad[me] += bishops[me] * (bishops[me] * TrAv(MatQuadMe, 5, 2, 0) + rooks[me] * TrAv(MatQuadMe, 5, 2, 1) + queens[me] * TrAv(MatQuadMe, 5, 2, 2)); quad[me] += rooks[me] * (rooks[me] * TrAv(MatQuadMe, 5, 3, 0) + queens[me] * TrAv(MatQuadMe, 5, 3, 1)); quad[me] += pawns[me] * (knights[opp] * TrAv(MatQuadOpp, 4, 0, 0) + bishops[opp] * TrAv(MatQuadOpp, 4, 0, 1) + rooks[opp] * TrAv(MatQuadOpp, 4, 0, 2) + queens[opp] * TrAv(MatQuadOpp, 4, 0, 3)); quad[me] += knights[me] * (bishops[opp] * TrAv(MatQuadOpp, 4, 1, 0) + rooks[opp] * TrAv(MatQuadOpp, 4, 1, 1) + queens[opp] * TrAv(MatQuadOpp, 4, 1, 2)); quad[me] += bishops[me] * (rooks[opp] * TrAv(MatQuadOpp, 4, 2, 0) + queens[opp] * TrAv(MatQuadOpp, 4, 2, 1)); quad[me] += rooks[me] * queens[opp] * TrAv(MatQuadOpp, 4, 3, 0); if (bishops[me] >= 2) quad[me] += pawns[me] * Av(BishopPairQuad, 0, 0, 0) + knights[me] * Av(BishopPairQuad, 0, 0, 1) + rooks[me] * Av(BishopPairQuad, 0, 0, 2) + queens[me] * Av(BishopPairQuad, 0, 0, 3) + pawns[opp] * Av(BishopPairQuad, 0, 0, 4) + knights[opp] * Av(BishopPairQuad, 0, 0, 5) + bishops[opp] * Av(BishopPairQuad, 0, 0, 6) + rooks[opp] * Av(BishopPairQuad, 0, 0, 7) + queens[opp] * Av(BishopPairQuad, 0, 0, 8); } score += (quad[White] - quad[Black]) / 100; for (me = 0; me < 2; me++) { const int opp = (1 ^ me); if (tot[me] - tot[opp] <= 3) { if (!pawns[me]) { if (tot[me] <= 3) mul[me] = 0; if (tot[me] == tot[opp] && major[me] == major[opp] && minor[me] == minor[opp]) mul[me] = major[me] + minor[me] <= 2 ? 0 : (major[me] + minor[me] <= 3 ? 16 : 32); else if (minor[me] + major[me] <= 2) { if (bishops[me] < 2) mat[me] = (bishops[me] && rooks[me]) ? 8 : 1; else if (bishops[opp] + rooks[opp] >= 1) mat[me] = 1; else mat[me] = 32; } else if (tot[me] - tot[opp] < 3 && minor[me] + major[me] - minor[opp] - major[opp] <= 1) mat[me] = 4; else if (minor[me] + major[me] <= 3) mat[me] = 8 * (1 + bishops[me]); else mat[me] = 8 * (2 + bishops[me]); } if (pawns[me] <= 1) { mul[me] = Min(28, mul[me]); if (rooks[me] == 1 && queens[me] + minor[me] == 0 && rooks[opp] == 1) mat[me] = Min(23, mat[me]); } } if (!major[me]) { if (!minor[me]) { if (!tot[me] && pawns[me] < pawns[opp]) DecV(score, (pawns[opp] - pawns[me]) * SeeValue[WhitePawn]); } else if (minor[me] == 1) { if (pawns[me] <= 1 && minor[opp] >= 1) mat[me] = 1; if (bishops[me] == 1) { if (minor[opp] == 1 && bishops[opp] == 1 && light[me] != light[opp]) { mul[me] = Min(mul[me], 15); if (pawns[me] - pawns[opp] <= 1) mul[me] = Min(mul[me], 11); } } } else if (!pawns[me] && knights[me] == 2 && !bishops[me]) { if (!tot[opp] && pawns[opp]) mat[me] = 6; else mul[me] = 0; } } if (!mul[me]) mat[me] = 0; if (mat[me] <= 1 && tot[me] != tot[opp]) mul[me] = Min(mul[me], 8); } if (bishops[White] == 1 && bishops[Black] == 1 && light[White] != light[Black]) { mul[White] = Min(mul[White], 24 + 2 * (knights[Black] + major[Black])); mul[Black] = Min(mul[Black], 24 + 2 * (knights[White] + major[White])); } else if (!minor[White] && !minor[Black] && major[White] == 1 && major[Black] == 1 && rooks[White] == rooks[Black]) { mul[White] = Min(mul[White], 25); mul[Black] = Min(mul[Black], 25); } for (me = 0; me < 2; me++) { Material[index].mul[me] = mul[me]; Material[index].pieces[me] = major[me] + minor[me]; } if (score > 0) score = (score * mat[White]) / 32; else score = (score * mat[Black]) / 32; Material[index].score = score; for (me = 0; me < 2; me++) { const int opp = (1 ^ me); if (major[me] == 0 && minor[me] == bishops[me] && minor[me] <= 1) Material[index].flags |= VarC(FlagSingleBishop, me); if (((major[me] == 0 || minor[me] == 0) && major[me] + minor[me] <= 1) || major[opp] + minor[opp] == 0 || (!pawns[me] && major[me] == rooks[me] && major[me] == 1 && minor[me] == bishops[me] && minor[me] == 1 && rooks[opp] == 1 && !minor[opp] && !queens[opp])) Material[index].flags |= VarC(FlagCallEvalEndgame, me); } } void init_material() { memset(Material,0,TotalMat * sizeof(GMaterial)); for (int index = 0; index < TotalMat; index++) calc_material(index); } #if 0 void init_shared() { char name[256]; int64_t size = SharedPVHashOffset + pv_hash_size * sizeof(GPVEntry); sprintf(name, "GULL_SHARED_%d", WinParId); if (parent && SHARED != NULL) { UnmapViewOfFile(Smpi); CloseHandle(SHARED); } if (parent) SHARED = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, size, name); else SHARED = OpenFileMapping(FILE_MAP_ALL_ACCESS, 0, name); Smpi = (GSMPI*)MapViewOfFile(SHARED, FILE_MAP_ALL_ACCESS, 0, 0, size); if (parent) memset(Smpi, 0, size); Material = (GMaterial*)(((char*)Smpi) + SharedMaterialOffset); MagicAttacks = (uint64_t*)(((char*)Smpi) + SharedMagicOffset); PVHash = (GPVEntry*)(((char*)Smpi) + SharedPVHashOffset); if (parent) memset(PVHash, 0, pv_hash_size * sizeof(GPVEntry)); } #endif void init() { /// init_shared(); init_misc(); if (parent) init_magic(); for (int i = 0; i < 64; i++) { BOffsetPointer[i] = MagicAttacks + BOffset[i]; ROffsetPointer[i] = MagicAttacks + ROffset[i]; } gen_kpk(); init_pst(); init_eval(); if (parent) init_material(); USI::init(); TT.init(); } // -->search.cpp //// void init_search(int clear_hash) #if 0 void setup_board() { int i; uint64_t occ; occ = 0; sp = 0; date++; if (date > 0x8000) { // musn't ever happen date = 2; // now GUI must wait for readyok... we have plenty of time :) TT.rewind(); PVHASH.rewind(); } Current->material = 0; Current->pst = 0; Current->key = PieceKey[0][0]; if (Current->turn) Current->key ^= TurnKey; Current->key ^= CastleKey[Current->castle_flags]; if (Current->ep_square) Current->key ^= EPKey[File(Current->ep_square)]; Current->pawn_key = 0; Current->pawn_key ^= CastleKey[Current->castle_flags]; for (i = 0; i < 16; i++) BB(i) = 0; for (i = 0; i < 64; i++) { if (Square(i)) { Add(BB(Square(i)),i); Add(BB(Square(i) & 1),i); Add(occ,i); Current->key ^= PieceKey[Square(i)][i]; if (Square(i) < WhiteKnight) Current->pawn_key ^= PieceKey[Square(i)][i]; if (Square(i) < WhiteKing) Current->material += MatCode[Square(i)]; else Current->pawn_key ^= PieceKey[Square(i)][i]; Current->pst += Pst(Square(i),i); } } if (popcnt(BB(WhiteKnight)) > 2 || popcnt(BB(WhiteLight)) > 1 || popcnt(BB(WhiteDark)) > 1 || popcnt(BB(WhiteRook)) > 2 || popcnt(BB(WhiteQueen)) > 2) Current->material |= FlagUnusualMaterial; if (popcnt(BB(BlackKnight)) > 2 || popcnt(BB(BlackLight)) > 1 || popcnt(BB(BlackDark)) > 1 || popcnt(BB(BlackRook)) > 2 || popcnt(BB(BlackQueen)) > 2) Current->material |= FlagUnusualMaterial; Current->capture = 0; Current->killer[1] = Current->killer[2] = 0; Current->ply = 0; Stack[sp] = Current->key; } void get_board(const char fen[]) { int pos, i, j; unsigned char c; Current = Data; memset(Board,0,sizeof(GBoard)); memset(Current,0,sizeof(GData)); pos = 0; c = fen[pos]; while (c == ' ') c = fen[++pos]; for (i = 56; i >= 0; i -= 8) { for (j = 0; j <= 7; ) { if (c <= '8') j += c - '0'; else { Square(i+j) = PieceFromChar[c]; if (Even(SDiag(i+j)) && (Square(i+j)/2) == 3) Square(i+j) += 2; j++; } c = fen[++pos]; } c = fen[++pos]; } if (c == 'b') Current->turn = 1; c = fen[++pos]; c = fen[++pos]; if (c == '-') c = fen[++pos]; if (c == 'K') { Current->castle_flags |= CanCastle_OO; c = fen[++pos]; } if (c == 'Q') { Current->castle_flags |= CanCastle_OOO; c = fen[++pos]; } if (c == 'k') { Current->castle_flags |= CanCastle_oo; c = fen[++pos]; } if (c == 'q') { Current->castle_flags |= CanCastle_ooo; c = fen[++pos]; } c = fen[++pos]; if (c != '-') { i = c + fen[++pos] * 8 - 489; j = i ^ 8; if (Square(i) != 0) i = 0; else if (Square(j) != (3 - Current->turn)) i = 0; else if (Square(j-1) != (Current->turn+2) && Square(j+1) != (Current->turn+2)) i = 0; Current->ep_square = i; } setup_board(); } #endif void move_to_string(int move, char string[]) { int pos = 0; string[pos++] = ((move >> 6) & 7) + 'a'; string[pos++] = ((move >> 9) & 7) + '1'; string[pos++] = (move & 7) + 'a'; string[pos++] = ((move >> 3) & 7) + '1'; if (IsPromotion(move)) { if ((move & 0xF000) == FlagPQueen) string[pos++] = 'q'; else if ((move & 0xF000) == FlagPRook) string[pos++] = 'r'; else if ((move & 0xF000) == FlagPLight || (move & 0xF000) == FlagPDark) string[pos++] = 'b'; else if ((move & 0xF000) == FlagPKnight) string[pos++] = 'n'; } string[pos] = 0; } int move_from_string(const char string[]) { int from, to, move; from = ((string[1] - '1') * 8) + (string[0] - 'a'); to = ((string[3] - '1') * 8) + (string[2] - 'a'); move = (from << 6) | to; if (Board->square[from] >= WhiteKing && Abs(to - from) == 2) move |= FlagCastling; if (T(Current->ep_square) && to == Current->ep_square) move |= FlagEP; if (string[4] != 0) { if (string[4] == 'q') move |= FlagPQueen; else if (string[4] == 'r') move |= FlagPRook; else if (string[4] == 'b') { if (Odd(to ^ Rank(to))) move |= FlagPLight; else move |= FlagPDark; } else if (string[4] == 'n') move |= FlagPKnight; } return move; } // -->search.cpp ////void pick_pv() ////template <bool me> int draw_in_pv() // -->position.cpp ////template <bool me> void do_move(int move) ////template <bool me> void undo_move(int move) ////void do_null() ////void undo_null() ////template <bool me> int is_legal(int move) ////template <bool me> int is_check(int move) // doesn't detect castling and ep checks // -->search.cpp ////void hash_high(int value, int depth) ////void hash_low(int move, int value, int depth) ////void hash_exact(int move, int value, int depth, int exclusion, int ex_depth, int knodes) ////template <bool pv> __forceinline int extension(int move, int depth) // -->genmove.cpp ////void sort(int * start, int * finish) // -->search.cpp ////void sort_moves(int * start, int * finish) // -->genmove.cpp ////__forceinline int pick_move() ////template <bool me> void gen_next_moves() ////template <bool me, bool root> int get_move() ////template <bool me> int see(int move, int margin) ////template <bool me> void gen_root_moves() ////template <bool me> int * gen_captures(int * list) ////template <bool me> int * gen_evasions(int * list) ////void mark_evasions(int * list) ////template <bool me> int * gen_quiet_moves(int * list) ////template <bool me> int * gen_checks(int * list) ////template <bool me> int * gen_delta_moves(int * list) // -->search.cpp ////template <bool me> int singular_extension(int ext, int prev_ext, int margin_one, int margin_two, int depth, int killer) ////template <bool me> __forceinline void capture_margin(int alpha, int &score) ////template <bool me, bool pv> int q_search(int alpha, int beta, int depth, int flags) ////template <bool me, bool pv> int q_evasion(int alpha, int beta, int depth, int flags) ////void send_position(GPos * Pos) ////void retrieve_board(GPos * Pos) ////void retrieve_position(GPos * Pos, int copy_stack) ////void halt_all(GSP * Sp, int locked) ////void halt_all(int from, int to) ////void init_sp(GSP * Sp, int alpha, int beta, int depth, int pv, int singular, int height) ////template <bool me> int smp_search(GSP * Sp) ////template <bool me, bool exclusion> int search(int beta, int depth, int flags) ////template <bool me, bool exclusion> int search_evasion(int beta, int depth, int flags) ////template <bool me, bool root> int pv_search(int alpha, int beta, int depth, int flags) ////template <bool me> void root() ////template <bool me> int multipv(int depth) ////void send_pv(int depth, int alpha, int beta, int score) ////void send_best_move() void get_position(char string[]) { #if 0 // ToDo: ちゃんと考える。 const char * fen; char * moves; const char * ptr; int move, move1 = 0; fen = strstr(string,"fen "); moves = strstr(string,"moves "); if (fen != NULL) get_board(fen+4); else get_board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); PrevMove = 0; if (moves != NULL) { ptr = moves+6; while (*ptr != 0) { pv_string[0] = *ptr++; pv_string[1] = *ptr++; pv_string[2] = *ptr++; pv_string[3] = *ptr++; if (*ptr == 0 || *ptr == ' ') pv_string[4] = 0; else { pv_string[4] = *ptr++; pv_string[5] = 0; } evaluate(); move = move_from_string(pv_string); PrevMove = move1; move1 = move; if (Current->turn) do_move<1>(move); else do_move<0>(move); memcpy(Data,Current,sizeof(GData)); Current = Data; while (*ptr == ' ') ptr++; } } memcpy(Stack, Stack + sp - Current->ply, (Current->ply + 1) * sizeof(uint64_t)); sp = Current->ply; #endif } void get_time_limit(char string[]) { const char * ptr; int i, time, inc, wtime, btime, winc, binc, moves, pondering, movetime = 0, exp_moves = MovesTg - 1; Infinite = 1; MoveTime = 0; SearchMoves = 0; SMPointer = 0; pondering = 0; TimeLimit1 = 0; TimeLimit2 = 0; wtime = btime = 0; winc = binc = 0; moves = 0; Stop = 0; DepthLimit = 128; ptr = strtok(string," "); for (ptr = strtok(NULL," "); ptr != NULL; ptr = strtok(NULL," ")) { if (!strcmp(ptr,"binc")) { ptr = strtok(NULL," "); binc = atoi(ptr); Infinite = 0; } else if (!strcmp(ptr,"btime")) { ptr = strtok(NULL," "); btime = atoi(ptr); Infinite = 0; } else if (!strcmp(ptr,"depth")) { ptr = strtok(NULL," "); DepthLimit = 2 * atoi(ptr) + 2; Infinite = 1; } else if (!strcmp(ptr,"infinite")) { Infinite = 1; } else if (!strcmp(ptr,"movestogo")) { ptr = strtok(NULL," "); moves = atoi(ptr); Infinite = 0; } else if (!strcmp(ptr,"winc")) { ptr = strtok(NULL," "); winc = atoi(ptr); Infinite = 0; } else if (!strcmp(ptr,"wtime")) { ptr = strtok(NULL," "); wtime = atoi(ptr); Infinite = 0; } else if (!strcmp(ptr,"movetime")) { ptr = strtok(NULL," "); movetime = atoi(ptr); MoveTime = 1; Infinite = 0; } else if (!strcmp(ptr,"searchmoves")) { if (F(SearchMoves)) { for (i = 0; i < 256; i++) SMoves[i] = 0; } SearchMoves = 1; ptr += 12; while (ptr != NULL && ptr[0] >= 'a' && ptr[0] <= 'h' && ptr[1] >= '1' && ptr[1] <= '8') { pv_string[0] = *ptr++; pv_string[1] = *ptr++; pv_string[2] = *ptr++; pv_string[3] = *ptr++; if (*ptr == 0 || *ptr == ' ') pv_string[4] = 0; else { pv_string[4] = *ptr++; pv_string[5] = 0; } SMoves[SMPointer] = move_from_string(pv_string); SMPointer++; ptr = strtok(NULL," "); } } else if (!strcmp(ptr,"ponder")) pondering = 1; } if (pondering) Infinite = 1; if (Current->turn == White) { time = wtime; inc = winc; } else { time = btime; inc = binc; } if (moves) moves = Max(moves - 1, 1); int time_max = Max(time - Min(1000, time/2), 0); int nmoves; if (moves) nmoves = moves; else { nmoves = MovesTg - 1; if (Current->ply > 40) nmoves += Min(Current->ply - 40, (100 - Current->ply)/2); exp_moves = nmoves; } TimeLimit1 = Min(time_max, (time_max + (Min(exp_moves, nmoves) * inc))/Min(exp_moves, nmoves)); TimeLimit2 = Min(time_max, (time_max + (Min(exp_moves, nmoves) * inc))/Min(3,Min(exp_moves, nmoves))); TimeLimit1 = Min(time_max, (TimeLimit1 * TimeRatio)/100); if (Ponder) TimeLimit1 = (TimeLimit1 * PonderRatio)/100; if (MoveTime) { TimeLimit2 = movetime; TimeLimit1 = TimeLimit2 * 100; } InfoTime = StartTime = get_time(); Searching = 1; /// if (MaxPrN > 1) SET_BIT_64(Smpi->searching, 0); if (F(Infinite)) PVN = 1; if (Current->turn == White) root<0>(); else root<1>(); } int time_to_stop(GSearchInfo * SI, int time, int searching) { if (Infinite) return 0; if (time > TimeLimit2) return 1; if (searching) return 0; if (2 * time > TimeLimit2 && F(MoveTime)) return 1; if (SI->Bad) return 0; if (time > TimeLimit1) return 1; if (T(SI->Change) || T(SI->FailLow)) return 0; if (time * 100 > TimeLimit1 * TimeNoChangeMargin) return 1; if (F(SI->Early)) return 0; if (time * 100 > TimeLimit1 * TimeNoPVSCOMargin) return 1; if (SI->Singular < 1) return 0; if (time * 100 > TimeLimit1 * TimeSingOneMargin) return 1; if (SI->Singular < 2) return 0; if (time * 100 > TimeLimit1 * TimeSingTwoMargin) return 1; return 0; } void check_time(int searching) { /// while (!Stop && input()) uci(); int Time; if (Stop) goto jump; CurrTime = get_time(); Time = Convert(CurrTime - StartTime,int); if (T(Print) && Time > InfoLag && CurrTime - InfoTime > InfoDelay) { InfoTime = CurrTime; if (info_string[0]) { fprintf(stdout,"%s",info_string); info_string[0] = 0; fflush(stdout); } } if (time_to_stop(CurrentSI, Time, searching)) goto jump; return; jump: Stop = 1; longjmp(Jump,1); } void check_time(int time, int searching) { /// while (!Stop && input()) uci(); int Time; if (Stop) goto jump; CurrTime = get_time(); Time = Convert(CurrTime - StartTime,int); if (T(Print) && Time > InfoLag && CurrTime - InfoTime > InfoDelay) { InfoTime = CurrTime; if (info_string[0]) { fprintf(stdout,"%s",info_string); info_string[0] = 0; fflush(stdout); } } if (time_to_stop(CurrentSI, time, searching)) goto jump; return; jump: Stop = 1; longjmp(Jump,1); } #if 0 // ToDo: ちゃんと考える。 void check_state() { GSP *Sp, *Spc; int n, nc, score, best, pv, alpha, beta, new_depth, r_depth, ext, move, value; GMove * M; if (parent) { for (uint64_t u = TEST_RESET(Smpi->fail_high); u; Cut(u)) { Sp = &Smpi->Sp[lsb(u)]; LOCK(Sp->lock); if (Sp->active && Sp->finished) { UNLOCK(Sp->lock); longjmp(Sp->jump, 1); } UNLOCK(Sp->lock); } return; } start: if (TEST_RESET_BIT(Smpi->stop, Id)) longjmp(CheckJump, 1); if (Smpi->searching & Bit(Id)) return; if (!(Smpi->searching & 1)) { Sleep(1); return; } while ((Smpi->searching & 1) && !Smpi->active_sp) _mm_pause(); while ((Smpi->searching & 1) && !(Smpi->searching & Bit(Id - 1))) _mm_pause(); Sp = NULL; best = -0x7FFFFFFF; for (uint64_t u = Smpi->active_sp; u; Cut(u)) { Spc = &Smpi->Sp[lsb(u)]; if (!Spc->active || Spc->finished || Spc->lock) continue; for (nc = Spc->current + 1; nc < Spc->move_number; nc++) if (!(Spc->move[nc].flags & FlagClaimed)) break; if (nc < Spc->move_number) score = 1024 * 1024 + 512 * 1024 * (Spc->depth >= 20) + 128 * 1024 * (!(Spc->split)) + ((Spc->depth + 2 * Spc->singular) * 1024) - (((16 * 1024) * (nc - Spc->current)) / nc); else continue; if (score > best) { best = score; Sp = Spc; n = nc; } } if (Sp == NULL) goto start; if (!Sp->active || Sp->finished || (Sp->move[n].flags & FlagClaimed) || n <= Sp->current || n >= Sp->move_number) goto start; if (Sp->lock) goto start; LOCK(Sp->lock); if (!Sp->active || Sp->finished || (Sp->move[n].flags & FlagClaimed) || n <= Sp->current || n >= Sp->move_number) { UNLOCK(Sp->lock); goto start; } M = &Sp->move[n]; M->flags |= FlagClaimed; M->id = Id; Sp->split |= Bit(Id); pv = Sp->pv; alpha = Sp->alpha; beta = Sp->beta; new_depth = M->reduced_depth; r_depth = M->research_depth; ext = M->ext; move = M->move; Current = Data; retrieve_position(Sp->Pos, 1); evaluate(); SET_BIT_64(Smpi->searching, Id); UNLOCK(Sp->lock); if (setjmp(CheckJump)) { ZERO_BIT_64(Smpi->searching, Id); return; } if (Current->turn == White) { do_move<0>(move); if (pv) { value = -search<1, 0>(-alpha, new_depth, FlagNeatSearch | ExtFlag(ext)); if (value > alpha) value = -pv_search<1, 0>(-beta, -alpha, r_depth, ExtFlag(ext)); } else { value = -search<1, 0>(1 - beta, new_depth, FlagNeatSearch | ExtFlag(ext)); if (value >= beta && new_depth < r_depth) value = -search<1, 0>(1 - beta, r_depth, FlagNeatSearch | FlagDisableNull | ExtFlag(ext)); } undo_move<0>(move); } else { do_move<1>(move); if (pv) { value = -search<0, 0>(-alpha, new_depth, FlagNeatSearch | ExtFlag(ext)); if (value > alpha) value = -pv_search<0, 0>(-beta, -alpha, r_depth, ExtFlag(ext)); } else { value = -search<0, 0>(1 - beta, new_depth, FlagNeatSearch | ExtFlag(ext)); if (value >= beta && new_depth < r_depth) value = -search<0, 0>(1 - beta, r_depth, FlagNeatSearch | FlagDisableNull | ExtFlag(ext)); } undo_move<1>(move); } LOCK(Sp->lock); ZERO_BIT_64(Smpi->searching, Id); if (TEST_RESET_BIT(Smpi->stop, Id)) { UNLOCK(Sp->lock); return; } M->flags |= FlagFinished; if (value > Sp->alpha) { Sp->alpha = Min(value, beta); Sp->best_move = move; if (value >= beta) { Sp->finished = 1; SET_BIT_64(Smpi->fail_high, (int)(Sp - Smpi->Sp)); } } UNLOCK(Sp->lock); } #endif HANDLE CreateChildProcess(int child_id) { char name[1024]; TCHAR szCmdline[1024]; PROCESS_INFORMATION piProcInfo; STARTUPINFO siStartInfo; BOOL bSuccess = FALSE; ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION)); ZeroMemory(&siStartInfo, sizeof(STARTUPINFO)); ZeroMemory(szCmdline, 1024 * sizeof(TCHAR)); ZeroMemory(name, 1024); siStartInfo.cb = sizeof(STARTUPINFO); siStartInfo.dwFlags |= STARTF_USESTDHANDLES; GetModuleFileName(NULL, name, 1024); sprintf(szCmdline, " child %d %d", WinParId, child_id); bSuccess = CreateProcess(TEXT(name), TEXT(szCmdline), NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &siStartInfo, &piProcInfo); if (bSuccess) { CloseHandle(piProcInfo.hThread); return piProcInfo.hProcess; } else { fprintf(stdout, "Error %d\n", GetLastError()); return NULL; } } int main(int argc, char *argv[]) { DWORD p; int i; if (argc >= 2) if (!memcmp(argv[1], "child", 5)) { child = 1; parent = 0; WinParId = atoi(argv[2]); Id = atoi(argv[3]); } int CPUInfo[4] = { -1 }; /// __cpuid(CPUInfo, 1); /// HardwarePopCnt = (CPUInfo[2] >> 23) & 1; HardwarePopCnt = 1; if (parent) { if (((CPUInfo[3] >> 28) & 1) && GetProcAddress(GetModuleHandle(TEXT("kernel32")), "GetLogicalProcessorInformation") != NULL) { SYSTEM_LOGICAL_PROCESSOR_INFORMATION syslogprocinfo[1]; p = sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); #ifndef W32_BUILD GetLogicalProcessorInformation(syslogprocinfo, &p); if (syslogprocinfo->ProcessorCore.Flags == 1) HT = 1; #endif } WinParId = GetProcessId(GetCurrentProcess()); HANDLE JOB = CreateJobObject(NULL, NULL); JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 }; jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; SetInformationJobObject(JOB, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli)); AssignProcessToJobObject(JOB, GetCurrentProcess()); if (MaxPrN > 1) { PrN = get_num_cpus(); } } init(); StreamHandle = GetStdHandle(STD_INPUT_HANDLE); Console = GetConsoleMode(StreamHandle, &p); if (Console) { SetConsoleMode(StreamHandle, p & (~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT))); FlushConsoleInputBuffer(StreamHandle); } setbuf(stdout, NULL); setbuf(stdin, NULL); setvbuf(stdout, NULL, _IONBF, 0); setvbuf(stdin, NULL, _IONBF, 0); fflush(NULL); #if 0 // ToDo reset_jump: if (parent) { if (setjmp(ResetJump)) { for (i = 1; i < PrN; i++) TerminateProcess(ChildPr[i], 0); for (i = 1; i < PrN; i++) { WaitForSingleObject(ChildPr[i], INFINITE); CloseHandle(ChildPr[i]); } Smpi->searching = Smpi->active_sp = Smpi->stop = 0; for (i = 0; i < MaxSplitPoints; i++) Smpi->Sp->active = Smpi->Sp->claimed = 0; Smpi->hash_size = hash_size; if (NewPrN) Smpi->PrN = PrN = NewPrN; goto reset_jump; } Smpi->hash_size = hash_size; Smpi->PrN = PrN; } else { hash_size = Smpi->hash_size; PrN = Smpi->PrN; } #endif /// if (ResetHash) init_hash(); if (ResetHash) TT.init(); /// init_search(0); #if 0 // ToDo: ちゃんと考える。 if (child) while (true) check_state(); #endif // if (parent) for (i = 1; i < PrN; i++) ChildPr[i] = CreateChildProcess(i); Threads.init(); USI::loop(argc, argv); Threads.set_size(0); return 0; }
33.592527
215
0.610114
kazu-nanoha
8e83bcfaabbf612acfdb038749b5043345b70b7a
2,346
cpp
C++
src/prod/src/ServiceModel/ContainerIsolationMode.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/ServiceModel/ContainerIsolationMode.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/ServiceModel/ContainerIsolationMode.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace Common; using namespace ServiceModel; namespace ServiceModel { namespace ContainerIsolationMode { void WriteToTextWriter(TextWriter & w, Enum const & val) { switch (val) { case ContainerIsolationMode::process: w << L"process"; return; case ContainerIsolationMode::hyperv: w << L"hyperv"; return; default: Assert::CodingError("Unknown ContainerIsolationMode value {0}", (int)val); } } ErrorCode FromString(wstring const & value, __out Enum & val) { if (value == L"process" || value == L"default") { val = ContainerIsolationMode::process; return ErrorCode(ErrorCodeValue::Success); } else if (value == L"hyperv") { val = ContainerIsolationMode::hyperv; return ErrorCode(ErrorCodeValue::Success); } else { return ErrorCode::FromHResult(E_INVALIDARG); } } wstring EnumToString(Enum val) { switch (val) { case ContainerIsolationMode::process: return L"process"; case ContainerIsolationMode::hyperv: return L"hyperv"; default: Assert::CodingError("Unknown ContainerIsolationMode value {0}", (int)val); } } FABRIC_CONTAINER_ISOLATION_MODE ContainerIsolationMode::ToPublicApi(Enum isolationMode) { switch (isolationMode) { case process: return FABRIC_CONTAINER_ISOLATION_MODE_PROCESS; case hyperv: return FABRIC_CONTAINER_ISOLATION_MODE_HYPER_V; default: return FABRIC_CONTAINER_ISOLATION_MODE_PROCESS; } } } }
29.696203
98
0.507246
vishnuk007
8e850a3a4cabb663a2f50ff67c9db7f68c1dd64c
413
cpp
C++
Number Theory/(CODEFORCES)122A.cpp
kothariji/Competitive-Programming
c49f8b0135c8e9dd284ce8ab583e85ba3d809b8c
[ "MIT" ]
1
2020-08-27T06:59:52.000Z
2020-08-27T06:59:52.000Z
Number Theory/(CODEFORCES)122A.cpp
kothariji/Competitive-Programming
c49f8b0135c8e9dd284ce8ab583e85ba3d809b8c
[ "MIT" ]
null
null
null
Number Theory/(CODEFORCES)122A.cpp
kothariji/Competitive-Programming
c49f8b0135c8e9dd284ce8ab583e85ba3d809b8c
[ "MIT" ]
null
null
null
//solution for 122A - https://codeforces.com/problemset/problem/122/A #include<bits/stdc++.h> using namespace std ; int main() { int a[]={4, 7, 44, 47, 74, 77, 444, 447, 474, 477, 744, 747, 774, 777}; int n;cin>>n; int i=0; while(a[i]<=777) { if(n%a[i]==0) { cout<<"YES"; return 0; } i++; } cout<<"NO"; return 0; }
17.956522
75
0.457627
kothariji
8e87d1ea8ddc6b31f98de81d6a9e252e1e4a26f9
580
cpp
C++
etc/FastIO.cpp
jinhan814/algorithms-implementation
b5185f98c5d5d34c0f98de645e5b755fcf75c120
[ "MIT" ]
null
null
null
etc/FastIO.cpp
jinhan814/algorithms-implementation
b5185f98c5d5d34c0f98de645e5b755fcf75c120
[ "MIT" ]
null
null
null
etc/FastIO.cpp
jinhan814/algorithms-implementation
b5185f98c5d5d34c0f98de645e5b755fcf75c120
[ "MIT" ]
null
null
null
/* * https://blog.naver.com/jinhan814/222400578937 */ #include <bits/stdc++.h> #include <sys/stat.h> #include <sys/mman.h> using namespace std; int main() { struct stat st; fstat(0, &st); char* p = (char*)mmap(0, st.st_size, PROT_READ, MAP_SHARED, 0, 0); auto ReadInt = [&]() { int ret = 0; for (char c = *p++; c & 16; ret = 10 * ret + (c & 15), c = *p++); return ret; }; auto ReadSignedInt = [&]() { int ret = 0; char c = *p++, flag = 0; if (c == '-') c = *p++, flag = 1; for (; c & 16; ret = 10 * ret + (c & 15), c = *p++); return flag ? -ret : ret; }; }
24.166667
67
0.524138
jinhan814
8e88ffdb44fa10c13a4a05e29143abca1544cfb5
426
hpp
C++
src/rstd/core.hpp
agerasev/cpp-rstd
cb4dcb510c4b3d562f7fed0d9eaa3eca94c9db36
[ "MIT" ]
null
null
null
src/rstd/core.hpp
agerasev/cpp-rstd
cb4dcb510c4b3d562f7fed0d9eaa3eca94c9db36
[ "MIT" ]
null
null
null
src/rstd/core.hpp
agerasev/cpp-rstd
cb4dcb510c4b3d562f7fed0d9eaa3eca94c9db36
[ "MIT" ]
null
null
null
#pragma once #include <rcore/prelude.hpp> namespace rstd { inline std::istream &stdin_() { return rcore::stdin_(); } inline std::ostream &stdout_() { return rcore::stdout_(); } inline std::ostream &stderr_() { return rcore::stderr_(); } typedef rcore::Once Once; typedef rcore::Thread Thread; namespace thread { inline Thread &current() { return rcore::thread::current(); } } // namespace thread } // namespace rstd
18.521739
61
0.694836
agerasev
8e8b2b55ebd85f56968f92046be4946bd7d01de8
27,439
cpp
C++
cpp/visual studio/CalculatorServer/reader/reader_statistics_screen.cpp
NiHoel/Anno1800UXEnhancer
b430fdb428696b5218ca65a5e9b977d659cfca01
[ "Apache-2.0" ]
27
2020-03-29T16:02:09.000Z
2021-12-18T20:08:51.000Z
cpp/visual studio/CalculatorServer/reader/reader_statistics_screen.cpp
NiHoel/Anno1800UXEnhancer
b430fdb428696b5218ca65a5e9b977d659cfca01
[ "Apache-2.0" ]
22
2020-04-03T03:40:59.000Z
2022-03-29T15:55:28.000Z
cpp/visual studio/CalculatorServer/reader/reader_statistics_screen.cpp
NiHoel/Anno1800UXEnhancer
b430fdb428696b5218ca65a5e9b977d659cfca01
[ "Apache-2.0" ]
2
2021-10-17T16:15:46.000Z
2022-01-10T18:56:49.000Z
#include "reader_statistics_screen.hpp" #include <iostream> #include <numeric> #include <regex> #include <boost/algorithm/string.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> namespace reader { //////////////////////////////////////// // // Class: statistics_screen_params // //////////////////////////////////////// const cv::Scalar statistics_screen_params::background_blue_dark = cv::Scalar(103, 87, 79, 255); const cv::Scalar statistics_screen_params::background_brown_light = cv::Scalar(124, 181, 213, 255); const cv::Scalar statistics_screen_params::foreground_brown_light = cv::Scalar(96, 195, 255, 255); const cv::Scalar statistics_screen_params::foreground_brown_dark = cv::Scalar(19, 53, 81, 255); const cv::Scalar statistics_screen_params::expansion_arrow = cv::Scalar(78, 98, 115, 255); const cv::Rect2f statistics_screen_params::pane_tabs = cv::Rect2f(cv::Point2f(0.2352f, 0.147f), cv::Point2f(0.7648f, 0.1839f)); const cv::Rect2f statistics_screen_params::pane_title = cv::Rect2f(cv::Point2f(0.3839f, 0), cv::Point2f(0.6176f, 0.0722f)); const cv::Rect2f statistics_screen_params::pane_all_islands = cv::Rect2f(cv::Point2f(0.0234f, 0.2658f), cv::Point2f(0.19f, 0.315f)); const cv::Rect2f statistics_screen_params::pane_islands = cv::Rect2f(cv::Point2f(0.0215f, 0.3326f), cv::Point2f(0.1917f, 0.9586f)); const cv::Rect2f statistics_screen_params::pane_finance_center = cv::Rect2f(cv::Point2f(0.2471f, 0.3084f), cv::Point2f(0.5805f, 0.9576f)); const cv::Rect2f statistics_screen_params::pane_finance_right = cv::Rect2f(cv::Point2f(0.6261f, 0.3603f), cv::Point2f(0.9635f, 0.9587f)); const cv::Rect2f statistics_screen_params::pane_production_center = cv::Rect2f(cv::Point2f(0.24802f, 0.3639f), cv::Point2f(0.583f, 0.9568f)); const cv::Rect2f statistics_screen_params::pane_production_right = cv::Rect2f(cv::Point2f(0.629f, 0.3613f), cv::Point2f(0.9619f, 0.9577f)); const cv::Rect2f statistics_screen_params::pane_population_center = cv::Rect2f(cv::Point2f(0.247f, 0.3571f), cv::Point2f(0.5802f, 0.7006f)); const cv::Rect2f statistics_screen_params::pane_header_center = cv::Rect2f(cv::Point2f(0.24485f, 0.21962f), cv::Point2f(0.4786f, 0.2581f)); const cv::Rect2f statistics_screen_params::pane_header_right = cv::Rect2f(cv::Point2f(0.6276f, 0.2238f), cv::Point2f(0.7946f, 0.2581f)); const cv::Rect2f statistics_screen_params::position_factory_icon = cv::Rect2f(0.0219f, 0.135f, 0.0838f, 0.7448f); const cv::Rect2f statistics_screen_params::position_small_factory_icon = cv::Rect2f(cv::Point2f(0.072590f, 0.062498f), cv::Point2f(0.14436f, 0.97523f)); const cv::Rect2f statistics_screen_params::position_population_icon = cv::Rect2f(0.f, 0.05f, 0.f, 0.9f); const cv::Rect2f statistics_screen_params::position_factory_output = cv::Rect2f(cv::Point2f(0.31963f, 0.58402f), cv::Point2f(0.49729f, 0.83325f)); //////////////////////////////////////// // // Class: statistics_screen // //////////////////////////////////////// const std::string statistics_screen::KEY_AMOUNT = "amount"; const std::string statistics_screen::KEY_EXISTING_BUILDINGS = "existingBuildings"; const std::string statistics_screen::KEY_LIMIT = "limit"; const std::string statistics_screen::KEY_PRODUCTIVITY = "percentBoost"; statistics_screen::statistics_screen(image_recognition& recog) : recog(recog), open_tab(tab::NONE), center_pane_selection(0), selected_session(0) { } void statistics_screen::update(const std::string& language, const cv::Mat& img) { selected_island = std::string(); multiple_islands_selected = false; selected_session = 0; center_pane_selection = 0; current_island_to_session.clear(); recog.update(language); // test if open cv::Mat cropped_image = recog.crop_widescreen(img); cv::Mat statistics_text_img = recog.binarize(recog.get_pane(statistics_screen_params::pane_title, cropped_image), true); if (recog.is_verbose()) { cv::imwrite("debug_images/statistics_text.png", statistics_text_img); cv::imwrite("debug_images/statistics_screenshot.png", cropped_image); } if (recog.get_guid_from_name(statistics_text_img, recog.make_dictionary({ phrase::STATISTICS })).empty()) { open_tab = tab::NONE; if (recog.is_verbose()) { std::cout << std::endl; } return; } if (recog.is_verbose()) { std::cout << std::endl; } cropped_image.copyTo(this->screenshot); open_tab = compute_open_tab(); if (open_tab == tab::NONE) return; bool update = true; if (prev_islands.size().area() == recog.get_pane(statistics_screen_params::pane_islands, screenshot).size().area()) { cv::Mat diff; cv::absdiff(recog.get_pane(statistics_screen_params::pane_islands, screenshot), prev_islands, diff); std::cout << ((float)cv::sum(diff).ddot(cv::Scalar::ones())) << std::endl; float match = ((float)cv::sum(diff).ddot(cv::Scalar::ones())) / prev_islands.rows / prev_islands.cols; update = match > 30; } if (update) { // island list changed recog.get_pane(statistics_screen_params::pane_islands, screenshot).copyTo(prev_islands); update_islands(); } } bool statistics_screen::is_open() const { return get_open_tab() != tab::NONE; } statistics_screen::tab statistics_screen::get_open_tab() const { return open_tab; } statistics_screen::tab statistics_screen::compute_open_tab() const { cv::Mat tabs = recog.get_pane(statistics_screen_params::pane_tabs, screenshot); int tabs_count = (int)tab::ITEMS; int tab_width = tabs.cols / tabs_count; int v_center = tabs.rows / 2; for (int i = 1; i <= (int)tabs_count; i++) { cv::Vec4b pixel = tabs.at<cv::Vec4b>(v_center, (int)(i * tab_width - 0.2f * tab_width)); if (is_tab_selected(pixel)) { if (recog.is_verbose()) { cv::imwrite("debug_images/tab.png", tabs(cv::Rect(static_cast<int>(i * tab_width - 0.2f * tab_width), v_center, 10, 10))); } if (recog.is_verbose()) { std::cout << "Open tab:\t" << i << std::endl; } return tab(i); } } return tab::NONE; } void statistics_screen::update_islands() { unsigned int session_guid = 0; const auto phrases = recog.make_dictionary({ phrase::THE_OLD_WORLD, phrase::THE_NEW_WORLD, phrase::THE_ARCTIC, phrase::CAPE_TRELAWNEY, phrase::ENBESA }); recog.iterate_rows(prev_islands, 0.75f, [&](const cv::Mat& row) { if (recog.is_verbose()) { cv::imwrite("debug_images/row.png", row); } cv::Mat subheading = recog.binarize(recog.get_cell(row, 0.01f, 0.6f, 0.f), true); if (recog.is_verbose()) { cv::imwrite("debug_images/subheading.png", subheading); } std::vector<unsigned int> ids = recog.get_guid_from_name(subheading, phrases); if (ids.size() == 1) { session_guid = ids.front(); return; } if (recog.is_verbose()) { cv::imwrite("debug_images/selection_test.png", row(cv::Rect((int)(0.8f * row.cols), (int)(0.5f * row.rows), 10, 10))); } bool selected = is_selected(row.at<cv::Vec4b>((int)(0.5f * row.rows), (int)(0.8f * row.cols))); cv::Mat island_name_image = recog.binarize(recog.get_cell(row, 0.15f, 0.65f), selected); if (recog.is_verbose()) { cv::imwrite("debug_images/island_name.png", island_name_image); } std::string island_name = recog.join(recog.detect_words(island_name_image), true); if (island_name.empty()) return; auto iter = island_to_session.find(island_name); if (iter != island_to_session.end()) { current_island_to_session.emplace(*iter); return; } cv::Mat session_icon = recog.get_cell(row, 0.025f, 0.14f); if (recog.is_verbose()) { cv::imwrite("debug_images/session_icon.png", session_icon); } session_guid = recog.get_session_guid(session_icon); if (session_guid) { island_to_session.emplace(island_name, session_guid); current_island_to_session.emplace(island_name, session_guid); } if (recog.is_verbose()) { std::cout << "Island added:\t" << island_name; try { std::cout << " (" << recog.get_dictionary().ui_texts.at(session_guid) << ")"; } catch (const std::exception&) {} std::cout << std::endl; } }); } bool statistics_screen::is_all_islands_selected() const { if (!screenshot.size || !is_open()) return false; cv::Mat button = recog.get_pane(statistics_screen_params::pane_all_islands, screenshot); if (button.empty()) return false; return is_selected(button.at<cv::Vec4b>(static_cast<int>(0.1f * button.rows), static_cast<int>(0.5f * button.cols))); } std::pair<std::string, unsigned int> statistics_screen::get_island_from_list(std::string name) const { for (const auto& entry : island_to_session) if (recog.lcs_length(entry.first, name) > 0.66f * std::max(entry.first.size(), name.size())) return entry; return std::make_pair(name, 0); } cv::Mat statistics_screen::get_center_pane() const { switch (get_open_tab()) { case tab::FINANCE: return recog.get_pane(statistics_screen_params::pane_finance_center, screenshot); case tab::PRODUCTION: return recog.get_pane(statistics_screen_params::pane_production_center, screenshot); case tab::POPULATION: return recog.get_pane(statistics_screen_params::pane_population_center, screenshot); default: return cv::Mat(); } } cv::Mat statistics_screen::get_left_pane() const { switch (get_open_tab()) { case tab::NONE: return cv::Mat(); default: return recog.get_pane(statistics_screen_params::pane_islands, screenshot); } } cv::Mat statistics_screen::get_right_pane() const { switch (get_open_tab()) { case tab::FINANCE: return recog.get_pane(statistics_screen_params::pane_finance_right, screenshot); case tab::PRODUCTION: return recog.get_pane(statistics_screen_params::pane_production_right, screenshot); default: return cv::Mat(); } } cv::Mat statistics_screen::get_center_header() const { switch (get_open_tab()) { case tab::NONE: return cv::Mat(); default: return recog.get_pane(statistics_screen_params::pane_header_center, screenshot); } } cv::Mat statistics_screen::get_right_header() const { switch (get_open_tab()) { case tab::NONE: return cv::Mat(); default: return recog.get_pane(statistics_screen_params::pane_header_right, screenshot); } } bool statistics_screen::is_selected(const cv::Vec4b& point) { return image_recognition::closer_to(point, statistics_screen_params::background_blue_dark, statistics_screen_params::background_brown_light); } bool statistics_screen::is_tab_selected(const cv::Vec4b& point) { return image_recognition::closer_to(point, cv::Scalar(234, 205, 149, 255), cv::Scalar(205, 169, 119, 255)); } std::pair<unsigned int, int> statistics_screen::get_optimal_productivity() { const cv::Mat& im = screenshot; if (get_open_tab() != statistics_screen::tab::PRODUCTION) return std::make_pair(0, 0); if (recog.is_verbose()) { std::cout << "Optimal productivities" << std::endl; } cv::Mat buildings_text = recog.binarize(im(cv::Rect(static_cast<int>(0.6522f * im.cols), static_cast<int>(0.373f * im.rows), static_cast<int>(0.093f * im.cols), static_cast<int>(0.0245f * im.rows)))); if (recog.is_verbose()) { cv::imwrite("debug_images/buildings_text.png", buildings_text); } int buildings_count = recog.number_from_region(buildings_text); if (recog.is_verbose()) { std::cout << std::endl; } if (buildings_count < 0) return std::make_pair(0, 0); cv::Mat roi = get_right_pane(); if (roi.empty()) return std::make_pair(0, 0); if (recog.is_verbose()) { cv::imwrite("debug_images/statistics_window_scroll_area.png", roi); } cv::Mat factory_text = im(cv::Rect(static_cast<int>(0.6522f * im.cols), static_cast<int>(0.373f * im.rows), static_cast<int>(0.093f * im.cols), static_cast<int>(0.0245f * im.rows))); if (recog.is_verbose()) { cv::imwrite("debug_images/factory_text.png", factory_text); } std::vector<unsigned int> guids = recog.get_guid_from_name(factory_text, recog.get_dictionary().factories); if (guids.size() != 1) return std::make_pair(0, 0); if (recog.is_verbose()) { try { std::cout << recog.get_dictionary().factories.at(guids.front()) << ":\t"; } catch (...) {} std::cout << std::endl; } std::vector<int> productivities; recog.iterate_rows(roi, 0.8f, [&](const cv::Mat& row) { int productivity = 0; for (const std::pair<float, float> cell : std::vector<std::pair<float, float>>({ {0.6f, 0.2f}, {0.8f, 0.2f} })) { cv::Mat productivity_text = recog.binarize(recog.get_cell(row, cell.first, cell.second)); if (recog.is_verbose()) { cv::imwrite("debug_images/productivity_text.png", productivity_text); } int prod = recog.number_from_region(productivity_text); if (prod > 1000) // sometimes '%' is detected as '0/0' or '00' prod /= 100; if (prod >= 0) productivity += prod; else return; } if (recog.is_verbose()) { std::cout << std::endl; } productivities.push_back(productivity); }); if (productivities.empty()) return std::make_pair(0, 0); int sum = std::accumulate(productivities.begin(), productivities.end(), 0); if (recog.is_verbose()) { std::cout << " = " << sum << std::endl; } if (productivities.size() != buildings_count) { std::sort(productivities.begin(), productivities.end()); sum += (buildings_count - productivities.size()) * productivities[productivities.size() / 2]; } return std::make_pair(guids.front(), sum / buildings_count); } std::map<unsigned int, statistics_screen::properties> statistics_screen::get_factory_properties() { const cv::Mat& im = screenshot; std::map<unsigned int, properties> result; if (get_open_tab() != statistics_screen::tab::PRODUCTION) return result; cv::Mat roi = get_center_pane(); if (roi.empty()) return result; if (recog.is_verbose()) { cv::imwrite("debug_images/statistics_window_scroll_area.png", roi); } if (recog.is_verbose()) { std::cout << "Average productivities" << std::endl; } recog.iterate_rows(roi, 0.9f, [&](const cv::Mat& row) { properties props; if (recog.is_verbose()) { cv::imwrite("debug_images/row.png", row); } cv::Mat product_icon = recog.get_square_region(row, statistics_screen_params::position_factory_icon); if (recog.is_verbose()) { cv::imwrite("debug_images/factory_icon.png", product_icon); } cv::Scalar background_color = statistics_screen::is_selected(product_icon.at<cv::Vec4b>(0, 0)) ? statistics_screen_params::background_blue_dark : statistics_screen_params::background_brown_light; std::vector<unsigned int> p_guids = recog.get_guid_from_icon(product_icon, recog.product_icons, background_color); if (p_guids.empty()) return; if (recog.is_verbose()) { try { std::cout << recog.get_dictionary().products.at(p_guids.front()) << ":\t"; } catch (...) {} } bool selected = is_selected(row.at<cv::Vec4b>(0.1f * row.rows, 0.5f * row.cols)); cv::Mat productivity_text = recog.binarize(recog.get_cell(row, 0.7f, 0.1f, 0.4f), selected); if (recog.is_verbose()) { cv::imwrite("debug_images/productivity_text.png", productivity_text); } int prod = recog.number_from_region(productivity_text); if (prod > 500 && prod % 100 == 0) prod /= 100; if (prod >= 0) props.emplace(KEY_PRODUCTIVITY, prod); cv::Mat text_img = recog.binarize(recog.get_pane(statistics_screen_params::position_factory_output, row), true, true, 200); if (recog.is_verbose()) { cv::imwrite("debug_images/factory_output_text.png", text_img); } auto pair = recog.read_number_slash_number(text_img); if (pair.first >= 0) props.emplace(KEY_AMOUNT, pair.first); if (pair.second >= 0 && pair.second >= pair.first) props.emplace(KEY_LIMIT, pair.second); if (prod >= 0) { for (unsigned int p_guid : p_guids) for (unsigned int f_guid : recog.product_to_factories[p_guid]) result.emplace(f_guid, props); } if (recog.is_verbose()) { std::cout << std::endl; } }); return result; } std::map<unsigned int, int> statistics_screen::get_assets_existing_buildings_from_finance_screen() { std::map<unsigned int, int> result; if (get_open_tab() != statistics_screen::tab::FINANCE) return result; cv::Mat roi = get_center_pane(); if (roi.empty()) return result; if (recog.is_verbose()) { cv::imwrite("debug_images/statistics_window_scroll_area.png", roi); } std::map<unsigned int, std::string> category_dict = recog.make_dictionary({ phrase::RESIDENTS, phrase::PRODUCTION, phrase::SKYSCRAPERS, phrase::FOOD_AND_DRINK_VENUES, phrase::MALLS }); cv::Mat text = recog.binarize(get_right_header()); std::vector<unsigned int> selection = recog.get_guid_from_name(text, category_dict); if (recog.is_verbose()) { try { std::cout << recog.get_dictionary().ui_texts.at(center_pane_selection) << std::endl; } catch (...) {} } if (selection.size() != 1) return result; // nothing selected that we want to evaluate center_pane_selection = selection.front(); const std::map<unsigned int, std::string>* dictionary = nullptr; switch ((phrase)center_pane_selection) { case phrase::RESIDENTS: dictionary = &recog.get_dictionary().population_levels; break; case phrase::PRODUCTION: dictionary = &recog.get_dictionary().factories; break; case phrase::SKYSCRAPERS: dictionary = &recog.get_dictionary().skyscrapers; break; case phrase::FOOD_AND_DRINK_VENUES: dictionary = &recog.get_dictionary().food_and_drink_venues; break; case phrase::MALLS: dictionary = &recog.get_dictionary().malls; break; } roi = get_right_pane(); if (recog.is_verbose()) { cv::imwrite("debug_images/statistics_window_table_area.png", roi); } std::vector<unsigned int> prev_guids; int prev_count = 0; recog.iterate_rows(roi, 0.75f, [&](const cv::Mat& row) { if (recog.is_verbose()) { cv::imwrite("debug_images/row.png", row); cv::imwrite("debug_images/selection_test.png", row(cv::Rect((int)(0.037f * row.cols), (int)(0.5f * row.rows), 10, 10))); } bool is_summary_entry = image_recognition::closer_to(row.at<cv::Vec4b>(0.5f * row.rows, 0.037f * row.cols), statistics_screen_params::expansion_arrow, statistics_screen_params::background_brown_light); if (is_summary_entry) { prev_guids.clear(); cv::Mat text = recog.binarize(recog.get_cell(row, 0.15f, 0.5f)); std::vector<unsigned int> guids = recog.get_guid_from_name(text, *dictionary); if (recog.is_verbose()) { try { for (unsigned int guid : guids) std::cout << dictionary->at(guid) << ", "; std::cout << "\t"; } catch (...) {} } cv::Mat count_text = recog.binarize(recog.get_cell(row, 0.15f, 0.6f)); if (recog.is_verbose()) { cv::imwrite("debug_images/count_text.png", count_text); } std::vector<std::pair<std::string, cv::Rect>> words = recog.detect_words(count_text, tesseract::PSM_SINGLE_LINE); std::string number_string; bool found_opening_bracket = false; for (const auto& word : words) { if (found_opening_bracket) number_string += word.first; else { std::vector<std::string> split_string; boost::split(split_string, word.first, [](char c) {return c == '('; }); if (split_string.size() > 1) { found_opening_bracket = true; number_string += split_string.back(); } } } number_string = std::regex_replace(number_string, std::regex("\\D"), ""); if (recog.is_verbose()) { std::cout << number_string; } int count = std::numeric_limits<int>::lowest(); try { count = std::stoi(number_string); } catch (...) { if (recog.is_verbose()) { std::cout << " (could not recognize number)"; } } if (count >= 0) { if (guids.size() != 1 && get_selected_session() && !is_all_islands_selected()) recog.filter_factories(guids, get_selected_session()); if (guids.size() != 1) { cv::Mat product_icon = recog.get_square_region(row, statistics_screen_params::position_small_factory_icon); if (recog.is_verbose()) { cv::imwrite("debug_images/factory_icon.png", product_icon); } cv::Scalar background_color = statistics_screen_params::background_brown_light; std::map<unsigned int, cv::Mat> icon_candidates; for (unsigned int guid : guids) { auto iter = recog.factory_icons.find(guid); if (iter != recog.factory_icons.end()) icon_candidates.insert(*iter); } guids = recog.get_guid_from_icon(product_icon, icon_candidates, background_color); } if (guids.size() == 1) result.emplace(guids.front(), count); else { prev_guids = guids; prev_count = count; } } } else if (!prev_guids.empty()) // no summary entry, test whether upper row is expanded { cv::Mat session_icon = recog.get_cell(row, 0.08f, 0.08f); if (recog.is_verbose()) { cv::imwrite("debug_images/session_icon.png", session_icon); } unsigned int session_guid = recog.get_session_guid(session_icon); if (!session_guid) { // prev_guids.clear(); return; } recog.filter_factories(prev_guids, session_guid); if (prev_guids.size() == 1) result.emplace(prev_guids.front(), prev_count); prev_guids.clear(); } if (recog.is_verbose()) { std::cout << std::endl; } }); return result; } std::map<unsigned int, statistics_screen::properties> statistics_screen::get_population_properties() const { const cv::Mat& im = screenshot; std::map<unsigned int, properties> result; if (get_open_tab() != statistics_screen::tab::POPULATION) return result; cv::Mat roi = get_center_pane(); if (roi.empty()) return result; if (recog.is_verbose()) { cv::imwrite("debug_images/statistics_window_scroll_area.png", roi); } recog.iterate_rows(roi, 0.75f, [&](const cv::Mat& row) { properties props; cv::Mat population_name = recog.binarize(recog.get_cell(row, 0.076f, 0.2f)); if (recog.is_verbose()) { cv::imwrite("debug_images/population_name.png", population_name); } std::vector<unsigned int> guids = recog.get_guid_from_name(population_name, recog.get_dictionary().population_levels); if (guids.size() != 1) return; // read amount and limit cv::Mat text_img = recog.binarize(recog.get_cell(row, 0.5f, 0.27f, 0.4f)); if (recog.is_verbose()) { cv::imwrite("debug_images/pop_amount_text.png", text_img); } if (recog.is_verbose()) { try { std::cout << recog.get_dictionary().population_levels.at(guids.front()) << "\t"; } catch (...) {} } auto pair = recog.read_number_slash_number(text_img); if (pair.first >= 0) props.emplace(KEY_AMOUNT, pair.first); if (pair.second >= 0 && pair.second >= pair.first) props.emplace(KEY_LIMIT, pair.second); // read existing buildings text_img = recog.binarize(recog.get_cell(row, 0.3f, 0.15f, 0.4f)); if (recog.is_verbose()) { cv::imwrite("debug_images/pop_houses_text.png", text_img); } int houses = recog.number_from_region(text_img); if (houses >= 0) props.emplace(KEY_EXISTING_BUILDINGS, houses); if (recog.is_verbose()) { std::cout << std::endl; } if (!props.empty()) result.emplace(guids.front(), props); }); if (result.size() < 6) for (const auto& entry : recog.get_dictionary().population_levels) { if (result.find(entry.first) == result.end()) result.emplace(entry.first, std::map<std::string, int>({ {KEY_AMOUNT, 0}, {KEY_EXISTING_BUILDINGS, 0}, {KEY_LIMIT, 0} })); } return result; } std::map<std::string, unsigned int> statistics_screen::get_islands() const { return island_to_session; } std::map<std::string, unsigned int> statistics_screen::get_current_islands() const { return current_island_to_session; } std::string statistics_screen::get_selected_island() { if (!selected_island.empty() || multiple_islands_selected) return selected_island; if (is_all_islands_selected()) { if (recog.is_verbose()) { std::cout << recog.ALL_ISLANDS << std::endl; } selected_session = recog.SESSION_META; selected_island = recog.ALL_ISLANDS; return selected_island; } std::string result; cv::Mat roi = recog.binarize(get_center_header()); if (roi.empty()) return result; if (recog.is_verbose()) { cv::imwrite("debug_images/header.png", roi); } auto words_and_boxes = recog.detect_words(roi, tesseract::PSM_SINGLE_LINE); // check whether mutliple islands are selected std::string joined_string = recog.join(words_and_boxes); std::vector<std::string> split_string; boost::split(split_string, joined_string, [](char c) {return c == '/' || c == '[' || c == '(' || c == '{'; }); if (!recog.get_guid_from_name(split_string.front(), recog.make_dictionary({ phrase::MULTIPLE_ISLANDS })).empty()) { if (recog.is_verbose()) { std::cout << recog.get_dictionary().ui_texts.at((unsigned int)phrase::MULTIPLE_ISLANDS) << std::endl; } multiple_islands_selected = true; return selected_island; } int max_dist = 0; int last_index = 0; // detect split between island and session for (int i = 0; i < words_and_boxes.size() - 1; i++) { int dist = words_and_boxes[i + 1].second.x - (words_and_boxes[i].second.x + words_and_boxes[i].second.width); if (dist > max_dist) { max_dist = dist; last_index = i; } } std::string island; std::string session; for (int i = 0; i < words_and_boxes.size(); i++) { if (i <= last_index) island += words_and_boxes[i].first + " "; else session += words_and_boxes[i].first; } island.pop_back(); selected_island = island; auto session_result = recog.get_guid_from_name(session, recog.make_dictionary({ phrase::THE_ARCTIC, phrase::THE_OLD_WORLD, phrase::THE_NEW_WORLD, phrase::CAPE_TRELAWNEY, phrase::ENBESA })); if (session_result.size()) { selected_session = session_result[0]; island_to_session.emplace(selected_island, selected_session); current_island_to_session.emplace(selected_island, selected_session); } if (recog.is_verbose()) { std::cout << result << std::endl; } return selected_island; } unsigned int statistics_screen::get_selected_session() { get_selected_island(); // update island information return selected_session; } std::map<unsigned int, int> statistics_screen::get_population_workforce() const { const cv::Mat& im = screenshot; std::map<unsigned int, int> result; if (get_open_tab() != statistics_screen::tab::POPULATION) return result; cv::Mat roi = get_center_pane(); if (roi.empty()) return result; if (recog.is_verbose()) { cv::imwrite("debug_images/statistics_window_scroll_area.png", roi); } recog.iterate_rows(roi, 0.75f, [&](const cv::Mat& row) { cv::Mat population_name = recog.binarize(recog.get_cell(row, 0.076f, 0.2f)); if (recog.is_verbose()) { cv::imwrite("debug_images/population_name.png", population_name); } std::vector<unsigned int> guids = recog.get_guid_from_name(population_name, recog.get_dictionary().population_levels); if (guids.size() != 1) return; cv::Mat text_img = recog.binarize(recog.get_cell(row, 0.8f, 0.1f)); if (recog.is_verbose()) { cv::imwrite("debug_images/pop_houses_text.png", text_img); } int workforce = recog.number_from_region(text_img); if (workforce >= 0) result.emplace(guids.front(), workforce); }); for (const auto& entry : recog.get_dictionary().population_levels) { if (result.find(entry.first) == result.end()) result[entry.first] = 0; } return result; } }
28.974657
204
0.688691
NiHoel
8e8bb26d3bd1b0a3b9ee833d10e5fb28224a1933
1,491
cpp
C++
src/mailews/src/base/MsgKeyArray.cpp
stonewell/exchange-ews-thunderbird
7b8cc41621ff29deb4145ad905344fecd60ccb0c
[ "MIT" ]
17
2016-02-24T15:13:04.000Z
2022-03-31T22:07:20.000Z
src/mailews/src/base/MsgKeyArray.cpp
stonewell/exchange-ews-thunderbird
7b8cc41621ff29deb4145ad905344fecd60ccb0c
[ "MIT" ]
3
2016-02-24T20:05:09.000Z
2017-04-18T04:23:56.000Z
src/mailews/src/base/MsgKeyArray.cpp
stonewell/exchange-ews-thunderbird
7b8cc41621ff29deb4145ad905344fecd60ccb0c
[ "MIT" ]
8
2018-06-01T08:32:35.000Z
2021-07-01T01:22:20.000Z
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "MsgKeyArray.h" #include "nsMemory.h" NS_IMPL_ISUPPORTS(MsgKeyArray, nsIMsgKeyArray) MsgKeyArray::MsgKeyArray() { } MsgKeyArray::~MsgKeyArray() { } NS_IMETHODIMP MsgKeyArray::Sort() { m_keys.Sort(); return NS_OK; } NS_IMETHODIMP MsgKeyArray::GetKeyAt(int32_t aIndex, nsMsgKey *aKey) { NS_ENSURE_ARG_POINTER(aKey); *aKey = m_keys[aIndex]; return NS_OK; } NS_IMETHODIMP MsgKeyArray::GetLength(uint32_t *aLength) { NS_ENSURE_ARG_POINTER(aLength); *aLength = m_keys.Length(); return NS_OK; } NS_IMETHODIMP MsgKeyArray::SetCapacity(uint32_t aCapacity) { m_keys.SetCapacity(aCapacity); return NS_OK; } NS_IMETHODIMP MsgKeyArray::AppendElement(nsMsgKey aKey) { m_keys.AppendElement(aKey); return NS_OK; } NS_IMETHODIMP MsgKeyArray::InsertElementSorted(nsMsgKey aKey) { m_keys.InsertElementSorted(aKey); return NS_OK; } NS_IMETHODIMP MsgKeyArray::GetArray(uint32_t *aCount, nsMsgKey **aKeys) { NS_ENSURE_ARG_POINTER(aCount); NS_ENSURE_ARG_POINTER(aKeys); *aCount = m_keys.Length(); *aKeys = (nsMsgKey *) nsMemory::Clone(&m_keys[0], m_keys.Length() * sizeof(nsMsgKey)); return (*aKeys) ? NS_OK : NS_ERROR_OUT_OF_MEMORY; }
21.926471
76
0.716298
stonewell
8e8c428082f3f640b1a82eaa4eea3a014391e900
1,796
cpp
C++
SDK/ARKSurvivalEvolved_Xenomorph_Character_BP_Male_Tamed_Gen2_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_Xenomorph_Character_BP_Male_Tamed_Gen2_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_Xenomorph_Character_BP_Male_Tamed_Gen2_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
// ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_Xenomorph_Character_BP_Male_Tamed_Gen2_parameters.hpp" namespace sdk { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function Xenomorph_Character_BP_Male_Tamed_Gen2.Xenomorph_Character_BP_Male_Tamed_Gen2_C.UserConstructionScript // () void AXenomorph_Character_BP_Male_Tamed_Gen2_C::UserConstructionScript() { static auto fn = UObject::FindObject<UFunction>("Function Xenomorph_Character_BP_Male_Tamed_Gen2.Xenomorph_Character_BP_Male_Tamed_Gen2_C.UserConstructionScript"); AXenomorph_Character_BP_Male_Tamed_Gen2_C_UserConstructionScript_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Xenomorph_Character_BP_Male_Tamed_Gen2.Xenomorph_Character_BP_Male_Tamed_Gen2_C.ExecuteUbergraph_Xenomorph_Character_BP_Male_Tamed_Gen2 // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void AXenomorph_Character_BP_Male_Tamed_Gen2_C::ExecuteUbergraph_Xenomorph_Character_BP_Male_Tamed_Gen2(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function Xenomorph_Character_BP_Male_Tamed_Gen2.Xenomorph_Character_BP_Male_Tamed_Gen2_C.ExecuteUbergraph_Xenomorph_Character_BP_Male_Tamed_Gen2"); AXenomorph_Character_BP_Male_Tamed_Gen2_C_ExecuteUbergraph_Xenomorph_Character_BP_Male_Tamed_Gen2_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
31.508772
197
0.754454
2bite
8e907c11dd1da0d4fb7850fd02019af2a6e95d0b
2,948
cpp
C++
test/source/local_shared_ptr_test.cpp
anders-wind/shared_ptr
ec5db7bf9a9516149b41dbf7e131c24536a393ae
[ "MIT" ]
null
null
null
test/source/local_shared_ptr_test.cpp
anders-wind/shared_ptr
ec5db7bf9a9516149b41dbf7e131c24536a393ae
[ "MIT" ]
1
2022-01-04T23:55:10.000Z
2022-01-04T23:55:10.000Z
test/source/local_shared_ptr_test.cpp
anders-wind/shared_ptr
ec5db7bf9a9516149b41dbf7e131c24536a393ae
[ "MIT" ]
null
null
null
#include <functional> #include <doctest/doctest.h> #include <shared_ptr/local_shared_ptr.hpp> TEST_SUITE("local::shared_ptr") // NOLINT { TEST_CASE("local::shared_ptr: make_shared works") // NOLINT { auto my_shared = wind::local::make_shared<int>(42); CHECK(*my_shared == 42); CHECK(my_shared.use_count() == 1); } TEST_CASE("local::shared_ptr: copy operator= works") // NOLINT { auto my_shared = wind::local::make_shared<int>(42); auto copy = my_shared; CHECK((*copy) == (*my_shared)); CHECK(my_shared.use_count() == 2); CHECK(copy.use_count() == 2); } TEST_CASE("local::shared_ptr: move operator= works") // NOLINT { auto my_shared = wind::local::make_shared<int>(42); auto moved = std::move(my_shared); CHECK(moved.use_count() == 1); } TEST_CASE("local::shared_ptr: Destructor does not delete when copy exists") // NOLINT { wind::local::shared_ptr<int> out_copy; { auto my_shared = wind::local::make_shared<int>(42); out_copy = my_shared; CHECK(out_copy.use_count() == 2); } CHECK(out_copy.use_count() == 1); CHECK(*out_copy == 42); } struct deleter_func_2 // NOLINT { std::function<void()> delete_func; explicit deleter_func_2(std::function<void()> func) : delete_func(std::move(func)) { } ~deleter_func_2() { this->delete_func(); } }; TEST_CASE("local::shared_ptr: Delete gets called") // NOLINT { bool was_called = false; { auto ptr = wind::local::make_shared<deleter_func_2>([&was_called]() { was_called = true; }); CHECK(!was_called); } CHECK(was_called); } TEST_CASE("local::shared_ptr: Delete gets called when supplying pointer") // NOLINT { bool was_called = false; { auto ptr = wind::local::shared_ptr<deleter_func_2>(new deleter_func_2([&was_called]() { was_called = true; })); CHECK(!was_called); } CHECK(was_called); } TEST_CASE("local::shared_ptr: Delete gets called when 2 copies") // NOLINT { bool was_called = false; { auto ptr = wind::local::make_shared<deleter_func_2>([&was_called]() { was_called = true; }); auto copy = ptr; // NOLINT CHECK(!was_called); } CHECK(was_called); } TEST_CASE("local::shared_ptr: Delete only gets called on last destructor") // NOLINT { bool was_called = false; { auto ptr = wind::local::make_shared<deleter_func_2>([&was_called]() { was_called = true; }); { auto copy = ptr; // NOLINT } CHECK(!was_called); } CHECK(was_called); } }
29.48
116
0.549864
anders-wind
8e90ad8a313ebb808860eb60c64b8a9db67a56c0
3,180
cpp
C++
src/scenes/SFPC/cantusFirmusRiley/cantusFirmusRiley.cpp
roymacdonald/ReCoded
3bcb3d579cdd17381e54a508a1e4ef9e3d5bc4f1
[ "MIT" ]
64
2017-06-12T19:24:08.000Z
2022-01-27T19:14:48.000Z
src/scenes/cantusFirmusRiley/cantusFirmusRiley.cpp
colaplate/recoded
934e1184c7502d192435c406e56b8a2106e9b6b4
[ "MIT" ]
10
2017-06-13T10:38:39.000Z
2017-11-15T11:21:05.000Z
src/scenes/cantusFirmusRiley/cantusFirmusRiley.cpp
colaplate/recoded
934e1184c7502d192435c406e56b8a2106e9b6b4
[ "MIT" ]
24
2017-06-11T08:14:46.000Z
2020-04-16T20:28:46.000Z
#include "cantusFirmusRiley.h" void cantusFirmusRiley::setup(){ ofBackground(255); size = 5000; y.c.setHex(0xA79C26); y.width = 9; p.c.setHex(0xC781A8); p.width = 9; b.c.setHex(0x64A2C9); b.width = 11; k.c.setHex(0x222B32); k.width = 39; w.c.setHex(0xE3E2DE); w.width = 29; g.c.set(127); g.width = 29; r.c.set(255,0,0); r.width = 10; int counter = 0; for (int i = 0; i <= size; i++){ if(i == size/2) stripes.push_back(w); else if(abs(i-size/2)% 8 == 1) stripes.push_back(y); else if(abs(i-size/2)% 8 == 2) stripes.push_back(p); else if(abs(i-size/2)% 8 == 3) stripes.push_back(b); else if(abs(i-size/2)% 8 == 5) stripes.push_back(b); else if(abs(i-size/2)% 8 == 6) stripes.push_back(p); else if(abs(i-size/2)% 8 == 7) stripes.push_back(y); else if(abs(i-size/2)%12 == 0) stripes.push_back(w); else if(abs(i-size/2)%12 == 8) stripes.push_back(k); else if(abs(i-size/2)%12 == 4) { int rand = ofRandom(120,180); g.c.set(rand); // cout << rand << endl; stripes.push_back(g); } else stripes.push_back(r); } parameters.add(posNoiseSpeed.set("offsetX", 0, -300, 300)); parameters.add(zoomNoiseSpeed.set("zoom", 0.2, 0.05, 1)); //parameters.add(range.set("scale", 0.3, 0.02, 1.0)); setAuthor("Reed Tothong"); setOriginalArtist("Bridget Riley"); loadCode("scenes/cantusFirmusRiley/cantusFirmusRiley.cpp"); } void cantusFirmusRiley::update(){ } void cantusFirmusRiley::draw(){ ofFill(); ofSetRectMode(OF_RECTMODE_CORNER); // posNoise = ofNoise(getElapsedTimef()*posNoiseSpeed); // // float posX = ofMap(posNoise, 0, 1.0, 0, ofGetWidth()/2); ofTranslate(posNoiseSpeed, 0); // zoomNoise = ofNoise(getElapsedTimef()*zoomNoiseSpeed); // // cinematic = 0.1 // motion sickness = 10 // //// float rangeNoise = ofNoise(getElapsedTimef()*rangeNoiseSpeed); // float microScale = ofMap(range, 0, 0.5, 0.015, 1.0, true); // float macroScale = ofMap(range, 0.5, 1.0, 1.0, 2.5,true); // // float maxZoomOut = range < 0.5 ? microScale : macroScale; // // zoom range control // float zoom = ofMap(zoomNoise, 0.0, 1.0, .0001, maxZoomOut, true); ofScale(zoomNoiseSpeed, 1); //midline stripes[size/2].x = -stripes[size/2].width/2; ofSetColor(stripes[size/2].c); ofDrawRectangle(stripes[size/2].x, 0, stripes[size/2].width, dimensions.width*2); //loop to the left for (int i = (size/2)-1; i> 0; i--){ ofSetColor(stripes[i].c); stripes[i].x = stripes[i+1].x - stripes[i].width; ofDrawRectangle(stripes[i].x, 0, stripes[i].width, dimensions.height*2); } //loop to the right for (int i = (size/2)+1; i< stripes.size();i++) { ofSetColor(stripes[i].c); stripes[i].x = stripes[i-1].x + stripes[i-1].width; ofDrawRectangle(stripes[i].x, 0, stripes[i].width, dimensions.height*2); } }
28.909091
85
0.56195
roymacdonald
8e92c72f104e18fe40c206ad6f39606eded00187
1,904
cpp
C++
src/plugins/shell/shell.cpp
Siddharth1698/MAVSDK
57ed6203c49b1fc39ad56e391b0b5d851a787d32
[ "BSD-3-Clause" ]
null
null
null
src/plugins/shell/shell.cpp
Siddharth1698/MAVSDK
57ed6203c49b1fc39ad56e391b0b5d851a787d32
[ "BSD-3-Clause" ]
null
null
null
src/plugins/shell/shell.cpp
Siddharth1698/MAVSDK
57ed6203c49b1fc39ad56e391b0b5d851a787d32
[ "BSD-3-Clause" ]
null
null
null
// WARNING: THIS FILE IS AUTOGENERATED! As such, it should not be edited. // Edits need to be made to the proto files // (see https://github.com/mavlink/MAVSDK-Proto/blob/master/protos/shell/shell.proto) #include <iomanip> #include "shell_impl.h" #include "plugins/shell/shell.h" namespace mavsdk { Shell::Shell(System& system) : PluginBase(), _impl{new ShellImpl(system)} {} Shell::~Shell() {} Shell::Result Shell::send(std::string command) const { return _impl->send(command); } void Shell::subscribe_receive(ReceiveCallback callback) { _impl->receive_async(callback); } const char* Shell::result_str(Shell::Result result) { switch (result) { case Shell::Result::Unknown: return "Unknown error"; case Shell::Result::Success: return "Request succeeded"; case Shell::Result::NoSystem: return "No system is connected"; case Shell::Result::ConnectionError: return "Connection error"; case Shell::Result::NoResponse: return "Response was not received"; case Shell::Result::Busy: return "Shell busy (transfer in progress)"; default: return "Unknown"; } } std::ostream& operator<<(std::ostream& str, Shell::Result const& result) { switch (result) { case Shell::Result::Unknown: return str << "Result Unknown"; case Shell::Result::Success: return str << "Result Success"; case Shell::Result::NoSystem: return str << "Result No System"; case Shell::Result::ConnectionError: return str << "Result Connection Error"; case Shell::Result::NoResponse: return str << "Result No Response"; case Shell::Result::Busy: return str << "Result Busy"; default: return str << "Unknown"; } } } // namespace mavsdk
28.848485
85
0.616597
Siddharth1698
8e92f360d0ac705f5227a0d178b6606a86c4d74d
7,195
cxx
C++
Libraries/QtVgCommon/vgColor.cxx
Acidburn0zzz/vivia
03326eca49c1d4fc8d3478b6750aef888df82a28
[ "BSD-3-Clause" ]
1
2017-07-31T07:08:05.000Z
2017-07-31T07:08:05.000Z
Libraries/QtVgCommon/vgColor.cxx
Acidburn0zzz/vivia
03326eca49c1d4fc8d3478b6750aef888df82a28
[ "BSD-3-Clause" ]
null
null
null
Libraries/QtVgCommon/vgColor.cxx
Acidburn0zzz/vivia
03326eca49c1d4fc8d3478b6750aef888df82a28
[ "BSD-3-Clause" ]
null
null
null
/*ckwg +5 * Copyright 2013 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "vgColor.h" #include <qtMath.h> #include <QColor> #include <QSettings> #include <QString> //----------------------------------------------------------------------------- vgColor::vgColor() { this->d.color.red = qQNaN(); this->d.color.green = qQNaN(); this->d.color.blue = qQNaN(); this->d.color.alpha = qQNaN(); } //----------------------------------------------------------------------------- vgColor::vgColor(const vgColor& other) { *this = other; } //----------------------------------------------------------------------------- vgColor::vgColor(const QColor& qc) { *this = qc; } //----------------------------------------------------------------------------- vgColor::vgColor(int red, int green, int blue, int alpha) { *this = QColor(red, green, blue, alpha); } //----------------------------------------------------------------------------- vgColor::vgColor(double red, double green, double blue, double alpha) { this->d.color.red = red; this->d.color.green = green; this->d.color.blue = blue; this->d.color.alpha = alpha; } //----------------------------------------------------------------------------- vgColor::vgColor(const double (&color)[3], double alpha) { this->d.color.red = color[0]; this->d.color.green = color[1]; this->d.color.blue = color[2]; this->d.color.alpha = alpha; } //----------------------------------------------------------------------------- vgColor::vgColor(const double (&color)[4]) { this->d.color.red = color[0]; this->d.color.green = color[1]; this->d.color.blue = color[2]; this->d.color.alpha = color[3]; } //----------------------------------------------------------------------------- vgColor& vgColor::operator=(const vgColor& other) { this->d.color.red = other.d.color.red; this->d.color.green = other.d.color.green; this->d.color.blue = other.d.color.blue; this->d.color.alpha = other.d.color.alpha; return *this; } //----------------------------------------------------------------------------- vgColor& vgColor::operator=(const QColor& qc) { this->d.color.red = qc.redF(); this->d.color.green = qc.greenF(); this->d.color.blue = qc.blueF(); this->d.color.alpha = qc.alphaF(); return *this; } //----------------------------------------------------------------------------- bool vgColor::isValid() const { return (qIsFinite(this->d.array[0]) && qIsFinite(this->d.array[1]) && qIsFinite(this->d.array[2]) && qIsFinite(this->d.array[3])); } //----------------------------------------------------------------------------- vgColor::ComponentData& vgColor::data() { return this->d; } //----------------------------------------------------------------------------- const vgColor::ComponentData& vgColor::constData() const { return this->d; } //----------------------------------------------------------------------------- vgColor::ComponentData vgColor::value() const { return this->d; } //----------------------------------------------------------------------------- void vgColor::fillArray(double (&out)[3]) const { out[0] = this->d.array[0]; out[1] = this->d.array[1]; out[2] = this->d.array[2]; } //----------------------------------------------------------------------------- void vgColor::fillArray(double (&out)[4]) const { out[0] = this->d.array[0]; out[1] = this->d.array[1]; out[2] = this->d.array[2]; out[3] = this->d.array[3]; } //----------------------------------------------------------------------------- void vgColor::fillArray(unsigned char (&out)[3]) const { vgColor::fillArray(this->toQColor(), out); } //----------------------------------------------------------------------------- void vgColor::fillArray(unsigned char (&out)[4]) const { vgColor::fillArray(this->toQColor(), out); } //----------------------------------------------------------------------------- void vgColor::fillArray(const QColor& color, double (&out)[3]) { out[0] = color.redF(); out[1] = color.greenF(); out[2] = color.blueF(); } //----------------------------------------------------------------------------- void vgColor::fillArray(const QColor& color, double (&out)[4]) { out[0] = color.redF(); out[1] = color.greenF(); out[2] = color.blueF(); out[3] = color.alphaF(); } //----------------------------------------------------------------------------- void vgColor::fillArray(const QColor& color, unsigned char (&out)[3]) { out[0] = static_cast<unsigned char>(color.red()); out[1] = static_cast<unsigned char>(color.green()); out[2] = static_cast<unsigned char>(color.blue()); } //----------------------------------------------------------------------------- void vgColor::fillArray(const QColor& color, unsigned char (&out)[4]) { out[0] = static_cast<unsigned char>(color.red()); out[1] = static_cast<unsigned char>(color.green()); out[2] = static_cast<unsigned char>(color.blue()); out[3] = static_cast<unsigned char>(color.alpha()); } //----------------------------------------------------------------------------- QString vgColor::toString(vgColor::StringType t) const { bool haveAlpha = (this->d.color.alpha > 0.0); int c[4] = { qRound(255.0 * this->d.color.red), qRound(255.0 * this->d.color.green), qRound(255.0 * this->d.color.blue), qRound(255.0 * this->d.color.alpha) }; if (t == vgColor::WithAlpha || (t == vgColor::AutoAlpha && haveAlpha)) { QString f("%1,%2,%3,%4"); return f.arg(c[0]).arg(c[1]).arg(c[2]).arg(c[3]); } else { QString f("%1,%2,%3"); return f.arg(c[0]).arg(c[1]).arg(c[2]); } } //----------------------------------------------------------------------------- QColor vgColor::toQColor() const { return QColor::fromRgbF(this->d.color.red, this->d.color.green, this->d.color.blue, this->d.color.alpha); } //----------------------------------------------------------------------------- vgColor vgColor::read( const QSettings& settings, const QString& key, vgColor defaultValue) { defaultValue.read(settings, key); return defaultValue; } //----------------------------------------------------------------------------- void vgColor::write( QSettings& settings, const QString& key, const vgColor& value) { value.write(settings, key); } //----------------------------------------------------------------------------- bool vgColor::read(const QSettings& settings, const QString& key) { QString s = settings.value(key).toString(); if (!s.isEmpty()) { QStringList parts = s.split(','); int k = parts.count(); if (k == 3 || k == 4) { *this = QColor(parts[0].toInt(), parts[1].toInt(), parts[2].toInt(), k == 4 ? parts[3].toInt() : 255); return true; } } return false; } //----------------------------------------------------------------------------- void vgColor::write(QSettings& settings, const QString& key) const { settings.setValue(key, this->toString()); }
29.012097
79
0.43975
Acidburn0zzz
8e96a905341164dea3c171b14db932528377fc12
20,491
cpp
C++
math/src/matrix.cpp
blobrobots/libs
cc11f56bc4e1112033e8b7352e5653f98f1bfc13
[ "MIT" ]
1
2015-10-21T14:36:43.000Z
2015-10-21T14:36:43.000Z
math/src/matrix.cpp
blobrobots/libs
cc11f56bc4e1112033e8b7352e5653f98f1bfc13
[ "MIT" ]
null
null
null
math/src/matrix.cpp
blobrobots/libs
cc11f56bc4e1112033e8b7352e5653f98f1bfc13
[ "MIT" ]
null
null
null
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2015 Blob Robotics * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * \file matrix.h * \brief implementation of matrix object and operations * \author adrian jimenez-gonzalez (blob.robots@gmail.com) * \copyright the MIT License Copyright (c) 2017 Blob Robots. * ******************************************************************************/ #include "blob/matrix.h" #include "blob/math.h" #if defined(__linux__) #include <iostream> #endif blob::MatrixR::MatrixR (uint8_t rows, uint8_t cols, real_t *data) : Matrix<real_t>(rows,cols,data) {}; bool blob::MatrixR::cholesky (bool zero) { bool retval = true; if(_nrows == _ncols) { real_t t; uint8_t n = _nrows; int i=0,j=0,k=0; for(i=0 ; i<n && retval == true; i++) { if(i > 0) { for(j=i; j<n; j++) { t = 0; for(k=0; k<i; k++) t += _data[j*n + k]*_data[i*n + k]; _data[j*n+i] -= t; } } if(_data[i*n + i] <= 0) { #if defined(__DEBUG__) & defined(__linux__) std::cerr << "MatrixR::cholesky() error: Matrix is not positive definite" << std::endl; #endif retval = false; } else { t = 1/blob::math::sqrtr(_data[i*n + i]); for(j = i ; j < n ; j++) _data[j*n + i] *= t; } } if(zero) { for(int i=n-1; i>0; i--) { for(int j=i-1; j>=0; j--) { _data[j*n+i]=0; } } } } else { #if defined(__DEBUG__) & defined(__linux__) std::cerr << "MatrixR::cholesky() error: Matrix is not square" << std::endl; #endif retval = false; } return retval; } bool blob::MatrixR::cholupdate (MatrixR & v, int sign) { bool retval = false; uint8_t n = _nrows; if(_nrows != _ncols) { #if defined(__DEBUG__) & defined(__linux__) std::cerr << "MatrixR::cholupdate() error: Matrix is not square"<< std::endl; #endif return false; } if((v.length() != n)||((v.nrows() != 1)&&(v.ncols() != 1))) { #if defined(__DEBUG__) & defined(__linux__) std::cerr << "MatrixR::cholupdate() error: vector not 1x" << (int)n << std::endl; #endif return false; } if((sign != -1)&&(sign != 1)) { #if defined(__DEBUG__) & defined(__linux__) std::cerr << "Matrix::cholupdate() error: sign not unitary s=" << sign << std::endl; #endif return false; } for (int i=0; i<n; i++) { real_t sr = _data[i*n+i]*_data[i*n+i] + (real_t)sign*v[i]*v[i]; if(_data[i*n+i] == 0.0) { #if defined(__DEBUG__) & defined(__linux__) std::cerr << "MatrixR::cholupdate() error: Matrix with zero diagonal " << "element " << i << std::endl; #endif return false; } if(sr < 0.0) { #if defined(__DEBUG__) & defined(__linux__) std::cerr << "Matrix::cholupdate() error: Result is not positive definite" << " sqrt(neg)" << std::endl; #endif return false; } real_t r = blob::math::sqrtr(_data[i*n+i]*_data[i*n+i] + (real_t)sign*v[i]*v[i]); real_t c = r/_data[i*n+i]; real_t s = v[i]/_data[i*n+i]; _data[i*n+i] = r; if(c == 0.0) { #if defined(__DEBUG__) & defined(__linux__) std::cerr << "MatrixR::cholupdate() error: Result is not positive definite" << std::endl; #endif return false; } for(int j=i+1; j<n; j++) { _data[j*n+i] = (_data[j*n+i] + sign*s*v[j])/c; v[j] = c*v[j] - s*_data[j*n+i]; } } return true; } bool blob::MatrixR::cholrestore (bool zero) { bool retval = false; if(_nrows == _ncols) { if(zero == false) // original matrix stored in upper triangle { uint8_t n = _nrows; for(int i=0; i<n; i++) { real_t t = 0.0; for(int j=0; j<i+1; j++) { t += _data[i*n+j]*_data[i*n+j]; // assumes original matrix stored in upper triangle _data[i*n+j] = (i==j)? t:_data[j*n+i]; } } retval = true; } else { // TODO #if defined(__DEBUG__) & defined(__linux__) std::cerr << "MatrixR::cholrestore() error: not implemented for zero=true" << std::endl; #endif } } #if defined(__DEBUG__) & defined(__linux__) else std::cerr << "MatrixR::cholinverse() error: Matrix is not square" << std::endl; #endif return retval; } bool blob::MatrixR::cholinverse () { bool retval = false; if(_nrows == _ncols) { uint8_t n = _nrows; for(int i=0; i<n; i++) { _data[i*n + i] = 1/_data[i*n + i]; for(int j=i+1; j<n; j++) { real_t t = 0.0; for(int k=i; k<j; k++) t -= _data[j*n + k]*_data[k*n + i]; _data[j*n + i] = t/_data[j*n + j]; } } retval = true; } #if defined(__DEBUG__) & defined(__linux__) else std::cerr <<"MatrixR::cholinverse() error: Matrix is not square"<< std::endl; #endif return retval; } bool blob::MatrixR::lu() { if(_nrows!=_ncols) { #if defined(__DEBUG__) & defined(__linux__) std::cerr << "MatrixR::lu() error: Matrix is not square" << std::endl; #endif return false; } for(int k=0; k<_ncols-1; k++) { for(int j=k+1; j<_ncols; j++) { _data[j*_ncols+k]=_data[j*_ncols+k]/_data[k*_ncols+k]; for(int l=k+1;l<_ncols;l++) _data[j*_ncols+l]=_data[j*_ncols+l]-_data[j*_ncols+k]*_data[k*_ncols+l]; } } return true; } bool blob::MatrixR::lurestore() { if(_nrows!=_ncols) { #if defined(__DEBUG__) & defined(__linux__) std::cerr << "MatrixR::lurestore() error: Matrix is not square" << std::endl; #endif return false; } for(int i=_nrows-1; i>0; i--) { for(int j=_ncols-1; j>=0; j--) { if(i>j) _data[i*_ncols+j]*=_data[j*_ncols+j]; for(int k=0;k<i&&k<j;k++) _data[i*_ncols+j]+=_data[i*_ncols+k]*_data[k*_ncols+j]; #if defined(__DEBUG__) & defined(__linux__) print(); std::cout << std::endl; std::cout << i << "," << j << std::endl; std::cout << std::endl; #endif } } return true; } bool blob::MatrixR::inverse (bool isPositiveDefinite) { bool retval = false; if((isPositiveDefinite == true) && (cholesky(false) == true) && (cholinverse() == true)) { // reconstruct inverse of A: inv(A) = inv(L)'*inv(L) uint8_t n = _nrows; for(int i=0; i<n; i++) { int ii = n-i-1; for(int j=0; j<=i; j++) { int jj = n-j-1; real_t t = 0.0; for(int k=0; k<=ii; k++) { int kk = n-k-1; t += _data[kk*n + i]*_data[kk*n + j]; } _data[i*n + j] = t; } } //de-triangularization for(int i=n-1; i>0; i--) { for(int j=i-1; j>=0; j--) { _data[j*n+i] = _data[i*n+j]; } } retval = true; } else // lu decomposition inverse { real_t r[this->length()]; //real_t r[MATRIX_MAX_LENGTH]; MatrixR LU(this->nrows(),this->ncols(),r); if( blob::MatrixR::lu(*this,LU)==true ) { this->zero(); real_t y[this->nrows()]; //real_t y[MATRIX_MAX_ROWCOL]; memset(y,0,sizeof(real_t)*this->nrows()); //memset(y,0,sizeof(real_t)*MATRIX_MAX_ROWCOL); uint8_t n = _nrows; for(int c=0;c<n;c++) { for(int i=0;i<n;i++) { real_t x=0; for(int j=0;j<=i-1;j++) { x += LU(i,j)*y[j]; } y[i] = (i==c)? (1-x):(-x); } for(int i=n-1;i>=0;i--) { real_t x=0; for(int j=i+1;j<n;j++) { x += LU(i,j)*_data[j*_ncols+c]; } _data[i*_ncols+c] = (y[i]-x)/LU(i,i); } } } } return retval; } bool blob::MatrixR::forcePositive () { bool retval = false; if(_nrows == _ncols) { real_t min = blob::math::rabs(_data[0]); real_t max = min; for (int i = 0; i<_nrows; i++) { real_t mm = blob::math::rabs(_data[i*_ncols + i]); if (mm < min) min = mm; if (mm > max) max = mm; } real_t epsilon = min/max; if(epsilon < 1.0) { #if defined(__DEBUG__) & defined(__linux__) std::cout << "MatrixR::forcePositive() epsilon=" << epsilon << std::endl; #endif for (int i = 0; i<_nrows; i++) _data[i*_ncols + i] += epsilon; } retval = true; } #if defined(__DEBUG__) & defined(__linux__) else std::cerr << "MatrixR::forcePositive() error: Matrix is not square" << std::endl; #endif return retval; } bool blob::MatrixR::simmetrize () { bool retval = false; if(_nrows == _ncols) { for (int i = 0; i<_nrows; i++) { for (int j = 0; j<i; j++) { real_t t = (_data[i*_ncols + j]+_data[j*_ncols + i])/2; _data[i*_ncols + j] = _data[j*_ncols + i] = t; } } retval = true; } #if defined(__DEBUG__) & defined(__linux__) else std::cerr<< "MatrixR::simmetrize() error: Matrix is not square" << std::endl; #endif return retval; } bool blob::MatrixR::divide (const blob::MatrixR & A, blob::MatrixR & B, blob::MatrixR & R) { bool retval = false; uint8_t n = B.nrows(); uint8_t m = A.nrows(); if((R.nrows() == m)&& (R.ncols() == n)&& B.cholesky(false) == true) { for(int c = 0; c<m; c++) { // forward solve Ly = I(c) for(int i = 0; i<n; i++) { R(c,i) = A(c,i); for(int j=0; j<i; j++) R(c,i) -= B(i,j)*R(c,j); R(c,i) /= B(i,i); } // backward solve L'x = y for(int i=n-1; i>=0; i--) { for (int j=i+1; j<n; j++) R(c,i) -= B(j,i)*R(c,j); R(c,i) /= B(i,i); } } // restore A from L B.cholrestore(false); retval = true; } return retval; } bool blob::MatrixR::cholesky (const blob::MatrixR & A, blob::MatrixR & L) { bool retval = true; real_t t; uint8_t n = A.nrows(); L.zero(); if((A.nrows() == A.ncols()) && (A.nrows() == L.nrows()) && (A.ncols() == L.ncols())) { for (int i = 0; i < n; i++) { for (int j = 0; j < (i+1); j++) { real_t s = 0; for (int k = 0; k < j; k++) { s += L[i*n + k]*L[j*n + k]; } if(i==j && (A[i*n + i] - s) <=0) { #if defined(__DEBUG__) & defined(__linux__) std::cerr << "MatrixR::cholesky() error: Matrix is not positive" << " definite" << std::endl; #endif return false; } else { L[i*n + j] = (i == j)? blob::math::sqrtr(A[i*n + i] - s) : (1/L[j*n + j]*(A[i*n + j] - s)); } } } } else { #if defined(__DEBUG__) & defined(__linux__) std::cerr << "MatrixR::cholesky() error: Matrix is not square" << std::endl; #endif retval = false; } return retval; } // TODO: optimize bool blob::MatrixR::inverse (blob::MatrixR & A, blob::MatrixR & R, bool isPositiveDefinite) { bool retval = false; if((R.nrows() == R.ncols())&& (R.nrows() == A.nrows())&& (R.ncols() == R.ncols())) { if(isPositiveDefinite == true && A.cholesky(false) == true) // A=L { uint8_t n = R.nrows(); for(int c = 0; c<n; c++) { // forward solve Ly = I(c) for(int i = 0; i<n; i++) { R(c,i) = (c==i)? 1:0; for(int j=0; j<i; j++) R(c,i) -= A(i,j)*R(c,j); R(c,i) /= A(i,i); } // backward solve L'x = y for(int i=n-1; i>=0; i--) { for (int j=i+1; j<n; j++) R(c,i) -= A(j,i)*R(c,j); R(c,i) /= A(i,i); } } // restore A from L A.cholrestore(false); retval = true; } else if (A.lu()==true) { real_t y[A.nrows()]; //real_t y[MATRIX_MAX_ROWCOL]; memset(y,0,sizeof(real_t)*A.nrows()); //memset(y,0,sizeof(real_t)*MATRIX_MAX_ROWCOL); R.zero(); uint8_t n = R.nrows(); for(int c=0;c<n;c++) { for(int i=0;i<n;i++) { real_t x=0; for(int j=0;j<=i-1;j++) { x+=A(i,j)*y[j]; } y[i] = (i==c)? (1-x):(-x); } for(int i=n-1;i>=0;i--) { real_t x=0; for(int j=i+1;j<n;j++) { x+=A(i,j)*R(j,c); } R(i,c)=(y[i]-x)/A(i,i); } } A.lurestore(); } } return retval; } bool blob::MatrixR::cholinverse (const blob::MatrixR & L, blob::MatrixR & R) { bool retval = false; if((L.nrows() == L.ncols())&& (R.nrows() == L.nrows())&& (R.ncols() == L.ncols())) { uint8_t n = L.nrows(); R.zero(); for(int i=0; i<n; i++) { R[i*n + i] = 1/L[i*n + i]; for(int j=i+1; j<n; j++) { real_t t = 0.0; for(int k=i; k<j; k++) t -= L[j*n + k]*L[k*n + i]; R[j*n + i] = t/L[j*n + j]; } } retval = true; } #if defined(__DEBUG__) & defined(__linux__) else std::cerr << "Matrix::cholinverse() error: " << (int)L.nrows() << "==" << (int)L.ncols() << "?" << (int)R.nrows() << "==" << (int)L.nrows() << "?" << (int)R.ncols() << "==" << (int)L.ncols() << "?" << std::endl; #endif return retval; } bool blob::MatrixR::ldl (const blob::MatrixR & A, blob::MatrixR & L, blob::MatrixR & d) { if((A.nrows()!=A.ncols())||(L.nrows()!=L.ncols())||(A.ncols()!=L.nrows())) { #if defined(__DEBUG__) & defined(__linux__) std::cerr << "Matrix::ldl() error: Matrix is not square" << std::endl; #endif return false; } if(((d.nrows() != 1)&&(d.ncols() != 1))||(d.length() != A.ncols())) { #if defined(__DEBUG__) & defined(__linux__) std::cerr << "Matrix::ldl() error: Matrix is not square" << std::endl; #endif return false; } uint8_t n = A.nrows(); int i,j,k; L.zero(); for(j=0; j<n; j++) { L(j,j) = 1.0; real_t t = A(j,j); for(k=1; k<j; k++) t -= d[k]*L(j,k)*L(j,k); d[j] = t; for(i=j+1; i<n; i++) { L(j,i) = 0.0; t = A(i,j); for (k=1; k<j;k++) t -= d[k]*L(i,k)*L(j,k); L(i,j) = t/d[j]; } } } bool blob::MatrixR::qr (const MatrixR & A, MatrixR &Q, MatrixR & R) { uint8_t m = A.nrows(); uint8_t n = A.ncols(); int i=0,j=0,k=0; if(A.length()>MATRIX_MAX_LENGTH) { #if defined(__DEBUG__) & defined(__linux__) std::cerr << "Matrix::qr() error: Matrix A length is greater than " << (int)MATRIX_MAX_LENGTH << std::endl; #endif return false; } if((Q.nrows() != m)||(Q.ncols() != m)) { #if defined(__DEBUG__) & defined(__linux__) std::cerr << "Matrix::qr() error: Matrix Q is not square with m=" << (int)m << std::endl; #endif return false; } if((R.nrows() != m)||(R.ncols() != n)) { #if defined(__DEBUG__) & defined(__linux__) std::cerr << "Matrix::qr() error: Matrix R has not the same size as A" << std::endl; #endif return false; } //real_t h[MATRIX_MAX_LENGTH]; //real_t aux[MATRIX_MAX_LENGTH]; real_t h[A.nrows()*A.nrows()]; real_t aux[A.ncols()*A.nrows()]; Matrix H(m,m,h); Matrix Aux(m,n,aux); Q.eye(); R.copy(A); for (i=0; i<n && i<(m-1); i++) { H.eye(); real_t sign = (R(i,i) < 0)? -1:1; real_t nrm = 0.0; for(k=i; k<m; k++) nrm += R(k,i)*R(k,i); nrm = blob::math::sqrtr(nrm); real_t d = (R(i,i) + sign*nrm); real_t t = 1; for(k=i+1; k<m; k++) t += (R(k,i)/d)*(R(k,i)/d); t=2/t; for(j=i; j<m; j++) { for(k=i; k<m; k++) { real_t vj = (j==i)? 1.0 : R(j,i)/d; real_t vk = (k==i)? 1.0 : R(k,i)/d; H(j,k) = H(j,k) - vj*vk*t; } } Aux.refurbish(m,m); multiply(Q,H,Aux); Q.copy(Aux); Aux.refurbish(m,n); multiply(H,R,Aux); R.copy(Aux); } return true; } // https://rosettacode.org/wiki/LU_decomposition // TODO: Check why partial pivoting, applied but A=LU instead of PA=LU and result differs from octave and rosettacode bool blob::MatrixR::lu (const MatrixR & A, MatrixR & L, MatrixR & U, MatrixR & P) { if((A.nrows()!=A.ncols())||(L.nrows()!=L.ncols())||(U.ncols()!=U.nrows())) { #if defined(__DEBUG__) & defined(__linux__) std::cerr << "Matrix::lu() error: Matrix are not square" << std::endl; #endif return false; } if((A.nrows()!=L.ncols())||(A.nrows()!=U.ncols())) { #if defined(__DEBUG__) & defined(__linux__) std::cerr << "Matrix::lu() error: Matrix sizes are not equal" << std::endl; #endif return false; } U.copy(A); L.eye(); P.eye(); for(int k=0; k<U.ncols()-1; k++) { // select next row to permute (partial pivoting) real_t max=blob::math::rabs(U(k,k)); uint8_t imax=k; for(int i=k+1; i<A.nrows(); i++) { real_t next=blob::math::rabs(U(i,k)); if(next>max) { max=next; imax=i; } } if(imax!=k) { U.permuteRows(k,imax,U.ncols()-k,k); L.permuteRows(k,imax,k,0); P.permuteRows(k,imax); } for(int j=k+1; j<A.ncols(); j++) { L(j,k)=U(j,k)/U(k,k); for(int l=k;l<A.ncols();l++) U(j,l)=U(j,l)-L(j,k)*U(k,l); } } } bool blob::MatrixR::lu (const MatrixR & A, MatrixR & L, MatrixR & U) { if((A.nrows()!=A.ncols())||(L.nrows()!=L.ncols())||(U.ncols()!=U.nrows())) { #if defined(__DEBUG__) & defined(__linux__) std::cerr << "Matrix::lu() error: Matrix are not square" << std::endl; #endif return false; } if((A.nrows()!=L.ncols())||(A.nrows()!=U.ncols())) { #if defined(__DEBUG__) & defined(__linux__) std::cerr << "Matrix::lu() error: Matrix sizes are not equal" << std::endl; #endif return false; } U.copy(A); L.eye(); for(int k=0; k<U.ncols()-1; k++) { // select next row to permute (partial pivoting) for(int j=k+1; j<A.ncols(); j++) { L(j,k)=U(j,k)/U(k,k); for(int l=k;l<A.ncols();l++) U(j,l)=U(j,l)-L(j,k)*U(k,l); } } } bool blob::MatrixR::lu (const MatrixR & A, MatrixR & R) { if((A.nrows()!=A.ncols())||(R.nrows()!=R.ncols())) { #if defined(__DEBUG__) & defined(__linux__) std::cerr << "Matrix::lu() error: Matrix are not square" << std::endl; #endif return false; } if(A.nrows()!=R.ncols()) { #if defined(__DEBUG__) & defined(__linux__) std::cerr << "Matrix::lu() error: Matrix sizes are not equal" << std::endl; #endif return false; } R.copy(A); for(int k=0; k<R.ncols()-1; k++) { for(int j=k+1; j<R.ncols(); j++) { R(j,k)=R(j,k)/R(k,k); for(int l=k+1;l<R.ncols();l++) R(j,l)=R(j,l)-R(j,k)*R(k,l); } } return true; }
24.078731
118
0.48636
blobrobots
8e99a5f9e14b0ebccbdb42dfaa97a698b4de9384
15,637
hpp
C++
runtime/cpp/src/collections/BulkFlatCollection.hpp
DaMSL/K3
51749157844e76ae79dba619116fc5ad9d685643
[ "Apache-2.0" ]
17
2015-05-27T17:36:33.000Z
2020-06-07T07:21:29.000Z
runtime/cpp/src/collections/BulkFlatCollection.hpp
DaMSL/K3
51749157844e76ae79dba619116fc5ad9d685643
[ "Apache-2.0" ]
3
2015-10-02T19:37:58.000Z
2016-01-05T18:26:48.000Z
runtime/cpp/src/collections/BulkFlatCollection.hpp
DaMSL/K3
51749157844e76ae79dba619116fc5ad9d685643
[ "Apache-2.0" ]
6
2015-03-18T20:05:24.000Z
2020-02-06T21:35:09.000Z
#ifndef K3_BULK_FLAT_COLLECTION #define K3_BULK_FLAT_COLLECTION #include <limits> #include <tuple> #if HAS_LIBDYNAMIC #include <boost/serialization/array.hpp> #include <boost/serialization/string.hpp> #include <boost/functional/hash.hpp> #include <yaml-cpp/yaml.h> #include <rapidjson/document.h> #include <csvpp/csv.h> #include "serialization/Json.hpp" #include "Common.hpp" #include "collections/STLDataspace.hpp" #include "collections/Collection.hpp" #include "collections/PageCollection.hpp" namespace K3 { namespace Libdynamic { ////////////////////////////////////////////////////// // BulkFlatCollection: // a contiguous bulk-oriented collection class, that // supports storage of flat (i.e., non-nested) elements. // template<class Elem, size_t PageSize = 2 << 21> class BulkFlatCollection { public: using FContainer = LibdynamicVector::vector; using VContainer = PageCollection<PageSize>; typedef struct { FContainer cfixed; VContainer cvariable; } Container; using ExternalizerT = Externalizer<PageSize>; using InternalizerT = Internalizer<PageSize>; BulkFlatCollection() : container() { vector_init(fixed(), sizeof(Elem)); variable()->internalize(false); variable()->rewind(); } BulkFlatCollection(const BulkFlatCollection& other) : container(), buffer() { vector_init(fixed(), sizeof(Elem)); variable()->internalize(false); variable()->rewind(); FContainer* me_fixed = fixed(); FContainer* other_fixed = const_cast<FContainer*>(other.fixedc()); auto os = vector_size(other_fixed); if ( fixseg_size() < os ) { reserve_fixed(os); } ExternalizerT etl(*variable(), ExternalizerT::ExternalizeOp::Create); InternalizerT itl(*variable()); for (const auto& e : other) { vector_push_back(fixed(), const_cast<Elem*>(&e)); reinterpret_cast<Elem*>(vector_back(fixed()))->externalize(etl).internalize(itl); } variable()->internalize(true); } BulkFlatCollection& operator=(const BulkFlatCollection& other) { freeContainer(); vector_init(fixed(), sizeof(Elem)); variable()->internalize(false); variable()->rewind(); FContainer* me_fixed = fixed(); FContainer* other_fixed = const_cast<FContainer*>(other.fixedc()); auto os = vector_size(other_fixed); if ( fixseg_size() < os ) { reserve_fixed(os); } ExternalizerT etl(*variable(), ExternalizerT::ExternalizeOp::Create); InternalizerT itl(*variable()); for (const auto& e : other) { vector_push_back(fixed(), const_cast<Elem*>(&e)); reinterpret_cast<Elem*>(vector_back(fixed()))->externalize(etl).internalize(itl); } variable()->internalize(true); return *this; } // TODO(jbw) Move constructors for BFC and PageCollection ~BulkFlatCollection() { freeContainer(); } void insert(const Elem& elem) { if (buffer.data()) { throw std::runtime_error("Invalid insert on a BFC: backed by a base_string"); } variable()->internalize(false); ExternalizerT etl(*variable(), ExternalizerT::ExternalizeOp::Create); InternalizerT itl(*variable()); vector_push_back(fixed(), const_cast<Elem*>(&elem)); reinterpret_cast<Elem*>(vector_back(fixed()))->externalize(etl).internalize(itl); variable()->internalize(true); } void freeContainer() { if (!buffer.data()) { vector_clear(fixed()); } } template <class V, class I> class bfc_iterator : public std::iterator<std::forward_iterator_tag, V> { using reference = typename std::iterator<std::forward_iterator_tag, V>::reference; public: template <class _I> bfc_iterator(FContainer* _m, _I&& _i) : m(_m), i(std::forward<_I>(_i)) {} bfc_iterator& operator++() { ++i; return *this; } bfc_iterator operator++(int) { bfc_iterator t = *this; *this++; return t; } auto operator -> () const { return static_cast<V*>(vector_at(m, i)); } auto& operator*() const { return *static_cast<V*>(vector_at(m, i)); } bool operator==(const bfc_iterator& other) const { return i == other.i; } bool operator!=(const bfc_iterator& other) const { return i != other.i; } private: FContainer* m; I i; }; using iterator = bfc_iterator<Elem, size_t>; using const_iterator = bfc_iterator<const Elem, size_t>; iterator begin() { return iterator(fixed(), 0); } iterator end() { return iterator(fixed(), vector_size(fixed())); } const_iterator begin() const { return const_iterator(const_cast<FContainer*>(fixedc()), 0); } const_iterator end() const { return const_iterator(const_cast<FContainer*>(fixedc()), vector_size(const_cast<FContainer*>(fixedc()))); } // Sizing utilities. size_t fixseg_size() const { return vector_size(const_cast<FContainer*>(fixedc())); } size_t fixseg_capacity() const { return vector_capacity(const_cast<FContainer*>(fixedc())); } void reserve_fixed(size_t sz) { vector_reserve(fixed(), sz); } size_t varseg_size() const { return variablec()->size(); } size_t varseg_capacity() const { return variablec()->capacity(); } size_t byte_size() const { return fixseg_size() * sizeof(Elem) + varseg_size() * PageSize; } size_t byte_capacity() const { return fixseg_capacity() * sizeof(Elem) + varseg_capacity() * PageSize; } /////////////////////////////////////////// // Bulk construction and externalization. unit_t append(const Collection<R_elem<Elem>>& other) { if ( !buffer && !variable()->internalized() ) { auto os = other.size(unit_t{}); if ( fixseg_size() < os ) { reserve_fixed(os); } ExternalizerT etl(*variable(), ExternalizerT::ExternalizeOp::Create); InternalizerT itl(*variable()); for (auto& e : other) { vector_push_back(fixed(), const_cast<Elem*>(&(e.elem))); reinterpret_cast<Elem*>(vector_back(fixed()))->externalize(etl).internalize(itl); } } else { throw std::runtime_error("Invalid append on a BulkFlatCollection"); } variable()->internalize(true); return unit_t {}; } // Externalizes an existing collection, reusing the variable-length segment. unit_t repack(unit_t) { FContainer* ncf = const_cast<FContainer*>(fixedc()); VContainer* ncv = const_cast<VContainer*>(variablec()); if ( ncv->internalized() ) { ExternalizerT etl(*ncv, ExternalizerT::ExternalizeOp::Reuse); auto sz = vector_size(ncf); for (size_t i = 0; i < sz; ++i) { reinterpret_cast<Elem*>(vector_at(ncf, i))->externalize(etl); } ncv->internalize(false); } return unit_t{}; } unit_t unpack(unit_t) { FContainer* ncf = const_cast<FContainer*>(fixedc()); VContainer* ncv = const_cast<VContainer*>(variablec()); if ( !ncv->internalized() ) { InternalizerT itl(*ncv); auto sz = vector_size(ncf); for (size_t i = 0; i < sz; ++i) { reinterpret_cast<Elem*>(vector_at(ncf, i))->internalize(itl); } ncv->internalize(true); } return unit_t{}; } base_string save(unit_t) { FContainer* ncf = fixed(); VContainer* ncv = variable(); // Reset element pointers to slot ids as necessary. repack(unit_t{}); uint64_t fixed_count = fixseg_size(); uint64_t page_count = varseg_size(); auto len = sizeof(size_t) + 2 * sizeof(uint64_t) + byte_size(); auto buffer_ = new char[len+1]; buffer_[len] = 0; size_t offset = sizeof(size_t); memcpy(buffer_ + offset, &fixed_count, sizeof(fixed_count)); offset += sizeof(uint64_t); memcpy(buffer_ + offset, &page_count, sizeof(page_count)); offset += sizeof(uint64_t); if (fixed_count > 0) { memcpy(buffer_ + offset, vector_data(ncf), fixseg_size() * sizeof(Elem)); offset += fixseg_size() * sizeof(Elem); } if (page_count > 0) { memcpy(buffer_ + offset, ncv->data(), varseg_size() * PageSize); } base_string str; len -= sizeof(size_t); memcpy(buffer_, &len, sizeof(size_t)); str.steal(buffer_); str.set_header(true); unpack(unit_t{}); return str; } unit_t load(const base_string& str) { return load(base_string(str)); } unit_t load(base_string&& str) { assert( vector_empty(fixed()) ); freeContainer(); buffer = std::move(str); size_t offset = 0; uint64_t fixed_count = *reinterpret_cast<uint64_t*>(buffer.begin()); offset += sizeof(uint64_t); uint64_t page_count = *reinterpret_cast<uint64_t*>(buffer.begin() + offset); offset += sizeof(uint64_t); variable()->externalBuffer(true); if (fixed_count > 0) { fixed()->buffer.data = buffer.begin() + offset; fixed()->buffer.size = fixed_count * sizeof(Elem); fixed()->buffer.capacity = fixed()->buffer.size; fixed()->object_size = sizeof(Elem); offset += fixed_count * sizeof(Elem); } if (page_count > 0) { variable()->container->buffer.data = buffer.begin() + offset; variable()->container->buffer.size = page_count * PageSize; variable()->container->buffer.capacity = variable()->container->buffer.size; variable()->container->object_size = PageSize; } unpack(unit_t{}); return unit_t{}; } /////////////////////////////////////////////////// // Accessors. int size(const unit_t&) const { return vector_size(const_cast<FContainer*>(fixedc())); } /////////////////////////////////////////////////// // Bulk transformations. template<class Fun> unit_t iterate(Fun f) const { FContainer* ncf = const_cast<FContainer*>(fixedc()); VContainer* ncv = const_cast<VContainer*>(variablec()); auto sz = fixseg_size(); for (size_t i = 0; i < sz; ++i) { auto& e = reinterpret_cast<Elem*>(vector_at(ncf, i)); f(e); } return unit_t{}; } // Produce a new collection by mapping a function over this external collection. template <typename Fun> auto map(Fun f) const -> BulkFlatCollection<R_elem<RT<Fun, Elem>>> { FContainer* ncf = const_cast<FContainer*>(fixedc()); VContainer* ncv = const_cast<VContainer*>(variablec()); BulkFlatCollection<R_elem<RT<Fun, Elem>>> result; auto sz = fixseg_size(); for (size_t i = 0; i < sz; ++i) { auto& e = reinterpret_cast<Elem*>(vector_at(ncf, i)); result.insert(R_elem<RT<Fun, Elem>>{ f(e) }); } return result; } // Create a new collection consisting of elements from this set that satisfy the predicate. template <typename Fun> BulkFlatCollection<R_elem<Elem>> filter(Fun predicate) const { FContainer* ncf = const_cast<FContainer*>(fixedc()); VContainer* ncv = const_cast<VContainer*>(variablec()); BulkFlatCollection<R_elem<Elem>> result; auto sz = fixseg_size(); for (size_t i = 0; i < sz; ++i) { auto& e = reinterpret_cast<Elem*>(vector_at(ncf, i)); if (predicate(e)) { result.insert(R_elem<Elem>{ e }); } } return result; } // Fold a function over this collection. template <typename Fun, typename Acc> Acc fold(Fun f, Acc acc) const { FContainer* ncf = const_cast<FContainer*>(fixedc()); VContainer* ncv = const_cast<VContainer*>(variablec()); auto sz = fixseg_size(); for (size_t i = 0; i < sz; ++i) { auto& e = reinterpret_cast<Elem*>(vector_at(ncf, i)); acc = f(std::move(acc), e); } return acc; } // TODO(jbw) group_by Container& getContainer() { return container; } const Container& getConstContainer() const { return container; } template <class archive> void save(archive& a, const unsigned int) const { auto p = const_cast<BulkFlatCollection*>(this); p->repack(unit_t {}); uint64_t fixed_count = fixseg_size(); uint64_t page_count = varseg_size(); a.save_binary(&fixed_count, sizeof(fixed_count)); a.save_binary(&page_count, sizeof(page_count)); if (fixed_count > 0) { a.save_binary(vector_data(const_cast<FContainer*>(fixedc())), fixseg_size() * sizeof(Elem)); } if (page_count > 0) { a.save_binary(const_cast<VContainer*>(variablec())->data(), varseg_size() * PageSize); } p->unpack(unit_t{}); } template <class archive> void load(archive& a, const unsigned int) { uint64_t fixed_count; uint64_t page_count; a.load_binary(&fixed_count, sizeof(fixed_count)); a.load_binary(&page_count, sizeof(page_count)); if (fixed_count > 0) { reserve_fixed(fixed_count); fixed()->buffer.size = fixed_count * sizeof(Elem); a.load_binary(vector_data(fixed()), fixed_count * sizeof(Elem)); } if (page_count > 0) { variable()->resize(page_count); a.load_binary(variable()->data(), page_count * PageSize); } unpack(unit_t{}); } template <class archive> void serialize(archive& a) const { auto p = const_cast<BulkFlatCollection*>(this); p->repack(unit_t {}); uint64_t fixed_count = fixseg_size(); uint64_t page_count = varseg_size(); a.write(&fixed_count, sizeof(fixed_count)); a.write(&page_count, sizeof(page_count)); if (fixed_count > 0) { a.write(vector_data(const_cast<FContainer*>(fixedc())), fixseg_size() * sizeof(Elem)); } if (page_count > 0) { a.write(const_cast<VContainer*>(variablec())->data(), varseg_size() * PageSize); } p->unpack(unit_t{}); } template <class archive> void serialize(archive& a) { uint64_t fixed_count; uint64_t page_count; a.read(&fixed_count, sizeof(fixed_count)); a.read(&page_count, sizeof(page_count)); if (fixed_count > 0) { reserve_fixed(fixed_count); fixed()->buffer.size = fixed_count * sizeof(Elem); a.read(vector_data(fixed()), fixed_count * sizeof(Elem)); } if (page_count > 0) { variable()->resize(page_count); a.read(variable()->data(), page_count * PageSize); } unpack(unit_t{}); } BOOST_SERIALIZATION_SPLIT_MEMBER() private: // BulkFlatCollection is backed by either a base_string or a Container Container container; FContainer* fixed() { return &(container.cfixed); } VContainer* variable() { return &(container.cvariable); } const FContainer* fixedc() const { return &(container.cfixed); } const VContainer* variablec() const { return &(container.cvariable); } base_string buffer; }; }; // end namespace Libdynamic template<class Elem, size_t PageSize = 2 << 21> using BulkFlatCollection = Libdynamic::BulkFlatCollection<Elem, PageSize>; }; // end namespace K3 namespace YAML { template <class E> struct convert<K3::BulkFlatCollection<E>> { static Node encode(const K3::BulkFlatCollection<E>& c) { Node node; bool flag = true; for (const auto& i : c) { if (flag) { flag = false; } node.push_back(convert<E>::encode(i)); } if (flag) { node = YAML::Load("[]"); } return node; } static bool decode(const Node& node, K3::BulkFlatCollection<E>& c) { K3::Collection<R_elem<E>> tmp; for (auto& i : node) { tmp.insert(i.as<E>()); } c.append(tmp); return true; } }; } // namespace YAML namespace JSON { using namespace rapidjson; template <class E> struct convert<K3::BulkFlatCollection<E>> { template <class Allocator> static Value encode(const K3::BulkFlatCollection<E>& c, Allocator& al) { Value v; v.SetObject(); v.AddMember("type", Value("BulkFlatCollection"), al); Value inner; inner.SetArray(); for (const auto& e : c) { inner.PushBack(convert<E>::encode(e, al), al); } v.AddMember("value", inner.Move(), al); return v; } }; } // namespace JSON #endif // HAS_LIBDYNAMIC #endif
30.129094
138
0.643218
DaMSL
8e9cf2b8fe01f2f6133f5fce8890fdde0816cda9
1,578
hpp
C++
src/core/testing/plg_multi_edit_test/multi_edit_test_data.hpp
wgsyd/wgtf
d8cacb43e2c5d40080d33c18a8c2f5bd27d21bed
[ "BSD-3-Clause" ]
28
2016-06-03T05:28:25.000Z
2019-02-14T12:04:31.000Z
src/core/testing/plg_multi_edit_test/multi_edit_test_data.hpp
karajensen/wgtf
740397bcfdbc02bc574231579d57d7c9cd5cc26d
[ "BSD-3-Clause" ]
null
null
null
src/core/testing/plg_multi_edit_test/multi_edit_test_data.hpp
karajensen/wgtf
740397bcfdbc02bc574231579d57d7c9cd5cc26d
[ "BSD-3-Clause" ]
14
2016-06-03T05:52:27.000Z
2019-03-21T09:56:03.000Z
#pragma once #include "core_reflection/object_handle.hpp" #include "core_reflection/reflected_object.hpp" #include "core_object/managed_object.hpp" #include "wg_types/vector2.hpp" #include "wg_types/vector3.hpp" #include "wg_types/vector4.hpp" #include <string> #include <vector> namespace wgt { class AbstractTreeModel; class IComponentContext; struct MultiEditTestStruct { Vector2 vector2Property_; Vector3 vector3Property_; Vector4 colorProperty_; Vector4 hdrcolorProperty_; }; class MultiEditTestObject1 { public: bool boolProperty_; int intProperty_; float floatProperty_; std::string stringProperty_; std::vector<int> collectionProperty_; ManagedObject<MultiEditTestStruct> structObj_; ObjectHandleT<MultiEditTestStruct> structProperty_; std::string fileUrl_; }; class MultiEditTestObject2 { public: bool boolProperty_; int intProperty_; float floatProperty_; int enumProperty_; std::string stringProperty_; std::vector<int> collectionProperty_; std::string fileUrl_; }; class MultiEditTestObject3 { public: bool boolProperty_; int intProperty_; float floatProperty_; int enumProperty_; float sliderProperty_; std::string stringProperty_; ManagedObject<MultiEditTestStruct> structObj_; ObjectHandleT<MultiEditTestStruct> structProperty_; std::string fileUrl_; }; class MultiEditTestModel { DECLARE_REFLECTED public: void init(IComponentContext& context); void fini(); private: std::vector<ManagedObjectPtr> data_; std::vector<std::shared_ptr<AbstractTreeModel>> trees_; std::vector<AbstractTreeModel*> objects_; }; }
20.230769
56
0.798479
wgsyd
8e9f59138b09dc898434bf521f18eabdf8421c4a
2,200
hpp
C++
third_party/omr/gc/stats/CollectionStatistics.hpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
third_party/omr/gc/stats/CollectionStatistics.hpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
third_party/omr/gc/stats/CollectionStatistics.hpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright (c) 1991, 2016 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this * distribution and is available at https://www.eclipse.org/legal/epl-2.0/ * or the Apache License, Version 2.0 which accompanies this distribution and * is available at https://www.apache.org/licenses/LICENSE-2.0. * * This Source Code may also be made available under the following * Secondary Licenses when the conditions for such availability set * forth in the Eclipse Public License, v. 2.0 are satisfied: GNU * General Public License, version 2 with the GNU Classpath * Exception [1] and GNU General Public License, version 2 with the * OpenJDK Assembly Exception [2]. * * [1] https://www.gnu.org/software/classpath/license.html * [2] http://openjdk.java.net/legal/assembly-exception.html * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception *******************************************************************************/ #if !defined(COLLECTIONSTATISTICS_HPP_) #define COLLECTIONSTATISTICS_HPP_ #include "omrcfg.h" #include "omrcomp.h" #include "Base.hpp" /** * A collection of interesting statistics for the Heap. * @ingroup GC_Stats */ class MM_CollectionStatistics : public MM_Base { private: protected: public: uintptr_t _totalHeapSize; /**< Total active heap size */ uintptr_t _totalFreeHeapSize; /**< Total free active heap */ uint64_t _startTime; /**< Collection start time */ uint64_t _endTime; /**< Collection end time */ omrthread_process_time_t _startProcessTimes; /**< Process (Kernel and User) start time(s) */ omrthread_process_time_t _endProcessTimes; /**< Process (Kernel and User) end time(s) */ private: protected: public: /** * Create a HeapStats object. */ MM_CollectionStatistics() : MM_Base() ,_totalHeapSize(0) ,_totalFreeHeapSize(0) ,_startTime(0) ,_endTime(0) ,_startProcessTimes() ,_endProcessTimes() {}; }; #endif /* COLLECTIONSTATISTICS_HPP_ */
32.835821
135
0.684545
xiacijie
8e9f66219c4e1c4667395a40fee16530b4ec4d5e
1,639
cpp
C++
src/Generic/patterns/multilingual/LanguageVariant.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
1
2022-03-24T19:57:00.000Z
2022-03-24T19:57:00.000Z
src/Generic/patterns/multilingual/LanguageVariant.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
src/Generic/patterns/multilingual/LanguageVariant.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
// Copyright 2013 by BBN Technologies Corp. // All Rights Reserved. #include "Generic/common/leak_detection.h" #include "LanguageVariant.h" const Symbol LanguageVariant::languageVariantAnySym(L"ANY"); std::map<Symbol,std::map<Symbol,LanguageVariant_ptr> > LanguageVariant::_instances; LanguageVariant_ptr LanguageVariant::_anyLanguageVariant; bool LanguageVariant::matchesConstraint(LanguageVariant const& languageVariant) const { if (languageVariant.getLanguage() == languageVariantAnySym) { return true; } if (languageVariant.getLanguage().is_null() || languageVariant.getLanguage() == _language) { return (languageVariant.getVariant().is_null() || languageVariant.getVariant() == _variant); } return false; } const LanguageVariant_ptr LanguageVariant::getLanguageVariantAny() { if (!_anyLanguageVariant) _anyLanguageVariant = boost::make_shared<LanguageVariant>(languageVariantAnySym,languageVariantAnySym); return _anyLanguageVariant; } const LanguageVariant_ptr LanguageVariant::getLanguageVariant(Symbol const& language, Symbol const& variant) { if (language.is_null() && variant.is_null()) { _instances[Symbol()][Symbol()] = boost::make_shared<LanguageVariant>(); } if (!language.is_null() && _instances.find(language) == _instances.end()) { _instances[language][Symbol()] = boost::make_shared<LanguageVariant>(language); } if (!variant.is_null() && _instances[language].find(variant) == _instances[language].end()) { _instances[language][variant] = boost::make_shared<LanguageVariant>(language,variant); } return _instances[language][variant]; }
39.02381
111
0.748627
BBN-E
8e9f91171e99d38aa2395dc468fc8b576f472760
698
cpp
C++
Olympiad Solutions/URI/1179.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
Olympiad Solutions/URI/1179.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
Olympiad Solutions/URI/1179.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
// Ivan Carvalho // Solution to https://www.urionlinejudge.com.br/judge/problems/view/1179 #include <cstdio> int main(){ int par[5],impar[5]; int pares=0,impares=0,i,j; for(i=0;i<15;i++){ int davez; scanf("%d",&davez); if (davez%2==0){ par[pares] = davez; pares += 1; } else { impar[impares] = davez; impares += 1; } if (pares==5){ pares = 0; for(j=0;j<5;j++){ printf("par[%d] = %d\n",j,par[j]); } } if (impares==5){ impares=0; for(j=0;j<5;j++){ printf("impar[%d] = %d\n",j,impar[j]); } } } for(i=0;i<impares;i++){ printf("impar[%d] = %d\n",i,impar[i]); } for(i=0;i<pares;i++){ printf("par[%d] = %d\n",i,par[i]); } return 0; }
17.897436
73
0.52149
Ashwanigupta9125
8ea6f00b0c9b4d1bc74066af4f9886f8c2aff88b
777
cpp
C++
Language_Coder/문자열2/형성평가/FormativeString209.cpp
NadanKim/CodingTest_JUNGOL
f1f448eb5a107b59bfa196c2682ba89e89431358
[ "MIT" ]
null
null
null
Language_Coder/문자열2/형성평가/FormativeString209.cpp
NadanKim/CodingTest_JUNGOL
f1f448eb5a107b59bfa196c2682ba89e89431358
[ "MIT" ]
null
null
null
Language_Coder/문자열2/형성평가/FormativeString209.cpp
NadanKim/CodingTest_JUNGOL
f1f448eb5a107b59bfa196c2682ba89e89431358
[ "MIT" ]
null
null
null
#include "FormativeString209.h" /// <summary> /// 문제 /// 정수, 실수, 문자열을 차례로 입력받아서 새로운 문자열에 출력한 후 전체의 길이를 2등분하여 출력하는 프로그램을 작성하시오. /// 실수는 반올림하여 소수 셋째자리까지 출력하는 것으로 하고, 새로운 문자열의 길이가 홀수일 때는 첫 번째 줄에 한 개를 더 출력한다. /// 각 문자열의 길이는 30자 이내이다. /// /// 입력 예 /// 12345 5.0123 fighting /// /// 출력 예 /// 123455.01 /// 2fighting /// /// http://www.jungol.co.kr/bbs/board.php?bo_table=pbank&wr_id=137&sca=10f0 /// </summary> void FormativeString209::Code() { int var1; double var2; string str; std::cin >> var1 >> var2 >> str; char buff[100]; std::sprintf(buff, "%d%.3f%s", var1, var2, str.c_str()); str = buff; bool isOdd{ str.size() % 2 == 1 }; std::cout << str.substr(0, str.size() / 2 + (isOdd ? 1 : 0)) << '\n'; std::cout << str.substr(str.size() / 2 + (isOdd ? 1 : 0)); }
22.2
77
0.594595
NadanKim
8eadbd122506a76c97abc89ea53a27bb84c106c3
2,229
cpp
C++
Plugins/MixedReality-OpenXR-Unreal/MsftOpenXRGame/Plugins/MicrosoftOpenXR/Source/MicrosoftOpenXR/Private/TrackedGeometryCollision.cpp
peted70/hl2-ue-worldanchor-sample
e64515ff5821d1d11274fa9b78289445d6883e71
[ "MIT" ]
105
2020-11-24T17:24:36.000Z
2022-03-31T05:33:24.000Z
MsftOpenXRGame/Plugins/MicrosoftOpenXR/Source/MicrosoftOpenXR/Private/TrackedGeometryCollision.cpp
Qianlixun/Microsoft-OpenXR-Unreal
977e4b16a016d29897f8bf2ee793ba034eddfbc8
[ "MIT" ]
20
2021-02-06T16:08:34.000Z
2022-03-10T15:07:30.000Z
MsftOpenXRGame/Plugins/MicrosoftOpenXR/Source/MicrosoftOpenXR/Private/TrackedGeometryCollision.cpp
Qianlixun/Microsoft-OpenXR-Unreal
977e4b16a016d29897f8bf2ee793ba034eddfbc8
[ "MIT" ]
36
2020-11-26T15:14:50.000Z
2022-03-30T21:34:42.000Z
// Copyright (c) 2020 Microsoft Corporation. // Licensed under the MIT License. #include "TrackedGeometryCollision.h" namespace MicrosoftOpenXR { TrackedGeometryCollision::TrackedGeometryCollision(const TArray<FVector> InVertices, const TArray<MRMESH_INDEX_TYPE> InIndices) { if (InVertices.Num() == 0) { return; } Vertices = std::move(InVertices); Indices = std::move(InIndices); // Create a bounding box from the input vertices to reduce the number of full meshes that need to be hit-tested. BoundingBox = FBox(&Vertices[0], Vertices.Num()); } void TrackedGeometryCollision::UpdateVertices(const TArray<FVector> InVertices, const TArray<MRMESH_INDEX_TYPE> InIndices) { Vertices = InVertices; Indices = InIndices; // Create a bounding box from the input vertices to reduce the number of full meshes that need to be hit-tested. BoundingBox = FBox(&Vertices[0], Vertices.Num()); } bool TrackedGeometryCollision::Collides(const FVector Start, const FVector End, const FTransform MeshToWorld, FVector& OutHitPoint, FVector& OutHitNormal, float& OutHitDistance) { if (MeshToWorld.GetScale3D().IsNearlyZero()) { return false; } // Check bounding box collision first so we don't check triangles for meshes we definitely won't collide with. if (!FMath::LineBoxIntersection(BoundingBox.TransformBy(MeshToWorld), Start, End, End - Start)) { return false; } // Check for triangle collision and set the output hit position, normal, and distance. for (int i = 0; i < Indices.Num(); i += 3) { // Ignore this triangle if it has indices out of range. if ((unsigned int)Indices[i] > (unsigned int)Vertices.Num() || (unsigned int)Indices[i + 1] > (unsigned int)Vertices.Num() || (unsigned int)Indices[i + 2] > (unsigned int)Vertices.Num()) { continue; } if (FMath::SegmentTriangleIntersection(Start, End, MeshToWorld.TransformPosition(Vertices[Indices[i]]), MeshToWorld.TransformPosition(Vertices[Indices[i + 1]]), MeshToWorld.TransformPosition(Vertices[Indices[i + 2]]), OutHitPoint, OutHitNormal)) { OutHitDistance = (OutHitPoint - Start).Size(); return true; } } return false; } } // namespace MicrosoftOpenXR
32.304348
178
0.717811
peted70
8eae656c140630fcb82003e67a13410f602d9a22
4,851
cpp
C++
cpp/MinQuintet.cpp
Tmyiri/QS-Net
d121ba9cea8105caed4bd0836ec23f8347935646
[ "MIT" ]
3
2019-04-21T00:58:44.000Z
2019-12-18T06:36:48.000Z
cpp/MinQuintet.cpp
Tmyiri/QS-Net
d121ba9cea8105caed4bd0836ec23f8347935646
[ "MIT" ]
2
2020-08-08T17:54:23.000Z
2021-04-29T05:23:13.000Z
cpp/MinQuintet.cpp
Tmyiri/QS-Net
d121ba9cea8105caed4bd0836ec23f8347935646
[ "MIT" ]
1
2019-04-21T01:20:20.000Z
2019-04-21T01:20:20.000Z
#include <iostream> #include "CSplitSys.h" using namespace std; // calculate w(21|543) // Method 1 w(21|543)= min{ // w(43|21)-w(51|43)+w(51|32)-w(54|32)+w(54|21), // w(53|21)-w(53|41)+w(41|32)-w(54|32)+w(54|21), // w(43|21)-w(51|43)+w(51|42)-w(53|42)+w(53|21), // w(54|21)-w(54|31)+w(42|31)-w(53|42)+w(53|21), // w(53|21)-w(53|41)+w(52|41)-w(52|43)+w(43|21), // w(54|21)-w(54|31)+w(52|31)-w(52|43)+w(43|21).} double CSplitSys::MinQuintet(unsigned int gLeft[2], unsigned int gRight[3]) { CQuartet qTemp; // specify all the possible blocks unsigned int iB21[2]; iB21[0] = gLeft[0]; iB21[1] = gLeft[1]; unsigned int iB31[2]; iB31[0] = gRight[2]; iB31[1] = gLeft[1]; unsigned int iB32[2]; iB32[0] = gRight[2]; iB32[1] = gLeft[0]; unsigned int iB41[2]; iB41[0] = gRight[1]; iB41[1] = gLeft[1]; unsigned int iB42[2]; iB42[0] = gRight[1]; iB42[1] = gLeft[0]; unsigned int iB43[2]; iB43[0] = gRight[1]; iB43[1] = gRight[2]; unsigned int iB51[2]; iB51[0] = gRight[0]; iB51[1] = gLeft[1]; unsigned int iB52[2]; iB52[0] = gRight[0]; iB52[1] = gLeft[0]; unsigned int iB53[2]; iB53[0] = gRight[0]; iB53[1] = gRight[2]; unsigned int iB54[2]; iB54[0] = gRight[0]; iB54[1] = gRight[1]; // First: w(43|21)-w(51|43)+w(51|32)-w(54|32)+w(54|21) double dTemp = 0; // + w(43|21) qTemp.SetLabel(iB43, iB21); double w4321 = m_gQuartet[qTemp.GetIndex()].GetWeight(); dTemp += w4321; //- w(51|43) qTemp.SetLabel(iB51, iB43); double w5143 = m_gQuartet[qTemp.GetIndex()].GetWeight(); dTemp -= w5143; //+w(51|32) qTemp.SetLabel(iB51, iB32); double w5132 = m_gQuartet[qTemp.GetIndex()].GetWeight(); dTemp += w5132; //-w(54|32) qTemp.SetLabel(iB54, iB32); double w5432 = m_gQuartet[qTemp.GetIndex()].GetWeight(); dTemp -= w5432; //+w(54|21) qTemp.SetLabel(iB54, iB21); double w5421 = m_gQuartet[qTemp.GetIndex()].GetWeight(); dTemp += w5421; if(dTemp <= 0) return 0; double dWei =dTemp; // Second: w(53|21)-w(53|41)+w(41|32)-w(54|32)+w(54|21) dTemp=0; // + w(53|21) qTemp.SetLabel(iB53, iB21); double w5321 = m_gQuartet[qTemp.GetIndex()].GetWeight(); dTemp += w5321; //- w(53|41) qTemp.SetLabel(iB53, iB41); double w5341 = m_gQuartet[qTemp.GetIndex()].GetWeight(); dTemp -= w5341; //+w(41|32) qTemp.SetLabel(iB41, iB32); double w4132 = m_gQuartet[qTemp.GetIndex()].GetWeight(); dTemp += w4132; //-w(54|32) dTemp -= w5432; //+w(54|21) dTemp += w5421; if(dTemp <= 0) return 0; if(dWei > dTemp) dWei = dTemp; // Third: w(43|21)-w(51|43)+w(51|42)-w(53|42)+w(53|21) dTemp=0; // + w(43|21) dTemp += w4321; //- w(51|43) dTemp -= w5143; //+w(51|42) qTemp.SetLabel(iB51, iB42); double w5142 = m_gQuartet[qTemp.GetIndex()].GetWeight(); dTemp += w5142; //-w(53|42) qTemp.SetLabel(iB53, iB42); double w5342 = m_gQuartet[qTemp.GetIndex()].GetWeight(); dTemp -= w5342; //+w(53|21) dTemp += w5321; if(dTemp <= 0) return 0; if(dWei > dTemp) dWei = dTemp; // Fourth: w(54|21)-w(54|31)+w(42|31)-w(53|42)+w(53|21), dTemp=0; // + w(54|21) dTemp += w5421; //-w(54|31) qTemp.SetLabel(iB54, iB31); double w5431 = m_gQuartet[qTemp.GetIndex()].GetWeight(); dTemp -= w5431; //+w(42|31) qTemp.SetLabel(iB42, iB31); double w4231 = m_gQuartet[qTemp.GetIndex()].GetWeight(); dTemp += w4231; //-w(53|42) dTemp -= w5342; //+w(53|21) dTemp += w5321; if(dTemp <= 0) return 0; if(dWei > dTemp) dWei = dTemp; // Fifth: w(53|21)-w(53|41)+w(52|41)-w(52|43)+w(43|21), dTemp=0; // + w(53|21) dTemp += w5321; //- w(53|41) dTemp -= w5341; //+w(52|41) qTemp.SetLabel(iB52, iB41); double w5241 = m_gQuartet[qTemp.GetIndex()].GetWeight(); dTemp += w5241; //-w(52|43) qTemp.SetLabel(iB52, iB43); double w5243 = m_gQuartet[qTemp.GetIndex()].GetWeight(); dTemp -= w5243; //+w(43|21) dTemp += w4321; if(dTemp <= 0) return 0; if(dWei > dTemp) dWei = dTemp; // Sixth: w(54|21)-w(54|31)+w(52|31)-w(52|43)+w(43|21) dTemp=0; // + w(54|21) dTemp += w5421; //- w(54|31) dTemp -= w5431; //+w(52|31) qTemp.SetLabel(iB52, iB31); double w5231 = m_gQuartet[qTemp.GetIndex()].GetWeight(); dTemp += w5231; //-w(52|43) dTemp -= w5243; //+w(43|21) dTemp += w4321; if(dTemp <= 0) return 0; if(dWei > dTemp) dWei = dTemp; return 0.5*dWei; } // EOF
22.354839
80
0.531025
Tmyiri
8eaedf4e36b6b3aacf8dbe5cab481d6cece203d4
8,753
hpp
C++
src/mlpack/methods/range_search/rs_model_impl.hpp
florian-rosenthal/mlpack
4287a89886e39703571165ef1d40693eb51d22c6
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
4,216
2015-01-01T02:06:12.000Z
2022-03-31T19:12:06.000Z
src/mlpack/methods/range_search/rs_model_impl.hpp
florian-rosenthal/mlpack
4287a89886e39703571165ef1d40693eb51d22c6
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2,621
2015-01-01T01:41:47.000Z
2022-03-31T19:01:26.000Z
src/mlpack/methods/range_search/rs_model_impl.hpp
florian-rosenthal/mlpack
4287a89886e39703571165ef1d40693eb51d22c6
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1,972
2015-01-01T23:37:13.000Z
2022-03-28T06:03:41.000Z
/** * @file methods/range_search/rs_model_impl.hpp * @author Ryan Curtin * * Implementation of serialize() and inline functions for RSModel. * * mlpack is free software; you may redistribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #ifndef MLPACK_METHODS_RANGE_SEARCH_RS_MODEL_IMPL_HPP #define MLPACK_METHODS_RANGE_SEARCH_RS_MODEL_IMPL_HPP // In case it hasn't been included yet. #include "rs_model.hpp" #include <mlpack/core/math/random_basis.hpp> namespace mlpack { namespace range { template<template<typename TreeMetricType, typename TreeStatType, typename TreeMatType> class TreeType> void RSWrapper<TreeType>::Train(util::Timers& timers, arma::mat&& referenceSet, const size_t /* leafSize */) { if (!Naive()) timers.Start("tree_building"); rs.Train(std::move(referenceSet)); if (!Naive()) timers.Stop("tree_building"); } template<template<typename TreeMetricType, typename TreeStatType, typename TreeMatType> class TreeType> void RSWrapper<TreeType>::Search(util::Timers& timers, arma::mat&& querySet, const math::Range& range, std::vector<std::vector<size_t>>& neighbors, std::vector<std::vector<double>>& distances, const size_t /* leafSize */) { if (!Naive() && !SingleMode()) { // We build the query tree manually, so that we can time how long it takes. timers.Start("tree_building"); typename decltype(rs)::Tree queryTree(std::move(querySet)); timers.Stop("tree_building"); timers.Start("computing_neighbors"); rs.Search(&queryTree, range, neighbors, distances); timers.Stop("computing_neighbors"); } else { timers.Start("computing_neighbors"); rs.Search(std::move(querySet), range, neighbors, distances); timers.Stop("computing_neighbors"); } } template<template<typename TreeMetricType, typename TreeStatType, typename TreeMatType> class TreeType> void RSWrapper<TreeType>::Search(util::Timers& timers, const math::Range& range, std::vector<std::vector<size_t>>& neighbors, std::vector<std::vector<double>>& distances) { timers.Start("computing_neighbors"); rs.Search(range, neighbors, distances); timers.Stop("computing_neighbors"); } template<template<typename TreeMetricType, typename TreeStatType, typename TreeMatType> class TreeType> void LeafSizeRSWrapper<TreeType>::Train(util::Timers& timers, arma::mat&& referenceSet, const size_t leafSize) { if (rs.Naive()) { rs.Train(std::move(referenceSet)); } else { timers.Start("tree_building"); std::vector<size_t> oldFromNewReferences; typename decltype(rs)::Tree* tree = new typename decltype(rs)::Tree(std::move(referenceSet), oldFromNewReferences, leafSize); rs.Train(tree); // Give the model ownership of the tree and the mappings. rs.treeOwner = true; rs.oldFromNewReferences = std::move(oldFromNewReferences); timers.Stop("tree_building"); } } template<template<typename TreeMetricType, typename TreeStatType, typename TreeMatType> class TreeType> void LeafSizeRSWrapper<TreeType>::Search( util::Timers& timers, arma::mat&& querySet, const math::Range& range, std::vector<std::vector<size_t>>& neighbors, std::vector<std::vector<double>>& distances, const size_t leafSize) { if (!rs.Naive() && !rs.SingleMode()) { // Build a second tree and search. timers.Start("tree_building"); Log::Info << "Building query tree..." << std::endl; std::vector<size_t> oldFromNewQueries; typename decltype(rs)::Tree queryTree(std::move(querySet), oldFromNewQueries, leafSize); Log::Info << "Tree built." << std::endl; timers.Stop("tree_building"); std::vector<std::vector<size_t>> neighborsOut; std::vector<std::vector<double>> distancesOut; timers.Start("computing_neighbors"); rs.Search(&queryTree, range, neighborsOut, distancesOut); timers.Stop("computing_neighbors"); // Remap the query points. neighbors.resize(queryTree.Dataset().n_cols); distances.resize(queryTree.Dataset().n_cols); for (size_t i = 0; i < queryTree.Dataset().n_cols; ++i) { neighbors[oldFromNewQueries[i]] = neighborsOut[i]; distances[oldFromNewQueries[i]] = distancesOut[i]; } } else { timers.Start("computing_neighbors"); rs.Search(std::move(querySet), range, neighbors, distances); timers.Stop("computing_neighbors"); } } // Serialize the model. template<typename Archive> void RSModel::serialize(Archive& ar, const uint32_t /* version */) { ar(CEREAL_NVP(treeType)); ar(CEREAL_NVP(randomBasis)); ar(CEREAL_NVP(q)); // This should never happen, but just in case... if (cereal::is_loading<Archive>()) InitializeModel(false, false); // Values will be overwritten. // Avoid polymorphic serialization by explicitly serializing the correct type. switch (treeType) { case KD_TREE: { LeafSizeRSWrapper<tree::KDTree>& typedSearch = dynamic_cast<LeafSizeRSWrapper<tree::KDTree>&>(*rSearch); ar(CEREAL_NVP(typedSearch)); break; } case COVER_TREE: { RSWrapper<tree::StandardCoverTree>& typedSearch = dynamic_cast<RSWrapper<tree::StandardCoverTree>&>(*rSearch); ar(CEREAL_NVP(typedSearch)); break; } case R_TREE: { RSWrapper<tree::RTree>& typedSearch = dynamic_cast<RSWrapper<tree::RTree>&>(*rSearch); ar(CEREAL_NVP(typedSearch)); break; } case R_STAR_TREE: { RSWrapper<tree::RStarTree>& typedSearch = dynamic_cast<RSWrapper<tree::RStarTree>&>(*rSearch); ar(CEREAL_NVP(typedSearch)); break; } case BALL_TREE: { LeafSizeRSWrapper<tree::BallTree>& typedSearch = dynamic_cast<LeafSizeRSWrapper<tree::BallTree>&>(*rSearch); ar(CEREAL_NVP(typedSearch)); break; } case X_TREE: { RSWrapper<tree::XTree>& typedSearch = dynamic_cast<RSWrapper<tree::XTree>&>(*rSearch); ar(CEREAL_NVP(typedSearch)); break; } case HILBERT_R_TREE: { RSWrapper<tree::HilbertRTree>& typedSearch = dynamic_cast<RSWrapper<tree::HilbertRTree>&>(*rSearch); ar(CEREAL_NVP(typedSearch)); break; } case R_PLUS_TREE: { RSWrapper<tree::RPlusTree>& typedSearch = dynamic_cast<RSWrapper<tree::RPlusTree>&>(*rSearch); ar(CEREAL_NVP(typedSearch)); break; } case R_PLUS_PLUS_TREE: { RSWrapper<tree::RPlusPlusTree>& typedSearch = dynamic_cast<RSWrapper<tree::RPlusPlusTree>&>(*rSearch); ar(CEREAL_NVP(typedSearch)); break; } case VP_TREE: { LeafSizeRSWrapper<tree::VPTree>& typedSearch = dynamic_cast<LeafSizeRSWrapper<tree::VPTree>&>(*rSearch); ar(CEREAL_NVP(typedSearch)); break; } case RP_TREE: { LeafSizeRSWrapper<tree::RPTree>& typedSearch = dynamic_cast<LeafSizeRSWrapper<tree::RPTree>&>(*rSearch); ar(CEREAL_NVP(typedSearch)); break; } case MAX_RP_TREE: { LeafSizeRSWrapper<tree::MaxRPTree>& typedSearch = dynamic_cast<LeafSizeRSWrapper<tree::MaxRPTree>&>(*rSearch); ar(CEREAL_NVP(typedSearch)); break; } case UB_TREE: { LeafSizeRSWrapper<tree::UBTree>& typedSearch = dynamic_cast<LeafSizeRSWrapper<tree::UBTree>&>(*rSearch); ar(CEREAL_NVP(typedSearch)); break; } case OCTREE: { LeafSizeRSWrapper<tree::Octree>& typedSearch = dynamic_cast<LeafSizeRSWrapper<tree::Octree>&>(*rSearch); ar(CEREAL_NVP(typedSearch)); break; } } } } // namespace range } // namespace mlpack #endif
30.929329
80
0.607677
florian-rosenthal
8eb22800d61e3b40e628fa1436bf42cdd446fa87
1,461
cpp
C++
algorithms/cpp/Problems 1201-1300/_1254_NumberOfClosedIslands.cpp
shivamacs/LeetCode
f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a
[ "MIT" ]
null
null
null
algorithms/cpp/Problems 1201-1300/_1254_NumberOfClosedIslands.cpp
shivamacs/LeetCode
f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a
[ "MIT" ]
null
null
null
algorithms/cpp/Problems 1201-1300/_1254_NumberOfClosedIslands.cpp
shivamacs/LeetCode
f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a
[ "MIT" ]
null
null
null
/* Source - https://leetcode.com/problems/number-of-closed-islands/ Author - Shivam Arora */ #include <bits/stdc++.h> using namespace std; int x[4] = {-1, 0, 1, 0}; int y[4] = {0, -1, 0, 1}; bool dfs(int sr, int sc, vector< vector<int> >& grid) { grid[sr][sc] = 1; if(sr == 0 || sc == 0 || sr == grid.size() - 1 || sc == grid[0].size() - 1) return false; int falseCount = 0; for(int d = 0; d < 4; d++) { int a = sr + x[d]; int b = sc + y[d]; if(grid[a][b] == 1) continue; bool result = dfs(a, b, grid); if(result == false) falseCount++; } return falseCount == 0; } int number_of_closed_islands(vector< vector<int> >& grid) { int n = grid.size(); int m = grid[0].size(); int result = 0; for(int i = 1; i < n - 1; i++) { for(int j = 1; j < m - 1; j++) { if(grid[i][j] == 0) result += dfs(i, j, grid) ? 1 : 0; } } return result; } int main() { int n, m; cout<<"Enter dimensions of the grid: "; cin>>n>>m; vector< vector<int> > grid(n, vector<int> (m)); cout<<"Enter the values in the grid (1 - water, 0 - land) row-wise: "<<endl; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) cin>>grid[i][j]; } cout<<"Number of closed islands: "<<number_of_closed_islands(grid)<<endl; }
22.476923
80
0.464066
shivamacs
8eb849f2a90f0aaac2f0f3de98d0a393fffc5fbb
15,981
cpp
C++
sp/src/game/client/gstring/vgui/vgui_gstringoptions.cpp
ChampionCynthia/g-string_2013
cae02cf5128be8a2469f242cff079a5f98e45427
[ "Unlicense" ]
28
2015-08-16T16:43:27.000Z
2022-02-19T23:37:08.000Z
sp/src/game/client/gstring/vgui/vgui_gstringoptions.cpp
ChampionCynthia/g-string_2013
cae02cf5128be8a2469f242cff079a5f98e45427
[ "Unlicense" ]
null
null
null
sp/src/game/client/gstring/vgui/vgui_gstringoptions.cpp
ChampionCynthia/g-string_2013
cae02cf5128be8a2469f242cff079a5f98e45427
[ "Unlicense" ]
6
2015-10-02T21:34:38.000Z
2019-09-20T11:09:41.000Z
#include "cbase.h" #include "tier1/KeyValues.h" #include "gstring/gstring_cvars.h" #include "gstring/vgui/vgui_gstringoptions.h" #include "ienginevgui.h" #include "vgui_controls/Panel.h" #include "vgui_controls/CheckButton.h" #include "vgui_controls/ComboBox.h" #include "vgui_controls/Slider.h" #include "vgui_controls/Button.h" #include "vgui_controls/PropertyPage.h" #include "matsys_controls/colorpickerpanel.h" using namespace vgui; extern ConVar gstring_firstpersonbody_enable; //extern ConVar gstring_firstpersonbody_shadow_enable; extern ConVar gstring_volumetrics_enabled; static PostProcessingState_t presets[] = { // Subtle { true, true, true, true, true, true, false, true, false, 0.0f, 0.3f, 0.7f, 0.3f, 0.2f, 0.1f, 0.2f, 0.2f }, // Vibrant { true, true, true, true, true, true, true, true, true, 0.0f, 0.7f, 1.0f, 0.5f, 0.0f, 0.2f, 0.6f, 0.8f }, // film noir { true, true, true, true, true, true, true, true, false, 0.0f, 0.8f, 1.0f, 0.5f, 1.0f, 0.3f, 0.2f, 0.9f }, // film noir red { true, true, true, true, true, true, true, true, false, 0.0f, 0.8f, 1.0f, 0.5f, 0.5f, 0.3f, 0.2f, 0.9f }, // bw { false, false, false, false, false, false, false, false, false, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f }, // bw red //{ false, false, false, false, false, false, false, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f }, // 70 mm { true, true, true, true, true, true, true, true, true, 1.0f, 0.2f, 0.8f, 0.1f, 0.1f, 0.2f, 0.7f, 0.6f }, // none { false, false, false, false, false, false, false, false, false, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }, }; static float scales[ PP_VALS ] = { 5.0f, 1.0f, 0.2f, 1.0f, 1.0f, 5.0f, 1.0f, 100.0f }; static Color HUDColors[ HUDCOLOR_VALS ] = { Color( 255, 229, 153, 255 ), Color( 255, 128, 0, 255 ), Color( 255, 255, 255, 255 ), Color( 164, 164, 164, 255 ), }; CVGUIGstringOptions::CVGUIGstringOptions( VPANEL parent, const char *pName ) : BaseClass( NULL, pName ) { SetParent( parent ); Activate(); m_pPropertySheet = new PropertySheet( this, "property_sheet" ); PropertyPage *pPagePostProcessing = new PropertyPage( m_pPropertySheet, "" ); PropertyPage *pPageGame = new PropertyPage( m_pPropertySheet, "" ); LoadControlSettings( "resource/gstring_options.res" ); m_pPropertySheet->AddPage( pPagePostProcessing, "#pp_postprocessing_title" ); m_pPropertySheet->AddPage( pPageGame, "#option_game_title" ); #define CREATE_VGUI_SLIDER( var, name, minRange, maxRange, ticks ) var = new Slider( pPagePostProcessing, name ); \ var->SetRange( minRange, maxRange ); \ var->SetNumTicks( ticks ); \ var->AddActionSignalTarget( this ) #define CREATE_VGUI_CHECKBOX( var, name, page ) var = new CheckButton( page, name, "" ); \ var->AddActionSignalTarget( this ) CREATE_VGUI_CHECKBOX( m_pCheck_HurtFX, "check_damageeffects", pPagePostProcessing ); CREATE_VGUI_CHECKBOX( m_pCheck_Vignette, "check_vignette", pPagePostProcessing ); CREATE_VGUI_CHECKBOX( m_pCheck_GodRays, "check_godrays", pPagePostProcessing ); CREATE_VGUI_CHECKBOX( m_pCheck_WaterEffects, "check_screenwater", pPagePostProcessing ); CREATE_VGUI_CHECKBOX( m_pCheck_LensFlare, "check_lensflare", pPagePostProcessing ); CREATE_VGUI_CHECKBOX( m_pCheck_DreamBlur, "check_dreamblur", pPagePostProcessing ); CREATE_VGUI_CHECKBOX( m_pCheck_ScreenBlur, "check_screenblur", pPagePostProcessing ); CREATE_VGUI_CHECKBOX( m_pCheck_CinemaOverlay, "check_cinemaoverlay", pPagePostProcessing ); CREATE_VGUI_CHECKBOX( m_pCheck_Dof, "check_dof", pPagePostProcessing ); m_pCBox_Preset = new ComboBox( pPagePostProcessing, "combo_preset", 10, false ); m_pCBox_Preset->AddItem( "#pp_preset_subtle", NULL ); m_pCBox_Preset->AddItem( "#pp_preset_vibrant", NULL ); m_pCBox_Preset->AddItem( "#pp_preset_filmnoir", NULL ); m_pCBox_Preset->AddItem( "#pp_preset_filmnoir_red", NULL ); m_pCBox_Preset->AddItem( "#pp_preset_bw", NULL ); //m_pCBox_Preset->AddItem( "#pp_preset_bw_red", NULL ); m_pCBox_Preset->AddItem( "#pp_preset_70mm", NULL ); m_pCBox_Preset->AddItem( "#pp_preset_none", NULL ); m_pCBox_Preset->AddActionSignalTarget( this ); CREATE_VGUI_SLIDER( m_pSlider_CinematicBars_Size, "slider_bars", 0, 10, 10 ); CREATE_VGUI_SLIDER( m_pSlider_MotionBlur_Strength, "slider_mblur", 0, 10, 10 ); CREATE_VGUI_SLIDER( m_pSlider_BloomFlare_Strength, "slider_bflare", 0, 10, 10 ); CREATE_VGUI_SLIDER( m_pSlider_ExplosionBlur_Strength, "slider_expblur", 0, 10, 10 ); CREATE_VGUI_SLIDER( m_pSlider_Desaturation_Strength, "slider_desat", 0, 10, 10 ); CREATE_VGUI_SLIDER( m_pSlider_FilmGrain_Strength, "slider_filmgrain", 0, 10, 10 ); CREATE_VGUI_SLIDER( m_pSlider_Bend_Strength, "slider_bend", 0, 10, 10 ); CREATE_VGUI_SLIDER( m_pSlider_Chromatic_Strength, "slider_chromatic", 0, 10, 10 ); m_pLabel_Value_CinematicBars = new Label( pPagePostProcessing, "label_bars", "" ); m_pLabel_Value_MotionBlur = new Label( pPagePostProcessing, "label_mblur", "" ); m_pLabel_Value_BloomFlare = new Label( pPagePostProcessing, "label_bflare", "" ); m_pLabel_Value_ExplosionBlur = new Label( pPagePostProcessing, "label_expblur", "" ); m_pLabel_Value_Desaturation = new Label( pPagePostProcessing, "label_desat", "" ); m_pLabel_Value_FilmGrain = new Label( pPagePostProcessing, "label_filmgrain", "" ); m_pLabel_Value_Bend = new Label( pPagePostProcessing, "label_bend", "" ); m_pLabel_Value_Chromatic = new Label( pPagePostProcessing, "label_chromatic", "" ); pPagePostProcessing->LoadControlSettings( "resource/gstring_options_page_postprocessing.res" ); CREATE_VGUI_CHECKBOX( m_pCheck_FirstPersonBody, "check_first_person_body", pPageGame ); //CREATE_VGUI_CHECKBOX( m_pCheck_FirstPersonShadow, "check_first_person_shadow", pPageGame ); CREATE_VGUI_CHECKBOX( m_pCheck_LightVolumetrics, "check_volumetrics", pPageGame ); m_pCBox_HUDColorPreset = new ComboBox( pPageGame, "cbox_color_preset", 10, false ); m_pCBox_HUDColorPreset->AddItem( "#options_game_hud_color_preset_default", NULL ); m_pCBox_HUDColorPreset->AddItem( "#options_game_hud_color_preset_orange", NULL ); m_pCBox_HUDColorPreset->AddItem( "#options_game_hud_color_preset_white", NULL ); m_pCBox_HUDColorPreset->AddItem( "#options_game_hud_color_preset_dark", NULL ); m_pCBox_HUDColorPreset->AddActionSignalTarget( this ); m_pHUDColorPicker = new CColorPickerButton( pPageGame, "hud_color_picker_button", this ); pPageGame->LoadControlSettings( "resource/gstring_options_page_game.res" ); DoModal(); SetDeleteSelfOnClose( true ); SetVisible( true ); SetSizeable(false); SetMoveable(true); SetTitle( "#pp_title", false ); m_pVarChecks[ 0 ] = &cvar_gstring_drawhurtfx; m_pVarChecks[ 1 ] = &cvar_gstring_drawgodrays; m_pVarChecks[ 2 ] = &cvar_gstring_drawwatereffects; m_pVarChecks[ 3 ] = &cvar_gstring_drawvignette; m_pVarChecks[ 4 ] = &cvar_gstring_drawlensflare; m_pVarChecks[ 5 ] = &cvar_gstring_drawdreamblur; m_pVarChecks[ 6 ] = &cvar_gstring_drawscreenblur; m_pVarChecks[ 7 ] = &cvar_gstring_drawcinemaoverlay; m_pVarChecks[ 8 ] = &cvar_gstring_drawdof; m_pVarValues[ 0 ] = &cvar_gstring_bars_scale; m_pVarValues[ 1 ] = &cvar_gstring_motionblur_scale; m_pVarValues[ 2 ] = &cvar_gstring_bloomflare_strength; m_pVarValues[ 3 ] = &cvar_gstring_explosionfx_strength; m_pVarValues[ 4 ] = &cvar_gstring_desaturation_strength; m_pVarValues[ 5 ] = &cvar_gstring_filmgrain_strength; m_pVarValues[ 6 ] = &cvar_gstring_bend_strength; m_pVarValues[ 7 ] = &cvar_gstring_chromatic_aberration; CvarToState(); OnSliderMoved( NULL ); } CVGUIGstringOptions::~CVGUIGstringOptions() { } void CVGUIGstringOptions::OnCommand( const char *cmd ) { if ( !Q_stricmp( cmd, "save" ) ) { #define CVAR_CHECK_INTEGER( x, y ) ( x.SetValue( ( y->IsSelected() ? 1 : int(0) ) ) ) //#define CVAR_SLIDER_FLOAT( x, y, ratio ) ( x.SetValue( (float)(y->GetValue()/(float)ratio ) ) ) // // CVAR_CHECK_INTEGER( cvar_gstring_drawhurtfx, m_pCheck_HurtFX ); // CVAR_CHECK_INTEGER( cvar_gstring_drawvignette, m_pCheck_Vignette ); // CVAR_CHECK_INTEGER( cvar_gstring_drawgodrays, m_pCheck_GodRays ); // CVAR_CHECK_INTEGER( cvar_gstring_drawscreenblur, m_pCheck_ScreenBlur ); // CVAR_CHECK_INTEGER( cvar_gstring_drawdreamblur, m_pCheck_DreamBlur ); // CVAR_CHECK_INTEGER( cvar_gstring_drawlensflare, m_pCheck_LensFlare ); // CVAR_CHECK_INTEGER( cvar_gstring_drawwatereffects, m_pCheck_WaterEffects ); // // CVAR_SLIDER_FLOAT( cvar_gstring_explosionfx_strength, m_pSlider_ExplosionBlur_Strength, 10 ); // CVAR_SLIDER_FLOAT( cvar_gstring_bars_scale, m_pSlider_CinematicBars_Size, 50 ); // CVAR_SLIDER_FLOAT( cvar_gstring_motionblur_scale, m_pSlider_MotionBlur_Strength, 10 ); // CVAR_SLIDER_FLOAT( cvar_gstring_bloomflare_strength, m_pSlider_BloomFlare_Strength, 2 ); // CVAR_SLIDER_FLOAT( cvar_gstring_desaturation_strength, m_pSlider_Desaturation_Strength, 10 ); // CVAR_SLIDER_FLOAT( cvar_gstring_filmgrain_strength, m_pSlider_FilmGrain_Strength, 50 ); // CVAR_SLIDER_FLOAT( cvar_gstring_bend_strength, m_pSlider_Bend_Strength, 10 ); // CVAR_SLIDER_FLOAT( cvar_gstring_chromatic_aberration, m_pSlider_Chromatic_Strength, 1000 ); CVAR_CHECK_INTEGER( gstring_firstpersonbody_enable, m_pCheck_FirstPersonBody ); CVAR_CHECK_INTEGER( gstring_volumetrics_enabled, m_pCheck_LightVolumetrics ); StateToCvar(); gstring_hud_color.SetValue( VarArgs( "%i %i %i 255", m_colHUD.r(), m_colHUD.g(), m_colHUD.b() ) ); engine->ClientCmd( "host_writeconfig" ); engine->ClientCmd( "hud_reloadscheme" ); CloseModal(); } else if ( !Q_stricmp( cmd, "defaults" ) ) { m_pCBox_Preset->ActivateItem( 0 ); gstring_hud_color.Revert(); ReadValues( true ); UpdateLabels(); } else { BaseClass::OnCommand( cmd ); } } void CVGUIGstringOptions::ApplySchemeSettings( vgui::IScheme *pScheme ) { BaseClass::ApplySchemeSettings( pScheme ); ReadValues( true ); UpdateLabels(); } void CVGUIGstringOptions::ReadValues( bool bUpdatePreset ) { #define CVAR_CHECK_SELECTED( x, y ) ( y->SetSelectedNoMessage( x.GetBool() ) ) //#define CVAR_SLIDER_INTEGER( x, y, ratio ) ( y->SetValue( x.GetFloat() * ratio, false ) ) CVAR_CHECK_SELECTED( gstring_firstpersonbody_enable, m_pCheck_FirstPersonBody ); CVAR_CHECK_SELECTED( gstring_volumetrics_enabled, m_pCheck_LightVolumetrics ); #define CVAR_STATE_CHECK_SELECTED( i, y ) ( y->SetSelectedNoMessage( m_state.checks[ i ] ) ) #define CVAR_STATE_SLIDER_INTEGER( i, y ) ( y->SetValue( m_state.val[ i ] * 10.1f, false ) ) CVAR_STATE_CHECK_SELECTED( 0, m_pCheck_HurtFX ); CVAR_STATE_CHECK_SELECTED( 1, m_pCheck_GodRays ); CVAR_STATE_CHECK_SELECTED( 2, m_pCheck_WaterEffects ); CVAR_STATE_CHECK_SELECTED( 3, m_pCheck_Vignette ); CVAR_STATE_CHECK_SELECTED( 4, m_pCheck_LensFlare ); CVAR_STATE_CHECK_SELECTED( 5, m_pCheck_DreamBlur ); CVAR_STATE_CHECK_SELECTED( 6, m_pCheck_ScreenBlur ); CVAR_STATE_CHECK_SELECTED( 7, m_pCheck_CinemaOverlay ); CVAR_STATE_CHECK_SELECTED( 8, m_pCheck_Dof ); CVAR_STATE_SLIDER_INTEGER( 0, m_pSlider_CinematicBars_Size ); CVAR_STATE_SLIDER_INTEGER( 1, m_pSlider_MotionBlur_Strength ); CVAR_STATE_SLIDER_INTEGER( 2, m_pSlider_BloomFlare_Strength ); CVAR_STATE_SLIDER_INTEGER( 3, m_pSlider_ExplosionBlur_Strength ); CVAR_STATE_SLIDER_INTEGER( 4, m_pSlider_Desaturation_Strength ); CVAR_STATE_SLIDER_INTEGER( 5, m_pSlider_FilmGrain_Strength ); CVAR_STATE_SLIDER_INTEGER( 6, m_pSlider_Bend_Strength ); CVAR_STATE_SLIDER_INTEGER( 7, m_pSlider_Chromatic_Strength ); UTIL_StringToColor( m_colHUD, gstring_hud_color.GetString() ); m_pHUDColorPicker->SetColor( m_colHUD ); for ( int i = 0; i < HUDCOLOR_VALS; ++i ) { const Color &col = HUDColors[ i ]; if ( col == m_colHUD ) { m_pCBox_HUDColorPreset->ActivateItem( i ); break; } } if ( bUpdatePreset ) { int presetIndex = FindCurrentPreset(); if ( presetIndex >= 0 ) { m_pCBox_Preset->ActivateItem( presetIndex ); } } } void CVGUIGstringOptions::PerformLayout() { BaseClass::PerformLayout(); MoveToCenterOfScreen(); } void CVGUIGstringOptions::OnCheckButtonChecked( Panel *panel ) { CheckButton *pCheckButton = dynamic_cast< CheckButton* >( panel ); if ( pCheckButton != NULL ) { bool value = pCheckButton->IsSelected(); CheckButton *checkButtons[ PP_CHECKS ] = { m_pCheck_HurtFX, m_pCheck_GodRays, m_pCheck_WaterEffects, m_pCheck_Vignette, m_pCheck_LensFlare, m_pCheck_DreamBlur, m_pCheck_ScreenBlur, m_pCheck_CinemaOverlay, m_pCheck_Dof }; for ( int i = 0; i < PP_CHECKS; ++i ) { if ( checkButtons[ i ] == panel ) { m_state.checks[ i ] = value; } } } OnPresetModified(); } void CVGUIGstringOptions::UpdateLabels() { m_pLabel_Value_CinematicBars->SetText( VarArgs( "%.1f", m_state.val[ 0 ] ) ); m_pLabel_Value_MotionBlur->SetText( VarArgs( "%.1f", m_state.val[ 1 ] ) ); m_pLabel_Value_BloomFlare->SetText( VarArgs( "%.1f", m_state.val[ 2 ] ) ); m_pLabel_Value_ExplosionBlur->SetText( VarArgs( "%.1f", m_state.val[ 3 ] ) ); m_pLabel_Value_Desaturation->SetText( VarArgs( "%.1f", m_state.val[ 4 ] ) ); m_pLabel_Value_FilmGrain->SetText( VarArgs( "%.1f", m_state.val[ 5 ] ) ); m_pLabel_Value_Bend->SetText( VarArgs( "%.1f", m_state.val[ 6 ] ) ); m_pLabel_Value_Chromatic->SetText( VarArgs( "%.1f", m_state.val[ 7 ] ) ); } void CVGUIGstringOptions::OnSliderMoved( Panel *panel ) { Slider *pSlider = dynamic_cast< Slider* >( panel ); if ( pSlider != NULL ) { int value = pSlider->GetValue(); Slider *sliders[ PP_VALS ] = { m_pSlider_CinematicBars_Size, m_pSlider_MotionBlur_Strength, m_pSlider_BloomFlare_Strength, m_pSlider_ExplosionBlur_Strength, m_pSlider_Desaturation_Strength, m_pSlider_FilmGrain_Strength, m_pSlider_Bend_Strength, m_pSlider_Chromatic_Strength }; for ( int i = 0; i < PP_VALS; ++i ) { if ( sliders[ i ] == panel ) { m_state.val[ i ] = value * 0.101f; } } } OnPresetModified(); UpdateLabels(); } void CVGUIGstringOptions::OnTextChanged( KeyValues *pKV ) { Panel *p = (Panel*)pKV->GetPtr( "panel" ); if ( p == m_pCBox_Preset ) { ApplyPreset( m_pCBox_Preset->GetActiveItem() ); } else if ( p == m_pCBox_HUDColorPreset ) { const Color &col = HUDColors[ m_pCBox_HUDColorPreset->GetActiveItem() ]; m_colHUD = col; m_pHUDColorPicker->SetColor( col ); } } void CVGUIGstringOptions::OnPicked( KeyValues *pKV ) { m_colHUD = pKV->GetColor( "color" ); } void CVGUIGstringOptions::ApplyPreset( int index ) { if ( index < 0 || index >= ARRAYSIZE( presets ) ) { return; } const PostProcessingState_t &p = presets[ index ]; for ( int c = 0; c < PP_CHECKS; ++c ) { m_state.checks[ c ] = p.checks[ c ]; } for ( int v = 0; v < PP_VALS; ++v ) { m_state.val[ v ] = p.val[ v ]; } ReadValues( false ); UpdateLabels(); } int CVGUIGstringOptions::FindCurrentPreset() { for ( int i = 0; i < ARRAYSIZE( presets ); ++i ) { const PostProcessingState_t &p = presets[ i ]; bool bWrong = false; for ( int c = 0; c < PP_CHECKS; ++c ) { if ( m_state.checks[ c ] != p.checks[ c ] ) { bWrong = true; } } for ( int v = 0; v < PP_VALS; ++v ) { if ( !CloseEnough( m_state.val[ v ], p.val[ v ] ) ) { bWrong = true; } } if ( !bWrong ) { return i; } } return -1; } void CVGUIGstringOptions::OnPresetModified() { m_pCBox_Preset->SetText( "#pp_preset_custom" ); } void CVGUIGstringOptions::CvarToState() { for ( int i = 0; i < PP_CHECKS; ++i ) { m_state.checks[ i ] = m_pVarChecks[ i ]->GetBool(); } for ( int i = 0; i < PP_VALS; ++i ) { m_state.val[ i ] = m_pVarValues[ i ]->GetFloat() * scales[ i ]; } } void CVGUIGstringOptions::StateToCvar() { for ( int i = 0; i < PP_CHECKS; ++i ) { m_pVarChecks[ i ]->SetValue( m_state.checks[ i ] ? 1 : int( 0 ) ); } for ( int i = 0; i < PP_VALS; ++i ) { m_pVarValues[ i ]->SetValue( m_state.val[ i ] / scales[ i ] ); } } CON_COMMAND( vgui_showGstringOptions, "" ) { vgui::VPANEL GameUIRoot = enginevgui->GetPanel( PANEL_GAMEUIDLL ); new CVGUIGstringOptions( GameUIRoot, "GstringOptions" ); }
34.074627
115
0.73093
ChampionCynthia
8ebc620eee4b12815926d4c6596310b0d5f981ff
519
hpp
C++
coreneuron/permute/data_layout.hpp
alexsavulescu/CoreNeuron
af7e95d98819c052b07656961d20de6a71b70740
[ "BSD-3-Clause" ]
109
2016-04-08T09:27:54.000Z
2022-03-15T02:10:47.000Z
coreneuron/permute/data_layout.hpp
alexsavulescu/CoreNeuron
af7e95d98819c052b07656961d20de6a71b70740
[ "BSD-3-Clause" ]
595
2016-04-01T09:12:47.000Z
2022-03-31T23:44:58.000Z
coreneuron/permute/data_layout.hpp
alexsavulescu/CoreNeuron
af7e95d98819c052b07656961d20de6a71b70740
[ "BSD-3-Clause" ]
52
2016-03-29T08:11:35.000Z
2022-03-11T07:37:38.000Z
/* # ============================================================================= # Copyright (c) 2016 - 2021 Blue Brain Project/EPFL # # See top-level LICENSE file for details. # ============================================================================= */ #ifndef NRN_DATA_LAYOUT_HPP #define NRN_DATA_LAYOUT_HPP #define SOA_LAYOUT 0 #define AOS_LAYOUT 1 namespace coreneuron { struct Memb_list; int get_data_index(int node_index, int variable_index, int mtype, Memb_list* ml); } // namespace coreneuron #endif
27.315789
81
0.535645
alexsavulescu
8ebc679c6e7131ac3b876970c2499840dc8323da
6,406
cpp
C++
src/testApp.cpp
zebradog/shaderTextureBlending
939cf34ccf0e7b490eb483c0ecfc6e118801b1df
[ "MIT" ]
null
null
null
src/testApp.cpp
zebradog/shaderTextureBlending
939cf34ccf0e7b490eb483c0ecfc6e118801b1df
[ "MIT" ]
null
null
null
src/testApp.cpp
zebradog/shaderTextureBlending
939cf34ccf0e7b490eb483c0ecfc6e118801b1df
[ "MIT" ]
null
null
null
#include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ cout << "WARNING: this program may take a while to load" << endl; ofBackground(127,127,127); ofSetWindowTitle( "Shader Texture Blending by Ruud Bijnen" ); ofSetFrameRate ( 30 ); ofSetVerticalSync(true); shadeBlendMix = 1.0; shadeBlendMode = 0; shadeContrast = 1.0; shadeBrightness = 0.0; readme.load(); readme.mOverlay = true; ofxControlPanel::setBackgroundColor(simpleColor(0, 0, 0, 200)); ofxControlPanel::setTextColor(simpleColor(255, 0, 128, 255)); ofxControlPanel::setForegroundColor(simpleColor(64, 64, 64, 255)); //gui.loadFont("monaco.ttf", 8); gui.setup("Shader Texture Blending", 10, 10, 570, ofGetHeight()-40); ofxControlPanel::setBackgroundColor(simpleColor(0, 0, 0, 50)); gui.addPanel("Shader settings", 3, false); ofxControlPanel::setBackgroundColor(simpleColor(255, 255, 255, 10)); //--------- PANEL 1 gui.setWhichPanel(0); gui.setWhichColumn(0); gui.addDrawableRect("Base Texture", &imgBase, 150, 150); listerBase.listDir("images/"); listerBase.setSelectedFile(0); imgBase.loadImage( listerBase.getSelectedPath() ); guiTypeFileLister * guiBaseLister = gui.addFileLister("Base Chooser", &listerBase, 150, 300); guiBaseLister->selection = 0; guiBaseLister->notify(); //-------------------- gui.setWhichColumn(1); gui.addDrawableRect("Blend Texture", &imgBlend, 150, 150); listerBlend.listDir("images/"); listerBlend.setSelectedFile(1); imgBlend.loadImage( listerBlend.getSelectedPath() ); guiTypeFileLister * guiBlendLister = gui.addFileLister("Blend Chooser", &listerBlend, 150, 300); guiBlendLister->selection = 1; //some dummy vars we will update to show the variable lister object elapsedTime = ofGetElapsedTimef(); appFrameCount = ofGetFrameNum(); appFrameRate = ofGetFrameRate(); //-------------------- gui.setWhichColumn(2); //gui.addSlider("motion threshold", "MOTION_THRESHOLD", 29.0, 1.0, 255.0, false); gui.addSlider("Contrast","SHADER_CONTRAST", shadeContrast, 0.0, 5.0, false); gui.addSlider("Brightness","SHADER_BRIGHTNESS", shadeBrightness, -1.0, 1.0, false); gui.addSlider("Blend Mix","SHADER_BLENDMIX", shadeBlendMix, 0.0, 1.0, false); vector <string> blendmodes; blendmodes.push_back("Normal"); blendmodes.push_back("Lighten"); blendmodes.push_back("Darken"); blendmodes.push_back("Multiply"); blendmodes.push_back("Average"); blendmodes.push_back("Add"); blendmodes.push_back("Substract"); blendmodes.push_back("Difference"); blendmodes.push_back("Negation"); blendmodes.push_back("Exclusion"); blendmodes.push_back("Screen"); blendmodes.push_back("Overlay"); blendmodes.push_back("SoftLight"); blendmodes.push_back("HardLight"); blendmodes.push_back("ColorDodge"); blendmodes.push_back("ColorBurn"); blendmodes.push_back("LinearDodge"); blendmodes.push_back("LinearBurn"); blendmodes.push_back("LinearLight"); blendmodes.push_back("VividLight"); blendmodes.push_back("PinLight"); blendmodes.push_back("HardMix"); blendmodes.push_back("Reflect"); blendmodes.push_back("Glow"); blendmodes.push_back("Phoenix"); //ofxControlPanel::setBackgroundColor(simpleColor(0, 0, 0, 255)); gui.addTextDropDown("Blendmode", "SHADER_BLENDMODE", shadeBlendMode, blendmodes); //ofxControlPanel::setBackgroundColor(simpleColor(255, 255, 255, 10)); //SETTINGS AND EVENTS //load from xml! gui.loadSettings("controlPanelSettings.xml"); //if you want to use events call this after you have added all your gui elements gui.setupEvents(); gui.enableEvents(); // -- this gives you back an ofEvent for all events in this control panel object ofAddListener(gui.guiEvent, this, &testApp::guiEvents); shader.setup( "shaders/myShader" ); } //this captures all our control panel events - unless its setup differently in testApp::setup //-------------------------------------------------------------- void testApp::guiEvents(guiCallbackData & data){ if ( data.getDisplayName() == "Base Chooser" ) { imgBase.loadImage( data.getString(1) ); } else if ( data.getDisplayName() == "Blend Chooser" ) { imgBlend.loadImage( data.getString(1) ); } } //-------------------------------------------------------------- void testApp::update(){ //some dummy vars we will update to show the variable lister object elapsedTime = ofGetElapsedTimef(); appFrameCount = ofGetFrameNum(); appFrameRate = ofGetFrameRate(); shadeBlendMode = gui.getValueI("SHADER_BLENDMODE"); shadeBlendMix = gui.getValueF("SHADER_BLENDMIX"); shadeContrast = gui.getValueF("SHADER_CONTRAST"); shadeBrightness = gui.getValueF("SHADER_BRIGHTNESS"); gui.update(); } //-------------------------------------------------------------- void testApp::draw(){ ofSetColor(0xffffff); //------------------ image shader.begin(); shader.setUniform( "contrast", shadeContrast ); shader.setUniform( "brightness", shadeBrightness ); shader.setUniform( "blendmix", shadeBlendMix ); shader.setUniform( "blendmode", shadeBlendMode ); //shader.setTexture( "texBase", imgBase, 0 ); shader.setTexture( "texBlend", imgBlend, 1 ); imgBase.draw ( 650, 10 ); shader.end(); //----------------- gui ofSetLineWidth(2); ofDisableSmoothing(); gui.draw(); //----------------- readme readme.draw(); } //-------------------------------------------------------------- void testApp::keyPressed (int key){ readme.hide(); } //-------------------------------------------------------------- void testApp::keyReleased (int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ gui.mouseDragged(x, y, button); } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ gui.mousePressed(x, y, button); } //-------------------------------------------------------------- void testApp::mouseReleased(){ gui.mouseReleased(); }
32.353535
98
0.607868
zebradog
8ec0d2798d81b381a0ee7da0d5a2cbd30bcd577c
22,778
cpp
C++
rmw_ecal_proto_cpp/src/rmw/rmw.cpp
ZhenshengLee/rmw_ecal
1dbd50c458c288ecd14238b02f4ec1050d21b378
[ "Apache-2.0" ]
30
2020-09-05T23:40:06.000Z
2022-03-09T09:30:21.000Z
rmw_ecal_proto_cpp/src/rmw/rmw.cpp
ZhenshengLee/rmw_ecal
1dbd50c458c288ecd14238b02f4ec1050d21b378
[ "Apache-2.0" ]
21
2020-09-08T09:58:23.000Z
2022-03-24T08:49:12.000Z
rmw_ecal_proto_cpp/src/rmw/rmw.cpp
ZhenshengLee/rmw_ecal
1dbd50c458c288ecd14238b02f4ec1050d21b378
[ "Apache-2.0" ]
7
2020-09-08T09:36:13.000Z
2021-11-09T09:31:46.000Z
// Copyright 2020 Continental AG // // 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 <rmw/rmw.h> #include <rmw_ecal_shared_cpp/rmw/rmw.hpp> #include "proto_typesupport_factory.hpp" #include "proto_serializer_factory.hpp" const auto identifier{"rmw_ecal_proto_cpp"}; const auto serialization_format{"protobuf"}; const char *rmw_get_implementation_identifier(void) { return identifier; } const char *rmw_get_serialization_format(void) { return serialization_format; } #if ROS_DISTRO >= GALACTIC rmw_node_t *rmw_create_node(rmw_context_t *context, const char *name, const char *namespace_) { return eCAL::rmw::rmw_create_node(::rmw_get_implementation_identifier(), context, name, namespace_); } #elif ROS_DISTRO == FOXY rmw_node_t *rmw_create_node(rmw_context_t *context, const char *name, const char *namespace_, size_t domain_id, bool localhost_only) { return eCAL::rmw::rmw_create_node(::rmw_get_implementation_identifier(), context, name, namespace_, domain_id, localhost_only); } #elif ROS_DISTRO == ELOQUENT rmw_node_t *rmw_create_node(rmw_context_t *context, const char *name, const char *namespace_, size_t domain_id, const rmw_node_security_options_t *security_options, bool local_host_only) { return eCAL::rmw::rmw_create_node(::rmw_get_implementation_identifier(), context, name, namespace_, domain_id, security_options, local_host_only); } #else rmw_node_t *rmw_create_node(rmw_context_t *context, const char *name, const char *namespace_, size_t domain_id, const rmw_node_security_options_t *security_options) { return eCAL::rmw::rmw_create_node(::rmw_get_implementation_identifier(), context, name, namespace_, domain_id, security_options); } #endif rmw_ret_t rmw_destroy_node(rmw_node_t *node) { return eCAL::rmw::rmw_destroy_node(::rmw_get_implementation_identifier(), node); } rmw_ret_t rmw_node_assert_liveliness(const rmw_node_t *node) { return eCAL::rmw::rmw_node_assert_liveliness(::rmw_get_implementation_identifier(), node); } const rmw_guard_condition_t *rmw_node_get_graph_guard_condition(const rmw_node_t *node) { return eCAL::rmw::rmw_node_get_graph_guard_condition(::rmw_get_implementation_identifier(), node); } #if ROS_DISTRO >= ELOQUENT rmw_publisher_t *rmw_create_publisher(const rmw_node_t *node, const rosidl_message_type_support_t *type_support, const char *topic_name, const rmw_qos_profile_t *qos_policies, const rmw_publisher_options_t *publisher_options) { return eCAL::rmw::rmw_create_publisher(::rmw_get_implementation_identifier(), eCAL::rmw::ProtoTypeSupportFactory{}, node, type_support, topic_name, qos_policies, publisher_options); } #else rmw_publisher_t *rmw_create_publisher(const rmw_node_t *node, const rosidl_message_type_support_t *type_support, const char *topic_name, const rmw_qos_profile_t *qos_policies) { return eCAL::rmw::rmw_create_publisher(::rmw_get_implementation_identifier(), eCAL::rmw::ProtoTypeSupportFactory{}, node, type_support, topic_name, qos_policies); } #endif rmw_ret_t rmw_destroy_publisher(rmw_node_t *node, rmw_publisher_t *publisher) { return eCAL::rmw::rmw_destroy_publisher(::rmw_get_implementation_identifier(), node, publisher); } rmw_ret_t rmw_publish(const rmw_publisher_t *publisher, const void *ros_message, rmw_publisher_allocation_t *allocation) { return eCAL::rmw::rmw_publish(::rmw_get_implementation_identifier(), publisher, ros_message, allocation); } rmw_ret_t rmw_publisher_count_matched_subscriptions(const rmw_publisher_t *publisher, size_t *subscription_count) { return eCAL::rmw::rmw_publisher_count_matched_subscriptions(::rmw_get_implementation_identifier(), publisher, subscription_count); } rmw_ret_t rmw_publisher_get_actual_qos(const rmw_publisher_t *publisher, rmw_qos_profile_t *qos) { return eCAL::rmw::rmw_publisher_get_actual_qos(::rmw_get_implementation_identifier(), publisher, qos); } rmw_ret_t rmw_publish_serialized_message(const rmw_publisher_t *publisher, const rmw_serialized_message_t *serialized_message, rmw_publisher_allocation_t *allocation) { return eCAL::rmw::rmw_publish_serialized_message(::rmw_get_implementation_identifier(), publisher, serialized_message, allocation); } #if ROS_DISTRO >= FOXY rmw_ret_t rmw_get_serialized_message_size(const rosidl_message_type_support_t *type_support, const rosidl_runtime_c__Sequence__bound *message_bounds, size_t *size) { return eCAL::rmw::rmw_get_serialized_message_size(::rmw_get_implementation_identifier(), type_support, message_bounds, size); } #else rmw_ret_t rmw_get_serialized_message_size(const rosidl_message_type_support_t *type_support, const rosidl_message_bounds_t *message_bounds, size_t *size) { return eCAL::rmw::rmw_get_serialized_message_size(::rmw_get_implementation_identifier(), type_support, message_bounds, size); } #endif rmw_ret_t rmw_serialize(const void *ros_message, const rosidl_message_type_support_t *type_support, rmw_serialized_message_t *serialized_message) { return eCAL::rmw::rmw_serialize(::rmw_get_implementation_identifier(), eCAL::rmw::ProtoSerializerFactory{}, ros_message, type_support, serialized_message); } rmw_ret_t rmw_deserialize(const rmw_serialized_message_t *serialized_message, const rosidl_message_type_support_t *type_support, void *ros_message) { return eCAL::rmw::rmw_deserialize(::rmw_get_implementation_identifier(), eCAL::rmw::ProtoSerializerFactory{}, serialized_message, type_support, ros_message); } #if ROS_DISTRO >= ELOQUENT rmw_subscription_t *rmw_create_subscription(const rmw_node_t *node, const rosidl_message_type_support_t *type_support, const char *topic_name, const rmw_qos_profile_t *qos_policies, const rmw_subscription_options_t *subscription_options) { return eCAL::rmw::rmw_create_subscription(::rmw_get_implementation_identifier(), eCAL::rmw::ProtoTypeSupportFactory{}, node, type_support, topic_name, qos_policies, subscription_options); } #else rmw_subscription_t *rmw_create_subscription(const rmw_node_t *node, const rosidl_message_type_support_t *type_support, const char *topic_name, const rmw_qos_profile_t *qos_policies, bool ignore_local_publications) { return eCAL::rmw::rmw_create_subscription(::rmw_get_implementation_identifier(), eCAL::rmw::ProtoTypeSupportFactory{}, node, type_support, topic_name, qos_policies, ignore_local_publications); } #endif rmw_ret_t rmw_destroy_subscription(rmw_node_t *node, rmw_subscription_t *subscription) { return eCAL::rmw::rmw_destroy_subscription(::rmw_get_implementation_identifier(), node, subscription); } rmw_ret_t rmw_subscription_count_matched_publishers(const rmw_subscription_t *subscription, size_t *publisher_count) { return eCAL::rmw::rmw_subscription_count_matched_publishers(::rmw_get_implementation_identifier(), subscription, publisher_count); } rmw_ret_t rmw_take(const rmw_subscription_t *subscription, void *ros_message, bool *taken, rmw_subscription_allocation_t *allocation) { return eCAL::rmw::rmw_take(::rmw_get_implementation_identifier(), subscription, ros_message, taken, allocation); } rmw_ret_t rmw_take_with_info(const rmw_subscription_t *subscription, void *ros_message, bool *taken, rmw_message_info_t *message_info, rmw_subscription_allocation_t *allocation) { return eCAL::rmw::rmw_take_with_info(::rmw_get_implementation_identifier(), subscription, ros_message, taken, message_info, allocation); } #if ROS_DISTRO >= FOXY rmw_ret_t rmw_take_sequence(const rmw_subscription_t *subscription, size_t count, rmw_message_sequence_t *message_sequence, rmw_message_info_sequence_t *message_info_sequence, size_t *taken, rmw_subscription_allocation_t *allocation) { return eCAL::rmw::rmw_take_sequence(::rmw_get_implementation_identifier(), subscription, count, message_sequence, message_info_sequence, taken, allocation); } #endif rmw_ret_t rmw_take_serialized_message(const rmw_subscription_t *subscription, rmw_serialized_message_t *serialized_message, bool *taken, rmw_subscription_allocation_t *allocation) { return eCAL::rmw::rmw_take_serialized_message(::rmw_get_implementation_identifier(), subscription, serialized_message, taken, allocation); } rmw_ret_t rmw_take_serialized_message_with_info(const rmw_subscription_t *subscription, rmw_serialized_message_t *serialized_message, bool *taken, rmw_message_info_t *message_info, rmw_subscription_allocation_t *allocation) { return eCAL::rmw::rmw_take_serialized_message_with_info(::rmw_get_implementation_identifier(), subscription, serialized_message, taken, message_info, allocation); } rmw_client_t *rmw_create_client(const rmw_node_t *node, const rosidl_service_type_support_t *type_support, const char *service_name, const rmw_qos_profile_t *qos_policies) { return eCAL::rmw::rmw_create_client(::rmw_get_implementation_identifier(), eCAL::rmw::ProtoTypeSupportFactory{}, node, type_support, service_name, qos_policies); } rmw_ret_t rmw_destroy_client(rmw_node_t *node, rmw_client_t *client) { return eCAL::rmw::rmw_destroy_client(::rmw_get_implementation_identifier(), node, client); } rmw_ret_t rmw_send_request(const rmw_client_t *client, const void *ros_request, int64_t *sequence_id) { return eCAL::rmw::rmw_send_request(::rmw_get_implementation_identifier(), client, ros_request, sequence_id); } #if ROS_DISTRO >= FOXY rmw_ret_t rmw_take_response(const rmw_client_t *client, rmw_service_info_t *request_header, void *ros_response, bool *taken) { return eCAL::rmw::rmw_take_response(::rmw_get_implementation_identifier(), client, request_header, ros_response, taken); } #else rmw_ret_t rmw_take_response(const rmw_client_t *client, rmw_request_id_t *rmw_request_id, void *ros_response, bool *taken) { return eCAL::rmw::rmw_take_response(::rmw_get_implementation_identifier(), client, rmw_request_id, ros_response, taken); } #endif rmw_service_t *rmw_create_service(const rmw_node_t *node, const rosidl_service_type_support_t *type_support, const char *service_name, const rmw_qos_profile_t *qos_policies) { return eCAL::rmw::rmw_create_service(::rmw_get_implementation_identifier(), eCAL::rmw::ProtoTypeSupportFactory{}, node, type_support, service_name, qos_policies); } rmw_ret_t rmw_destroy_service(rmw_node_t *node, rmw_service_t *service) { return eCAL::rmw::rmw_destroy_service(::rmw_get_implementation_identifier(), node, service); } #if ROS_DISTRO >= FOXY rmw_ret_t rmw_take_request(const rmw_service_t *service, rmw_service_info_t *request_header, void *ros_request, bool *taken) { return eCAL::rmw::rmw_take_request(::rmw_get_implementation_identifier(), service, request_header, ros_request, taken); } #else rmw_ret_t rmw_take_request(const rmw_service_t *service, rmw_request_id_t *request_header, void *ros_request, bool *taken) { return eCAL::rmw::rmw_take_request(::rmw_get_implementation_identifier(), service, request_header, ros_request, taken); } #endif rmw_ret_t rmw_send_response(const rmw_service_t *service, rmw_request_id_t *request_header, void *ros_response) { return eCAL::rmw::rmw_send_response(::rmw_get_implementation_identifier(), service, request_header, ros_response); } rmw_guard_condition_t *rmw_create_guard_condition(rmw_context_t *context) { return eCAL::rmw::rmw_create_guard_condition(::rmw_get_implementation_identifier(), context); } rmw_ret_t rmw_destroy_guard_condition(rmw_guard_condition_t *guard_condition) { return eCAL::rmw::rmw_destroy_guard_condition(::rmw_get_implementation_identifier(), guard_condition); } rmw_ret_t rmw_trigger_guard_condition(const rmw_guard_condition_t *guard_condition) { return eCAL::rmw::rmw_trigger_guard_condition(::rmw_get_implementation_identifier(), guard_condition); } rmw_wait_set_t *rmw_create_wait_set(rmw_context_t *context, size_t max_conditions) { return eCAL::rmw::rmw_create_wait_set(::rmw_get_implementation_identifier(), context, max_conditions); } rmw_ret_t rmw_destroy_wait_set(rmw_wait_set_t *wait_set) { return eCAL::rmw::rmw_destroy_wait_set(::rmw_get_implementation_identifier(), wait_set); } rmw_ret_t rmw_wait(rmw_subscriptions_t *subscriptions, rmw_guard_conditions_t *guard_conditions, rmw_services_t *services, rmw_clients_t *clients, rmw_events_t *events, rmw_wait_set_t *wait_set, const rmw_time_t *wait_timeout) { return eCAL::rmw::rmw_wait(::rmw_get_implementation_identifier(), subscriptions, guard_conditions, services, clients, events, wait_set, wait_timeout); } rmw_ret_t rmw_get_node_names(const rmw_node_t *node, rcutils_string_array_t *node_names, rcutils_string_array_t *node_namespaces) { return eCAL::rmw::rmw_get_node_names(::rmw_get_implementation_identifier(), node, node_names, node_namespaces); } #if ROS_DISTRO >= FOXY rmw_ret_t rmw_get_node_names_with_enclaves(const rmw_node_t *node, rcutils_string_array_t *node_names, rcutils_string_array_t *node_namespaces, rcutils_string_array_t *enclaves) { return eCAL::rmw::rmw_get_node_names_with_enclaves(::rmw_get_implementation_identifier(), node, node_names, node_namespaces, enclaves); } #endif rmw_ret_t rmw_count_publishers(const rmw_node_t *node, const char *topic_name, size_t *count) { return eCAL::rmw::rmw_count_publishers(::rmw_get_implementation_identifier(), node, topic_name, count); } rmw_ret_t rmw_count_subscribers(const rmw_node_t *node, const char *topic_name, size_t *count) { return eCAL::rmw::rmw_count_subscribers(::rmw_get_implementation_identifier(), node, topic_name, count); } rmw_ret_t rmw_get_gid_for_publisher(const rmw_publisher_t *publisher, rmw_gid_t *gid) { return eCAL::rmw::rmw_get_gid_for_publisher(::rmw_get_implementation_identifier(), publisher, gid); } rmw_ret_t rmw_compare_gids_equal(const rmw_gid_t *gid1, const rmw_gid_t *gid2, bool *result) { return eCAL::rmw::rmw_compare_gids_equal(::rmw_get_implementation_identifier(), gid1, gid2, result); } rmw_ret_t rmw_service_server_is_available(const rmw_node_t *node, const rmw_client_t *client, bool *is_available) { return eCAL::rmw::rmw_service_server_is_available(::rmw_get_implementation_identifier(), node, client, is_available); } rmw_ret_t rmw_set_log_severity(rmw_log_severity_t severity) { return eCAL::rmw::rmw_set_log_severity(::rmw_get_implementation_identifier(), severity); } rmw_ret_t rmw_subscription_get_actual_qos(const rmw_subscription_t *subscription, rmw_qos_profile_t *qos) { return eCAL::rmw::rmw_subscription_get_actual_qos(::rmw_get_implementation_identifier(), subscription, qos); } #if ROS_DISTRO >= FOXY rmw_ret_t rmw_init_publisher_allocation(const rosidl_message_type_support_t *type_support, const rosidl_runtime_c__Sequence__bound *message_bounds, rmw_publisher_allocation_t *allocation) { return eCAL::rmw::rmw_init_publisher_allocation(::rmw_get_implementation_identifier(), type_support, message_bounds, allocation); } #else rmw_ret_t rmw_init_publisher_allocation(const rosidl_message_type_support_t *type_support, const rosidl_message_bounds_t *message_bounds, rmw_publisher_allocation_t *allocation) { return eCAL::rmw::rmw_init_publisher_allocation(::rmw_get_implementation_identifier(), type_support, message_bounds, allocation); } #endif rmw_ret_t rmw_fini_publisher_allocation(rmw_publisher_allocation_t *allocation) { return eCAL::rmw::rmw_fini_publisher_allocation(::rmw_get_implementation_identifier(), allocation); } rmw_ret_t rmw_publisher_assert_liveliness(const rmw_publisher_t *publisher) { return eCAL::rmw::rmw_publisher_assert_liveliness(::rmw_get_implementation_identifier(), publisher); } #if ROS_DISTRO >= FOXY rmw_ret_t rmw_init_subscription_allocation(const rosidl_message_type_support_t *type_support, const rosidl_runtime_c__Sequence__bound *message_bounds, rmw_subscription_allocation_t *allocation) { return eCAL::rmw::rmw_init_subscription_allocation(::rmw_get_implementation_identifier(), type_support, message_bounds, allocation); } #else rmw_ret_t rmw_init_subscription_allocation(const rosidl_message_type_support_t *type_support, const rosidl_message_bounds_t *message_bounds, rmw_subscription_allocation_t *allocation) { return eCAL::rmw::rmw_init_subscription_allocation(::rmw_get_implementation_identifier(), type_support, message_bounds, allocation); } #endif rmw_ret_t rmw_fini_subscription_allocation(rmw_subscription_allocation_t *allocation) { return eCAL::rmw::rmw_fini_subscription_allocation(::rmw_get_implementation_identifier(), allocation); } rmw_ret_t rmw_take_loaned_message(const rmw_subscription_t *subscription, void **loaned_message, bool *taken, rmw_subscription_allocation_t *allocation) { return eCAL::rmw::rmw_take_loaned_message(::rmw_get_implementation_identifier(), subscription, loaned_message, taken, allocation); } rmw_ret_t rmw_take_loaned_message_with_info(const rmw_subscription_t *subscription, void **loaned_message, bool *taken, rmw_message_info_t *message_info, rmw_subscription_allocation_t *allocation) { return eCAL::rmw::rmw_take_loaned_message_with_info(::rmw_get_implementation_identifier(), subscription, loaned_message, taken, message_info, allocation); } rmw_ret_t rmw_return_loaned_message_from_subscription(const rmw_subscription_t *subscription, void *loaned_message) { return eCAL::rmw::rmw_return_loaned_message_from_subscription(::rmw_get_implementation_identifier(), subscription, loaned_message); } rmw_ret_t rmw_borrow_loaned_message(const rmw_publisher_t *publisher, const rosidl_message_type_support_t *type_support, void **ros_message) { return eCAL::rmw::rmw_borrow_loaned_message(::rmw_get_implementation_identifier(), publisher, type_support, ros_message); } rmw_ret_t rmw_publish_loaned_message(const rmw_publisher_t *publisher, void *ros_message, rmw_publisher_allocation_t *allocation) { return eCAL::rmw::rmw_publish_loaned_message(::rmw_get_implementation_identifier(), publisher, ros_message, allocation); } rmw_ret_t rmw_return_loaned_message_from_publisher(const rmw_publisher_t *publisher, void *loaned_message) { return eCAL::rmw::rmw_return_loaned_message_from_publisher(::rmw_get_implementation_identifier(), publisher, loaned_message); }
44.750491
194
0.672271
ZhenshengLee
8ec17823b724f8047599e4bf863425aaf8d744e2
1,883
cpp
C++
readFile.cpp
sidvishnoi/filesystem-simulation
d1534795736c5938eba07a288e9996236211025b
[ "MIT" ]
4
2018-01-24T22:21:29.000Z
2021-03-21T18:14:57.000Z
readFile.cpp
sidvishnoi/filesystem-simulation
d1534795736c5938eba07a288e9996236211025b
[ "MIT" ]
null
null
null
readFile.cpp
sidvishnoi/filesystem-simulation
d1534795736c5938eba07a288e9996236211025b
[ "MIT" ]
1
2017-04-18T10:24:51.000Z
2017-04-18T10:24:51.000Z
#include "filesystem.h" int FileSystem::readFile(const char *title) { /* objective: to read a single file from multiple non-continuous sectors input: title: title of file return: 0: success 1: error effect: contents of file are printed, if success */ TypeCastEntry entry; if (strlen(title) == 0) { std::cout << "File title: "; std::cin >> entry.entry.name; std::cin.ignore(32767, '\n'); } else { strcpy(entry.entry.name, title); } entry.entry.startsAt = 0; char buf[kSectorSize]; TypeCastEntry test; for (int i = 0; i < sectorsForDir; ++i) { readSector(currentDir + i, buf); for (int j = 0; j < kSectorSize; j += 32) { for (int k = 0; k < 32; ++k) { test.str[k] = buf[j+k]; } if (strcmp(test.entry.name, entry.entry.name) == 0) { entry.entry.startsAt = test.entry.startsAt; entry.entry.size = test.entry.size; entry.entry.parent = test.entry.parent; if (test.entry.type != 'F') return 1; break; } } if (entry.entry.startsAt != 0) break; } if (entry.entry.startsAt == 0) { std::cout << "file not found" << std::endl; return 1; } else { // read file content std::cout << "READING FILE WITH" << std::endl; std::cout << "TITLE = " << test.entry.name << std::endl; std::cout << "SIZE = " << entry.entry.size << " bytes." << std::endl; int sec = entry.entry.startsAt; while (sec != 1) { readSector(sec, buf); for (int i = 0; i < kSectorSize; ++i) { std::cout << buf[i]; } sec = getStatus(sec); } std::cout << std::endl; } return 0; }
30.370968
77
0.491768
sidvishnoi
8ec21fbffb9a28de422becf918f06a2869bc32f4
4,498
cpp
C++
lib/Analysis/Intrinsics.cpp
yukatan1701/tsar
a6f95cdaeb117ccd5fcb775b471b1aa17c45f4e8
[ "Apache-2.0" ]
14
2019-11-04T15:03:40.000Z
2021-09-07T17:29:40.000Z
lib/Analysis/Intrinsics.cpp
yukatan1701/tsar
a6f95cdaeb117ccd5fcb775b471b1aa17c45f4e8
[ "Apache-2.0" ]
11
2019-11-29T21:18:12.000Z
2021-12-22T21:36:40.000Z
lib/Analysis/Intrinsics.cpp
yukatan1701/tsar
a6f95cdaeb117ccd5fcb775b471b1aa17c45f4e8
[ "Apache-2.0" ]
17
2019-10-15T13:56:35.000Z
2021-10-20T17:21:14.000Z
//===-- Instrinsics.cpp - TSAR Intrinsic Function Handling ------*- C++ -*-===// // // Traits Static Analyzer (SAPFOR) // // Copyright 2018 DVM System Group // // 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. // //===----------------------------------------------------------------------===// // // This file implements functions from Intrinsics.h which allow to process // TSAR intrinsics. // //===----------------------------------------------------------------------===// #include "tsar/Analysis/Intrinsics.h" #include <llvm/ADT/SmallVector.h> #include <llvm/IR/DerivedTypes.h> #include <llvm/IR/Intrinsics.h> #include <llvm/IR/Module.h> #include <tuple> using namespace llvm; using namespace tsar; /// Table of string intrinsic names indexed by enum value. static const char * const IntrinsicNameTable[] = { "not_intrinsic", #define GET_INTRINSIC_NAME_TABLE #include "tsar/Analysis/Intrinsics.gen" #undef GET_INTRINSIC_NAME_TABLE }; namespace { /// Kinds of types which can be used in an intrinsic prototype. enum TypeKind : unsigned { #define GET_INTRINSIC_TYPE_KINDS #include "tsar/Analysis/Intrinsics.gen" #undef GET_INTRINSIC_TYPE_KINDS }; /// This literal type contains offsets for a prototype in table of prototypes /// (see PrototypeOffsetTable and PrototypeTable for details). struct PrototypeDescriptor { unsigned Start; unsigned End; }; } ///\brief Table of offsets in prototype table indexed by enum value. /// /// Each intrinsic has a prototype which is described by a table of prototypes. /// Each description record has start and end points which are stored in this /// table. So start point of a prototype for an intrinsic Id can be accessed /// in a following way `PrototypeTable[PrototypeOffsetTable[Id].first]`. static constexpr PrototypeDescriptor PrototypeOffsetTable[] = { #define PROTOTYPE(Start,End) {Start, End}, PROTOTYPE(0,0) // there is no prototype for `tsar_not_intrinsic` #define GET_INTRINSIC_PROTOTYPE_OFFSET_TABLE #include "tsar/Analysis/Intrinsics.gen" #undef GET_INTRINSIC_PROTOTYPE_OFFSET_TABLE #undef PROTOTYPE }; /// Table of intrinsic prototypes indexed by records in prototype offset table. static constexpr TypeKind PrototypeTable[] = { #define GET_INTRINSIC_PROTOTYPE_TABLE #include "tsar/Analysis/Intrinsics.gen" #undef GET_INTRINSIC_PROTOTYPE_TABLE }; /// Builds LLVM type for a type which is described in PrototypeTable and is /// started at a specified position. static Type * DecodeType(LLVMContext &Ctx, unsigned &Start) { switch (PrototypeTable[Start]) { case Void: ++Start; return Type::getVoidTy(Ctx); case Any: ++Start; return Type::getInt8Ty(Ctx); case Size: ++Start; return Type::getInt64Ty(Ctx); case Pointer: return PointerType::getUnqual(DecodeType(Ctx, ++Start)); default: llvm_unreachable("Unknown kind of intrinsic parameter type!"); return nullptr; } } namespace tsar { StringRef getName(IntrinsicId Id) { assert(Id < IntrinsicId::num_intrinsics && Id > IntrinsicId::not_intrinsic && "Invalid intrinsic ID!"); return IntrinsicNameTable[static_cast<unsigned>(Id)]; } FunctionType *getType(LLVMContext &Ctx, IntrinsicId Id) { auto Offset = PrototypeOffsetTable[static_cast<unsigned>(Id)]; Type *ResultTy = DecodeType(Ctx, Offset.Start); SmallVector<Type *, 8> ArgsTys; while (Offset.Start < Offset.End) ArgsTys.push_back(DecodeType(Ctx, Offset.Start)); return FunctionType::get(ResultTy, ArgsTys, false); } llvm::FunctionCallee getDeclaration(Module *M, IntrinsicId Id) { return M->getOrInsertFunction(getName(Id), getType(M->getContext(), Id)); } bool getTsarLibFunc(StringRef funcName, IntrinsicId &Id) { const char* const *Start = &IntrinsicNameTable[0]; const char* const *End = &IntrinsicNameTable[(unsigned)IntrinsicId::num_intrinsics]; if (funcName.empty()) return false; const char* const *I = std::find(Start, End, funcName); if (I != End) { Id = (IntrinsicId)(I - Start); return true; } return false; } }
34.868217
80
0.715874
yukatan1701
8ec60b892dfde400957339b54081d17ad3f108e7
7,644
hxx
C++
windows/core/ntgdi/gre/icmobj.hxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
windows/core/ntgdi/gre/icmobj.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
windows/core/ntgdi/gre/icmobj.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/******************************Module*Header******************************* * Module Name: icmobj.hxx * * This file contains the class prototypes for Color Space and ICM * objects * * Created: 23-Mar-1994 * Author: Mark Enstrom (marke) * * Copyright (c) 1994-1999 Microsoft Corporation * \**************************************************************************/ #ifndef _ICMOBJ_HXX #define _ICMOBJ_HXX #if DBG #define DBG_ICM 1 #else #define DBG_ICM 0 #endif /******************************Public*Class*******************************\ * class COLORSPACE * * COLORSPACE class * * Fields * * DWORD _lcsSignature; * DWORD _lcsVersion; * DWORD _lcsSize; * LCSCSTYPE _lcsCSType; * LCSGAMUTMATCH _lcsIntent; * CIEXYZTRIPLE _lcsEndpoints; * DWORD _lcsGammaRed; * DWORD _lcsGammaGreen; * DWORD _lcsGammaBlue; * WCHAR _lcsFilename[MAX_PATH]; * DWORD _lcsExFlags; * * 23-Mar-1994 * * Mark Enstrom (marke) * \**************************************************************************/ class COLORSPACE : public OBJECT { private: DWORD _lcsSignature; DWORD _lcsVersion; DWORD _lcsSize; LCSCSTYPE _lcsCSType; LCSGAMUTMATCH _lcsIntent; CIEXYZTRIPLE _lcsEndpoints; DWORD _lcsGammaRed; DWORD _lcsGammaGreen; DWORD _lcsGammaBlue; WCHAR _lcsFilename[MAX_PATH]; DWORD _lcsExFlags; public: VOID lcsSignature(DWORD lcsSig) {_lcsSignature = lcsSig;} DWORD lcsSignature() {return(_lcsSignature);} VOID lcsVersion(DWORD lcsVer) {_lcsVersion = lcsVer;} DWORD lcsVersion() {return(_lcsVersion);} VOID lcsSize(DWORD lcsSize) {_lcsSize = lcsSize;} DWORD lcsSize() {return(_lcsSize);} VOID lcsCSType(DWORD lcsCSType) {_lcsCSType = lcsCSType;} DWORD lcsCSType() {return(_lcsCSType);} VOID lcsIntent(DWORD lcsIntent) {_lcsIntent = lcsIntent;} DWORD lcsIntent() {return(_lcsIntent);} VOID lcsGammaRed(DWORD lcsRed) {_lcsGammaRed = lcsRed;} DWORD lcsGammaRed() {return(_lcsGammaRed);} VOID lcsGammaGreen(DWORD lcsGreen) {_lcsGammaGreen = lcsGreen;} DWORD lcsGammaGreen() {return(_lcsGammaGreen);} VOID lcsGammaBlue(DWORD lcsBlue) {_lcsGammaBlue = lcsBlue;} DWORD lcsGammaBlue() {return(_lcsGammaBlue);} VOID vSETlcsEndpoints(LPCIEXYZTRIPLE pcz) {_lcsEndpoints = *pcz;} VOID vGETlcsEndpoints(LPCIEXYZTRIPLE pcz) {*pcz = _lcsEndpoints;} VOID vSETlcsFilename(PWCHAR pwName,ULONG length) { memcpy(&_lcsFilename[0],pwName,length); } VOID vGETlcsFilename(PWCHAR pwName,ULONG length) { memcpy(pwName,&_lcsFilename[0],length); } VOID lcsExFlags(DWORD dwFlags) { _lcsExFlags = dwFlags; } DWORD lcsExFlags() {return(_lcsExFlags);} // // common features // HCOLORSPACE hColorSpace() { return((HCOLORSPACE) hGet()); } }; typedef COLORSPACE *PCOLORSPACE; /******************************Public*Class*******************************\ * class COLORSPACEREF * * COLORSPACE reference from pointer or handle * * 23-Mar-1994 * * Mark Enstrom (marke) * \**************************************************************************/ class COLORSPACEREF { private: PCOLORSPACE _pColorSpace; public: COLORSPACEREF() { _pColorSpace = (PCOLORSPACE)NULL; } COLORSPACEREF(HCOLORSPACE hColorSpace) { _pColorSpace = (PCOLORSPACE)HmgShareCheckLock((HOBJ)hColorSpace, ICMLCS_TYPE); } ~COLORSPACEREF() { if (_pColorSpace != (PCOLORSPACE)NULL) { DEC_SHARE_REF_CNT(_pColorSpace); } } BOOL bValid() {return(_pColorSpace != (PCOLORSPACE)NULL);} PCOLORSPACE pColorSpace() {return(_pColorSpace);} }; /******************************Public*Class*******************************\ * class COLORTRANSFORM * * COLORTRANSFORM class * \*************************************************************************/ class COLORTRANSFORM : public OBJECT { public: // // Color transform handle of driver's realization. // HANDLE _hDeviceColorTransform; public: // // common features // HANDLE hColorTransform() { return((HANDLE) hGet()); } }; typedef COLORTRANSFORM *PCOLORTRANSFORM; /******************************Public*Class*******************************\ * class COLORTRANSFORMOBJ * * COLORTRANSFORM reference class * \*************************************************************************/ class COLORTRANSFORMOBJ { private: PCOLORTRANSFORM _pColorTransform; public: COLORTRANSFORMOBJ() { _pColorTransform = (PCOLORTRANSFORM) NULL; } COLORTRANSFORMOBJ(HANDLE hColorTransform) { _pColorTransform = (PCOLORTRANSFORM) HmgShareCheckLock((HOBJ)hColorTransform, ICMCXF_TYPE); } ~COLORTRANSFORMOBJ() { if (_pColorTransform != (PCOLORTRANSFORM) NULL) { DEC_SHARE_REF_CNT(_pColorTransform); } } // // Validation check // BOOL bValid() { return(_pColorTransform != (PCOLORTRANSFORM)NULL); } HANDLE hGetDeviceColorTransform() { return(_pColorTransform->_hDeviceColorTransform); } VOID vSetDeviceColorTransform(HANDLE h) { _pColorTransform->_hDeviceColorTransform = h; } HANDLE hCreate(XDCOBJ& dco, LOGCOLORSPACEW *pLogColorSpaceW, PVOID pvSource, ULONG cjSource, PVOID pvDestination, ULONG cjDestination, PVOID pvTarget, ULONG cjTarget); BOOL bDelete(XDCOBJ& dco, BOOL bProcessCleanup = FALSE); }; // // Functions in icmapi.cxx // extern "C" { BOOL APIENTRY GreSetColorSpace( HDC hdc, HCOLORSPACE hColorSpace ); BOOL WINAPI GreGetDeviceGammaRamp( HDC, LPVOID ); BOOL WINAPI GreGetDeviceGammaRampInternal( HDEV, LPVOID ); BOOL WINAPI GreSetDeviceGammaRamp( HDC, LPVOID, BOOL ); BOOL WINAPI GreSetDeviceGammaRampInternal( HDEV, LPVOID, BOOL ); } BOOL bDeleteColorSpace(HCOLORSPACE); INT cjGetLogicalColorSpace(HANDLE,INT,LPVOID); BOOL UpdateGammaRampOnDevice(HDEV,BOOL); ULONG GetColorManagementCaps(PDEVOBJ&); typedef struct _GAMMARAMP_ARRAY { WORD Red[256]; WORD Green[256]; WORD Blue[256]; } GAMMARAMP_ARRAY, *PGAMMARAMP_ARRAY; #if DBG_ICM extern ULONG IcmDebugLevel; #define ICMDUMP(s) \ if (IcmDebugLevel & 0x4) \ { \ DbgPrint ## s; \ } #define ICMMSG(s) \ if (IcmDebugLevel & 0x2) \ { \ DbgPrint ## s; \ } #define ICMAPI(s) \ if (IcmDebugLevel & 0x1) \ { \ DbgPrint ## s; \ } #else #define ICMDUMP(s) #define ICMMSG(s) #define ICMAPI(s) #endif // DBG #endif
23.024096
100
0.522109
npocmaka
8ecccc22e118a6bff9fc0589ec5024f050aa2f82
3,988
cpp
C++
Sail/src/Sail/entities/systems/network/receivers/NetworkReceiverSystemHost.cpp
BTH-StoraSpel-DXR/SPLASH
1bf4c9b96cbcce570ed3a97f30a556a992e1ad08
[ "MIT" ]
12
2019-09-11T15:52:31.000Z
2021-11-14T20:33:35.000Z
Sail/src/Sail/entities/systems/network/receivers/NetworkReceiverSystemHost.cpp
BTH-StoraSpel-DXR/Game
1bf4c9b96cbcce570ed3a97f30a556a992e1ad08
[ "MIT" ]
227
2019-09-11T08:40:24.000Z
2020-06-26T14:12:07.000Z
Sail/src/Sail/entities/systems/network/receivers/NetworkReceiverSystemHost.cpp
BTH-StoraSpel-DXR/Game
1bf4c9b96cbcce570ed3a97f30a556a992e1ad08
[ "MIT" ]
2
2020-10-26T02:35:18.000Z
2020-10-26T02:36:01.000Z
#include "pch.h" #include "NetworkReceiverSystemHost.h" #include "../NetworkSenderSystem.h" #include "Network/NWrapperSingleton.h" #include "Sail/utils/Utils.h" #include "Sail/utils/GameDataTracker.h" #include "Sail/events/types/StartKillCamEvent.h" #include "Sail/events/types/StopKillCamEvent.h" #include "../SPLASH/src/game/states/GameState.h" NetworkReceiverSystemHost::NetworkReceiverSystemHost() { EventDispatcher::Instance().subscribe(Event::Type::START_KILLCAM, this); EventDispatcher::Instance().subscribe(Event::Type::STOP_KILLCAM, this); } NetworkReceiverSystemHost::~NetworkReceiverSystemHost() { EventDispatcher::Instance().unsubscribe(Event::Type::START_KILLCAM, this); EventDispatcher::Instance().unsubscribe(Event::Type::STOP_KILLCAM, this); } void NetworkReceiverSystemHost::handleIncomingData(const std::string& data) { pushDataToBuffer(data); // The host will also save the data in the sender system so that it can be forwarded to all other clients m_netSendSysPtr->pushDataToBuffer(data); } void NetworkReceiverSystemHost::stop() { m_startEndGameTimer = false; m_finalKillCamOver = true; } #ifdef DEVELOPMENT unsigned int NetworkReceiverSystemHost::getByteSize() const { return BaseComponentSystem::getByteSize() + sizeof(*this); } #endif void NetworkReceiverSystemHost::endGame() { m_startEndGameTimer = true; } // HOST ONLY FUNCTIONS void NetworkReceiverSystemHost::endMatchAfterTimer(const float dt) { static float endGameClock = 0.f; if (m_startEndGameTimer) { endGameClock += dt; } // Wait until the final killcam has ended or until 2 seconds has passed if (m_finalKillCamOver && endGameClock > 2.0f) { NWrapperSingleton::getInstance().queueGameStateNetworkSenderEvent( Netcode::MessageType::ENDGAME_STATS, nullptr, false ); m_gameStatePtr->requestStackClear(); m_gameStatePtr->requestStackPush(States::EndGame); // Reset clock for next session m_startEndGameTimer = false; endGameClock = 0.f; } } void NetworkReceiverSystemHost::prepareEndScreen(const Netcode::PlayerID sender, const EndScreenInfo& info) { GlobalTopStats* gts = &GameDataTracker::getInstance().getStatisticsGlobal(); // Process the data if (info.bulletsFired > gts->bulletsFired) { gts->bulletsFired = info.bulletsFired; gts->bulletsFiredID = sender; } if (info.distanceWalked > gts->distanceWalked) { gts->distanceWalked = info.distanceWalked; gts->distanceWalkedID = sender; } if (info.jumpsMade > gts->jumpsMade) { gts->jumpsMade = info.jumpsMade; gts->jumpsMadeID = sender; } // Send data back in Netcode::MessageType::ENDGAME_STATS endGame(); // Starts the end game timer. Runs only for the host } bool NetworkReceiverSystemHost::onEvent(const Event& event) { NetworkReceiverSystem::onEvent(event); switch (event.type) { case Event::Type::START_KILLCAM: if (((const StartKillCamEvent&)event).finalKillCam) { m_finalKillCamOver = false; } break; case Event::Type::STOP_KILLCAM: if (((const StopKillCamEvent&)event).isFinalKill) { m_finalKillCamOver = true; } break; default: break; } return true; } void NetworkReceiverSystemHost::mergeHostsStats() { GameDataTracker* gdt = &GameDataTracker::getInstance(); Netcode::PlayerID id = NWrapperSingleton::getInstance().getMyPlayerID(); if (gdt->getStatisticsLocal().bulletsFired > gdt->getStatisticsGlobal().bulletsFired) { gdt->getStatisticsGlobal().bulletsFired = gdt->getStatisticsLocal().bulletsFired; gdt->getStatisticsGlobal().bulletsFiredID = id; } if (gdt->getStatisticsLocal().distanceWalked > gdt->getStatisticsGlobal().distanceWalked) { gdt->getStatisticsGlobal().distanceWalked = gdt->getStatisticsLocal().distanceWalked; gdt->getStatisticsGlobal().distanceWalkedID = id; } if (gdt->getStatisticsLocal().jumpsMade > gdt->getStatisticsGlobal().jumpsMade) { gdt->getStatisticsGlobal().jumpsMade = gdt->getStatisticsLocal().jumpsMade; gdt->getStatisticsGlobal().jumpsMadeID = id; } endGame(); }
29.323529
109
0.758275
BTH-StoraSpel-DXR
8ecd011beb2490a5a17b4c47e446719c0d6880e4
1,733
cpp
C++
javacompiler/pokitto/femto/mode/HiRes16Color/drawHLine.cpp
bl-ackrain/FemtoIDE
df642c39abb1a45b71ce1d7ce5abc1388879345a
[ "MIT" ]
18
2019-04-28T12:25:47.000Z
2022-01-24T22:36:45.000Z
javacompiler/pokitto/femto/mode/HiRes16Color/drawHLine.cpp
bl-ackrain/FemtoIDE
df642c39abb1a45b71ce1d7ce5abc1388879345a
[ "MIT" ]
97
2019-05-11T14:40:27.000Z
2021-09-15T12:20:30.000Z
javacompiler/pokitto/femto/mode/HiRes16Color/drawHLine.cpp
bl-ackrain/FemtoIDE
df642c39abb1a45b71ce1d7ce5abc1388879345a
[ "MIT" ]
12
2019-05-04T21:26:44.000Z
2020-12-12T07:24:02.000Z
if( w<0 ){ x += w; w = -w; } if( x < 0 ){ w += x; x = 0; } const std::uint32_t screenWidth = 220; const std::uint32_t screenHeight = 176; if( (x + w) >= (int32_t) screenWidth ) w = screenWidth - x; if( std::uint32_t(x)>=screenWidth || std::uint32_t(y)>=screenHeight || w<1 ) return; color = (color<<4) | (color&0xF); color |= color<<8; color |= color<<16; auto *b = buffer->elements+y*(screenWidth>>1)+(x>>1); if( x&1 ){ // setPixel(x, y, color); *b++ = (*b & 0xF0) | (color&0xF); w--; x++; if(!w) return; } int rem = (w>>1); if( rem < 4 ){ while( rem ){ *b++ = color; rem--; } }else{ if( uintptr_t(b)&3 ){ *b++ = color; rem--; if( uintptr_t(b)&3 ){ *b++ = color; rem--; if( uintptr_t(b)&3 ){ *b++ = color; rem--; } } } /* * / while( rem >= 4 ){ *((uint32_t*)b) = color; b += 4; rem -= 4; } /*/ asm volatile( ".syntax unified \n" "b drawHLineCheck%= \n" "drawHLineLoop%=: \n" "stmia %[b]!, {%[color]} \n" "drawHLineCheck%=: \n" "subs %[rem], 4 \n" "bpl drawHLineLoop%= \n" "adds %[rem], 4 \n" : [b]"+l"(b), [rem]"+l"(rem) : [color]"l"(color) : "cc" ); /* */ if( rem ){ *b++ = color; rem--; if( rem ){ *b++ = color; rem--; if( rem ){ *b++ = color; rem--; } } } } if( w&1 ) *b = (*b & 0xF) | (color&0xF0); // setPixel( x+w-1, y, color );
18.836957
76
0.366994
bl-ackrain
8ecd289f93aedd0c2cc88098ac3d8885840171ab
3,185
cpp
C++
sp/src/game/server/czeror/weapon_fiveseven.cpp
ZombieRoxtar/cZeroR
8c67b9e2e2da2479581d5a3863b8598d44ee69bb
[ "Unlicense" ]
2
2016-11-22T04:25:54.000Z
2020-02-02T12:24:42.000Z
sp/src/game/server/czeror/weapon_fiveseven.cpp
ZombieRoxtar/cZeroR
8c67b9e2e2da2479581d5a3863b8598d44ee69bb
[ "Unlicense" ]
null
null
null
sp/src/game/server/czeror/weapon_fiveseven.cpp
ZombieRoxtar/cZeroR
8c67b9e2e2da2479581d5a3863b8598d44ee69bb
[ "Unlicense" ]
null
null
null
//===== Copyright Bit Mage's Stuff, All rights probably reserved. ===== // // Purpose: Five-SeveN weapon, FN Five-seven, ES Five-seven // //============================================================================= #include "cbase.h" #include "baseadvancedweapon.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" //----------------------------------------------------------------------------- // CWeaponFiveSeven //----------------------------------------------------------------------------- class CWeaponFiveSeven : public CBaseAdvancedWeapon { public: DECLARE_CLASS( CWeaponFiveSeven, CBaseAdvancedWeapon ); DECLARE_NETWORKCLASS(); DECLARE_PREDICTABLE(); float GetFireRate() { return 0.15f; } // 400 Rounds per minute DECLARE_ACTTABLE(); }; IMPLEMENT_SERVERCLASS_ST( CWeaponFiveSeven, DT_WeaponFiveSeven ) END_SEND_TABLE() LINK_ENTITY_TO_CLASS( weapon_fiveseven, CWeaponFiveSeven ); PRECACHE_WEAPON_REGISTER( weapon_fiveseven ); acttable_t CWeaponFiveSeven::m_acttable[] = { { ACT_RANGE_ATTACK1, ACT_RANGE_ATTACK_PISTOL, true }, { ACT_RELOAD, ACT_RELOAD_PISTOL, true }, { ACT_IDLE, ACT_IDLE_PISTOL, true }, { ACT_IDLE_ANGRY, ACT_IDLE_ANGRY_PISTOL, true }, { ACT_WALK, ACT_WALK_PISTOL, true }, { ACT_IDLE_RELAXED, ACT_IDLE_SMG1_RELAXED, false }, { ACT_IDLE_STIMULATED, ACT_IDLE_SMG1_STIMULATED, false }, { ACT_IDLE_AGITATED, ACT_IDLE_ANGRY_SMG1, false }, { ACT_WALK_RELAXED, ACT_WALK_RIFLE_RELAXED, false }, { ACT_WALK_STIMULATED, ACT_WALK_RIFLE_STIMULATED, false }, { ACT_WALK_AGITATED, ACT_WALK_AIM_PISTOL, false }, { ACT_RUN_RELAXED, ACT_RUN_RIFLE_RELAXED, false }, { ACT_RUN_STIMULATED, ACT_RUN_RIFLE_STIMULATED, false }, { ACT_RUN_AGITATED, ACT_RUN_AIM_PISTOL, false }, { ACT_IDLE_AIM_RELAXED, ACT_IDLE_SMG1_RELAXED, false }, { ACT_IDLE_AIM_STIMULATED, ACT_IDLE_AIM_RIFLE_STIMULATED, false }, { ACT_IDLE_AIM_AGITATED, ACT_IDLE_ANGRY_SMG1, false }, { ACT_WALK_AIM_RELAXED, ACT_WALK_RIFLE_RELAXED, false }, { ACT_WALK_AIM_STIMULATED, ACT_WALK_AIM_RIFLE_STIMULATED, false }, { ACT_WALK_AIM_AGITATED, ACT_RUN_AIM_PISTOL, false }, { ACT_RUN_AIM_RELAXED, ACT_RUN_RIFLE_RELAXED, false }, { ACT_RUN_AIM_STIMULATED, ACT_RUN_AIM_RIFLE_STIMULATED, false }, { ACT_RUN_AIM_AGITATED, ACT_RUN_AIM_PISTOL, false }, { ACT_WALK_AIM, ACT_WALK_AIM_PISTOL, true }, { ACT_WALK_CROUCH, ACT_WALK_CROUCH_RIFLE, true }, { ACT_WALK_CROUCH_AIM, ACT_WALK_CROUCH_AIM_RIFLE, true }, { ACT_RUN, ACT_RUN_PISTOL, true }, { ACT_RUN_AIM, ACT_RUN_AIM_PISTOL, true }, { ACT_RUN_CROUCH, ACT_RUN_CROUCH_RIFLE, true }, { ACT_RUN_CROUCH_AIM, ACT_RUN_CROUCH_AIM_RIFLE, true }, { ACT_GESTURE_RANGE_ATTACK1, ACT_GESTURE_RANGE_ATTACK_PISTOL, false}, { ACT_COVER_LOW, ACT_COVER_PISTOL_LOW, false }, { ACT_RANGE_AIM_LOW, ACT_RANGE_AIM_AR2_LOW, false }, { ACT_RANGE_ATTACK1_LOW, ACT_RANGE_ATTACK_PISTOL_LOW, true }, { ACT_RELOAD_LOW, ACT_RELOAD_PISTOL_LOW, false }, { ACT_GESTURE_RELOAD, ACT_GESTURE_RELOAD_PISTOL, true }, }; IMPLEMENT_ACTTABLE( CWeaponFiveSeven );
38.841463
79
0.686342
ZombieRoxtar
8ece732793da8be7ab07619ee3af03073f8e1d3c
1,001
hpp
C++
core/logging.hpp
sdulloor/cyclone
a4606bfb50fb8ce01e21f245624d2f4a98961039
[ "Apache-2.0" ]
7
2017-11-21T03:08:15.000Z
2019-02-13T08:05:37.000Z
core/logging.hpp
IntelLabs/LogReplicationRocksDB
74f33e9a54f3ae820060230e28c42274696bf2f7
[ "Apache-2.0" ]
null
null
null
core/logging.hpp
IntelLabs/LogReplicationRocksDB
74f33e9a54f3ae820060230e28c42274696bf2f7
[ "Apache-2.0" ]
4
2020-03-27T18:06:33.000Z
2021-03-24T09:56:17.000Z
#ifndef _LOGGING_ #define _LOGGING_ #include<iostream> #include<string> #include<sstream> #include<boost/thread.hpp> #include<boost/date_time/posix_time/posix_time.hpp> enum log_state { fatal = 0, error = 1, warning = 2, info = 3, debug=4, total = 5 }; static const char *log_headers[total] = {"FATAL", "ERROR", "WARNING", "INFO", "DEBUG"}; class BOOST_LOG_TRIVIAL { enum log_state level; public: std::stringstream state; BOOST_LOG_TRIVIAL(enum log_state level_in) :level(level_in) { } template<typename T> BOOST_LOG_TRIVIAL& operator<< (T value) { state << value; return *this; } ~BOOST_LOG_TRIVIAL() { std::stringstream final; final << "<" << log_headers[level] << " "; final << boost::posix_time::to_simple_string(boost::posix_time::microsec_clock::local_time()) << " "; final << boost::this_thread::get_id() << "> "; final << state.str() << std::endl; std::cerr << final.str() << std::flush; } }; #endif
19.627451
105
0.636364
sdulloor
8ed1fa2a918006b038fde4fa7a9d94ec0b4ec003
1,635
cpp
C++
targets/apps/argobots_1/main.cpp
range3/spack-playground
3220494a7ee3266c1bd1dc55b98fb08a1c7840ba
[ "Apache-2.0" ]
null
null
null
targets/apps/argobots_1/main.cpp
range3/spack-playground
3220494a7ee3266c1bd1dc55b98fb08a1c7840ba
[ "Apache-2.0" ]
null
null
null
targets/apps/argobots_1/main.cpp
range3/spack-playground
3220494a7ee3266c1bd1dc55b98fb08a1c7840ba
[ "Apache-2.0" ]
null
null
null
#include <abt.h> #include <fmt/core.h> #include <algorithm> #include <iostream> #include <memory> #include <range/v3/view.hpp> #include <unused.hpp> #include <vector> using thread_arg_t = struct { size_t tid; }; void helloWorld(void* arg) { size_t tid = reinterpret_cast<thread_arg_t*>(arg)->tid; int rank; ABT_xstream_self_rank(&rank); fmt::print("Hello world! (thread = {:d}, ES = {:d})\n", tid, rank); } auto main(int argc, char** argv) -> int { ABT_init(argc, argv); constexpr int kNxstreams = 2; constexpr int kNthreads = 8; std::vector<ABT_xstream> xstreams{kNxstreams}; std::vector<ABT_pool> pools{xstreams.size()}; std::vector<ABT_thread> threads{kNthreads}; std::vector<thread_arg_t> thread_args{threads.size()}; size_t i; // get primary ES ABT_xstream_self(&xstreams[0]); // create seconday ESs for (auto& xstream : xstreams | ranges::views::drop(1)) { ABT_xstream_create(ABT_SCHED_NULL, &xstream); } // get default pools i = 0; for (auto& xstream : xstreams) { ABT_xstream_get_main_pools(xstream, 1, &pools[i]); ++i; } // create ULTs i = 0; for (auto& thread : threads) { size_t pool_id = i % xstreams.size(); thread_args[i].tid = i; ABT_thread_create(pools[pool_id], helloWorld, &thread_args[i], ABT_THREAD_ATTR_NULL, &thread); ++i; } // Join and free ULTs. for (auto& thread : threads) { ABT_thread_free(&thread); } // Join and free secondary execution streams. for (auto& xstream : xstreams) { ABT_xstream_join(xstream); ABT_xstream_free(&xstream); } ABT_finalize(); return 0; }
22.708333
69
0.654434
range3
8ed4682c74d4d5c39226e7bcaa727f5608a305af
3,225
hpp
C++
signal_logger_std/include/signal_logger_std/LogElementStd.hpp
mcx/signal_logger
7d209bb42ae563fe78175f4b52a8f5c648984a39
[ "BSD-3-Clause" ]
null
null
null
signal_logger_std/include/signal_logger_std/LogElementStd.hpp
mcx/signal_logger
7d209bb42ae563fe78175f4b52a8f5c648984a39
[ "BSD-3-Clause" ]
4
2019-07-09T08:49:38.000Z
2021-09-13T11:26:02.000Z
signal_logger_std/include/signal_logger_std/LogElementStd.hpp
mcx/signal_logger
7d209bb42ae563fe78175f4b52a8f5c648984a39
[ "BSD-3-Clause" ]
3
2020-05-28T08:50:03.000Z
2022-03-27T12:54:55.000Z
/*! * @file LogElementStd.hpp * @author Gabriel Hottiger * @date Sep 22, 2016 * @brief Implementation of a Log element for std logging. Save data to binary file. */ #pragma once // Signal logger #include "signal_logger_core/LogElementBase.hpp" #include "signal_logger_std/signal_logger_std_traits.hpp" // STL #include <fstream> #include <unordered_set> namespace signal_logger_std { template <typename ValueType_> class LogElementStd: public signal_logger::LogElementBase<ValueType_> { public: /** Constructor * @param ptr pointer to the log var * @param bufferType buffer type of the log var * @param bufferSize buffer size of the log var * @param name name of the log var * @param unit unit of the log var * @param divider log_freq = ctrl_freq/divider * @param action save, publish or save and publish * @param textStream string stream for text part of the log file * @param binaryStream string stream for binary part of the log file */ LogElementStd(const ValueType_ * const ptr, const signal_logger::BufferType bufferType, const std::size_t bufferSize, const std::string & name, const std::string & unit, const std::size_t divider, const signal_logger::LogElementAction action, std::stringstream * textStream, std::stringstream * binaryStream) : signal_logger::LogElementBase<ValueType_>(ptr, bufferType, bufferSize, name, unit, divider, action), textStream_(textStream), binaryStream_(binaryStream) { } //! Destructor virtual ~LogElementStd() { } //! Save Data to file void saveDataToLogFile(const signal_logger::TimeElement & times, unsigned int nrCollectDataCalls, signal_logger::LogFileType type) override { // Lock the copy mutex std::unique_lock<std::mutex> lock(this->mutexCopy_); if(this->bufferCopy_.noTotalItems() > 0 ) { unsigned int startDiff = 0; unsigned int endDiff = (nrCollectDataCalls - 1) % this->optionsCopy_.getDivider(); if( type == signal_logger::LogFileType::CSV ) { if(this->bufferCopy_.getBufferType() == signal_logger::BufferType::LOOPING) { /* Last index of time: (times.size() - 1) * Index of newest time corresponding to a data point: (nrCollectDataCalls - 1) % this->dividerCopy_ * Offset of oldest time that corresponds to a data point: (this->bufferCopy_.size()-1) * this->dividerCopy_ */ startDiff = (times.getTimeBufferCopy().noTotalItems() - 1) - endDiff - (this->bufferCopy_.noTotalItems()-1) * this->optionsCopy_.getDivider(); } } // Write to fill signal_logger_std::traits::sls_traits<ValueType_, ValueType_>::writeLogElementToStreams( textStream_, binaryStream_, type, this->bufferCopy_, this->optionsCopy_.getName(), this->optionsCopy_.getDivider(), startDiff, endDiff); } } protected: //! Text stream std::stringstream* textStream_; //! Binary stream std::stringstream* binaryStream_; }; } /* namespace signal_logger */
34.677419
152
0.656434
mcx
8ed662912286c535204cac69650dd1c405d9c916
532
cpp
C++
src/cuda-kernels/identities.cpp
nikoladze/awkward-1.0
7e1001b6ee59f1cba96cf57d144e7f2719f07e69
[ "BSD-3-Clause" ]
null
null
null
src/cuda-kernels/identities.cpp
nikoladze/awkward-1.0
7e1001b6ee59f1cba96cf57d144e7f2719f07e69
[ "BSD-3-Clause" ]
null
null
null
src/cuda-kernels/identities.cpp
nikoladze/awkward-1.0
7e1001b6ee59f1cba96cf57d144e7f2719f07e69
[ "BSD-3-Clause" ]
null
null
null
#include "awkward/cuda-kernels/identities.h" template <typename T> ERROR awkward_cuda_new_identities( T *toptr, int64_t length) { for (T i = 0; i < length; i++) { toptr[i] = i; } return success(); } ERROR awkward_cuda_new_identities32( int32_t *toptr, int64_t length) { return awkward_cuda_new_identities<int32_t>( toptr, length); } ERROR awkward_cuda_new_identities64( int64_t *toptr, int64_t length) { return awkward_cuda_new_identities<int64_t>( toptr, length); }
17.733333
46
0.672932
nikoladze
8ed6787cacf0aa586551ffd376e38b8c12137bc9
2,899
hxx
C++
include/itkSegmentationVolumeEstimator.hxx
mseng10/LesionSizingToolkit
407b7eb14dfa8f824383d1a93f3b2177d6466e18
[ "Apache-2.0" ]
null
null
null
include/itkSegmentationVolumeEstimator.hxx
mseng10/LesionSizingToolkit
407b7eb14dfa8f824383d1a93f3b2177d6466e18
[ "Apache-2.0" ]
null
null
null
include/itkSegmentationVolumeEstimator.hxx
mseng10/LesionSizingToolkit
407b7eb14dfa8f824383d1a93f3b2177d6466e18
[ "Apache-2.0" ]
null
null
null
/*========================================================================= * * Copyright NumFOCUS * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkSegmentationVolumeEstimator_hxx #define itkSegmentationVolumeEstimator_hxx #include "itkSegmentationVolumeEstimator.h" #include "itkImageSpatialObject.h" #include "itkImageRegionIterator.h" namespace itk { /** * Constructor */ template <unsigned int NDimension> SegmentationVolumeEstimator<NDimension>::SegmentationVolumeEstimator() { this->SetNumberOfRequiredInputs(1); // for the segmentation Spatial Object this->SetNumberOfRequiredOutputs(1); // for the Volume RealObjectType::Pointer output = RealObjectType::New(); this->ProcessObject::SetNthOutput(0, output.GetPointer()); } /** * Destructor */ template <unsigned int NDimension> SegmentationVolumeEstimator<NDimension>::~SegmentationVolumeEstimator() = default; /** * Return the value of the estimated volume */ template <unsigned int NDimension> typename SegmentationVolumeEstimator<NDimension>::RealType SegmentationVolumeEstimator<NDimension>::GetVolume() const { return this->GetVolumeOutput()->Get(); } /** * Return the value of the estimated volume stored in a DataObject decorator * that can be passed down a pipeline. */ template <unsigned int NDimension> const typename SegmentationVolumeEstimator<NDimension>::RealObjectType * SegmentationVolumeEstimator<NDimension>::GetVolumeOutput() const { return static_cast<const RealObjectType *>(this->ProcessObject::GetOutput(0)); } /** * Set the input SpatialObject representing the segmentation whose volume will * be estimated by this class. */ template <unsigned int NDimension> void SegmentationVolumeEstimator<NDimension>::SetInput(const SpatialObjectType * inputSpatialObject) { this->SetNthInput(0, const_cast<SpatialObjectType *>(inputSpatialObject)); } /** * PrintSelf */ template <unsigned int NDimension> void SegmentationVolumeEstimator<NDimension>::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); } /* * Generate Data */ template <unsigned int NDimension> void SegmentationVolumeEstimator<NDimension>::GenerateData() { // This method is intended to be overridden by derived classes } } // end namespace itk #endif
26.59633
95
0.726457
mseng10
8ed742b2a725aaeabaca5df0f7478ca02b000376
539
cpp
C++
bzoj/5104.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
3
2017-09-17T09:12:50.000Z
2018-04-06T01:18:17.000Z
bzoj/5104.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
bzoj/5104.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
#include <bits/stdc++.h> #define N 100020 #define ll long long using namespace std; inline int read(){ int x=0,f=1;char ch=getchar(); while(ch>'9'||ch<'0')ch=='-'&&(f=0)||(ch=getchar()); while(ch<='9'&&ch>='0')x=(x<<3)+(x<<1)+ch-'0',ch=getchar(); return f?x:-x; } int main(int argc, char const *argv[]) { int a = 1, b = 1; int x = read(); if (x == 1) return puts("1")&0; for (int p = 3; p; p++) { int c = a + b; if (c >= 1000000009) c -= 1000000009; if (c == x) return printf("%d\n", p)&0; a = b; b = c; } return 0; }
23.434783
60
0.528757
swwind
8eded0dc91a769c24e5a7ed1dcde2e36e19577ad
1,974
hpp
C++
examples/mechanics/RockingBlock/src/RockingR.hpp
vacary/siconos-tutorials
93c0158321077a313692ed52fed69ff3c256ae32
[ "Apache-2.0" ]
6
2017-01-12T23:09:28.000Z
2021-03-20T17:03:58.000Z
examples/mechanics/RockingBlock/src/RockingR.hpp
vacary/siconos-tutorials
93c0158321077a313692ed52fed69ff3c256ae32
[ "Apache-2.0" ]
3
2019-01-14T13:44:51.000Z
2021-05-17T13:57:27.000Z
examples/mechanics/RockingBlock/src/RockingR.hpp
vacary/siconos-tutorials
93c0158321077a313692ed52fed69ff3c256ae32
[ "Apache-2.0" ]
2
2019-10-22T13:30:39.000Z
2020-10-06T10:19:57.000Z
#ifndef ROCKING_R_HPP #define ROCKING_R_HPP #include "LagrangianScleronomousR.hpp" class RockingBlockR : public LagrangianScleronomousR { public: double LengthBlock = 0.2; double HeightBlock = 0.1; void computeh(const BlockVector& q, BlockVector& z, SiconosVector& y) { double q1 = q.getValue(1); double q2 = q.getValue(2); y.setValue(0, q1 - 0.5 * LengthBlock * sin(q2) - 0.5 * HeightBlock * cos(q2)); } void computeJachq(const BlockVector& q, BlockVector& z) { double q2 = q.getValue(2); _jachq->setValue(0, 0, 0.0); _jachq->setValue(0, 1, 1.0); _jachq->setValue(0, 2, -0.5 * LengthBlock * cos(q2) + 0.5 * HeightBlock * sin(q2)); } void computeDotJachq(const BlockVector& q, BlockVector& z, const BlockVector& qdot) { double q2 = q.getValue(2); double qdot2 = qdot.getValue(2); _dotjachq->setValue(0, 0, 0.0); _dotjachq->setValue(0, 1, 0.0); _dotjachq->setValue(0, 2, (0.5 * LengthBlock * sin(q2) + 0.5 * HeightBlock * cos(q2)) * qdot2); } }; class RockingBlockR2 : public LagrangianScleronomousR { public: double LengthBlock = 0.2; double HeightBlock = 0.1; void computeh(const BlockVector& q, BlockVector& z, SiconosVector& y) { double q1 = q.getValue(1); double q2 = q.getValue(2); y.setValue(0, q1 + 0.5 * LengthBlock * sin(q2) - 0.5 * HeightBlock * cos(q2)); } void computeJachq(const BlockVector& q, BlockVector& z) { double q2 = q.getValue(2); _jachq->setValue(0, 0, 0.0); _jachq->setValue(0, 1, 1.0); _jachq->setValue(0, 2, 0.5 * LengthBlock * cos(q2) + 0.5 * HeightBlock * sin(q2)); } void computeDotJachq(const BlockVector& q, BlockVector& z, const BlockVector& qdot) { double q2 = q.getValue(2); double qdot2 = qdot.getValue(2); _dotjachq->setValue(0, 0, 0.0); _dotjachq->setValue(0, 1, 0.0); _dotjachq->setValue(0, 2, (-0.5 * LengthBlock * sin(q2) + 0.5 * HeightBlock * cos(q2)) * qdot2); } }; #endif
25.973684
100
0.639818
vacary
8ee459f7963a2eef725bd4b1b9102b9fbb011d33
984
hpp
C++
include/geometry/serialization/point_set_serialization.hpp
qaskai/MLCMST
0fa0529347eb6a44f45cf52dff477291c6fad433
[ "MIT" ]
null
null
null
include/geometry/serialization/point_set_serialization.hpp
qaskai/MLCMST
0fa0529347eb6a44f45cf52dff477291c6fad433
[ "MIT" ]
null
null
null
include/geometry/serialization/point_set_serialization.hpp
qaskai/MLCMST
0fa0529347eb6a44f45cf52dff477291c6fad433
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <memory> #include <geometry/serialization/point_serialization.hpp> #include <serializer.hpp> #include <deserializer.hpp> namespace MLCMST::geometry::serialization { class PointSetSerializer final : public Serializer< std::vector<Point> > { public: PointSetSerializer(); PointSetSerializer(std::shared_ptr< Serializer<Point> > point_serializer); ~PointSetSerializer() override; void serialize(const std::vector<Point>& points, std::ostream& stream) override; private: std::shared_ptr< Serializer<Point> > _point_serializer; }; class PointSetDeserializer final : public Deserializer< std::vector<Point> > { public: PointSetDeserializer(); PointSetDeserializer(std::shared_ptr< Deserializer<Point> > point_deserializer); ~PointSetDeserializer() override; std::vector<Point> deserialize(std::istream& stream) override; private: std::shared_ptr< Deserializer<Point> > _point_deserializer; }; }
22.363636
84
0.748984
qaskai
8ee56b3553ff5b363d713e64adfb0ec99cf1a37d
10,991
cpp
C++
Flight_controller/HEAR_nodelet/trajectory_node.cpp
AhmedHumais/HEAR_FC
2e9abd990757f8b14711aa4f02f5ad85698da6fe
[ "Unlicense" ]
null
null
null
Flight_controller/HEAR_nodelet/trajectory_node.cpp
AhmedHumais/HEAR_FC
2e9abd990757f8b14711aa4f02f5ad85698da6fe
[ "Unlicense" ]
null
null
null
Flight_controller/HEAR_nodelet/trajectory_node.cpp
AhmedHumais/HEAR_FC
2e9abd990757f8b14711aa4f02f5ad85698da6fe
[ "Unlicense" ]
null
null
null
#include <ros/ros.h> #include <std_srvs/SetBool.h> #include <hear_msgs/set_float.h> #include <hear_msgs/set_bool.h> #include <std_msgs/Float32.h> #include <geometry_msgs/Point.h> #include <std_srvs/Empty.h> #include <tf2/LinearMath/Matrix3x3.h> #include <fstream> #include <sstream> #include <string> #include <vector> const std::string dir_name = "/home/pi/Waypoints/"; const float TAKE_OFF_VELOCITY = 0.5; //in m/s const float LAND_VELOCITY = 0.75; // in m/s const std::string file_path_x = dir_name + "waypoints_x.csv"; const std::string file_path_y = dir_name + "waypoints_y.csv"; const std::string file_path_z = dir_name + "waypoints_z.csv"; const std::string file_path_vel_x = dir_name + "waypoints_vel_x.csv"; const std::string file_path_vel_y = dir_name + "waypoints_vel_y.csv"; const std::string file_path_acc_x = dir_name + "waypoints_acc_x.csv"; const std::string file_path_acc_y = dir_name + "waypoints_acc_y.csv"; bool start_traj = false; bool take_off_flag = false; bool land_flag = false; bool send_curr_pos_opti = false; bool send_curr_pos_slam = false; bool on_opti = true; float take_off_height = 1.0; float land_height = -0.1; geometry_msgs::Point current_pos_opti; geometry_msgs::Point current_pos_slam; std_msgs::Float32 current_yaw; ros::ServiceClient height_offset_client; bool read_file(std::string fileName, std::vector<float>& vec){ std::ifstream ifs(fileName); if(ifs.is_open()){ std::string line; while(std::getline(ifs, line)){ vec.push_back(std::stof(line)); } return true; } return false; } void opti_pos_Cb(const geometry_msgs::Point::ConstPtr& msg){ current_pos_opti = *msg; } void slam_pos_Cb(const geometry_msgs::Point::ConstPtr& msg){ current_pos_slam = *msg; } void yaw_Cb(const geometry_msgs::Point::ConstPtr& msg){ current_yaw.data = msg->x; } bool height_Cb(std_srvs::Empty::Request& req, std_srvs::Empty::Response& res){ hear_msgs::set_float t_srv; t_srv.request.data = current_pos_opti.z; height_offset_client.call(t_srv); ROS_INFO("height offset called"); return true; } bool take_off_Cb(hear_msgs::set_float::Request& req, hear_msgs::set_float::Response& res){ take_off_height = req.data; ROS_INFO("take off called"); take_off_flag = true; return true; } bool land_Cb(hear_msgs::set_float::Request& req, hear_msgs::set_float::Response& res){ land_height = req.data; ROS_INFO("land called"); land_flag = true; return true; } bool send_curr_pos_opti_Cb(std_srvs::Empty::Request& req, std_srvs::Empty::Response& res){ send_curr_pos_opti = true; on_opti = true; ROS_INFO("sending curr opti position as reference"); return true; } bool send_curr_pos_slam_Cb(std_srvs::Empty::Request& req, std_srvs::Empty::Response& res){ send_curr_pos_slam = true; on_opti = false; ROS_INFO("sending curr slam position as reference"); return true; } bool srvCallback(hear_msgs::set_bool::Request& req, hear_msgs::set_bool::Response& res){ start_traj = req.data; ROS_INFO("start trajectory called"); return true; } int main(int argc, char **argv){ ros::init(argc, argv, "trajectory_node"); ros::NodeHandle nh; ros::Rate rt = 100; ros::ServiceServer srv = nh.advertiseService("start_trajectory", &srvCallback); ros::ServiceServer takeOff_srv = nh.advertiseService("take_off", &take_off_Cb); ros::ServiceServer land_srv = nh.advertiseService("land", &land_Cb); ros::ServiceServer height_offset_srv = nh.advertiseService("init_height", &height_Cb); ros::ServiceServer send_curr_pos_opti_srv = nh.advertiseService("send_curr_pos_opti", &send_curr_pos_opti_Cb); ros::ServiceServer send_curr_pos_slam_srv = nh.advertiseService("send_curr_pos_slam", &send_curr_pos_slam_Cb); height_offset_client = nh.serviceClient<hear_msgs::set_float>("set_height_offset"); ros::Subscriber pos_opti_sub = nh.subscribe<geometry_msgs::Point>("/opti/pos", 10, &opti_pos_Cb); ros::Subscriber pos_slam_sub = nh.subscribe<geometry_msgs::Point>("/slam/pos", 10, &slam_pos_Cb); ros::Subscriber yaw_sub = nh.subscribe<geometry_msgs::Point>("/providers/yaw", 10, &yaw_Cb); ros::Publisher pub_waypoint_pos = nh.advertise<geometry_msgs::Point>("/waypoint_reference/pos", 10); ros::Publisher pub_waypoint_yaw = nh.advertise<std_msgs::Float32>("/waypoint_reference/yaw", 10); ros::Publisher pub_waypoint_vel = nh.advertise<geometry_msgs::Point>("/waypoint_reference/vel", 10); ros::Publisher pub_waypoint_acc = nh.advertise<geometry_msgs::Point>("/waypoint_reference/acc", 10); std::vector<float> wp_x, wp_y, wp_z, wp_vel_x, wp_vel_y, wp_acc_x, wp_acc_y; bool en_wp_x, en_wp_y, en_wp_z, en_wp_vel_x, en_wp_vel_y, en_wp_acc_x, en_wp_acc_y; if(!(read_file(file_path_x, wp_x))){ ROS_WARN("Could not read file for x waypoints.\n ...Disabling trajectory for x channel"); en_wp_x = false; }else{ en_wp_x = true; } if(!(read_file(file_path_y, wp_y))){ ROS_WARN("Could not read file for y waypoints.\n ...Disabling trajectory for y channel"); en_wp_y = false; }else{ en_wp_y = true; } if(!(read_file(file_path_z, wp_z))){ ROS_WARN("Could not read file for z waypoints.\n ...Disabling trajectory for z channel"); en_wp_z = false; }else{ en_wp_z = true; } if(!(read_file(file_path_vel_x, wp_vel_x))){ ROS_WARN("Could not read file for vel_x waypoints.\n ...Disabling velocity reference for x channel"); en_wp_vel_x = false; }else{ en_wp_vel_x = true; } if(!(read_file(file_path_vel_y, wp_vel_y))){ ROS_WARN("Could not read file for vel_y waypoints.\n ...Disabling velocity reference for y channel"); en_wp_vel_y = false; }else{ en_wp_vel_y = true; } if(!(read_file(file_path_acc_x, wp_acc_x))){ ROS_WARN("Could not read file for acc_x waypoints.\n ...Disabling acceleration reference for x channel"); en_wp_acc_x = false; }else{ en_wp_acc_x = true; } if(!(read_file(file_path_acc_y, wp_acc_y))){ ROS_WARN("Could not read file for acc_y waypoints.\n ...Disabling acceleration reference for y channel"); en_wp_acc_y = false; }else{ en_wp_acc_y = true; } int i = 0; int sz_x = wp_x.size(), sz_y = wp_y.size(), sz_z = wp_z.size(); if(en_wp_vel_x){ if(wp_vel_x.size() != sz_x){ ROS_ERROR("Size of velocity reference vector is not equal to position reference"); return 1; } } if(en_wp_vel_y){ if(wp_vel_y.size() != sz_y){ ROS_ERROR("Size of velocity reference vector is not equal to position reference"); return 1; } } if(en_wp_acc_x){ if(wp_acc_x.size() != sz_x){ ROS_ERROR("Size of acceleration reference vector is not equal to position reference"); return 1; } } if(en_wp_acc_y){ if(wp_acc_y.size() != sz_y){ ROS_ERROR("Size of acceleration reference vector is not equal to position reference"); return 1; } } geometry_msgs::Point wp_pos_msg, wp_vel_msg, wp_acc_msg, offset_pos; float z_ref = 0.0; bool take_off_started = false; bool land_started = false; bool trajectory_finished = false, trajectory_started = false; while(ros::ok()){ if(send_curr_pos_opti){ send_curr_pos_opti = false; wp_pos_msg = current_pos_opti; pub_waypoint_pos.publish(wp_pos_msg); } if(send_curr_pos_slam){ send_curr_pos_slam = false; wp_pos_msg = current_pos_slam; pub_waypoint_pos.publish(wp_pos_msg); } if(land_flag){ if(!land_started){ ROS_INFO("land started"); land_started = true; wp_pos_msg.x = current_pos_opti.x; wp_pos_msg.y = current_pos_opti.y; z_ref = current_pos_opti.z - 0.1; pub_waypoint_pos.publish(wp_pos_msg); } z_ref -= (rt.expectedCycleTime()).toSec()*LAND_VELOCITY; if(z_ref <= land_height){ land_flag = false; land_started = false; ROS_INFO("land finished"); }else{ wp_pos_msg.z = z_ref; pub_waypoint_pos.publish(wp_pos_msg); } } else if(take_off_flag){ if(!take_off_started){ ROS_INFO("take off started"); take_off_started = true; wp_pos_msg.x = current_pos_opti.x; wp_pos_msg.y = current_pos_opti.y; z_ref = current_pos_opti.z + 0.1; pub_waypoint_pos.publish(wp_pos_msg); pub_waypoint_yaw.publish(current_yaw); } z_ref += (rt.expectedCycleTime()).toSec()*TAKE_OFF_VELOCITY; if(z_ref >= take_off_height){ take_off_flag = false; take_off_started = false; ROS_INFO("take off finished"); } else{ wp_pos_msg.z = z_ref; pub_waypoint_pos.publish(wp_pos_msg); } } else if(start_traj){ trajectory_finished = true; if(!trajectory_started){ ROS_INFO("Trajectory Started"); trajectory_started = true; if(on_opti){ offset_pos = current_pos_opti; }else { offset_pos = current_pos_slam; } } if(i < sz_x && en_wp_x){ wp_pos_msg.x = wp_x[i] + offset_pos.x; if(en_wp_vel_x){ wp_vel_msg.x = wp_vel_x[i]; } if(en_wp_acc_x){ wp_acc_msg.x = wp_acc_x[i]; } trajectory_finished = false; } if(i < sz_y && en_wp_y){ wp_pos_msg.y = wp_y[i] + offset_pos.y; if(en_wp_vel_y){ wp_vel_msg.y = wp_vel_y[i]; } if(en_wp_acc_y){ wp_acc_msg.y = wp_acc_y[i]; } trajectory_finished = false; } if(i < sz_z && en_wp_z){ wp_pos_msg.z = wp_z[i]; trajectory_finished = false; } if(trajectory_finished){ ROS_INFO("Trajectory finished"); start_traj = false; trajectory_started = false; i = 0; } else { pub_waypoint_pos.publish(wp_pos_msg); pub_waypoint_vel.publish(wp_vel_msg); pub_waypoint_acc.publish(wp_acc_msg); i++; } } rt.sleep(); ros::spinOnce(); } }
36.036066
114
0.61514
AhmedHumais
8ee8651d0747e061eb611630311ed8e0ead513f9
718
hpp
C++
src/analyzer/SatStaticAnalyzer.hpp
aristk/static-analyser
6e3973b79c1e9bd6c9e7281ba9a9c75b348e42c6
[ "MIT" ]
1
2018-08-25T07:11:59.000Z
2018-08-25T07:11:59.000Z
src/analyzer/SatStaticAnalyzer.hpp
aristk/static-analyser
6e3973b79c1e9bd6c9e7281ba9a9c75b348e42c6
[ "MIT" ]
null
null
null
src/analyzer/SatStaticAnalyzer.hpp
aristk/static-analyser
6e3973b79c1e9bd6c9e7281ba9a9c75b348e42c6
[ "MIT" ]
null
null
null
// // Created by arist on 19/11/2016. // #include "incSatAnalyzer.hpp" #ifndef STATICANALYZERROOT_SATSTATICANALYZER_HPP #define STATICANALYZERROOT_SATSTATICANALYZER_HPP // TODO(arist): inheritance should be reverse class SatStaticAnalyzer : public IncrementalSatStaticAnalyzer { // key + operator name + position in the file vector<tuple<FullVariableNameOccurrence, string, int> > variablesToCheck; public: SatStaticAnalyzer(): IncrementalSatStaticAnalyzer(), variablesToCheck() { } void updateAnswers(const string &opName, FullVariableName &keyLhs, const NIdentifier &lhs) override; vector<pair<int, unsigned int> > getAnswers() override; }; #endif //STATICANALYZERROOT_SATSTATICANALYZER_HPP
32.636364
104
0.78273
aristk
8eeaa453dfee7eb78ccbc6267bd696e73e1e496b
1,542
cpp
C++
src/QGCQmlWidgetHolder.cpp
DonLakeFlyer/PDCDogDatabase
23700d16f21005b84738887d98c6c9c368b9eb6f
[ "Apache-2.0" ]
null
null
null
src/QGCQmlWidgetHolder.cpp
DonLakeFlyer/PDCDogDatabase
23700d16f21005b84738887d98c6c9c368b9eb6f
[ "Apache-2.0" ]
null
null
null
src/QGCQmlWidgetHolder.cpp
DonLakeFlyer/PDCDogDatabase
23700d16f21005b84738887d98c6c9c368b9eb6f
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** * * (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> * * QGroundControl is licensed according to the terms in the file * COPYING.md in the root of the source code directory. * ****************************************************************************/ #include "QGCQmlWidgetHolder.h" #include <QQmlContext> #include <QQmlError> QGCQmlWidgetHolder::QGCQmlWidgetHolder(const QString& title, QAction* action, QWidget *parent) : QWidget(parent) { _ui.setupUi(this); layout()->setContentsMargins(0,0,0,0); setResizeMode(QQuickWidget::SizeRootObjectToView); } QGCQmlWidgetHolder::~QGCQmlWidgetHolder() { } bool QGCQmlWidgetHolder::setSource(const QUrl& qmlUrl) { bool success = _ui.qmlWidget->setSource(qmlUrl); for (QQmlError error: _ui.qmlWidget->errors()) { qDebug() << "Error" << error.toString(); } return success; } void QGCQmlWidgetHolder::setContextPropertyObject(const QString& name, QObject* object) { _ui.qmlWidget->rootContext()->setContextProperty(name, object); } QQmlContext* QGCQmlWidgetHolder::getRootContext(void) { return _ui.qmlWidget->rootContext(); } QQuickItem* QGCQmlWidgetHolder::getRootObject(void) { return _ui.qmlWidget->rootObject(); } QQmlEngine* QGCQmlWidgetHolder::getEngine() { return _ui.qmlWidget->engine(); } void QGCQmlWidgetHolder::setResizeMode(QQuickWidget::ResizeMode resizeMode) { _ui.qmlWidget->setResizeMode(resizeMode); }
24.870968
96
0.659533
DonLakeFlyer
8eee3f2db028e9df12a5ffe16c14f15f4cf61b72
2,250
cpp
C++
XGF/Src/Core/Asyn.cpp
kadds/XGF
610c98a93c0f287546f97efc654b95dc846721ad
[ "MIT" ]
5
2017-11-09T05:02:52.000Z
2020-06-23T09:50:25.000Z
XGF/Src/Core/Asyn.cpp
kadds/XGF
610c98a93c0f287546f97efc654b95dc846721ad
[ "MIT" ]
null
null
null
XGF/Src/Core/Asyn.cpp
kadds/XGF
610c98a93c0f287546f97efc654b95dc846721ad
[ "MIT" ]
null
null
null
#include "../../Include/Asyn.hpp" #include <chrono> #include "../../Include/Timer.hpp" #include "../../Include/Logger.hpp" namespace XGF { Asyn::Asyn() { } Asyn::~Asyn() { } void Asyn::PostEvent(EventIdType id, EventGroupType evGroup, std::initializer_list< EventDataType> init) { if (mIsExit) return; mMessageQueue.enqueue(Event(evGroup, id, init)); } EventGroupType GetType(EventIdType t) { if (std::get_if<SystemEventId>(&t) != nullptr) return EventGroupType::System; if (std::get_if<KeyBoardEventId>(&t) != nullptr) return EventGroupType::KeyBoard; if (std::get_if<MouseEventId>(&t) != nullptr) return EventGroupType::Mouse; return EventGroupType::Custom; } void Asyn::PostEvent(EventIdType id, std::initializer_list<EventDataType> init) { PostEvent(id, GetType(id), init); } void Asyn::PostExitEvent() { mIsExit = true; mMessageQueue.enqueue(Event(EventGroupType::System, SystemEventId::Exit, {})); } void Asyn::Wait() { auto m = std::unique_lock<std::mutex>(mutex); mcVariable.wait(m); } void Asyn::Wait(unsigned long long microseconds) { auto m = std::unique_lock<std::mutex>(mutex); mcVariable.wait_for(m, std::chrono::microseconds(microseconds)); } void Asyn::Wait(std::function<bool()> predicate) { auto m = std::unique_lock<std::mutex>(mutex); mcVariable.wait(m, predicate); } void Asyn::Notify() { mcVariable.notify_all(); } void Asyn::DoAsyn(std::function<void(Asyn * asyn)> fun) { mThread = std::make_unique<std::thread>(fun, this); mId = mThread->get_id(); mThread->detach(); } bool Asyn::HandleMessage() { Event ev; Timer timer; float dt = 0; while(mMessageQueue.try_dequeue(ev)) { if (ev.GetEventGroup() == EventGroupType::System && ev.GetSystemEventId() == SystemEventId::Exit) { return true; } else { mHandleCallback(ev); } dt += timer.Tick(); if (dt > 0.001f) { break; //XGF_Info(Framework, "Handle event time is too long ", time * 1000, "ms"); } } return false; } void Asyn::Sleep(unsigned long long microseconds) { auto d = std::chrono::microseconds(microseconds); std::this_thread::sleep_for(d); } std::thread::id Asyn::GetThreadId() const { return mId; } }
21.028037
105
0.662667
kadds
8eef2a200c768a99ab2f01a79ee34ea8cc9e36a4
938
cpp
C++
src/allocateMem.cpp
neilenns/MobiFlight-FirmwareSource
af4d771ab26e8633f338298805e6fe56a855aa85
[ "MIT" ]
2
2022-03-07T08:10:51.000Z
2022-03-08T20:59:45.000Z
src/allocateMem.cpp
Jak-Kav/MobiFlight-FirmwareSource
fb14a2e134d12bbd26b18e15dd1e5fa16063c97a
[ "MIT" ]
13
2021-10-03T07:14:38.000Z
2021-10-14T14:11:42.000Z
src/allocateMem.cpp
Jak-Kav/MobiFlight-FirmwareSource
fb14a2e134d12bbd26b18e15dd1e5fa16063c97a
[ "MIT" ]
1
2021-10-16T15:57:18.000Z
2021-10-16T15:57:18.000Z
#include <Arduino.h> #include "MFBoards.h" #include "mobiflight.h" #include "allocateMem.h" #include "commandmessenger.h" char deviceBuffer[MF_MAX_DEVICEMEM] = {0}; uint16_t nextPointer = 0; char * allocateMemory(uint8_t size) { uint16_t actualPointer = nextPointer; nextPointer = actualPointer + size; if (nextPointer >= MF_MAX_DEVICEMEM) { cmdMessenger.sendCmd(kStatus,F("DeviceBuffer Overflow!")); return nullptr; } #ifdef DEBUG2CMDMESSENGER cmdMessenger.sendCmdStart(kStatus); cmdMessenger.sendCmdArg(F("BufferUsage")); cmdMessenger.sendCmdArg(nextPointer); cmdMessenger.sendCmdEnd(); #endif return &deviceBuffer[actualPointer]; } void ClearMemory() { nextPointer = 0; } uint16_t GetAvailableMemory() { return MF_MAX_DEVICEMEM - nextPointer; } bool FitInMemory(uint8_t size) { if (nextPointer + size > MF_MAX_DEVICEMEM) return false; return true; }
22.878049
66
0.712154
neilenns
8ef60df2a1095a38a703f3b4dca398e357701095
240
hpp
C++
levels/rocketball/rocketball.hpp
piotrplaza/MouseSpaceShooter
9aed0c16889b6ce70e725c165bf28307201e81d1
[ "MIT" ]
null
null
null
levels/rocketball/rocketball.hpp
piotrplaza/MouseSpaceShooter
9aed0c16889b6ce70e725c165bf28307201e81d1
[ "MIT" ]
null
null
null
levels/rocketball/rocketball.hpp
piotrplaza/MouseSpaceShooter
9aed0c16889b6ce70e725c165bf28307201e81d1
[ "MIT" ]
1
2020-06-16T10:32:06.000Z
2020-06-16T10:32:06.000Z
#pragma once #include <memory> #include "../level.hpp" namespace Levels { class Rocketball: public Level { public: Rocketball(); ~Rocketball(); void step() override; private: class Impl; std::unique_ptr<Impl> impl; }; }
10.909091
31
0.658333
piotrplaza
8ef969a50a44272e85057ccb0650e7a97df7182d
12,017
cpp
C++
libs/numeric/ublasx/test/trace.cpp
sguazt/boost-ublasx
21c9b393d33a6ec2a8071ba8d48680073d766409
[ "BSL-1.0" ]
7
2016-05-14T11:08:44.000Z
2021-08-05T14:22:20.000Z
libs/numeric/ublasx/test/trace.cpp
sguazt/boost-ublasx
21c9b393d33a6ec2a8071ba8d48680073d766409
[ "BSL-1.0" ]
1
2020-12-28T18:36:04.000Z
2021-01-06T11:28:51.000Z
libs/numeric/ublasx/test/trace.cpp
sguazt/boost-ublasx
21c9b393d33a6ec2a8071ba8d48680073d766409
[ "BSL-1.0" ]
1
2019-12-23T02:53:27.000Z
2019-12-23T02:53:27.000Z
/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */ /** * \file libs/numeric/ublasx/test/trace.cpp * * \brief Test suite for the \c trace operation. * * \author Marco Guazzone (marco.guazzone@gmail.com) * * <hr/> * * Copyright (c) 2010, Marco Guazzone * * Distributed under the Boost Software License, Version 1.0. (See * accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ #include <boost/numeric/ublas/fwd.hpp> #include <boost/numeric/ublas/io.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublasx/detail/debug.hpp> #include <boost/numeric/ublasx/operation/trace.hpp> #include <complex> #include <cstddef> #include "libs/numeric/ublasx/test/utils.hpp" namespace ublas = boost::numeric::ublas; namespace ublasx = boost::numeric::ublasx; const double tol = 1.0e-5; BOOST_UBLASX_TEST_DEF( real_square_col_major ) { BOOST_UBLASX_DEBUG_TRACE("Test Case: Real Type - Square Matrix - Column-Major"); typedef double value_type; typedef ublas::matrix<value_type,ublas::column_major> matrix_type; const std::size_t n = 3; matrix_type A(n,n); A(0,0) = 1; A(0,1) = 2; A(0,2) = 3; A(1,0) = 4; A(1,1) = 5; A(1,2) = 6; A(2,0) = 7; A(2,1) = 8; A(2,2) = 9; value_type expect_tr = A(0,0)+A(1,1)+A(2,2); value_type tr = ublasx::trace(A); BOOST_UBLASX_DEBUG_TRACE( "A = " << A ); BOOST_UBLASX_DEBUG_TRACE( "tr(A) = " << tr ); BOOST_UBLASX_TEST_CHECK_CLOSE( tr, expect_tr, tol ); } BOOST_UBLASX_TEST_DEF( real_square_row_major ) { BOOST_UBLASX_DEBUG_TRACE("Test Case: Real Type - Square Matrix - Row-Major"); typedef double value_type; typedef ublas::matrix<value_type,ublas::row_major> matrix_type; const std::size_t n = 3; matrix_type A(n,n); A(0,0) = 1; A(0,1) = 2; A(0,2) = 3; A(1,0) = 4; A(1,1) = 5; A(1,2) = 6; A(2,0) = 7; A(2,1) = 8; A(2,2) = 9; value_type expect_tr = A(0,0)+A(1,1)+A(2,2); value_type tr = ublasx::trace(A); BOOST_UBLASX_DEBUG_TRACE( "A = " << A ); BOOST_UBLASX_DEBUG_TRACE( "tr(A) = " << tr ); BOOST_UBLASX_TEST_CHECK_CLOSE( tr, expect_tr, tol ); } BOOST_UBLASX_TEST_DEF( complex_square_col_major ) { BOOST_UBLASX_DEBUG_TRACE("Test Case: Complex Type - Square Matrix - Column-Major"); typedef double real_type; typedef std::complex<real_type> value_type; typedef ublas::matrix<value_type,ublas::column_major> matrix_type; const std::size_t n = 3; matrix_type A(n,n); A(0,0) = value_type(1,-5); A(0,1) = value_type(2, 3); A(0,2) = value_type(3,-9); A(1,0) = value_type(4, 4); A(1,1) = value_type(5,-2); A(1,2) = value_type(6, 8); A(2,0) = value_type(7,-3); A(2,1) = value_type(8, 1); A(2,2) = value_type(9,-7); value_type expect_tr = A(0,0)+A(1,1)+A(2,2); value_type tr = ublasx::trace(A); BOOST_UBLASX_DEBUG_TRACE( "A = " << A ); BOOST_UBLASX_DEBUG_TRACE( "tr(A) = " << tr ); BOOST_UBLASX_TEST_CHECK_CLOSE( tr, expect_tr, tol ); } BOOST_UBLASX_TEST_DEF( complex_square_row_major ) { BOOST_UBLASX_DEBUG_TRACE("Test Case: Complex Type - Square Matrix - Row-Major"); typedef double real_type; typedef std::complex<real_type> value_type; typedef ublas::matrix<value_type,ublas::row_major> matrix_type; const std::size_t n = 3; matrix_type A(n,n); A(0,0) = value_type(1,-5); A(0,1) = value_type(2, 3); A(0,2) = value_type(3,-9); A(1,0) = value_type(4, 4); A(1,1) = value_type(5,-2); A(1,2) = value_type(6, 8); A(2,0) = value_type(7,-3); A(2,1) = value_type(8, 1); A(2,2) = value_type(9,-7); value_type expect_tr = A(0,0)+A(1,1)+A(2,2); value_type tr = ublasx::trace(A); BOOST_UBLASX_DEBUG_TRACE( "A = " << A ); BOOST_UBLASX_DEBUG_TRACE( "tr(A) = " << tr ); BOOST_UBLASX_TEST_CHECK_CLOSE( tr, expect_tr, tol ); } BOOST_UBLASX_TEST_DEF( real_recth_col_major ) { BOOST_UBLASX_DEBUG_TRACE("Test Case: Real Type - Rectangular Horizontal Matrix - Column-Major"); typedef double value_type; typedef ublas::matrix<value_type,ublas::column_major> matrix_type; const std::size_t n = 3; const std::size_t m = 5; matrix_type A(n,m); A(0,0) = 1; A(0,1) = 2; A(0,2) = 3; A(0,3) = 4; A(0,4) = 5; A(1,0) = 6; A(1,1) = 7; A(1,2) = 8; A(1,3) = 9; A(1,4) = 10; A(2,0) = 11; A(2,1) = 12; A(2,2) = 13; A(2,3) = 14; A(2,4) = 15; value_type expect_tr = A(0,0)+A(1,1)+A(2,2); value_type tr = ublasx::trace(A); BOOST_UBLASX_DEBUG_TRACE( "A = " << A ); BOOST_UBLASX_DEBUG_TRACE( "tr(A) = " << tr ); BOOST_UBLASX_TEST_CHECK_CLOSE( tr, expect_tr, tol ); } BOOST_UBLASX_TEST_DEF( real_recth_row_major ) { BOOST_UBLASX_DEBUG_TRACE("Test Case: Real Type - Rectangular Horizontal Matrix - Row-Major"); typedef double value_type; typedef ublas::matrix<value_type,ublas::row_major> matrix_type; const std::size_t n = 3; const std::size_t m = 5; matrix_type A(n,m); A(0,0) = 1; A(0,1) = 2; A(0,2) = 3; A(0,3) = 4; A(0,4) = 5; A(1,0) = 6; A(1,1) = 7; A(1,2) = 8; A(1,3) = 9; A(1,4) = 10; A(2,0) = 11; A(2,1) = 12; A(2,2) = 13; A(2,3) = 14; A(2,4) = 15; value_type expect_tr = A(0,0)+A(1,1)+A(2,2); value_type tr = ublasx::trace(A); BOOST_UBLASX_DEBUG_TRACE( "A = " << A ); BOOST_UBLASX_DEBUG_TRACE( "tr(A) = " << tr ); BOOST_UBLASX_TEST_CHECK_CLOSE( tr, expect_tr, tol ); } BOOST_UBLASX_TEST_DEF( complex_recth_col_major ) { BOOST_UBLASX_DEBUG_TRACE("Test Case: Complex Type - Rectangular Horizontal Matrix - Column-Major"); typedef double real_type; typedef std::complex<real_type> value_type; typedef ublas::matrix<value_type,ublas::column_major> matrix_type; const std::size_t n = 3; const std::size_t m = 5; matrix_type A(n,m); A(0,0) = value_type( 1,-11); A(0,1) = value_type( 2, 12); A(0,2) = value_type( 3,-13); A(0,3) = value_type( 4, 14); A(0,4) = value_type( 5, -15); A(1,0) = value_type( 6, 6); A(1,1) = value_type( 7,- 7); A(1,2) = value_type( 8, 8); A(1,3) = value_type( 9,- 9); A(1,4) = value_type(10, 10); A(2,0) = value_type(11,- 1); A(2,1) = value_type(12, 2); A(2,2) = value_type(13,- 3); A(2,3) = value_type(14, 4); A(2,4) = value_type(15, - 5); value_type expect_tr = A(0,0)+A(1,1)+A(2,2); value_type tr = ublasx::trace(A); BOOST_UBLASX_DEBUG_TRACE( "A = " << A ); BOOST_UBLASX_DEBUG_TRACE( "tr(A) = " << tr ); BOOST_UBLASX_TEST_CHECK_CLOSE( tr, expect_tr, tol ); } BOOST_UBLASX_TEST_DEF( complex_recth_row_major ) { BOOST_UBLASX_DEBUG_TRACE("Test Case: Complex Type - Rectangular Horizontal Matrix - Row-Major"); typedef double real_type; typedef std::complex<real_type> value_type; typedef ublas::matrix<value_type,ublas::row_major> matrix_type; const std::size_t n = 3; const std::size_t m = 5; matrix_type A(n,m); A(0,0) = value_type( 1,-11); A(0,1) = value_type( 2, 12); A(0,2) = value_type( 3,-13); A(0,3) = value_type( 4, 14); A(0,4) = value_type( 5,-15); A(1,0) = value_type( 6, 6); A(1,1) = value_type( 7,- 7); A(1,2) = value_type( 8, 8); A(1,3) = value_type( 9,- 9); A(1,4) = value_type(10, 10); A(2,0) = value_type(11,- 1); A(2,1) = value_type(12, 2); A(2,2) = value_type(13,- 3); A(2,3) = value_type(14, 4); A(2,4) = value_type(15,- 5); value_type expect_tr = A(0,0)+A(1,1)+A(2,2); value_type tr = ublasx::trace(A); BOOST_UBLASX_DEBUG_TRACE( "A = " << A ); BOOST_UBLASX_DEBUG_TRACE( "tr(A) = " << tr ); BOOST_UBLASX_TEST_CHECK_CLOSE( tr, expect_tr, tol ); } BOOST_UBLASX_TEST_DEF( real_rectv_col_major ) { BOOST_UBLASX_DEBUG_TRACE("Test Case: Real Type - Rectangular Vertical Matrix - Column-Major"); typedef double value_type; typedef ublas::matrix<value_type,ublas::column_major> matrix_type; const std::size_t n = 5; const std::size_t m = 3; matrix_type A(n,m); A(0,0) = 1; A(0,1) = 2; A(0,2) = 3; A(1,0) = 4; A(1,1) = 5; A(1,2) = 6; A(2,0) = 7; A(2,1) = 8; A(2,2) = 9; A(3,0) = 10; A(3,1) = 11; A(3,2) = 12; A(4,0) = 13; A(4,1) = 14; A(4,2) = 15; value_type expect_tr = A(0,0)+A(1,1)+A(2,2); value_type tr = ublasx::trace(A); BOOST_UBLASX_DEBUG_TRACE( "A = " << A ); BOOST_UBLASX_DEBUG_TRACE( "tr(A) = " << tr ); BOOST_UBLASX_TEST_CHECK_CLOSE( tr, expect_tr, tol ); } BOOST_UBLASX_TEST_DEF( real_rectv_row_major ) { BOOST_UBLASX_DEBUG_TRACE("Test Case: Real Type - Rectangular Vertical Matrix - Row-Major"); typedef double value_type; typedef ublas::matrix<value_type,ublas::row_major> matrix_type; const std::size_t n = 5; const std::size_t m = 3; matrix_type A(n,m); A(0,0) = 1; A(0,1) = 2; A(0,2) = 3; A(1,0) = 4; A(1,1) = 5; A(1,2) = 6; A(2,0) = 7; A(2,1) = 8; A(2,2) = 9; A(3,0) = 10; A(3,1) = 11; A(3,2) = 12; A(4,0) = 13; A(4,1) = 14; A(4,2) = 15; value_type expect_tr = A(0,0)+A(1,1)+A(2,2); value_type tr = ublasx::trace(A); BOOST_UBLASX_DEBUG_TRACE( "A = " << A ); BOOST_UBLASX_DEBUG_TRACE( "tr(A) = " << tr ); BOOST_UBLASX_TEST_CHECK_CLOSE( tr, expect_tr, tol ); } BOOST_UBLASX_TEST_DEF( complex_rectv_col_major ) { BOOST_UBLASX_DEBUG_TRACE("Test Case: Complex Type - Rectangular Vertical Matrix - Column-Major"); typedef double real_type; typedef std::complex<real_type> value_type; typedef ublas::matrix<value_type,ublas::column_major> matrix_type; const std::size_t n = 5; const std::size_t m = 3; matrix_type A(n,m); A(0,0) = value_type( 1,-13); A(0,1) = value_type( 2, 14); A(0,2) = value_type( 3,-15); A(1,0) = value_type( 4, 10); A(1,1) = value_type( 5,-11); A(1,2) = value_type( 6, 12); A(2,0) = value_type( 7,- 7); A(2,1) = value_type( 8, 8); A(2,2) = value_type( 9,- 9); A(3,0) = value_type(10, 4); A(3,1) = value_type(11,- 5); A(3,2) = value_type(12, 6); A(4,0) = value_type(13,- 1); A(4,1) = value_type(14, 2); A(4,2) = value_type(15, 3); value_type expect_tr = A(0,0)+A(1,1)+A(2,2); value_type tr = ublasx::trace(A); BOOST_UBLASX_DEBUG_TRACE( "A = " << A ); BOOST_UBLASX_DEBUG_TRACE( "tr(A) = " << tr ); BOOST_UBLASX_TEST_CHECK_CLOSE( tr, expect_tr, tol ); } BOOST_UBLASX_TEST_DEF( complex_rectv_row_major ) { BOOST_UBLASX_DEBUG_TRACE("Test Case: Complex Type - Vertical Horizontal Matrix - Row-Major"); typedef double real_type; typedef std::complex<real_type> value_type; typedef ublas::matrix<value_type,ublas::row_major> matrix_type; const std::size_t n = 5; const std::size_t m = 3; matrix_type A(n,m); A(0,0) = value_type( 1,-13); A(0,1) = value_type( 2, 14); A(0,2) = value_type( 3,-15); A(1,0) = value_type( 4, 10); A(1,1) = value_type( 5,-11); A(1,2) = value_type( 6, 12); A(2,0) = value_type( 7,- 7); A(2,1) = value_type( 8, 8); A(2,2) = value_type( 9,- 9); A(3,0) = value_type(10, 4); A(3,1) = value_type(11,- 5); A(3,2) = value_type(12, 6); A(4,0) = value_type(13,- 1); A(4,1) = value_type(14, 2); A(4,2) = value_type(15, 3); value_type expect_tr = A(0,0)+A(1,1)+A(2,2); value_type tr = ublasx::trace(A); BOOST_UBLASX_DEBUG_TRACE( "A = " << A ); BOOST_UBLASX_DEBUG_TRACE( "tr(A) = " << tr ); BOOST_UBLASX_TEST_CHECK_CLOSE( tr, expect_tr, tol ); } int main() { BOOST_UBLASX_TEST_BEGIN(); BOOST_UBLASX_TEST_DO( real_square_col_major ); BOOST_UBLASX_TEST_DO( real_square_row_major ); BOOST_UBLASX_TEST_DO( complex_square_col_major ); BOOST_UBLASX_TEST_DO( complex_square_row_major ); BOOST_UBLASX_TEST_DO( real_recth_col_major ); BOOST_UBLASX_TEST_DO( real_recth_row_major ); BOOST_UBLASX_TEST_DO( complex_recth_col_major ); BOOST_UBLASX_TEST_DO( complex_recth_row_major ); BOOST_UBLASX_TEST_DO( real_rectv_col_major ); BOOST_UBLASX_TEST_DO( real_rectv_row_major ); BOOST_UBLASX_TEST_DO( complex_rectv_col_major ); BOOST_UBLASX_TEST_DO( complex_rectv_row_major ); BOOST_UBLASX_TEST_END(); }
35.034985
149
0.627112
sguazt
8efd92da6912e7d5cc64bf4eaf1be08f91c912d5
11,383
cpp
C++
DerivedSources/WebCore/JSWMLElementWrapperFactory.cpp
VincentWei/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
6
2017-05-31T01:46:45.000Z
2018-06-12T10:53:30.000Z
DerivedSources/WebCore/JSWMLElementWrapperFactory.cpp
FMSoftCN/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
null
null
null
DerivedSources/WebCore/JSWMLElementWrapperFactory.cpp
FMSoftCN/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
2
2017-07-17T06:02:42.000Z
2018-09-19T10:08:38.000Z
/* * THIS FILE WAS AUTOMATICALLY GENERATED, DO NOT EDIT. * * This file was generated by the dom/make_names.pl script. * * Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h" #include "JSWMLElementWrapperFactory.h" #if ENABLE(WML) #include "JSWMLAElement.h" #include "JSWMLAccessElement.h" #include "JSWMLAnchorElement.h" #include "JSWMLBRElement.h" #include "JSWMLCardElement.h" #include "JSWMLDoElement.h" #include "JSWMLFieldSetElement.h" #include "JSWMLGoElement.h" #include "JSWMLImageElement.h" #include "JSWMLInputElement.h" #include "JSWMLInsertedLegendElement.h" #include "JSWMLMetaElement.h" #include "JSWMLNoopElement.h" #include "JSWMLOnEventElement.h" #include "JSWMLOptGroupElement.h" #include "JSWMLOptionElement.h" #include "JSWMLPElement.h" #include "JSWMLPostfieldElement.h" #include "JSWMLPrevElement.h" #include "JSWMLRefreshElement.h" #include "JSWMLSelectElement.h" #include "JSWMLSetvarElement.h" #include "JSWMLTableElement.h" #include "JSWMLTemplateElement.h" #include "JSWMLTimerElement.h" #include "WMLNames.h" #include "WMLAElement.h" #include "WMLAccessElement.h" #include "WMLAnchorElement.h" #include "WMLBRElement.h" #include "WMLCardElement.h" #include "WMLDoElement.h" #include "WMLFieldSetElement.h" #include "WMLGoElement.h" #include "WMLElement.h" #include "WMLImageElement.h" #include "WMLInputElement.h" #include "WMLInsertedLegendElement.h" #include "WMLMetaElement.h" #include "WMLNoopElement.h" #include "WMLOnEventElement.h" #include "WMLOptGroupElement.h" #include "WMLOptionElement.h" #include "WMLPElement.h" #include "WMLPostfieldElement.h" #include "WMLPrevElement.h" #include "WMLRefreshElement.h" #include "WMLSelectElement.h" #include "WMLSetvarElement.h" #include "WMLTableElement.h" #include "WMLTemplateElement.h" #include "WMLTimerElement.h" #include <wtf/StdLibExtras.h> #if ENABLE(VIDEO) #include "Document.h" #include "Settings.h" #endif using namespace JSC; namespace WebCore { using namespace WMLNames; typedef JSNode* (*CreateWMLElementWrapperFunction)(ExecState*, JSDOMGlobalObject*, PassRefPtr<WMLElement>); static JSNode* createWMLAElementWrapper(ExecState* exec, JSDOMGlobalObject* globalObject, PassRefPtr<WMLElement> element) { return CREATE_DOM_NODE_WRAPPER(exec, globalObject, WMLAElement, element.get()); } static JSNode* createWMLAccessElementWrapper(ExecState* exec, JSDOMGlobalObject* globalObject, PassRefPtr<WMLElement> element) { return CREATE_DOM_NODE_WRAPPER(exec, globalObject, WMLAccessElement, element.get()); } static JSNode* createWMLAnchorElementWrapper(ExecState* exec, JSDOMGlobalObject* globalObject, PassRefPtr<WMLElement> element) { return CREATE_DOM_NODE_WRAPPER(exec, globalObject, WMLAnchorElement, element.get()); } static JSNode* createWMLBRElementWrapper(ExecState* exec, JSDOMGlobalObject* globalObject, PassRefPtr<WMLElement> element) { return CREATE_DOM_NODE_WRAPPER(exec, globalObject, WMLBRElement, element.get()); } static JSNode* createWMLCardElementWrapper(ExecState* exec, JSDOMGlobalObject* globalObject, PassRefPtr<WMLElement> element) { return CREATE_DOM_NODE_WRAPPER(exec, globalObject, WMLCardElement, element.get()); } static JSNode* createWMLDoElementWrapper(ExecState* exec, JSDOMGlobalObject* globalObject, PassRefPtr<WMLElement> element) { return CREATE_DOM_NODE_WRAPPER(exec, globalObject, WMLDoElement, element.get()); } static JSNode* createWMLFieldSetElementWrapper(ExecState* exec, JSDOMGlobalObject* globalObject, PassRefPtr<WMLElement> element) { return CREATE_DOM_NODE_WRAPPER(exec, globalObject, WMLFieldSetElement, element.get()); } static JSNode* createWMLGoElementWrapper(ExecState* exec, JSDOMGlobalObject* globalObject, PassRefPtr<WMLElement> element) { return CREATE_DOM_NODE_WRAPPER(exec, globalObject, WMLGoElement, element.get()); } static JSNode* createWMLImageElementWrapper(ExecState* exec, JSDOMGlobalObject* globalObject, PassRefPtr<WMLElement> element) { return CREATE_DOM_NODE_WRAPPER(exec, globalObject, WMLImageElement, element.get()); } static JSNode* createWMLInputElementWrapper(ExecState* exec, JSDOMGlobalObject* globalObject, PassRefPtr<WMLElement> element) { return CREATE_DOM_NODE_WRAPPER(exec, globalObject, WMLInputElement, element.get()); } static JSNode* createWMLInsertedLegendElementWrapper(ExecState* exec, JSDOMGlobalObject* globalObject, PassRefPtr<WMLElement> element) { return CREATE_DOM_NODE_WRAPPER(exec, globalObject, WMLInsertedLegendElement, element.get()); } static JSNode* createWMLMetaElementWrapper(ExecState* exec, JSDOMGlobalObject* globalObject, PassRefPtr<WMLElement> element) { return CREATE_DOM_NODE_WRAPPER(exec, globalObject, WMLMetaElement, element.get()); } static JSNode* createWMLNoopElementWrapper(ExecState* exec, JSDOMGlobalObject* globalObject, PassRefPtr<WMLElement> element) { return CREATE_DOM_NODE_WRAPPER(exec, globalObject, WMLNoopElement, element.get()); } static JSNode* createWMLOnEventElementWrapper(ExecState* exec, JSDOMGlobalObject* globalObject, PassRefPtr<WMLElement> element) { return CREATE_DOM_NODE_WRAPPER(exec, globalObject, WMLOnEventElement, element.get()); } static JSNode* createWMLOptGroupElementWrapper(ExecState* exec, JSDOMGlobalObject* globalObject, PassRefPtr<WMLElement> element) { return CREATE_DOM_NODE_WRAPPER(exec, globalObject, WMLOptGroupElement, element.get()); } static JSNode* createWMLOptionElementWrapper(ExecState* exec, JSDOMGlobalObject* globalObject, PassRefPtr<WMLElement> element) { return CREATE_DOM_NODE_WRAPPER(exec, globalObject, WMLOptionElement, element.get()); } static JSNode* createWMLPElementWrapper(ExecState* exec, JSDOMGlobalObject* globalObject, PassRefPtr<WMLElement> element) { return CREATE_DOM_NODE_WRAPPER(exec, globalObject, WMLPElement, element.get()); } static JSNode* createWMLPostfieldElementWrapper(ExecState* exec, JSDOMGlobalObject* globalObject, PassRefPtr<WMLElement> element) { return CREATE_DOM_NODE_WRAPPER(exec, globalObject, WMLPostfieldElement, element.get()); } static JSNode* createWMLPrevElementWrapper(ExecState* exec, JSDOMGlobalObject* globalObject, PassRefPtr<WMLElement> element) { return CREATE_DOM_NODE_WRAPPER(exec, globalObject, WMLPrevElement, element.get()); } static JSNode* createWMLRefreshElementWrapper(ExecState* exec, JSDOMGlobalObject* globalObject, PassRefPtr<WMLElement> element) { return CREATE_DOM_NODE_WRAPPER(exec, globalObject, WMLRefreshElement, element.get()); } static JSNode* createWMLSelectElementWrapper(ExecState* exec, JSDOMGlobalObject* globalObject, PassRefPtr<WMLElement> element) { return CREATE_DOM_NODE_WRAPPER(exec, globalObject, WMLSelectElement, element.get()); } static JSNode* createWMLSetvarElementWrapper(ExecState* exec, JSDOMGlobalObject* globalObject, PassRefPtr<WMLElement> element) { return CREATE_DOM_NODE_WRAPPER(exec, globalObject, WMLSetvarElement, element.get()); } static JSNode* createWMLTableElementWrapper(ExecState* exec, JSDOMGlobalObject* globalObject, PassRefPtr<WMLElement> element) { return CREATE_DOM_NODE_WRAPPER(exec, globalObject, WMLTableElement, element.get()); } static JSNode* createWMLTemplateElementWrapper(ExecState* exec, JSDOMGlobalObject* globalObject, PassRefPtr<WMLElement> element) { return CREATE_DOM_NODE_WRAPPER(exec, globalObject, WMLTemplateElement, element.get()); } static JSNode* createWMLTimerElementWrapper(ExecState* exec, JSDOMGlobalObject* globalObject, PassRefPtr<WMLElement> element) { return CREATE_DOM_NODE_WRAPPER(exec, globalObject, WMLTimerElement, element.get()); } JSNode* createJSWMLWrapper(ExecState* exec, JSDOMGlobalObject* globalObject, PassRefPtr<WMLElement> element) { typedef HashMap<WTF::AtomicStringImpl*, CreateWMLElementWrapperFunction> FunctionMap; DEFINE_STATIC_LOCAL(FunctionMap, map, ()); if (map.isEmpty()) { map.set(aTag.localName().impl(), createWMLAElementWrapper); map.set(accessTag.localName().impl(), createWMLAccessElementWrapper); map.set(anchorTag.localName().impl(), createWMLAnchorElementWrapper); map.set(brTag.localName().impl(), createWMLBRElementWrapper); map.set(cardTag.localName().impl(), createWMLCardElementWrapper); map.set(doTag.localName().impl(), createWMLDoElementWrapper); map.set(fieldsetTag.localName().impl(), createWMLFieldSetElementWrapper); map.set(goTag.localName().impl(), createWMLGoElementWrapper); map.set(imgTag.localName().impl(), createWMLImageElementWrapper); map.set(inputTag.localName().impl(), createWMLInputElementWrapper); map.set(insertedLegendTag.localName().impl(), createWMLInsertedLegendElementWrapper); map.set(metaTag.localName().impl(), createWMLMetaElementWrapper); map.set(noopTag.localName().impl(), createWMLNoopElementWrapper); map.set(oneventTag.localName().impl(), createWMLOnEventElementWrapper); map.set(optgroupTag.localName().impl(), createWMLOptGroupElementWrapper); map.set(optionTag.localName().impl(), createWMLOptionElementWrapper); map.set(pTag.localName().impl(), createWMLPElementWrapper); map.set(postfieldTag.localName().impl(), createWMLPostfieldElementWrapper); map.set(prevTag.localName().impl(), createWMLPrevElementWrapper); map.set(refreshTag.localName().impl(), createWMLRefreshElementWrapper); map.set(selectTag.localName().impl(), createWMLSelectElementWrapper); map.set(setvarTag.localName().impl(), createWMLSetvarElementWrapper); map.set(tableTag.localName().impl(), createWMLTableElementWrapper); map.set(templateTag.localName().impl(), createWMLTemplateElementWrapper); map.set(timerTag.localName().impl(), createWMLTimerElementWrapper); } CreateWMLElementWrapperFunction createWrapperFunction = map.get(element->localName().impl()); if (createWrapperFunction) return createWrapperFunction(exec, globalObject, element); return CREATE_DOM_NODE_WRAPPER(exec, globalObject, WMLElement, element.get()); } } #endif
42.315985
134
0.789599
VincentWei
8efdf2d451fbf9fa2d5f5a722b548439c4daa461
3,302
cpp
C++
src/wiggleDetector.cpp
malachi-iot/washer-monitor
af7786bbb204bf6dc31c30b759a82910feb6e946
[ "MIT" ]
null
null
null
src/wiggleDetector.cpp
malachi-iot/washer-monitor
af7786bbb204bf6dc31c30b759a82910feb6e946
[ "MIT" ]
null
null
null
src/wiggleDetector.cpp
malachi-iot/washer-monitor
af7786bbb204bf6dc31c30b759a82910feb6e946
[ "MIT" ]
null
null
null
// // Created by malachi on 2/22/17. // #include <Arduino.h> #include <fact/CircularBuffer.h> #include <SimpleTimer.h> #include "state.h" namespace util = FactUtilEmbedded; const int SENSOR_PIN = 13; volatile uint16_t wigglesDetected = 0; util::layer1::CircularBuffer<uint16_t, 60> wigglesPerSecond; util::layer1::CircularBuffer<uint32_t, 60> wigglesPerMinute; // Utilize this if we want idle state to be HIGH (utilizing "weak" internal pullup) // This mode means wiggle detection will go to LOW/ground when activated // UNTESTED #define WIGGLE_IDLE_HIGH void wiggleDetector() { wigglesDetected++; } void wiggleDetector_setup() { #ifdef WIGGLE_IDLE_HIGH pinMode(SENSOR_PIN, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(SENSOR_PIN), wiggleDetector, FALLING); #else pinMode(SENSOR_PIN, INPUT); attachInterrupt(digitalPinToInterrupt(SENSOR_PIN), wiggleDetector, RISING); #endif } // FIX: Some kind of odd alignment issue if I use a uint8_t here, so kludging it // and using a uint32_t . I expect is related to above CircularBuffers perhaps not landing // on perfect alignments //__attribute__((section(".iram0.text"))) uint8_t minutesCounter = 0; uint32_t minutesCounter = 0; int wiggleTimeoutTimer = -1; extern SimpleTimer timer; // In seconds #define WIGGLE_TIMEOUT (60 * 5) void wiggle_stop_event() { state_change(State::NotifyingTimeout); // specifically do not requeue stop event, instead let threshold manager do that wiggleTimeoutTimer = -1; } void wiggle_set_detector_timeout() { wiggleTimeoutTimer = timer.setTimeout(WIGGLE_TIMEOUT * 1000, wiggle_stop_event); } uint32_t getTotalWigglesInLast60Seconds(); uint32_t getTotalWigglesInLast5Minutes(); void printWiggleStatus() { // represents number of wiggles detected since last we entered detected state static uint32_t wd_timeout = 0; uint16_t wd = wigglesDetected; // FIX: we should divide up things that have side effects outside of // printWiggleStatus if(wd > 0) { // we must get more than a "little" bit of wiggling to think that stuff is shaking // will need fine tuning // also wiggleTimeoutTimer == -1 means we are not initialized/listening for a timeout if(wd > 5 && wiggleTimeoutTimer != -1) { state_change(State::Detected); timer.restartTimer(wiggleTimeoutTimer); } // Side effect wigglesDetected = 0; } wigglesPerSecond.put(wd); uint32_t wd60s = getTotalWigglesInLast60Seconds(); Serial.print("Wiggles detected/second ("); Serial.print(minutesCounter); Serial.print("): "); Serial.print(wd); Serial.print(" of "); Serial.print(wd60s); Serial.println(" in the last 60 seconds"); if(++minutesCounter == 60) { wigglesPerMinute.put(wd60s); Serial.print("Wiggles in last minute: "); Serial.println(wd60s); minutesCounter = 0; } } template <class TArray> uint32_t array_sum(const TArray& array, uint16_t size) { uint32_t total = 0; for(int i = 0; i < size; i++) { total += array[i]; } return total; } uint32_t getTotalWigglesInLast60Seconds() { auto array = wigglesPerSecond.getUnderlyingArray(); return array_sum(array, 60); }
24.279412
93
0.698365
malachi-iot
8eff81ca36a0040952bc1a80c5f14d334c5d881d
9,695
cpp
C++
admin/snapin/corecopy/guidhelp.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/snapin/corecopy/guidhelp.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/snapin/corecopy/guidhelp.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//____________________________________________________________________________ // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1995 - 1996. // // File: guidhelp.cpp // // Contents: // // Classes: // // Functions: // // History: 9/18/1996 JonN Created // //____________________________________________________________________________ #include <objbase.h> #include <basetyps.h> #include "dbg.h" #include "cstr.h" #ifndef DECLSPEC_UUID #if _MSC_VER >= 1100 #define DECLSPEC_UUID(x) __declspec(uuid(x)) #else #define DECLSPEC_UUID(x) #endif #endif #include <mmc.h> #include "guidhelp.h" #include "atlbase.h" // USES_CONVERSION #include "macros.h" USE_HANDLE_MACROS("GUIDHELP(guidhelp.cpp)") #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif static CLIPFORMAT g_CFNodeType = 0; static CLIPFORMAT g_CFSnapInCLSID = 0; static CLIPFORMAT g_CFDisplayName = 0; HRESULT ExtractData( IDataObject* piDataObject, CLIPFORMAT cfClipFormat, PVOID pbData, DWORD cbData ) { TEST_NONNULL_PTR_PARAM( piDataObject ); TEST_NONNULL_PTR_PARAM( pbData ); HRESULT hr = S_OK; FORMATETC formatetc = {cfClipFormat, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL}; STGMEDIUM stgmedium = {TYMED_HGLOBAL, NULL}; stgmedium.hGlobal = ::GlobalAlloc(GPTR, cbData); do // false loop { if (NULL == stgmedium.hGlobal) { ASSERT(FALSE); ////AfxThrowMemoryException(); hr = E_OUTOFMEMORY; break; } hr = piDataObject->GetDataHere( &formatetc, &stgmedium ); if ( FAILED(hr) ) { // JonN Jan 7 1999: don't assert here, some errors are perfectly reasonable break; } PVOID pbNewData = reinterpret_cast<PVOID>(stgmedium.hGlobal); if (NULL == pbNewData) { ASSERT(FALSE); hr = E_UNEXPECTED; break; } ::memcpy( pbData, pbNewData, cbData ); } while (FALSE); // false loop if (NULL != stgmedium.hGlobal) { //VERIFY( stgmedium.hGlobal); VERIFY( NULL == ::GlobalFree(stgmedium.hGlobal) ); } return hr; } // ExtractData() HRESULT ExtractString( IDataObject* piDataObject, CLIPFORMAT cfClipFormat, CStr* pstr, // OUT: Pointer to CStr to store data DWORD cchMaxLength) { TEST_NONNULL_PTR_PARAM( piDataObject ); TEST_NONNULL_PTR_PARAM( pstr ); ASSERT( cchMaxLength > 0 ); HRESULT hr = S_OK; FORMATETC formatetc = {cfClipFormat, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL}; STGMEDIUM stgmedium = {TYMED_HGLOBAL, NULL}; stgmedium.hGlobal = ::GlobalAlloc(GPTR, sizeof(WCHAR)*cchMaxLength); do // false loop { if (NULL == stgmedium.hGlobal) { ASSERT(FALSE); ////AfxThrowMemoryException(); hr = E_OUTOFMEMORY; break; } hr = piDataObject->GetDataHere( &formatetc, &stgmedium ); if ( FAILED(hr) ) { // This failure happens when 'searching' for // clipboard format supported by the IDataObject. // t-danmo (24-Oct-96) // Skipping ASSERT( FALSE ); break; } LPWSTR pszNewData = reinterpret_cast<LPWSTR>(stgmedium.hGlobal); if (NULL == pszNewData) { ASSERT(FALSE); hr = E_UNEXPECTED; break; } pszNewData[cchMaxLength-1] = L'\0'; // just to be safe USES_CONVERSION; *pstr = OLE2T(pszNewData); } while (FALSE); // false loop if (NULL != stgmedium.hGlobal) { VERIFY(NULL == ::GlobalFree(stgmedium.hGlobal)); } return hr; } // ExtractString() HRESULT ExtractSnapInCLSID( IDataObject* piDataObject, CLSID* pclsidSnapin ) { if( !g_CFSnapInCLSID ) { USES_CONVERSION; g_CFSnapInCLSID = (CLIPFORMAT)RegisterClipboardFormat(W2T(CCF_SNAPIN_CLASSID)); // ISSUE-2002/04/01-JonN ASSERT(NULL != g_CFSnapInCLSID) } return ExtractData( piDataObject, g_CFSnapInCLSID, (PVOID)pclsidSnapin, sizeof(CLSID) ); } HRESULT ExtractObjectTypeGUID( IDataObject* piDataObject, GUID* pguidObjectType ) { if( !g_CFNodeType ) { USES_CONVERSION; g_CFNodeType = (CLIPFORMAT)RegisterClipboardFormat(W2T(CCF_NODETYPE)); // ISSUE-2002/04/01-JonN ASSERT(NULL != g_CFSnapInCLSID) } return ExtractData( piDataObject, g_CFNodeType, (PVOID)pguidObjectType, sizeof(GUID) ); } HRESULT GuidToCStr( CStr* pstr, const GUID& guid ) { WCHAR awch[MAX_PATH]; // ISSUE-2002/04/01-JonN call ZeroMemory HRESULT hr = StringFromGUID2(guid, awch, MAX_PATH); // JonN 11/21/00 PREFIX 226769 ASSERT(SUCCEEDED(hr)); USES_CONVERSION; LPTSTR lptstr = OLE2T(awch); *pstr = lptstr; return hr; } HRESULT CStrToGuid( const CStr& str, GUID* pguid ) { USES_CONVERSION; LPOLESTR lpolestr = T2OLE(((LPTSTR)(LPCTSTR)str)); HRESULT hr = CLSIDFromString(lpolestr, pguid); ASSERT(SUCCEEDED(hr)); return hr; } #if 0 HRESULT bstrToGuid( const bstr& str, GUID* pguid ) { HRESULT hr = CLSIDFromString(const_cast<LPOLESTR>((LPCWSTR)str), pguid); ASSERT(SUCCEEDED(hr)); return hr; } #endif HRESULT LoadRootDisplayName(IComponentData* pIComponentData, CStr& strDisplayName) { // ISSUE-2002/04/01-JonN test pIComponentData IDataObject* pIDataObject = NULL; HRESULT hr = pIComponentData->QueryDataObject(NULL, CCT_SNAPIN_MANAGER, &pIDataObject); CHECK_HRESULT(hr); if ( FAILED(hr) ) return hr; if( !g_CFDisplayName ) { USES_CONVERSION; g_CFDisplayName = (CLIPFORMAT)RegisterClipboardFormat(W2T(CCF_DISPLAY_NAME)); // ISSUE-2002/04/01-JonN ASSERT(NULL != g_CFSnapInCLSID) } hr = ExtractString( pIDataObject, g_CFDisplayName, &strDisplayName, MAX_PATH); // CODEWORK maximum length CHECK_HRESULT(hr); if (pIDataObject) pIDataObject->Release(); // JonN 3/28/02 return hr; } HRESULT LoadAndAddMenuItem( IContextMenuCallback* pIContextMenuCallback, UINT nResourceID, // contains text and status text seperated by '\n' long lCommandID, long lInsertionPointID, long fFlags, HINSTANCE hInst, PCTSTR pszLanguageIndependentName) { // ISSUE-2002/04/01-JonN handle these cases ASSERT( pIContextMenuCallback != NULL ); ASSERT( pszLanguageIndependentName != NULL ); CComPtr<IContextMenuCallback2> spiCallback2; HRESULT hr = pIContextMenuCallback->QueryInterface(IID_IContextMenuCallback2, (void **)&spiCallback2); if (FAILED(hr)) return hr; // load the resource CStr strText; strText.LoadString(hInst, nResourceID ); ASSERT( !strText.IsEmpty() ); // split the resource into the menu text and status text CStr strStatusText; int iSeparator = strText.Find(_T('\n')); if (0 > iSeparator) { ASSERT( FALSE ); strStatusText = strText; } else { strStatusText = strText.Right( strText.GetLength()-(iSeparator+1) ); strText = strText.Left( iSeparator ); } // add the menu item USES_CONVERSION; CONTEXTMENUITEM2 contextmenuitem; ::ZeroMemory( &contextmenuitem, sizeof(contextmenuitem) ); contextmenuitem.strName = T2OLE(const_cast<LPTSTR>((LPCTSTR)strText)); contextmenuitem.strStatusBarText = T2OLE(const_cast<LPTSTR>((LPCTSTR)strStatusText)); contextmenuitem.lCommandID = lCommandID; contextmenuitem.lInsertionPointID = lInsertionPointID; contextmenuitem.fFlags = fFlags; contextmenuitem.fSpecialFlags = ((fFlags & MF_POPUP) ? CCM_SPECIAL_SUBMENU : 0L); contextmenuitem.strLanguageIndependentName = T2OLE(const_cast<LPTSTR>(pszLanguageIndependentName)); hr = spiCallback2->AddItem( &contextmenuitem ); ASSERT(hr == S_OK); return hr; } HRESULT AddSpecialSeparator( IContextMenuCallback* pIContextMenuCallback, long lInsertionPointID ) { CONTEXTMENUITEM contextmenuitem; ::ZeroMemory( &contextmenuitem, sizeof(contextmenuitem) ); contextmenuitem.strName = NULL; contextmenuitem.strStatusBarText = NULL; contextmenuitem.lCommandID = 0; contextmenuitem.lInsertionPointID = lInsertionPointID; contextmenuitem.fFlags = MF_SEPARATOR; contextmenuitem.fSpecialFlags = CCM_SPECIAL_SEPARATOR; HRESULT hr = pIContextMenuCallback->AddItem( &contextmenuitem ); ASSERT(hr == S_OK); return hr; } HRESULT AddSpecialInsertionPoint( IContextMenuCallback* pIContextMenuCallback, long lCommandID, long lInsertionPointID ) { // ISSUE-2002/04/01-JonN handle NULL CONTEXTMENUITEM contextmenuitem; ::ZeroMemory( &contextmenuitem, sizeof(contextmenuitem) ); contextmenuitem.strName = NULL; contextmenuitem.strStatusBarText = NULL; contextmenuitem.lCommandID = lCommandID; contextmenuitem.lInsertionPointID = lInsertionPointID; contextmenuitem.fFlags = 0; contextmenuitem.fSpecialFlags = CCM_SPECIAL_INSERTION_POINT; HRESULT hr = pIContextMenuCallback->AddItem( &contextmenuitem ); ASSERT(hr == S_OK); return hr; }
29.739264
107
0.635895
npocmaka
f106aff47a1ae4cd247c4fed7146af25c047dd6f
2,966
cpp
C++
02-functions-and-libs/readerEx.02.07/main.cpp
heavy3/programming-abstractions
e10eab5fe7d9ca7d7d4cc96551524707214e43a8
[ "MIT" ]
81
2018-11-15T21:23:19.000Z
2022-03-06T09:46:36.000Z
02-functions-and-libs/readerEx.02.07/main.cpp
heavy3/programming-abstractions
e10eab5fe7d9ca7d7d4cc96551524707214e43a8
[ "MIT" ]
null
null
null
02-functions-and-libs/readerEx.02.07/main.cpp
heavy3/programming-abstractions
e10eab5fe7d9ca7d7d4cc96551524707214e43a8
[ "MIT" ]
41
2018-11-15T21:23:24.000Z
2022-02-24T03:02:26.000Z
// // main.cpp // // This program implements the sqrt() function for taking the square root // of a number using the following successive approximation technique: // // 1. Begin by guessing that the square root is x / 2. Call that guess g. // // 2. The actual square root must lie between g and x / g. // At each step in the successive approximation, generate a new guess // by averaging g and x / g. // // 3. Repeat step 2 until the values g and x / g are as close together as the // machine precision allows. In C++, the best way to check for this // condition is to test whether the average is equal to either of the values // used to generate it. // // -------------------------------------------------------------------------- // Attribution: "Programming Abstractions in C++" by Eric Roberts // Chapter 2, Exercise 7 // Stanford University, Autumn Quarter 2012 // http://web.stanford.edu/class/archive/cs/cs106b/cs106b.1136/materials/CS106BX-Reader.pdf // -------------------------------------------------------------------------- // // Created by Glenn Streiff on 9/18/15. // Copyright © 2015 Glenn Streiff. All rights reserved. // #include <iostream> #include <cstdlib> #include <string> // Function prototypes double sqrt(double n); bool refineGuess(double n, double & nextGuess); void error(std::string msg); // Main program int main(int argc, char * argv[]) { double n = 10; double answer = sqrt(n); std::cout << "sqrt(" << n << ") = " << answer << std::endl; return 0; } // Function definitions // // Function: sqrt // Usage: double d = sqrt(9); // -------------------------- // Returns square root of a number. // double sqrt(double n) { double guess = n / 2.0; if (n < 0) { error("square root of a negative number is undefined"); } if (n == 0) { return 0; // short circuit to avoid divide by 0; } while(refineGuess(n, guess)) continue; return guess; } // // Function: refineGuess // Usage: double n = 9; // double nextGuess = n/2.0; // while (refineGuess(n, nextGuess)) continue; // --------------------------------------------------- // Returns true once a successive approximation algorithm // has convered on an answer to within the accuracy supported // by the machine. // // When the routine converges on an answer and returns boolean // false, the pass by reference variable, g, will hold the // approximate solution. // bool refineGuess(double x, double & g) { double nextG = (g + x/g) / 2.0; if (nextG == g) { return false; } else { g = nextG; return true; } } // // Function: error // Usage: error("Something bad happened. Exitting."); // --------------------------------------------------- // Exits program with the standard failure code EXIT_FAILURE // defined in <cstdlib>. // void error(std::string msg) { std::cerr << msg << std::endl; exit(EXIT_FAILURE); }
26.963636
91
0.58294
heavy3
f10b116eee8ffd2d0bf1142c06cb1c9e980da5e8
3,075
cpp
C++
9.29.7.cpp
luckylove/extra
8d27ec0e62bdc2ab6a261d197b455fea07120a55
[ "CC-BY-4.0", "MIT" ]
null
null
null
9.29.7.cpp
luckylove/extra
8d27ec0e62bdc2ab6a261d197b455fea07120a55
[ "CC-BY-4.0", "MIT" ]
null
null
null
9.29.7.cpp
luckylove/extra
8d27ec0e62bdc2ab6a261d197b455fea07120a55
[ "CC-BY-4.0", "MIT" ]
null
null
null
// merge two shorted linked list // by using the dummy node #include<stdio.h> #include<stdlib.h> // for malloc function stdlib .h will support it accordingly struct node { int data; struct node* next; }; void push(struct node **head,int data1) // here i am passing the address of the pointer to the struct node so that we can change the valueof the struct node { // fist of all we have to create a new node struct node* newnode=NULL; // now allocates memory to it newnode=(struct node*)malloc(sizeof(struct node)); // set the data of the newnode newnode->data=data1; newnode->next=*head; *head=newnode; } void printlinkedlist(struct node* head) { // now we have to print the node one by one /* if(head==NULL) { return; }*/ while(head!=NULL) { printf("%d",head->data); head=head->next; // pointing to the next address } } // function for merging shorted linked list // solving by using the dummy node // the idea behind it is taking the one sphere node // call it dummy node // now use the pointer to this node to create the linked list as the starting address // in this the whole linked list is created in the sense // that new node is created every time and then it is attached to the address of the dummy node // at last when one list becomes empty then the address of the next node is appended to the address of the dummy node reached // here we have to create 2 function one is the main function and second is the // function used to move the node from source to destination // which is the dummy node next // now lets start void movenode(struct node** second, struct node** first) { // data is moved form first to second // we i have to use the asset // when the first is empty list // in the geeks for geeks it is written but i am unable to understand struct node* newnode=*first; *first=newnode->next; newnode->next=*second; *second=newnode; } struct node* mergeshortedlinkedlist(struct node**head1, struct node** head2) { struct node dummy; struct node* tail=&dummy; dummy.next=NULL; while(1) { if(*head1==NULL) { tail->next=*head2; break; } else if(*head2==NULL) { tail->next=*head1; break; } if((*head1)->data<=(*head2)->data) { movenode(&(tail->next),head1); } else { movenode(&(tail->next),head2); } tail=tail->next; } return dummy.next; } int main() { struct node*head1=NULL; struct node*head2=NULL; struct node*head3=NULL; push(&head1,8); push(&head1,6); push(&head1,4); push(&head1,1); push(&head2,7); push(&head2,5); push(&head2,3); push(&head2,2); printlinkedlist(head1); printf("\n"); printlinkedlist(head2); printf("\n"); printlinkedlist(head1); printf("\n\n\n"); head3 = mergeshortedlinkedlist(&head1,&head2); printlinkedlist(head3); }
26.508621
157
0.625366
luckylove
f10c6dd590deb8c07b296a3e9b9a6c77a397d68a
1,079
cpp
C++
codes/HDU/hdu4649.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/HDU/hdu4649.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/HDU/hdu4649.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <cstring> #include <cmath> #include <algorithm> using namespace std; const int maxn = 205; double P[maxn], dp[maxn][2]; int N, A[maxn]; char sig[maxn][2]; double solve (int bit, double s) { dp[0][0] = 1 - s, dp[0][1] = s; for (int i = 1; i <= N; i++) { for (int j = 0; j < 2; j++) dp[i][j] = dp[i-1][j] * P[i]; double p = 1 - P[i]; int v = (A[i]>>bit)&1; if (sig[i][0] == '&') { dp[i][v&0] += dp[i-1][0] * p; dp[i][v&1] += dp[i-1][1] * p; } else if (sig[i][0] == '|') { dp[i][v|0] += dp[i-1][0] * p; dp[i][v|1] += dp[i-1][1] * p; } else { dp[i][v^0] += dp[i-1][0] * p; dp[i][v^1] += dp[i-1][1] * p; } } return dp[N][1]; } int main () { int cas = 1, s; while (scanf("%d", &N) == 1) { scanf("%d", &s); for (int i = 1; i <= N; i++) scanf("%d", &A[i]); for (int i = 1; i <= N; i++) scanf("%s", sig[i]); for (int i = 1; i <= N; i++) scanf("%lf", &P[i]); double ans = 0; for (int i = 0; i <= 20; i++) ans += solve(i, (s>>i)&1) * (1<<i); printf("Case %d:\n%.6lf\n", cas++, ans); } return 0; }
21.58
51
0.437442
JeraKrs
f10cec96038fa56d2dc5f19e933b1745930dca38
1,273
cpp
C++
tests/test050.cpp
mjj29/rapidcsv
d717299b59d19c421b3bb023e890b33000016a9c
[ "BSD-3-Clause" ]
1
2020-01-13T17:39:20.000Z
2020-01-13T17:39:20.000Z
tests/test050.cpp
mjj29/rapidcsv
d717299b59d19c421b3bb023e890b33000016a9c
[ "BSD-3-Clause" ]
null
null
null
tests/test050.cpp
mjj29/rapidcsv
d717299b59d19c421b3bb023e890b33000016a9c
[ "BSD-3-Clause" ]
1
2019-12-14T12:07:48.000Z
2019-12-14T12:07:48.000Z
// test050.cpp - read column header / label by index #include <rapidcsv.h> #include "unittest.h" int main() { int rv = 0; std::string csv = "-,A,B,C\n" "1,3,9,81\n" "2,4,16,256\n" ; std::string path = unittest::TempPath(); unittest::WriteFile(path, csv); try { rapidcsv::Document doc(path); unittest::ExpectEqual(std::string, doc.GetColumnName(0), "A"); unittest::ExpectEqual(std::string, doc.GetColumnName(1), "B"); unittest::ExpectEqual(std::string, doc.GetColumnName(2), "C"); ExpectException(doc.GetColumnName(3), std::out_of_range); rapidcsv::Document doc2(path, rapidcsv::LabelParams(-1, -1)); ExpectException(doc2.GetColumnName(0), std::out_of_range); rapidcsv::Document doc3(path, rapidcsv::LabelParams(0, -1)); unittest::ExpectEqual(std::string, doc3.GetColumnName(0), "-"); unittest::ExpectEqual(std::string, doc3.GetColumnName(1), "A"); unittest::ExpectEqual(std::string, doc3.GetColumnName(2), "B"); unittest::ExpectEqual(std::string, doc3.GetColumnName(3), "C"); ExpectException(doc3.GetColumnName(4), std::out_of_range); } catch(const std::exception& ex) { std::cout << ex.what() << std::endl; rv = 1; } unittest::DeleteFile(path); return rv; }
26.520833
67
0.649647
mjj29
f10d654211dcb5c0b5131f29e7d40ff19dd249a3
5,659
cpp
C++
STL & Sorting Algorithm/Vector.cpp
FattyMieo/Semester-3
29498bfca2aaca84e4595510bbc21a6043b16d77
[ "MIT" ]
1
2017-05-12T19:46:57.000Z
2017-05-12T19:46:57.000Z
STL & Sorting Algorithm/Vector.cpp
FattyMieo/Semester-3
29498bfca2aaca84e4595510bbc21a6043b16d77
[ "MIT" ]
null
null
null
STL & Sorting Algorithm/Vector.cpp
FattyMieo/Semester-3
29498bfca2aaca84e4595510bbc21a6043b16d77
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdlib> // same as stdlib.h (old) #include <ctime> // same as time.h (old) #include <vector> #include <limits> using namespace std; vector<char> charVector; void DisplayVector() { for(int i = 0; i < charVector.size(); i++) { cout << "[" << (i < 10 ? "0" : "") << i << "] " << charVector[i] << endl; } } void PushToBackVector() { char character; cout << " @ Please input a character" << endl; cout << "> "; cin >> character; cout << endl; charVector.push_back(character); } void PushToFrontVector() { char character; cout << " @ Please input a character" << endl; cout << "> "; cin >> character; cout << endl; charVector.insert(charVector.begin(), character); } void PushToVector() { char character; cout << " @ Please input a character" << endl; cout << "> "; cin >> character; cout << endl; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); int i = -1; while(true) { cout << " @ Where do you want to place it?" << endl; cout << "> "; cin >> i; if(cin.good() && i >= 0) { if(i >= charVector.size()) { charVector.resize(i + 1, ' '); } charVector.insert(charVector.begin() + i, character); break; } else { cout << "Wrong Input!" << endl; } cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << endl; } } void PopFromBackVector() { if(!charVector.empty()) { charVector.pop_back(); } else { cout << "Vector is empty!" << endl; system("PAUSE"); } } void PopFromFrontVector() { if(!charVector.empty()) { charVector.erase(charVector.begin()); } else { cout << "Vector is empty!" << endl; system("PAUSE"); } } void PopFromVector() { if(!charVector.empty()) { int i = -1; while(true) { cout << " @ Where do you want to erase?" << endl; cout << "> "; cin >> i; if(cin.good() && i >= 0) { if(i < charVector.size()) { charVector.erase(charVector.begin() + i); } else { cout << "Nothing to erase!" << endl; system("PAUSE"); } break; } else { cout << "Wrong Input!" << endl; } cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << endl; } } else { cout << "Vector is empty!" << endl; system("PAUSE"); } } void SwapCharacters() { int i = -1; int j = -1; while(true) { cout << " @ Which characters to be swapped?" << endl; cout << "> "; cin >> i >> j; if(cin.good() && i >= 0 && j >= 0) { if(i == j) { cout << "Cannot swap with the same index." << endl; system("PAUSE"); } else if(i < charVector.size() && j < charVector.size()) { char tmp = charVector[i]; charVector[i] = charVector[j]; charVector[j] = tmp; break; } else if(i < charVector.size()) { charVector.resize(j + 1, ' '); charVector[j] = charVector[i]; charVector[i] = ' '; break; } else if(j < charVector.size()) { charVector.resize(i + 1, ' '); charVector[i] = charVector[j]; charVector[j] = ' '; break; } else { cout << "Both characters are not existing!" << endl; system("PAUSE"); } break; } else { cout << "Wrong Input!" << endl; } cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << endl; } } void ReverseOrder() { int i = 0, j = charVector.size() - 1; while(i < j) { char tmp = charVector[i]; charVector[i] = charVector[j]; charVector[j] = tmp; i++; j--; } } void DeleteEmptyCharacters() { for(int i = 0; i < charVector.size(); i++) { if(charVector[i] == ' ') charVector.erase(charVector.begin() + i--); } } void ClearVector() { charVector.clear(); } void PopEmptyBehindVector() { for(int i = charVector.size() - 1; i >= 0; i--) { if(charVector[i] == ' ') charVector.pop_back(); else break; } } void DoChoice(int choice) { switch(choice) { case 1: PushToBackVector(); break; case 2: PushToFrontVector(); break; case 3: PushToVector(); break; case 4: PopFromBackVector(); break; case 5: PopFromFrontVector(); break; case 6: PopFromVector(); break; case 7: SwapCharacters(); break; case 8: ReverseOrder(); break; case 9: DeleteEmptyCharacters(); break; case 10: ClearVector(); break; default: break; } } int main() { srand(time(NULL)); int randomSize = rand() % 7 + 3; for(int i = 0; i < randomSize; i++) { charVector.push_back(i + 65); } int choice = -1; do { system("CLS"); DisplayVector(); cout << "==========================================" << endl; cout << " 1. Add character to the back" << endl; cout << " 2. Add character to the front" << endl; cout << " 3. Add character at specific index" << endl; cout << " 4. Remove character from the back" << endl; cout << " 5. Remove character from the front" << endl; cout << " 6. Remove character at specific index" << endl; cout << " 7. Swap character at specific indexes" << endl; cout << " 8. Reverse order" << endl; cout << " 9. Delete all empty characters" << endl; cout << " 10. Delete all characters" << endl; cout << endl; cout << " -1. Exit Program" << endl; cout << "==========================================" << endl; cout << " @ What would you like to do?" << endl; cout << "> "; cin >> choice; cout << endl; if(cin.good()) { DoChoice(choice); PopEmptyBehindVector(); } else { cout << "Wrong Input!" << endl; system("PAUSE"); } cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); } while(choice != -1); return 0; }
17.148485
75
0.545856
FattyMieo
f10ddf0f79d7e4cd24e51978d40b0ce6be9cea81
751
hpp
C++
example/Timer.hpp
BetaJester/nopengl
6220eab842db531d275e7c0f9276992d22170e3a
[ "MIT" ]
null
null
null
example/Timer.hpp
BetaJester/nopengl
6220eab842db531d275e7c0f9276992d22170e3a
[ "MIT" ]
null
null
null
example/Timer.hpp
BetaJester/nopengl
6220eab842db531d275e7c0f9276992d22170e3a
[ "MIT" ]
null
null
null
// Copyright (C) 2021 Glenn Duncan <betajester@betajester.com> // See README.md, LICENSE, or go to https://github.com/BetaJester/nopengl // for details. #pragma once #include <chrono> #include <concepts> template<std::floating_point T> class [[nodiscard]] Timer final { std::chrono::high_resolution_clock::time_point timeLast{ std::chrono::high_resolution_clock::now() }; std::chrono::duration<T> timeElapsed; public: void tick() noexcept { std::chrono::high_resolution_clock::time_point timeNow = std::chrono::high_resolution_clock::now(); timeElapsed = timeNow - timeLast; timeLast = timeNow; } T elapsed() const noexcept { return timeElapsed.count(); } };
25.896552
108
0.661784
BetaJester
f10e4f51bce8cc153d79154dfe45f610abe162b5
728
cpp
C++
A2OnlineJudge/Ladder_1400_1499/Median.cpp
seeva92/Competitive-Programming
69061c5409bb806148616fe7d86543e94bf76edd
[ "Apache-2.0" ]
null
null
null
A2OnlineJudge/Ladder_1400_1499/Median.cpp
seeva92/Competitive-Programming
69061c5409bb806148616fe7d86543e94bf76edd
[ "Apache-2.0" ]
null
null
null
A2OnlineJudge/Ladder_1400_1499/Median.cpp
seeva92/Competitive-Programming
69061c5409bb806148616fe7d86543e94bf76edd
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> typedef long long ll; const int mod = 1e9 + 7; const int MAX = 1e5 + 7; using namespace std; typedef vector<int> vi; class Median { public: int n, x; vector<int> arr; void solve() { cin >> n >> x; int val; for (int i = 0; i < n; i++) { cin >> val; arr.push_back(val); } sort(arr.begin(), arr.end()); int cnt = 0; while (arr[(arr.size() - 1) / 2] != x) { cnt++; arr.push_back(x); sort(arr.begin(), arr.end()); } cout << cnt; } }; int main() { #ifndef ONLINE_JUDGE freopen("/Users/seeva92/Workspace/Contests/1.txt", "r", stdin); freopen("/Users/seeva92/Workspace/Contests/2.txt", "w", stdout); #endif ios::sync_with_stdio(false); cin.tie(0); Median m; m.solve(); }
19.157895
65
0.596154
seeva92
f111e135a21497ed46ed960a65d78879f8af88e9
3,253
cpp
C++
src/CommandHandlers.cpp
Helios-vmg/BorderlessAnimator
6d73e1806d84e35711a4dd030f367e533e549d8b
[ "BSD-2-Clause" ]
null
null
null
src/CommandHandlers.cpp
Helios-vmg/BorderlessAnimator
6d73e1806d84e35711a4dd030f367e533e549d8b
[ "BSD-2-Clause" ]
null
null
null
src/CommandHandlers.cpp
Helios-vmg/BorderlessAnimator
6d73e1806d84e35711a4dd030f367e533e549d8b
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (c), Helios All rights reserved. Distributed under a permissive license. See COPYING.txt for details. */ #include "ImageViewerApplication.h" #include "MainWindow.h" #include "Script.h" #include <sstream> void ImageViewerApplication::handle_load(const QStringList &args){ if (args.size() < 4) return; this->main_window->load(args[2], args[3].toStdString()); } void ImageViewerApplication::handle_scale(const QStringList &args){ if (args.size() < 4) return; auto name = args[2].toStdString(); auto scale = expect_real(args[3]); auto window = this->main_window->get_window(name); if (!window) return; window->set_scale(scale); } void ImageViewerApplication::handle_setorigin(const QStringList &args){ if (args.size() < 5) return; auto name = args[2].toStdString(); auto x = expect_integer(args[3]); auto y = expect_integer(args[4]); auto window = this->main_window->get_window(name); if (!window) return; window->set_origin(x, y); } void ImageViewerApplication::handle_move(const QStringList &args){ if (args.size() < 5) return; auto name = args[2].toStdString(); auto x = expect_relabs_integer(args[3]); auto y = expect_relabs_integer(args[4]); auto window = this->main_window->get_window(name); if (!window) return; window->move_by_command(set(window->get_position(), x, y)); } void ImageViewerApplication::handle_rotate(const QStringList &args){ if (args.size() < 4) return; auto name = args[2].toStdString(); auto theta = expect_relabs_real(args[3]); auto window = this->main_window->get_window(name); if (!window) return; auto rotation = window->get_rotation(); if (theta.second) rotation += theta.first; else rotation = theta.first; window->set_rotation(rotation); } void ImageViewerApplication::handle_animmove(const QStringList &args){ if (args.size() < 6) return; auto name = args[2].toStdString(); auto x = expect_integer(args[3]); auto y = expect_integer(args[4]); auto speed = expect_real(args[5]); auto window = this->main_window->get_window(name); if (!window) return; window->anim_move(x, y, speed); } void ImageViewerApplication::handle_animrotate(const QStringList &args){ if (args.size() < 4) return; auto name = args[2].toStdString(); auto speed = expect_real(args[3]); auto window = this->main_window->get_window(name); if (!window) return; window->anim_rotate(speed); } void ImageViewerApplication::handle_fliph(const QStringList &args){ if (args.size() < 2) return; auto name = args[2].toStdString(); auto window = this->main_window->get_window(name); if (!window) return; window->fliph(); } void ImageViewerApplication::handle_flipv(const QStringList &args){ if (args.size() < 3) return; auto name = args[2].toStdString(); auto window = this->main_window->get_window(name); if (!window) return; window->flipv(); } void ImageViewerApplication::handle_loadscript(const QStringList &args){ if (args.size() < 4) return; auto name = args[2].toStdString(); auto &path = args[3]; auto window = this->main_window->get_window(name); if (!window) return; window->load_script(path); }
25.414063
73
0.682754
Helios-vmg
f1122b0f1c354a887a6ab28ffc007360f2f3673c
1,213
hpp
C++
include/codegen/include/System/UriParser_BuiltInUriParser.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/System/UriParser_BuiltInUriParser.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/System/UriParser_BuiltInUriParser.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: System.UriParser #include "System/UriParser.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Skipping declaration: UriSyntaxFlags because it is already included! } // Completed forward declares // Type namespace: System namespace System { // Autogenerated type: System.UriParser/BuiltInUriParser class UriParser::BuiltInUriParser : public System::UriParser { public: // System.Void .ctor(System.String lwrCaseScheme, System.Int32 defaultPort, System.UriSyntaxFlags syntaxFlags) // Offset: 0x1957DA8 static UriParser::BuiltInUriParser* New_ctor(::Il2CppString* lwrCaseScheme, int defaultPort, System::UriSyntaxFlags syntaxFlags); }; // System.UriParser/BuiltInUriParser } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(System::UriParser::BuiltInUriParser*, "System", "UriParser/BuiltInUriParser"); #pragma pack(pop)
40.433333
133
0.732069
Futuremappermydud
f1123c19542dad9ead9e42f61fd7ec62d88ddcec
1,634
cpp
C++
src/add-ons/kernel/file_systems/exfat/DataStream.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
src/add-ons/kernel/file_systems/exfat/DataStream.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
src/add-ons/kernel/file_systems/exfat/DataStream.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
/* * Copyright 2011, Haiku Inc. All rights reserved. * This file may be used under the terms of the MIT License. * * Authors: * Jérôme Duval */ #include "DataStream.h" #include "Volume.h" //#define TRACE_EXFAT #ifdef TRACE_EXFAT # define TRACE(x...) dprintf("\33[34mexfat:\33[0m " x) #else # define TRACE(x...) ; #endif #define ERROR(x...) dprintf("\33[34mexfat:\33[0m " x) DataStream::DataStream(Volume* volume, Inode* inode, off_t size) : kBlockSize(volume->BlockSize()), kClusterSize(volume->ClusterSize()), fVolume(volume), fInode(inode), fSize(size) { fNumBlocks = size == 0 ? 0 : ((size - 1) / kBlockSize) + 1; } DataStream::~DataStream() { } status_t DataStream::FindBlock(off_t pos, off_t& physical, off_t *_length) { if (pos >= fSize) { TRACE("FindBlock: offset larger than size\n"); return B_ENTRY_NOT_FOUND; } cluster_t clusterIndex = pos / kClusterSize; uint32 offset = pos % kClusterSize; cluster_t cluster = fInode->StartCluster(); for (uint32 i = 0; i < clusterIndex; i++) cluster = fInode->NextCluster(cluster); fsblock_t block; if (fVolume->ClusterToBlock(cluster, block) != B_OK) return B_BAD_DATA; physical = block * kBlockSize + offset; for (uint32 i = 0; i < 64; i++) { cluster_t extentEnd = fInode->NextCluster(cluster); if (extentEnd == EXFAT_CLUSTER_END || extentEnd == cluster + 1) break; cluster = extentEnd; } *_length = min_c((cluster - clusterIndex + 1) * kClusterSize - offset, fSize - pos); TRACE("inode %" B_PRIdINO ": cluster %" B_PRIu32 ", pos %" B_PRIdOFF ", %" B_PRIdOFF "\n", fInode->ID(), clusterIndex, pos, physical); return B_OK; }
23.014085
75
0.674419
Kirishikesan
f1139c8813c05e9c131a8782cc62d19d010e4c2d
786
cpp
C++
EJERCICIOS/EJERCICIO4-Imprimir valores de todas las variables/todas-las-variabes.cpp
AntonioVillatoro/cpp
dbbfcbf7d31c3c0e64399a487d05398e53d9428d
[ "MIT" ]
null
null
null
EJERCICIOS/EJERCICIO4-Imprimir valores de todas las variables/todas-las-variabes.cpp
AntonioVillatoro/cpp
dbbfcbf7d31c3c0e64399a487d05398e53d9428d
[ "MIT" ]
null
null
null
EJERCICIOS/EJERCICIO4-Imprimir valores de todas las variables/todas-las-variabes.cpp
AntonioVillatoro/cpp
dbbfcbf7d31c3c0e64399a487d05398e53d9428d
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(int argc, char const *argv[]) { // DECLARACIONES DE VARIABLES // int para declarar varibales enteras // double para declarar variables numeros reales // string para delcarar cadena de caracteres // char para declara un caracter // bool para delcarar bool valorBoolean= false; int valorEntero=15; double valorDouble=20.99; string valorString= "Hola Como Estan"; char valorChar= 'B'; cout << "Valor Boolean: " << valorBoolean << endl; cout << "Valor Entero: " << valorEntero << endl; cout << "Valor Double: " << valorDouble << endl; cout << "Valor String: " << valorString << endl; cout << "Valor Char: " << valorChar << endl; return 0; }
25.354839
56
0.620865
AntonioVillatoro
47dc6fa9fdfaa424ff307ef9283a962d5ee88048
38,047
cpp
C++
python/pythonalgoadapters.cpp
VITObelgium/geodynamix
6d3323bc4cae1b85e26afdceab2ecf3686b11369
[ "MIT" ]
null
null
null
python/pythonalgoadapters.cpp
VITObelgium/geodynamix
6d3323bc4cae1b85e26afdceab2ecf3686b11369
[ "MIT" ]
null
null
null
python/pythonalgoadapters.cpp
VITObelgium/geodynamix
6d3323bc4cae1b85e26afdceab2ecf3686b11369
[ "MIT" ]
1
2021-06-16T11:55:27.000Z
2021-06-16T11:55:27.000Z
#include "pythonalgoadapters.h" #include "infra/cast.h" #include "maskedrasteralgo.h" #include "pythonutils.h" #include "rasterargument.h" #include "gdx/algo/accuflux.h" #include "gdx/algo/blurfilter.h" #include "gdx/algo/cast.h" #include "gdx/algo/category.h" #include "gdx/algo/clusterid.h" #include "gdx/algo/clustersize.h" #include "gdx/algo/conditionals.h" #include "gdx/algo/distance.h" #include "gdx/algo/distancedecay.h" #include "gdx/algo/logical.h" #include "gdx/algo/majorityfilter.h" #include "gdx/algo/mathoperations.h" #include "gdx/algo/maximum.h" #include "gdx/algo/minimum.h" #include "gdx/algo/nodata.h" #include "gdx/algo/normalise.h" #include "gdx/algo/random.h" #include "gdx/algo/reclass.h" #include "gdx/algo/shape.h" #include "gdx/algo/sum.h" #include "gdx/algo/suminbuffer.h" #include "gdx/log.h" #include "gdx/rastercompare.h" #include <fmt/ostream.h> namespace gdx { namespace pyalgo { namespace py = pybind11; using namespace inf; template <typename T> using value_type = typename std::remove_cv_t<std::remove_reference_t<T>>::value_type; namespace { void throwOnInvalidClusterRaster(const Raster& raster) { if (raster.type() != typeid(int32_t)) { throw InvalidArgument("Expected cluster raster to be of type int (numpy.dtype(int))"); } } void throwOnRasterTypeMismatch(const Raster& raster1, const Raster& raster2) { if (raster1.type() != raster2.type()) { throw InvalidArgument("Expected raster types to be the same ({} <-> {})", raster1.type().name(), raster2.type().name()); } } } Raster blurFilter(py::object rasterArg) { return std::visit([&](auto&& raster) { return Raster(gdx::blur_filter(raster)); }, RasterArgument(rasterArg).variant()); } Raster majorityFilter(py::object rasterArg, double radiusInMeter) { return std::visit([&](auto&& raster) { return Raster(gdx::majority_filter(raster, static_cast<float>(radiusInMeter))); }, RasterArgument(rasterArg).variant()); } template <typename RasterType> std::vector<const RasterType*> createRasterVectorFromArgs(py::args args) { try { std::vector<const Raster*> anyRasters; for (auto arg : args) { anyRasters.push_back(arg.cast<Raster*>()); } using T = value_type<RasterType>; std::vector<const RasterType*> rasters; for (auto* ras : anyRasters) { rasters.push_back(&ras->get<T>()); } return rasters; } catch (const std::bad_variant_access&) { throw InvalidArgument("Only raster objects of the same type are supported as argument"); } catch (const py::cast_error&) { throw InvalidArgument("Only raster objects are supported as argument"); } } Raster min(py::args args) { if (args.size() == 0) { throw InvalidArgument("No raster objects provided"); } auto* rasterPtr = args[0].cast<Raster*>(); if (!rasterPtr) { throw InvalidArgument("Min arguments should be raster objects"); } return std::visit([&args](auto&& raster) { return Raster(gdx::minimum(createRasterVectorFromArgs<std::remove_reference_t<decltype(raster)>>(args))); }, rasterPtr->get()); } Raster max(py::args args) { if (args.size() == 0) { throw InvalidArgument("No raster objects provided"); } auto* rasterPtr = args[0].cast<Raster*>(); if (!rasterPtr) { throw InvalidArgument("Max arguments should be raster objects"); } return std::visit([&args](auto&& raster) { return Raster(gdx::maximum(createRasterVectorFromArgs<std::remove_reference_t<decltype(raster)>>(args))); }, rasterPtr->get()); } Raster clip(pybind11::object rasterArg, double low, double high) { return std::visit([&](auto&& raster) { using T = value_type<decltype(raster)>; return Raster(gdx::clip(raster, static_cast<T>(low), static_cast<T>(high))); }, RasterArgument(rasterArg).variant()); } Raster clipLow(pybind11::object rasterArg, double low) { return std::visit([&](auto&& raster) { using T = value_type<decltype(raster)>; return Raster(gdx::clip_low(raster, static_cast<T>(low))); }, RasterArgument(rasterArg).variant()); } Raster clipHigh(pybind11::object rasterArg, double high) { return std::visit([&](auto&& raster) { using T = value_type<decltype(raster)>; return Raster(gdx::clip_high(raster, static_cast<T>(high))); }, RasterArgument(rasterArg).variant()); } Raster abs(py::object rasterArg) { return std::visit([&](auto&& raster) { return Raster(gdx::abs(raster)); }, RasterArgument(rasterArg).variant()); } Raster round(py::object rasterArg) { return std::visit([&](auto&& raster) { return Raster(gdx::round(raster)); }, RasterArgument(rasterArg).variant()); } Raster sin(py::object rasterArg) { return std::visit([&](auto&& raster) { return Raster(gdx::sin(raster)); }, RasterArgument(rasterArg).variant()); } Raster cos(py::object rasterArg) { return std::visit([&](auto&& raster) { return Raster(gdx::cos(raster)); }, RasterArgument(rasterArg).variant()); } Raster log(py::object rasterArg) { return std::visit([&](auto&& raster) { return Raster(gdx::log(raster)); }, RasterArgument(rasterArg).variant()); } Raster log10(py::object rasterArg) { return std::visit([&](auto&& raster) { return Raster(gdx::log10(raster)); }, RasterArgument(rasterArg).variant()); } Raster exp(py::object rasterArg) { return std::visit([&](auto&& raster) { return Raster(gdx::exp(raster)); }, RasterArgument(rasterArg).variant()); } Raster pow(py::object rasterArg1, py::object rasterArg2) { RasterArgument r1(rasterArg1); RasterArgument r2(rasterArg2); throwOnRasterTypeMismatch(r1.raster(), r2.raster(r1.raster())); return std::visit([&](auto&& raster) { using T = value_type<decltype(raster)>; return Raster(gdx::pow(raster, r2.get<T>(r1.raster()))); }, RasterArgument(rasterArg1).variant()); } Raster normalise(pybind11::object rasterArg) { return std::visit([&](auto&& raster) { return Raster(gdx::normalise<float>(raster)); }, RasterArgument(rasterArg).variant()); } Raster normaliseToByte(pybind11::object rasterArg) { return std::visit([&](auto&& raster) { return Raster(gdx::normalise<uint8_t>(raster)); }, RasterArgument(rasterArg).variant()); } bool any(py::object rasterArg) { return std::visit([&](auto&& raster) { return gdx::any_of(raster); }, RasterArgument(rasterArg).variant()); } bool all(py::object rasterArg) { return std::visit([&](auto&& raster) { return gdx::all_of(raster); }, RasterArgument(rasterArg).variant()); } py::object minimumValue(py::object rasterArg) { return std::visit([&](auto&& raster) { return pybind11::cast(gdx::minimum(raster)); }, RasterArgument(rasterArg).variant()); } py::object maximumValue(py::object rasterArg) { return std::visit([&](auto&& raster) { return pybind11::cast(gdx::maximum(raster)); }, RasterArgument(rasterArg).variant()); } double sum(py::object rasterArg) { return std::visit([&](auto&& raster) { return gdx::sum(raster); }, RasterArgument(rasterArg).variant()); } Raster clusterSize(py::object rasterArg, bool includeDiagonal) { auto diagonalSetting = includeDiagonal ? ClusterDiagonals::Include : ClusterDiagonals::Exclude; return std::visit([&](auto&& raster) { return Raster(gdx::cluster_size(raster, diagonalSetting)); }, RasterArgument(rasterArg).variant()); } Raster clusterSum(py::object rasterArg, py::object rasterToSumArg, bool includeDiagonal) { auto diagonalSetting = includeDiagonal ? ClusterDiagonals::Include : ClusterDiagonals::Exclude; return std::visit([diagonalSetting](auto&& raster, auto&& rasterToSum) { return Raster(gdx::cluster_sum<float>(raster, rasterToSum, diagonalSetting)); }, RasterArgument(rasterArg).variant(), RasterArgument(rasterToSumArg).variant()); } Raster clusterId(py::object rasterArg, bool includeDiagonal) { auto diagonalSetting = includeDiagonal ? ClusterDiagonals::Include : ClusterDiagonals::Exclude; return std::visit([&](auto&& raster) { return Raster(gdx::cluster_id(raster, diagonalSetting)); }, RasterArgument(rasterArg).variant()); } Raster clusterIdWithObstacles(py::object rasterArg, py::object obstacleRasterArg) { RasterArgument obstacleRaster(obstacleRasterArg); auto& obstacles = obstacleRaster.raster(); if (obstacles.type() != typeid(uint8_t)) { throw InvalidArgument("Expected obstacle raster to be of type uint8 (numpy.dtype('B'))"); } return std::visit([&](auto&& raster) { // Categories and obstacles have fixed types, so cast them auto categories = raster_cast<int32_t>(raster); return Raster(gdx::cluster_id_with_obstacles(categories, obstacles.get<uint8_t>())); }, RasterArgument(rasterArg).variant()); } Raster fuzzyClusterId(py::object rasterArg, float radius) { return std::visit([&](auto&& raster) { show_warning_if_clustering_on_floats(raster); return Raster(gdx::fuzzy_cluster_id(raster, radius)); }, RasterArgument(rasterArg).variant()); } Raster fuzzyClusterIdWithObstacles(py::object rasterArg, py::object obstacleRasterArg, float radius) { RasterArgument obstacleRaster(obstacleRasterArg); auto& obstacles = obstacleRaster.raster(); if (obstacles.type() != typeid(uint8_t)) { throw InvalidArgument("Expected obstacle raster to be of type uint8 (numpy.dtype('B'))"); } return std::visit([&](auto&& raster) { show_warning_if_clustering_on_floats(raster); // Categories and obstacles have fixed types, so cast them auto categories = raster_cast<int32_t>(raster); return Raster(gdx::fuzzy_cluster_id_with_obstacles(categories, obstacles.get<uint8_t>(), radius)); }, RasterArgument(rasterArg).variant()); } Raster distance(py::object targetArg, py::object obstaclesArg) { RasterArgument targetRasterArg(targetArg); auto& target = targetRasterArg.raster(); if (target.type() != typeid(uint8_t)) { throw InvalidArgument("Expected target raster to be of type uint8 (numpy.dtype('B')) actual type is {}", target.type().name()); } if (obstaclesArg.is_none()) { return Raster(gdx::distance(target.get<uint8_t>())); } else { RasterArgument obstaclesRasterArg(obstaclesArg); auto& obstacles = obstaclesRasterArg.raster(target); return Raster(gdx::distance(target.get<uint8_t>(), obstacles.get<uint8_t>())); } } Raster travelDistance(py::object rasterArg, py::object anyTravelTimeArg) { RasterArgument targetArg(rasterArg); auto& target = targetArg.raster(); if (target.type() != typeid(uint8_t)) { throw InvalidArgument("Expected target raster to be of type uint8 (numpy.dtype('B')) actual type is {}", target.type().name()); } return std::visit([&target](auto&& travelTime) { return Raster(gdx::travel_distance(target.get<uint8_t>(), travelTime)); }, RasterArgument(anyTravelTimeArg).variant()); } Raster sumWithinTravelDistance(py::object anyMask, py::object anyResistance, py::object anyValuesMap, double maxResistance, bool includeAdjacent) { return std::visit([maxResistance, includeAdjacent](auto&& mask, auto&& resistance, auto&& values) { return Raster(gdx::sum_within_travel_distance<float>(mask, resistance, values, static_cast<float>(maxResistance), includeAdjacent)); }, RasterArgument(anyMask).variant(), RasterArgument(anyResistance).variant(), RasterArgument(anyValuesMap).variant()); } Raster closestTarget(py::object rasterTargetsArg) { return std::visit([](auto&& target) { return Raster(gdx::closest_target(target)); }, RasterArgument(rasterTargetsArg).variant()); } Raster valueAtClosestTarget(py::object rasterTargetsArg, py::object valuesArg) { return std::visit([](auto&& target, auto&& values) { return Raster(gdx::value_at_closest_target(target, values)); }, RasterArgument(rasterTargetsArg).variant(), RasterArgument(valuesArg).variant()); } Raster valueAtClosestTravelTarget(py::object rasterTargetsArg, py::object travelTimeArg, py::object valuesArg) { return std::visit([](auto&& target, auto&& travelTimes, auto&& values) { return Raster(gdx::value_at_closest_travel_target(target, travelTimes, values)); }, RasterArgument(rasterTargetsArg).variant(), RasterArgument(travelTimeArg).variant(), RasterArgument(valuesArg).variant()); } Raster valueAtClosestLessThenTravelTarget(py::object rasterTargetsArg, py::object travelTimeArg, double maxTravelTime, py::object valuesArg) { return std::visit([maxTravelTime](auto&& target, auto&& travelTimes, auto&& values) { return Raster(gdx::value_at_closest_less_then_travel_target(target, travelTimes, static_cast<float>(maxTravelTime), values)); }, RasterArgument(rasterTargetsArg).variant(), RasterArgument(travelTimeArg).variant(), RasterArgument(valuesArg).variant()); } Raster nodeValueDistanceDecay(pybind11::object targetArg, pybind11::object travelTimeArg, double maxTravelTime, double a, double b) { return std::visit([maxTravelTime, a, b](auto&& target, auto&& travelTimes) { using TTravelTime = value_type<decltype(travelTimes)>; return Raster(gdx::node_value_distance_decay(target, travelTimes, truncate<TTravelTime>(maxTravelTime), truncate<float>(a), truncate<float>(b))); }, RasterArgument(targetArg).variant(), RasterArgument(travelTimeArg).variant()); } Raster categorySum(py::object clusterArg, py::object valuesArg) { RasterArgument clusters(clusterArg); throwOnInvalidClusterRaster(clusters.raster()); return std::visit([&](auto&& raster) { return Raster(gdx::category_sum(clusters.get<int32_t>(), raster)); }, RasterArgument(valuesArg).variant(clusters.raster())); } Raster categoryMin(py::object clusterArg, py::object valuesArg) { RasterArgument clusters(clusterArg); throwOnInvalidClusterRaster(clusters.raster()); return std::visit([&](auto&& raster) { return Raster(gdx::category_min(clusters.get<int32_t>(), raster)); }, RasterArgument(valuesArg).variant(clusters.raster())); } Raster categoryMax(py::object clusterArg, py::object valuesArg) { RasterArgument clusters(clusterArg); throwOnInvalidClusterRaster(clusters.raster()); return std::visit([&](auto&& raster) { return Raster(gdx::category_max(clusters.get<int32_t>(), raster)); }, RasterArgument(valuesArg).variant(clusters.raster())); } Raster categoryMode(py::object clusterArg, py::object valuesArg) { RasterArgument clusters(clusterArg); throwOnInvalidClusterRaster(clusters.raster()); return std::visit([&](auto&& raster) { return Raster(gdx::category_mode(clusters.get<int32_t>(), raster)); }, RasterArgument(valuesArg).variant(clusters.raster())); } Raster categoryFilterOr(py::object clusterArg, py::object filterArg) { RasterArgument clusters(clusterArg); throwOnInvalidClusterRaster(clusters.raster()); return std::visit([&](auto&& raster) { return Raster(gdx::category_filter_or(clusters.get<int32_t>(), raster)); }, RasterArgument(filterArg).variant()); } Raster categoryFilterAnd(py::object clusterArg, py::object filterArg) { RasterArgument clusters(clusterArg); throwOnInvalidClusterRaster(clusters.raster()); return std::visit([&](auto&& raster) { return Raster(gdx::category_filter_and(clusters.get<int32_t>(), raster)); }, RasterArgument(filterArg).variant()); } Raster categoryFilterNot(py::object clusterArg, py::object filterArg) { RasterArgument clusters(clusterArg); throwOnInvalidClusterRaster(clusters.raster()); return std::visit([&](auto&& raster) { return Raster(gdx::category_filter_not(clusters.get<int32_t>(), raster)); }, RasterArgument(filterArg).variant()); } Raster categorySumInBuffer(py::object clusterArg, py::object valuesArg, double radiusInMeter) { RasterArgument clusters(clusterArg); throwOnInvalidClusterRaster(clusters.raster()); return std::visit([&](auto&& raster) { return Raster(gdx::category_sum_in_buffer(clusters.get<int32_t>(), raster, static_cast<float>(radiusInMeter))); }, RasterArgument(valuesArg).variant()); } Raster sumInBuffer(const Raster& anyRaster, float radius, BufferStyle bufferStyle) { return std::visit([&](auto&& raster) { return Raster(gdx::sum_in_buffer(raster, radius, bufferStyle)); }, anyRaster.get()); } Raster maxInBuffer(const Raster& anyRaster, float radius) { return std::visit([&](auto&& raster) { return Raster(gdx::max_in_buffer(raster, radius)); }, anyRaster.get()); } Raster reclass(const std::string& mappingFilepath, py::object rasterArg) { RasterArgument r(rasterArg); return std::visit([&](auto&& inputRaster) { return std::visit([](auto&& resultRaster) { return Raster(std::move(resultRaster)); }, gdx::reclass(mappingFilepath, inputRaster)); }, r.variant()); } Raster reclass(const std::string& mappingFilepath, py::object rasterArg1, py::object rasterArg2) { RasterArgument r1(rasterArg1); RasterArgument r2(rasterArg2); return std::visit([&](auto&& raster1, auto&& raster2) { return std::visit([](auto&& resultRaster) { return Raster(std::move(resultRaster)); }, gdx::reclass(mappingFilepath, raster1, raster2)); }, r1.variant(), r2.variant()); } Raster reclass(const std::string& mappingFilepath, py::object rasterArg1, py::object rasterArg2, py::object rasterArg3) { RasterArgument r1(rasterArg1); RasterArgument r2(rasterArg2); RasterArgument r3(rasterArg3); return std::visit([&](auto&& raster1, auto&& raster2, auto&& raster3) { return std::visit([](auto&& resultRaster) { return Raster(std::move(resultRaster)); }, gdx::reclass(mappingFilepath, raster1, raster2, raster3)); }, r1.variant(), r2.variant(), r3.variant()); } Raster reclassi(const std::string& mappingFilepath, py::object rasterArg, int32_t index) { RasterArgument r(rasterArg); return std::visit([&](auto&& raster) { return std::visit([](auto&& resultRaster) { return Raster(std::move(resultRaster)); }, gdx::reclassi(mappingFilepath, raster, index)); }, r.variant()); } Raster reclassi(const std::string& mappingFilepath, py::object rasterArg1, py::object rasterArg2, int32_t index) { RasterArgument r1(rasterArg1); RasterArgument r2(rasterArg2); return std::visit([&](auto&& raster1, auto&& raster2) { return std::visit([](auto&& resultRaster) { return Raster(std::move(resultRaster)); }, gdx::reclassi(mappingFilepath, raster1, raster2, index)); }, r1.variant(), r2.variant()); } Raster reclassi(const std::string& mappingFilepath, py::object rasterArg1, py::object rasterArg2, py::object rasterArg3, int32_t index) { RasterArgument r1(rasterArg1); RasterArgument r2(rasterArg2); RasterArgument r3(rasterArg3); return std::visit([&](auto&& raster1, auto&& raster2, auto&& raster3) { return std::visit([](auto&& resultRaster) { return Raster(std::move(resultRaster)); }, gdx::reclassi(mappingFilepath, raster1, raster2, raster3, index)); }, r1.variant(), r2.variant(), r3.variant()); } Raster nreclass(const std::string& mappingFilepath, py::object rasterArg) { return std::visit([&](auto&& raster) { return Raster(gdx::nreclass(mappingFilepath, raster)); }, RasterArgument(rasterArg).variant()); } Raster logicalAnd(py::object rasterArg1, py::object rasterArg2) { return RasterArgument(rasterArg1).raster() && RasterArgument(rasterArg2).raster(); } Raster logicalAnd(py::object rasterArg1, py::object rasterArg2, py::object rasterArg3) { return RasterArgument(rasterArg1).raster() && RasterArgument(rasterArg2).raster() && RasterArgument(rasterArg3).raster(); } Raster logicalAnd(py::object rasterArg1, py::object rasterArg2, py::object rasterArg3, py::object rasterArg4) { return RasterArgument(rasterArg1).raster() && RasterArgument(rasterArg2).raster() && RasterArgument(rasterArg3).raster() && RasterArgument(rasterArg4).raster(); } Raster logicalAnd(py::object rasterArg1, py::object rasterArg2, py::object rasterArg3, py::object rasterArg4, py::object rasterArg5) { return RasterArgument(rasterArg1).raster() && RasterArgument(rasterArg2).raster() && RasterArgument(rasterArg3).raster() && RasterArgument(rasterArg4).raster() && RasterArgument(rasterArg5).raster(); } Raster logicalAnd(py::object rasterArg1, py::object rasterArg2, py::object rasterArg3, py::object rasterArg4, py::object rasterArg5, py::object rasterArg6) { return RasterArgument(rasterArg1).raster() && RasterArgument(rasterArg2).raster() && RasterArgument(rasterArg3).raster() && RasterArgument(rasterArg4).raster() && RasterArgument(rasterArg5).raster() && RasterArgument(rasterArg6).raster(); } Raster logicalAnd(py::object rasterArg1, py::object rasterArg2, py::object rasterArg3, py::object rasterArg4, py::object rasterArg5, py::object rasterArg6, py::object rasterArg7) { return RasterArgument(rasterArg1).raster() && RasterArgument(rasterArg2).raster() && RasterArgument(rasterArg3).raster() && RasterArgument(rasterArg4).raster() && RasterArgument(rasterArg5).raster() && RasterArgument(rasterArg6).raster() && RasterArgument(rasterArg7).raster(); } Raster logicalAnd(py::object rasterArg1, py::object rasterArg2, py::object rasterArg3, py::object rasterArg4, py::object rasterArg5, py::object rasterArg6, py::object rasterArg7, py::object rasterArg8) { return RasterArgument(rasterArg1).raster() && RasterArgument(rasterArg2).raster() && RasterArgument(rasterArg3).raster() && RasterArgument(rasterArg4).raster() && RasterArgument(rasterArg5).raster() && RasterArgument(rasterArg6).raster() && RasterArgument(rasterArg7).raster() && RasterArgument(rasterArg8).raster(); } Raster logicalOr(py::object rasterArg1, py::object rasterArg2) { return RasterArgument(rasterArg1).raster() || RasterArgument(rasterArg2).raster(); } Raster logicalOr(py::object rasterArg1, py::object rasterArg2, py::object rasterArg3) { return RasterArgument(rasterArg1).raster() || RasterArgument(rasterArg2).raster() || RasterArgument(rasterArg3).raster(); } Raster logicalOr(py::object rasterArg1, py::object rasterArg2, py::object rasterArg3, py::object rasterArg4) { return RasterArgument(rasterArg1).raster() || RasterArgument(rasterArg2).raster() || RasterArgument(rasterArg3).raster() || RasterArgument(rasterArg4).raster(); } Raster logicalOr(py::object rasterArg1, py::object rasterArg2, py::object rasterArg3, py::object rasterArg4, py::object rasterArg5) { return RasterArgument(rasterArg1).raster() || RasterArgument(rasterArg2).raster() || RasterArgument(rasterArg3).raster() || RasterArgument(rasterArg4).raster() || RasterArgument(rasterArg5).raster(); } Raster logicalOr(py::object rasterArg1, py::object rasterArg2, py::object rasterArg3, py::object rasterArg4, py::object rasterArg5, py::object rasterArg6) { return RasterArgument(rasterArg1).raster() || RasterArgument(rasterArg2).raster() || RasterArgument(rasterArg3).raster() || RasterArgument(rasterArg4).raster() || RasterArgument(rasterArg5).raster() || RasterArgument(rasterArg6).raster(); } Raster logicalOr(py::object rasterArg1, py::object rasterArg2, py::object rasterArg3, py::object rasterArg4, py::object rasterArg5, py::object rasterArg6, py::object rasterArg7) { return RasterArgument(rasterArg1).raster() || RasterArgument(rasterArg2).raster() || RasterArgument(rasterArg3).raster() || RasterArgument(rasterArg4).raster() || RasterArgument(rasterArg5).raster() || RasterArgument(rasterArg6).raster() || RasterArgument(rasterArg7).raster(); } Raster logicalOr(py::object rasterArg1, py::object rasterArg2, py::object rasterArg3, py::object rasterArg4, py::object rasterArg5, py::object rasterArg6, py::object rasterArg7, py::object rasterArg8) { return RasterArgument(rasterArg1).raster() || RasterArgument(rasterArg2).raster() || RasterArgument(rasterArg3).raster() || RasterArgument(rasterArg4).raster() || RasterArgument(rasterArg5).raster() || RasterArgument(rasterArg6).raster() || RasterArgument(rasterArg7).raster() || RasterArgument(rasterArg8).raster(); } Raster logicalNot(py::object rasterArg) { return !RasterArgument(rasterArg).raster(); } Raster ifThenElse(py::object ifArg, py::object thenArg, py::object elseArg) { RasterArgument ifRasterArg(ifArg); auto& ifRaster = ifRasterArg.raster(); return std::visit([](auto&& rasterIf, auto&& rasterThen, auto&& rasterElse) -> Raster { return Raster(gdx::if_then_else(rasterIf, rasterThen, rasterElse)); }, ifRaster.get(), RasterArgument(thenArg).variant(ifRaster.metadata()), RasterArgument(elseArg).variant(ifRaster.metadata())); } bool rasterEqual(py::object rasterArg1, py::object rasterArg2) { RasterArgument r1(rasterArg1); auto& raster1 = r1.raster(); return raster1.equalTo(RasterArgument(rasterArg2).raster(raster1)); } Raster rasterEqualOneOf(py::object rasterArg, const std::vector<double>& values) { return std::visit([&values](auto&& raster) -> Raster { using T = value_type<decltype(raster)>; std::vector<T> tvalues(values.size()); std::transform(values.begin(), values.end(), tvalues.begin(), [](auto v) { return static_cast<T>(v); }); return Raster(gdx::rasterEqualOneOf(raster, tvalues)); }, RasterArgument(rasterArg).variant()); } bool allClose(py::object rasterArg1, py::object rasterArg2, double tolerance) { RasterArgument r1(rasterArg1); auto& raster1 = r1.raster(); return raster1.tolerant_data_equal_to(RasterArgument(rasterArg2).raster(raster1), tolerance); } Raster isClose(py::object rasterArg1, py::object rasterArg2, double relTolerance) { RasterArgument r1(rasterArg1); auto& raster1 = r1.raster(); RasterArgument r2(rasterArg2); auto& raster2 = r2.raster(raster1); throwOnRasterTypeMismatch(raster1, raster2); return std::visit([&raster2, relTolerance](auto&& raster1) -> Raster { using T = value_type<decltype(raster1)>; return Raster(gdx::isClose(raster1, raster2.get<T>(), static_cast<T>(relTolerance))); }, raster1.get()); } template <typename T> static MaskedRaster<uint8_t> maskedis_nodata(const MaskedRaster<T>& input) { MaskedRaster<uint8_t> output(input.metadata()); // input.metadata().nodata may not be representable as uint8, and that gives numpy error // when doing "result.array" on the result in python. So set nodata to 255. output.set_nodata(255); gdx::is_nodata(input, output); return output; } Raster is_nodata(py::object rasterArg) { return std::visit([&](auto&& raster) { return Raster(maskedis_nodata(raster)); }, RasterArgument(rasterArg).variant()); } Raster replaceValue(py::object rasterArg, py::object searchValue, py::object replaceValue) { return std::visit([&](auto&& raster) { using T = value_type<decltype(raster)>; return Raster(gdx::replace_value(raster, searchValue.cast<T>(), replaceValue.cast<T>())); }, RasterArgument(rasterArg).variant()); } Raster replaceNodata(py::object rasterArg, py::object replaceValue) { return std::visit([&](auto&& raster) { using T = value_type<decltype(raster)>; return Raster(gdx::replace_nodata(raster, replaceValue.cast<T>())); }, RasterArgument(rasterArg).variant()); } Raster& replaceNodataInPlace(Raster& raster, double replaceValue) { std::visit([replaceValue](auto&& ras) { using T = value_type<decltype(ras)>; gdx::replace_nodata_in_place(ras, static_cast<T>(replaceValue)); }, raster.get()); return raster; } void drawShapeFileOnRaster(Raster& anyRaster, const std::string& shapeFilepath) { return std::visit([&](auto&& raster) { gdx::draw_shapefile_on_raster(raster, shapeFilepath); }, anyRaster.get()); } bool lddValidate(py::object rasterArg, const std::function<void(int32_t, int32_t)>& loopCb, const std::function<void(int32_t, int32_t)>& invalidValueCb, const std::function<void(int32_t, int32_t)>& endsInNodataCb, const std::function<void(int32_t, int32_t)>& outsideOfMapCb) { return std::visit([&](auto&& raster) -> bool { using T = value_type<decltype(raster)>; if constexpr (std::is_same_v<T, uint8_t>) { return gdx::validate_ldd(raster, loopCb, invalidValueCb, endsInNodataCb, outsideOfMapCb); } else { throw InvalidArgument("Ldd raster should be of type uint8_t"); } }, RasterArgument(rasterArg).variant()); } Raster lddFix(py::object rasterArg) { return std::visit([&](auto&& raster) -> Raster { using T = value_type<decltype(raster)>; if constexpr (std::is_same_v<T, uint8_t>) { auto& meta = raster.metadata(); Point<int32_t> topLeft(int32_t(meta.xll), int32_t(meta.yll - meta.rows)); std::set<Cell> errors; auto res = gdx::fix_ldd(raster, errors); for (auto& cell : errors) { auto point = inf::gdal::projected_to_geographic(31370, Point<double>(topLeft.x + cell.c, topLeft.y + cell.r)); fmt::print(stderr, "Error cell: {}x{} -> {}x{}\n", cell.r, cell.c, point.x, point.y); } if (!errors.empty()) { throw RuntimeError("{} cells could not be fixed", errors.size()); } return Raster(std::move(res)); } else { throw InvalidArgument("Ldd raster should be of type uint8_t"); } }, RasterArgument(rasterArg).variant()); } Raster accuflux(py::object lddArg, py::object freightArg) { RasterArgument ldd(lddArg); auto& lddRaster = ldd.raster(); if (lddRaster.type() != typeid(uint8_t)) { throw InvalidArgument("Expected ldd raster to be of type uint8 (numpy.dtype('B'))"); } RasterArgument freight(freightArg); auto& freightRaster = freight.raster(lddRaster, typeid(float)); if (freightRaster.type() != typeid(float)) { throw InvalidArgument("Expected freightMap raster to be of type float (numpy.dtype('float32'))"); } return Raster(gdx::accuflux(lddRaster.get<uint8_t>(), freightRaster.get<float>())); } Raster accufractionflux(py::object lddArg, py::object freightArg, py::object fractionArg) { RasterArgument ldd(lddArg); auto& lddRaster = ldd.raster(); if (lddRaster.type() != typeid(uint8_t)) { throw InvalidArgument("Expected ldd raster to be of type uint8 (numpy.dtype('B'))"); } RasterArgument freight(freightArg); auto& freightRaster = freight.raster(lddRaster, typeid(float)); if (freightRaster.type() != typeid(float)) { throw InvalidArgument("Expected freight map raster to be of type float (numpy.dtype('float32'))"); } RasterArgument fraction(fractionArg); auto& fractionRaster = fraction.raster(lddRaster, typeid(float)); if (fractionRaster.type() != typeid(float)) { throw InvalidArgument("Expected fraction map raster to be of type float (numpy.dtype('float32'))"); } return Raster(gdx::accufractionflux(lddRaster.get<uint8_t>(), freightRaster.get<float>(), fractionRaster.get<float>())); } Raster fluxOrigin(py::object lddArg, py::object freightArg, py::object fractionArg, py::object stationArg) { RasterArgument ldd(lddArg); auto& lddRaster = ldd.raster(); if (lddRaster.type() != typeid(uint8_t)) { throw InvalidArgument("Expected ldd raster to be of type uint8 (numpy.dtype('B'))"); } RasterArgument freight(freightArg); auto& freightRaster = freight.raster(lddRaster, typeid(float)); if (freightRaster.type() != typeid(float)) { throw InvalidArgument("Expected freight map raster to be of type float (numpy.dtype('float32'))"); } RasterArgument fraction(fractionArg); auto& fractionRaster = fraction.raster(lddRaster, typeid(float)); if (fractionRaster.type() != typeid(float)) { throw InvalidArgument("Expected fraction map raster to be of type float (numpy.dtype('float32'))"); } RasterArgument station(stationArg); auto& stationRaster = fraction.raster(); if (stationRaster.type() != typeid(int32_t)) { throw InvalidArgument("Expected station map raster to be of type int (numpy.dtype('int32'))"); } return Raster(gdx::flux_origin(lddRaster.get<uint8_t>(), freightRaster.get<float>(), fractionRaster.get<float>(), stationRaster.get<int32_t>())); } Raster lddCluster(py::object lddArg, py::object idArg) { RasterArgument ldd(lddArg); auto& lddRaster = ldd.raster(); if (lddRaster.type() != typeid(uint8_t)) { throw InvalidArgument("Expected ldd raster to be of type uint8 (numpy.dtype('B'))"); } RasterArgument ids(idArg); auto& idsRaster = ids.raster(); if (idsRaster.type() != typeid(int32_t)) { throw InvalidArgument("Expected id map raster to be of type int (numpy.dtype('int32'))"); } return Raster(gdx::ldd_cluster(lddRaster.get<uint8_t>(), idsRaster.get<int32_t>())); } Raster lddDist(py::object lddArg, py::object pointsArg, py::object frictionArg) { RasterArgument ldd(lddArg); auto& lddRaster = ldd.raster(); if (lddRaster.type() != typeid(uint8_t)) { throw InvalidArgument("Expected ldd raster to be of type uint8 (numpy.dtype('B'))"); } RasterArgument points(pointsArg); auto& pointsRaster = points.raster(); if (pointsRaster.type() != typeid(float)) { throw InvalidArgument("Expected points map raster to be of type float (numpy.dtype('float32'))"); } RasterArgument friction(frictionArg); auto& frictionRaster = friction.raster(lddRaster, typeid(float)); if (frictionRaster.type() != typeid(float)) { throw InvalidArgument("Expected friction map raster to be of type float (numpy.dtype('float32'))"); } return Raster(gdx::ldd_dist(lddRaster.get<uint8_t>(), pointsRaster.get<float>(), frictionRaster.get<float>())); } Raster slopeLength(py::object lddArg, py::object frictionArg) { RasterArgument ldd(lddArg); auto& lddRaster = ldd.raster(); if (lddRaster.type() != typeid(uint8_t)) { throw InvalidArgument("Expected ldd raster to be of type uint8 (numpy.dtype('B'))"); } RasterArgument friction(frictionArg); auto& frictionRaster = friction.raster(lddRaster, typeid(float)); if (frictionRaster.type() != typeid(float)) { throw InvalidArgument("Expected friction map raster to be of type float (numpy.dtype('float32'))"); } return Raster(gdx::slope_length(lddRaster.get<uint8_t>(), frictionRaster.get<float>())); } Raster max_upstream_dist(py::object lddArg) { RasterArgument ldd(lddArg); auto& lddRaster = ldd.raster(); if (lddRaster.type() != typeid(uint8_t)) { throw InvalidArgument("Expected ldd raster to be of type uint8 (numpy.dtype('B'))"); } return Raster(gdx::max_upstream_dist(lddRaster.get<uint8_t>())); } RasterStats<512> statistics(pybind11::object rasterArg) { return std::visit([&](auto&& raster) { using T = value_type<decltype(raster)>; return gdx::statistics<decltype(raster), 512>(raster, std::numeric_limits<T>::max()); }, RasterArgument(rasterArg).variant()); } void tableRow(const std::string& output, pybind11::object rasterArg, pybind11::object categoryArg, Operation op, const std::string& label, bool append) { RasterArgument r1(rasterArg); RasterArgument r2(categoryArg); return std::visit([&](auto&& raster, auto&& categories) { return gdx::table_row(raster, categories, op, output, label, append); }, r1.variant(), r2.variant()); } Raster& randomFill(Raster& raster, double minValue, double maxValue) { std::visit([minValue, maxValue](auto&& typedRaster) { using T = value_type<decltype(typedRaster)>; if (minValue < static_cast<double>(std::numeric_limits<T>::lowest())) { throw InvalidArgument("minimum value does not fit in the raster datatype ({} < {})", minValue, std::numeric_limits<T>::lowest()); } if (maxValue > static_cast<double>(std::numeric_limits<T>::max())) { throw InvalidArgument("maximum value does not fit in the raster datatype ({} > {})", maxValue, std::numeric_limits<T>::max()); } gdx::fill_random(typedRaster, truncate<T>(minValue), truncate<T>(maxValue)); }, raster.get()); return raster; } } }
34.556767
201
0.671117
VITObelgium
47dd6b1a6ea7124288472a0a0d0021ee76da3162
98
cpp
C++
Chroma/src/Chroma/Core/Time.cpp
ttalexander2/chroma
0e9946e66158938ebd6497d5bf3acfba8fbe9fee
[ "MIT" ]
1
2022-03-07T01:54:59.000Z
2022-03-07T01:54:59.000Z
Chroma/src/Chroma/Core/Time.cpp
ttalexander2/chroma
0e9946e66158938ebd6497d5bf3acfba8fbe9fee
[ "MIT" ]
20
2021-08-16T16:52:43.000Z
2022-03-26T02:47:09.000Z
Chroma/src/Chroma/Core/Time.cpp
ttalexander2/chroma
0e9946e66158938ebd6497d5bf3acfba8fbe9fee
[ "MIT" ]
null
null
null
#include "chromapch.h" #include "Time.h" namespace Chroma { Time* Time::m_Instance = nullptr; }
12.25
34
0.704082
ttalexander2
47df4e7e7ac69a26794d53e8fbb72b7b2611ffc9
2,239
cpp
C++
Source/WebCore/bindings/js/JSAnimationTimelineCustom.cpp
ijsf/DeniseEmbeddableWebKit
57dfc6783d60f8f59b7129874e60f84d8c8556c9
[ "BSD-3-Clause" ]
null
null
null
Source/WebCore/bindings/js/JSAnimationTimelineCustom.cpp
ijsf/DeniseEmbeddableWebKit
57dfc6783d60f8f59b7129874e60f84d8c8556c9
[ "BSD-3-Clause" ]
9
2020-04-18T18:47:18.000Z
2020-04-18T18:52:41.000Z
Source/WebCore/bindings/js/JSAnimationTimelineCustom.cpp
ijsf/DeniseEmbeddableWebKit
57dfc6783d60f8f59b7129874e60f84d8c8556c9
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) Canon Inc. 2016 * * Redistribution and use in source and binary forms, with or without * modification, are permitted, provided that the following conditions * are required to be met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Canon Inc. nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CANON INC. AND ITS 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 CANON INC. AND ITS CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #if ENABLE(WEB_ANIMATIONS) #include "JSAnimationTimeline.h" #include "DocumentTimeline.h" #include "JSDOMBinding.h" #include "JSDocumentTimeline.h" using namespace JSC; namespace WebCore { JSValue toJSNewlyCreated(ExecState*, JSDOMGlobalObject* globalObject, Ref<AnimationTimeline>&& value) { if (value->isDocumentTimeline()) return createWrapper<DocumentTimeline>(globalObject, WTFMove(value)); return createWrapper<AnimationTimeline>(globalObject, WTFMove(value)); } JSValue toJS(ExecState* state, JSDOMGlobalObject* globalObject, AnimationTimeline& value) { return wrap(state, globalObject, value); } } // namespace WebCore #endif // ENABLE(WEB_ANIMATIONS)
39.280702
101
0.770433
ijsf
47e1cdc967d6d730212be9ed68faf2379bd503fd
2,152
cpp
C++
ENgine/Root/Assets/AssetScene.cpp
ENgineE777/OakEngine
6890fc89a0e9d151e7a0bcc1c276c13594616e9a
[ "Zlib" ]
13
2020-12-02T02:13:29.000Z
2022-03-11T06:14:54.000Z
ENgine/Root/Assets/AssetScene.cpp
ENgineE777/OakEngine
6890fc89a0e9d151e7a0bcc1c276c13594616e9a
[ "Zlib" ]
null
null
null
ENgine/Root/Assets/AssetScene.cpp
ENgineE777/OakEngine
6890fc89a0e9d151e7a0bcc1c276c13594616e9a
[ "Zlib" ]
null
null
null
#include "Root/Root.h" #ifdef OAK_EDITOR #include "Editor/Editor.h" #endif namespace Oak { CLASSREG(Asset, AssetScene, "AssetScene") META_DATA_DESC(AssetScene) META_DATA_DESC_END() void AssetScene::EnableTasks(bool set) { GetScene()->EnableTasks(set); } Scene* AssetScene::GetScene() { if (!scene) { scene = new Scene(); scene->Init(); scene->Load(path.c_str()); scene->EnableTasks(false); } return scene; } void AssetScene::Reload() { } void AssetScene::LoadMetaData(JsonReader& reader) { reader.Read("selected_entity", selectedEntityID); reader.Read("camera2DMode", camera2DMode); reader.Read("camera3DAngles", camera3DAngles); reader.Read("camera3DPos", camera3DPos); reader.Read("camera2DPos", camera2DPos); reader.Read("camera2DZoom", camera2DZoom); } #ifdef OAK_EDITOR void AssetScene::SaveMetaData(JsonWriter& writer) { writer.Write("selected_entity", selectedEntityID); writer.Write("camera2DMode", camera2DMode); writer.Write("camera3DAngles", camera3DAngles); writer.Write("camera3DPos", camera3DPos); writer.Write("camera2DPos", camera2DPos); writer.Write("camera2DZoom", camera2DZoom); GetScene()->Save(GetScene()->projectScenePath); } void AssetScene::ActivateScene(bool act) { if (!act) { camera2DMode = editor.freeCamera.mode2D; camera3DAngles = editor.freeCamera.angles; camera3DPos = editor.freeCamera.pos; camera2DPos = editor.freeCamera.pos2D; camera2DZoom = editor.freeCamera.zoom2D; selectedEntityID = editor.selectedEntity ? editor.selectedEntity->GetUID() : -1; editor.SelectEntity(nullptr); EnableTasks(false); } else { editor.freeCamera.mode2D = camera2DMode; editor.freeCamera.angles = camera3DAngles; editor.freeCamera.pos = camera3DPos; editor.freeCamera.pos2D = camera2DPos; editor.freeCamera.zoom2D = camera2DZoom; EnableTasks(true); if (selectedEntityID != -1) { editor.SelectEntity(scene->FindEntity(selectedEntityID)); } } } const char* AssetScene::GetSceneEntityType() { return nullptr; } #endif void AssetScene::Release() { DELETE_PTR(scene) } };
19.743119
83
0.71329
ENgineE777
47e5c0da8f9310c17607f0b4d123db2fb0d999f8
510
hpp
C++
include/tao/pegtl/internal/eol_pair.hpp
TheBB/PEGTL
9370da4e99e6836555321ac60fd988b5d1bcbaed
[ "BSL-1.0" ]
null
null
null
include/tao/pegtl/internal/eol_pair.hpp
TheBB/PEGTL
9370da4e99e6836555321ac60fd988b5d1bcbaed
[ "BSL-1.0" ]
null
null
null
include/tao/pegtl/internal/eol_pair.hpp
TheBB/PEGTL
9370da4e99e6836555321ac60fd988b5d1bcbaed
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2017-2021 Dr. Colin Hirsch and Daniel Frey // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) #ifndef TAO_PEGTL_INTERNAL_EOL_PAIR_HPP #define TAO_PEGTL_INTERNAL_EOL_PAIR_HPP #include <cstddef> #include <utility> #include "../config.hpp" namespace TAO_PEGTL_NAMESPACE::internal { using eol_pair = std::pair< bool, std::size_t >; } // namespace TAO_PEGTL_NAMESPACE::internal #endif
25.5
91
0.766667
TheBB
47e7711fb408021c72e492e4e604f3609a06de80
245
cpp
C++
sources/SkyboxShader.cpp
HamilcarR/Echeyde
c7b177834fcabe6ac31c563edc6d4627ebb24b98
[ "MIT" ]
2
2021-08-25T08:03:07.000Z
2021-11-20T17:00:03.000Z
sources/SkyboxShader.cpp
HamilcarR/Echeyde
c7b177834fcabe6ac31c563edc6d4627ebb24b98
[ "MIT" ]
2
2017-03-11T02:30:13.000Z
2017-04-07T09:00:02.000Z
sources/SkyboxShader.cpp
HamilcarR/Echeyde
c7b177834fcabe6ac31c563edc6d4627ebb24b98
[ "MIT" ]
1
2018-11-16T17:08:47.000Z
2018-11-16T17:08:47.000Z
#include "../headers/SkyboxShader.h" SkyboxShader::SkyboxShader() :Shader() { } SkyboxShader::SkyboxShader(const char* vertex, const char* fragment) : Shader(std::string(vertex), std::string(fragment)){ } SkyboxShader::~SkyboxShader() { }
15.3125
122
0.714286
HamilcarR
47f6b6f0c8282717583e13aa4389050ab25e646c
2,044
cpp
C++
LeetCode/0019/0019_1.cpp
samsonwang/ToyCpp
a6a757aacf1a0e6d9ba3c943c5744fde611a2f7c
[ "MIT" ]
null
null
null
LeetCode/0019/0019_1.cpp
samsonwang/ToyCpp
a6a757aacf1a0e6d9ba3c943c5744fde611a2f7c
[ "MIT" ]
null
null
null
LeetCode/0019/0019_1.cpp
samsonwang/ToyCpp
a6a757aacf1a0e6d9ba3c943c5744fde611a2f7c
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(NULL) {} }; void printList(ListNode* head, const string& info) { cout << info; ListNode* roll = head; while (roll) { cout << roll->val << " "; roll = roll->next; } cout << endl; } // 翻转链表 ListNode* reverseList(ListNode* head) { printList(head, "**before reverse: "); ListNode* temp1 = head; ListNode* temp2 = head->next; while (temp2) { ListNode* t = temp2->next; temp2->next = temp1; temp1 = temp2; temp2 = t; } head->next = NULL; printList(temp1, "**after reverse: "); return temp1; } // 单向链表删去倒数第n个节点 // 这道题是链表的基本操作 ListNode* removeNthFromEnd(ListNode* head, int n) { if (head == NULL) { return NULL; } // 删去最后一个 if (n==1) { if (head->next == NULL) { return NULL; } ListNode* temp = head; while (temp->next) { if (temp->next->next == NULL) { temp->next = NULL; break; } temp = temp->next; } return head; } // 翻转链表 ListNode* temp1 = reverseList(head); // temp1 此时是翻转后链表的头结点 // 找到需要删除的倒数第n个结点 ListNode* temp3 = temp1; for (int i=2; i<n; ++i) { temp3 = temp3->next; } // temp3 此时是需要删除的节点的前一个节点 // 如果删去的是头结点 if (temp3->next == head) { temp3->next = NULL; } else { temp3->next = temp3->next->next; } // 关于内存释放问题,由于不知道内存是如何申请的(malloc,new),所以不能轻易释放 // 此时节点删除完成 return reverseList(temp1); } int main(int argc, char* argv[]) { ListNode preHead(0); ListNode* temp = &preHead; for (int i=0; i<1; ++i) { temp->next = new ListNode(i+1); temp = temp->next; } printList(preHead.next, "original: "); ListNode* ret = removeNthFromEnd(preHead.next, 1); printList(ret, "result: "); return 0; }
17.773913
54
0.521526
samsonwang
47fa055422237635afb65e95b064a9c958d3d95d
1,570
hpp
C++
remodet_repository_wdh_part/include/caffe/tracker/halfmerge_layer.hpp
UrwLee/Remo_experience
a59d5b9d6d009524672e415c77d056bc9dd88c72
[ "MIT" ]
null
null
null
remodet_repository_wdh_part/include/caffe/tracker/halfmerge_layer.hpp
UrwLee/Remo_experience
a59d5b9d6d009524672e415c77d056bc9dd88c72
[ "MIT" ]
null
null
null
remodet_repository_wdh_part/include/caffe/tracker/halfmerge_layer.hpp
UrwLee/Remo_experience
a59d5b9d6d009524672e415c77d056bc9dd88c72
[ "MIT" ]
null
null
null
#ifndef CAFFE_TRACKER_HALFMERGE_LAYER_HPP_ #define CAFFE_TRACKER_HALFMERGE_LAYER_HPP_ #include "caffe/blob.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" namespace caffe { /** * 该层用于对双通道样本进行合并。 * 计算方法: * Input(x): [2N,C,H,W] -> Output(y): [N,2C,H,W] * y(n,C+l,i,j) = x(N+n,l,i,j) * 该层在Tracker中使用,用于对prev/curr特征进行融合。 */ template <typename Dtype> void Merge(Dtype* bottom_data, const vector<int> shape, const bool forward, Dtype* top_data); template <typename Dtype> class HalfmergeLayer : public Layer<Dtype> { public: explicit HalfmergeLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "Halfmerge"; } virtual inline int ExactNumBottomBlobs() const { return 1; } virtual inline int ExactNumTopBlobs() const { return 1; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); }; } // namespace caffe #endif
31.4
78
0.703185
UrwLee
47fea34b9e1de67436a5ffda9629ad86a9810779
2,043
hpp
C++
include/irc/ctcp_parser.hpp
libircpp/libircpp
b7df7f3b20881c11c842b81224bc520bc742cdb1
[ "BSL-1.0" ]
3
2016-02-01T19:57:44.000Z
2020-11-12T22:59:29.000Z
include/irc/ctcp_parser.hpp
libircpp/libircpp
b7df7f3b20881c11c842b81224bc520bc742cdb1
[ "BSL-1.0" ]
null
null
null
include/irc/ctcp_parser.hpp
libircpp/libircpp
b7df7f3b20881c11c842b81224bc520bc742cdb1
[ "BSL-1.0" ]
null
null
null
// Copyright Joseph Dobson, Andrea Zanellato 2014 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef IRC_CTCP_PARSER_HPP #define IRC_CTCP_PARSER_HPP //SPEEDS UP SPIRIT COMPILE TIMES #define BOOST_SPIRIT_NO_PREDEFINED_TERMINALS 1 #define BOOST_SPIRIT_USE_PHOENIX_V3 1 #include "ctcp.hpp" #include <boost/fusion/include/vector.hpp> #include <boost/spirit/home/qi.hpp> #include <string> namespace irc { namespace fsn = boost::fusion; namespace qi = boost::spirit::qi; template<typename Iterator> struct ctcp_parser : qi::grammar<Iterator, fsn::vector<ctcp::command, std::string>(), qi::space_type> { template<typename Val> using rule = qi::rule<Iterator, Val(), qi::space_type>; // Space sensitive template<typename Val> using rule_ss = qi::rule<Iterator, Val()>; ctcp_parser() : ctcp_parser::base_type(ctcp_msg) { qi::attr_type attr; qi::char_type char_; qi::lit_type lit; ctcp_cmd.add ("ACTION", ctcp::command::action)("CLIENTINFO", ctcp::command::clientinfo) ("DCC", ctcp::command::dcc) ("ERRMSG", ctcp::command::errmsg) ("FINGER", ctcp::command::finger)("PING", ctcp::command::ping) ("SED", ctcp::command::sed) ("SOURCE", ctcp::command::source) ("TIME", ctcp::command::time) ("USERINFO", ctcp::command::userinfo) ("VERSION", ctcp::command::version); ctcp_args %= +~char_('\001'); ctcp_msg %= ( (lit('\001') >> ctcp_cmd) >> -ctcp_args ) | ( attr(ctcp::command::none) >> attr(std::string{}) ); } private: rule_ss<std::string> ctcp_args; qi::symbols<char, ctcp::command> ctcp_cmd; rule<fsn::vector<ctcp::command, std::string>> ctcp_msg; }; } // namespace irc #endif // IRC_CTCP_PARSER_HPP
31.430769
83
0.605972
libircpp
9a00f9184b5d906a9a36bbcebec68a8c2b83c024
7,041
cpp
C++
Src/Editor/FrEdToolBar.cpp
VladGordienko28/FluorineEngine-I
31114c41884d41ec60d04dba7965bc83be47d229
[ "MIT" ]
null
null
null
Src/Editor/FrEdToolBar.cpp
VladGordienko28/FluorineEngine-I
31114c41884d41ec60d04dba7965bc83be47d229
[ "MIT" ]
null
null
null
Src/Editor/FrEdToolBar.cpp
VladGordienko28/FluorineEngine-I
31114c41884d41ec60d04dba7965bc83be47d229
[ "MIT" ]
null
null
null
/*============================================================================= FrEdToolBar.cpp: An editor main toolbar. Copyright Aug.2016 Vlad Gordienko. =============================================================================*/ #include "Editor.h" /*----------------------------------------------------------------------------- WEditorToolBar implementation. -----------------------------------------------------------------------------*/ // // ToolBar constructor. // WEditorToolBar::WEditorToolBar( WContainer* InOwner, WWindow* InRoot ) : WToolBar( InOwner, InRoot ) { // Initialize own fields. SetSize( 150, 35 ); // Create buttons. NewProjectButton = new WPictureButton( this, InRoot ); NewProjectButton->Tooltip = L"New Project"; NewProjectButton->Scale = TSize( 16, 16 ); NewProjectButton->Offset = TPoint( 0, 64 ); NewProjectButton->Picture = Root->Icons; NewProjectButton->EventClick = WIDGET_EVENT(WEditorToolBar::ButtonNewProjectClick); NewProjectButton->SetSize( 25, 25 ); this->AddElement( NewProjectButton ); OpenProjectButton = new WPictureButton( this, InRoot ); OpenProjectButton->Tooltip = L"Open Project"; OpenProjectButton->Scale = TSize( 16, 16 ); OpenProjectButton->Offset = TPoint( 16, 64 ); OpenProjectButton->Picture = Root->Icons; OpenProjectButton->EventClick = WIDGET_EVENT(WEditorToolBar::ButtonOpenProjectClick); OpenProjectButton->SetSize( 25, 25 ); this->AddElement( OpenProjectButton ); SaveProjectButton = new WPictureButton( this, InRoot ); SaveProjectButton->Tooltip = L"Save Project"; SaveProjectButton->Scale = TSize( 16, 16 ); SaveProjectButton->Offset = TPoint( 32, 64 ); SaveProjectButton->Picture = Root->Icons; SaveProjectButton->EventClick = WIDGET_EVENT(WEditorToolBar::ButtonSaveProjectClick); SaveProjectButton->SetSize( 25, 25 ); this->AddElement( SaveProjectButton ); this->AddElement( nullptr ); UndoButton = new WPictureButton( this, InRoot ); UndoButton->Tooltip = L"Undo"; UndoButton->Scale = TSize( 16, 16 ); UndoButton->Offset = TPoint( 48, 64 ); UndoButton->Picture = Root->Icons; UndoButton->EventClick = WIDGET_EVENT(WEditorToolBar::ButtonUndoClick); UndoButton->SetSize( 25, 25 ); this->AddElement( UndoButton ); RedoButton = new WPictureButton( this, InRoot ); RedoButton->Tooltip = L"Redo"; RedoButton->Scale = TSize( 16, 16 ); RedoButton->Offset = TPoint( 64, 64 ); RedoButton->Picture = Root->Icons; RedoButton->EventClick = WIDGET_EVENT(WEditorToolBar::ButtonRedoClick); RedoButton->SetSize( 25, 25 ); this->AddElement( RedoButton ); this->AddElement( nullptr ); PlayModeCombo = new WComboBox( this, InRoot ); PlayModeCombo->SetSize( 96, 25 ); PlayModeCombo->AddItem( L"Debug", nullptr ); PlayModeCombo->AddItem( L"Release", nullptr ); PlayModeCombo->SetItemIndex( 0, false ); this->AddElement( PlayModeCombo ); PlayButton = new WPictureButton( this, InRoot ); PlayButton->Tooltip = L"Play Level!"; PlayButton->Scale = TSize( 16, 16 ); PlayButton->Offset = TPoint( 80, 64 ); PlayButton->Picture = Root->Icons; PlayButton->EventClick = WIDGET_EVENT(WEditorToolBar::ButtonPlayClick); PlayButton->SetSize( 25, 25 ); this->AddElement( PlayButton ); this->AddElement(nullptr); PauseButton = new WPictureButton( this, InRoot ); PauseButton->Tooltip = L"Pause Level"; PauseButton->Scale = TSize( 16, 16 ); PauseButton->Offset = TPoint( 96, 64 ); PauseButton->Picture = Root->Icons; PauseButton->EventClick = WIDGET_EVENT(WEditorToolBar::ButtonPauseClick); PauseButton->SetSize( 25, 25 ); this->AddElement( PauseButton ); StopButton = new WPictureButton( this, InRoot ); StopButton->Tooltip = L"Stop Level"; StopButton->Scale = TSize( 16, 16 ); StopButton->Offset = TPoint( 112, 64 ); StopButton->Picture = Root->Icons; StopButton->EventClick = WIDGET_EVENT(WEditorToolBar::ButtonStopClick); StopButton->SetSize( 25, 25 ); this->AddElement( StopButton ); this->AddElement( nullptr ); BuildButton = new WPictureButton( this, InRoot ); BuildButton->Tooltip = L"Build Game..."; BuildButton->Scale = TSize( 16, 16 ); BuildButton->Offset = TPoint( 128, 64 ); BuildButton->Picture = Root->Icons; BuildButton->EventClick = WIDGET_EVENT(WEditorToolBar::ButtonBuildClick); BuildButton->SetSize( 25, 25 ); this->AddElement( BuildButton ); } // // Toolbar paint. // void WEditorToolBar::OnPaint( CGUIRenderBase* Render ) { // Call parent. WToolBar::OnPaint(Render); WEditorPage* Page = GEditor->GetActivePage(); EPageType Type = Page ? Page->PageType : PAGE_None; // Turn on, or turn off buttons. SaveProjectButton->bEnabled = GProject != nullptr; UndoButton->bEnabled = Type == PAGE_Level || Type == PAGE_Script; RedoButton->bEnabled = Type == PAGE_Level || Type == PAGE_Script; PlayModeCombo->bEnabled = Type == PAGE_Level; PlayButton->bEnabled = Type == PAGE_Level || (Type == PAGE_Play && ((FLevel*)Page->GetResource())->bIsPause); PauseButton->bEnabled = Type == PAGE_Play && !((FLevel*)Page->GetResource())->bIsPause; StopButton->bEnabled = Type == PAGE_Play; BuildButton->bEnabled = GProject != nullptr && Type != PAGE_Play; } /*----------------------------------------------------------------------------- Buttons click. -----------------------------------------------------------------------------*/ void WEditorToolBar::ButtonNewProjectClick( WWidget* Sender ) { GEditor->NewProject(); } void WEditorToolBar::ButtonOpenProjectClick( WWidget* Sender ) { GEditor->OpenProject(); } void WEditorToolBar::ButtonSaveProjectClick( WWidget* Sender ) { GEditor->SaveProject(); } void WEditorToolBar::ButtonUndoClick( WWidget* Sender ) { WEditorPage* EdPage = GEditor->GetActivePage(); if( EdPage ) EdPage->Undo(); } void WEditorToolBar::ButtonRedoClick( WWidget* Sender ) { WEditorPage* EdPage = GEditor->GetActivePage(); if( EdPage ) EdPage->Redo(); } void WEditorToolBar::ButtonPlayClick( WWidget* Sender ) { WEditorPage* EdPage = GEditor->GetActivePage(); if( EdPage ) { if( EdPage->PageType == PAGE_Level ) GEditor->PlayLevel( ((WLevelPage*)EdPage)->Level ); if( EdPage->PageType == PAGE_Play ) ((FLevel*)EdPage->GetResource())->bIsPause = false; } } void WEditorToolBar::ButtonPauseClick( WWidget* Sender ) { WEditorPage* EdPage = GEditor->GetActivePage(); if( EdPage && EdPage->PageType == PAGE_Play ) ((FLevel*)EdPage->GetResource())->bIsPause = true; } void WEditorToolBar::ButtonStopClick( WWidget* Sender ) { WEditorPage* EdPage = GEditor->GetActivePage(); if( EdPage && EdPage->PageType == PAGE_Play ) EdPage->Close(); } void WEditorToolBar::ButtonBuildClick( WWidget* Sender ) { GEditor->GameBuilder->Show(); } /*----------------------------------------------------------------------------- The End. -----------------------------------------------------------------------------*/
32.901869
111
0.635989
VladGordienko28
9a0136876639975c58b343745082aad130f868bc
250
hpp
C++
src/parser/Expression.hpp
rlucca/aslan
1f283c22fb72f717c590cf11482ac97c171f8518
[ "Unlicense" ]
null
null
null
src/parser/Expression.hpp
rlucca/aslan
1f283c22fb72f717c590cf11482ac97c171f8518
[ "Unlicense" ]
null
null
null
src/parser/Expression.hpp
rlucca/aslan
1f283c22fb72f717c590cf11482ac97c171f8518
[ "Unlicense" ]
null
null
null
#pragma once class Expression : public Symbol { public: Expression(Symbol *left); virtual ~Expression(); void setOp(int operation); int op(); virtual void add(Symbol *); protected: Symbol *m_left; Symbol *m_right; int m_op; };
12.5
32
0.668
rlucca
9a047c7f52d0b8ef23a63c442c700759dc8f7b82
9,712
cpp
C++
src/glCompact/MemoryBarrier.cpp
PixelOfDeath/glCompact
68334cc9c3aa20255e8986ad1ee5fa8e23df354d
[ "MIT" ]
null
null
null
src/glCompact/MemoryBarrier.cpp
PixelOfDeath/glCompact
68334cc9c3aa20255e8986ad1ee5fa8e23df354d
[ "MIT" ]
null
null
null
src/glCompact/MemoryBarrier.cpp
PixelOfDeath/glCompact
68334cc9c3aa20255e8986ad1ee5fa8e23df354d
[ "MIT" ]
null
null
null
#include "glCompact/MemoryBarrier.hpp" #include "glCompact/Context_.hpp" #include "glCompact/threadContext_.hpp" #include "glCompact/gl/Constants.hpp" /** MEMORY BARRIER COMMANDS Memory barriers got introduced with image load/store operations. To be lightwight and performant there is no automatic ordering or syncronisation provided by OpenGL. Its design entierly relies on the developer to take care of this. are used since the inclusion of image load/store operations to order different - between image load/store operations themself - between image load/store operations and other OpenGL commands. GL_ARB_shader_image_load_store (Core since 4.2) introduces glMemoryBarrier(GLbitfield barriers) GL_ARB_shader_atomic_counters (Core since 4.2) GL_ARB_shader_storage_buffer_object (Core since 4.3) GL_ARB_ES3_1_compatibility (Core since 4.5) introduces glMemoryBarrierByRegion(GLbitfield barriers) Only applies to memory transactions that may be read by or written by a fragment shader (Also other laod/store operations in other shader stages???) Seems to be mainly aimed at tilled hardware!? and bindless textures (Not Core) and bindless buffers (Not Core, Nvidia only) glMemoryBarrier | glMemoryBarrierByRegion | | y GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT GL_VERTEX_ATTRIB_ARRAY_BUFFER y GL_ELEMENT_ARRAY_BARRIER_BIT GL_ELEMENT_ARRAY_BUFFER y GL_COMMAND_BARRIER_BIT GL_DRAW_INDIRECT_BUFFER, GL_DISPATCH_INDIRECT_BUFFER y GL_PIXEL_BUFFER_BARRIER_BIT GL_PIXEL_PACK_BUFFER, GL_PIXEL_UNPACK_BUFFER y GL_TEXTURE_UPDATE_BARRIER_BIT Tex(Sub)Image*, ClearTex*Image, CopyTex*, or CompressedTex*, and reads via GetTexImage after the barrier will not execute until all shader writes initiated prior to the barrier complete. y GL_BUFFER_UPDATE_BARRIER_BIT y GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT y GL_QUERY_BUFFER_BARRIER_BIT y GL_TRANSFORM_FEEDBACK_BARRIER_BIT y y GL_FRAMEBUFFER_BARRIER_BIT y y GL_UNIFORM_BARRIER_BIT All uniform buffers y y GL_TEXTURE_FETCH_BARRIER_BIT Textures and buffer textures y y GL_SHADER_IMAGE_ACCESS_BARRIER_BIT image load, store, and atomic functions y y GL_ATOMIC_COUNTER_BARRIER_BIT y y GL_SHADER_STORAGE_BARRIER_BIT y y GL_ALL_BARRIER_BITS (In case of glMemoryBarrierByRegion, only includes all other values that are supported by it) Simple upload functions like TexSubImage* or BufferSubData are automatically synchronized by OpenGL? For performance reasons writes to directly mapped memory or by shaders (Excluding FB or FBO rendering) are NOT synchronised by OpenGL. They need explicit synchronization (memory barriers) before commands are issues that access data that is written by previous commands or before changing data that may still is accessed by previous commands! GL Docs: Calling memoryBarrier guarantees that any memory transactions issued by the shader invocation prior to the call complete prior to the memory transactions issued after the call. "To permit cases where textures or buffers may be read or written in different pipeline stages without the overhead of automatic synchronization, buffer object and texture stores performed by shaders are not automatically synchronized with other GL operations using the same memory. Explicit synchronization is required to ensure that the effects of buffer and texture data stores performed by shaders will be visible to subsequent operations using the same objects and will not overwrite data still to be read by previously requested operations." */ /*enum class MemoryBarrierType : GLenum { attributeBuffer = GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT, attributeIndexBuffer = GL_ELEMENT_ARRAY_BARRIER_BIT, uniformBuffer = GL_UNIFORM_BARRIER_BIT, textureFetch = GL_TEXTURE_FETCH_BARRIER_BIT, //also texture-buffer objects imageShaderAccess = GL_SHADER_IMAGE_ACCESS_BARRIER_BIT, parameterBuffer = GL_COMMAND_BARRIER_BIT, bufferUploadDownloadImage = GL_PIXEL_BUFFER_BARRIER_BIT, imageUploadClearDownload = GL_TEXTURE_UPDATE_BARRIER_BIT, bufferCreateClearCopyInvalidate = GL_BUFFER_UPDATE_BARRIER_BIT, //copy only means from/to another buffer, not upload download to unmanaged client memory(?!) frame = GL_FRAMEBUFFER_BARRIER_BIT, = GL_TRANSFORM_FEEDBACK_BARRIER_BIT, = GL_QUERY_BUFFER_BARRIER_BIT, = GL_ATOMIC_COUNTER_BARRIER_BIT, = GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT, shaderStorage = GL_SHADER_STORAGE_BARRIER_BIT, all = GL_ALL_BARRIER_BITS };*/ using namespace glCompact::gl; namespace glCompact { //read access after barrier void MemoryBarrier::attributeBuffer() { threadContext_->memoryBarrierMask |= GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT; } void MemoryBarrier::attributeIndexBuffer() { threadContext_->memoryBarrierMask |= GL_ELEMENT_ARRAY_BARRIER_BIT; } //GL_DRAW_INDIRECT_BUFFER and GL_DISPATCH_INDIRECT_BUFFER //Also GL_PARAMETER_BUFFER_ARB if the extension GL_ARB_indirect_parameters (Not part of Core) is present void MemoryBarrier::parameterBuffer() { threadContext_->memoryBarrierMask |= GL_COMMAND_BARRIER_BIT; } void MemoryBarrier::uniformBuffer() { threadContext_->memoryBarrierMask |= GL_UNIFORM_BARRIER_BIT; } //This also affects bufferTexture objects! //NOT for glTex(Sub)Image*, glCopyTex(Sub)Image*, glClearTex*Image, glCompressedTex(Sub)Image* ! void MemoryBarrier::texture() { threadContext_->memoryBarrierMask |= GL_TEXTURE_FETCH_BARRIER_BIT; } //read/write access after barrier void MemoryBarrier::image() { threadContext_->memoryBarrierMask |= GL_SHADER_IMAGE_ACCESS_BARRIER_BIT; } //needs GL_ARB_shader_storage_buffer_object (Core since 4.3) or throws error if glMemoryBarrier is called with it void MemoryBarrier::shaderStorageBuffer() { threadContext_->memoryBarrierMask |= GL_SHADER_STORAGE_BARRIER_BIT; } //the barrier is for buffers only, that are involved in copys from/to images void MemoryBarrier::bufferImageTransfer() { threadContext_->memoryBarrierMask |= GL_PIXEL_BUFFER_BARRIER_BIT; } //also delete?; Only copy from/to other buffers?! void MemoryBarrier::bufferCreateClearCopyInvalidate() { threadContext_->memoryBarrierMask |= GL_BUFFER_UPDATE_BARRIER_BIT; } //Barrier for textures that was or will be changed by: //glTex(Sub)Image*, glCopyTex(Sub)Image*, glClearTex*Image, glCompressedTex(Sub)Image* //TODO: also need this as a barrier in the image download function! (glGetTexImage) //not sure if glGetTexImage needs its own explecite barrier or if a previous barrier on a shader call is enough?!?!?! void MemoryBarrier::imageUploadDownloadClear() { threadContext_->memoryBarrierMask |= GL_TEXTURE_UPDATE_BARRIER_BIT; } void MemoryBarrier::frame() { threadContext_->memoryBarrierMask |= GL_FRAMEBUFFER_BARRIER_BIT; } void MemoryBarrier::transformFeedback() { threadContext_->memoryBarrierMask |= GL_TRANSFORM_FEEDBACK_BARRIER_BIT; } void MemoryBarrier::query() { threadContext_->memoryBarrierMask |= GL_QUERY_BUFFER_BARRIER_BIT; } void MemoryBarrier::atomicCounterBuffer() { threadContext_->memoryBarrierMask |= GL_ATOMIC_COUNTER_BARRIER_BIT; } /* For server->client this one is needed for persistenly mapped buffers that do NOT have the MAP_COHERENT_BIT set and then waiting for a sync object (or glFinish). For client->server data without MAP_COHERENT_BIT one must use a FlushMapped*BufferRange command before issuing commands using the data changed by the client side. */ void MemoryBarrier::stagingBufferFlushWrites() { threadContext_->memoryBarrierMask |= GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT; } void MemoryBarrier::all() { threadContext_->memoryBarrierMask |= GL_ALL_BARRIER_BITS; } void MemoryBarrier::RasterizationRegion::uniformBuffer() { threadContext_->memoryBarrierRasterizationRegionMask |= GL_UNIFORM_BARRIER_BIT; } void MemoryBarrier::RasterizationRegion::texture() { threadContext_->memoryBarrierRasterizationRegionMask |= GL_TEXTURE_FETCH_BARRIER_BIT; } void MemoryBarrier::RasterizationRegion::image() { threadContext_->memoryBarrierRasterizationRegionMask |= GL_SHADER_IMAGE_ACCESS_BARRIER_BIT; } void MemoryBarrier::RasterizationRegion::shaderStorageBuffer() { threadContext_->memoryBarrierRasterizationRegionMask |= GL_SHADER_STORAGE_BARRIER_BIT; } void MemoryBarrier::RasterizationRegion::atomicCounterBuffer() { threadContext_->memoryBarrierRasterizationRegionMask |= GL_ATOMIC_COUNTER_BARRIER_BIT; } void MemoryBarrier::RasterizationRegion::frame() { threadContext_->memoryBarrierRasterizationRegionMask |= GL_FRAMEBUFFER_BARRIER_BIT; } void MemoryBarrier::RasterizationRegion::all() { threadContext_->memoryBarrierRasterizationRegionMask |= GL_ALL_BARRIER_BITS; } }
48.56
234
0.727759
PixelOfDeath
9a04bd03ec8aaed321813bc2040d7831823579b4
1,851
cpp
C++
3rdParty/occa/src/lang/expr/leftUnaryOpNode.cpp
krowe-alcf/nekBench
d314ca6b942076620dd7dab8f11df97be977c5db
[ "BSD-3-Clause" ]
4
2020-02-26T19:33:16.000Z
2020-12-06T07:50:11.000Z
3rdParty/occa/src/lang/expr/leftUnaryOpNode.cpp
krowe-alcf/nekBench
d314ca6b942076620dd7dab8f11df97be977c5db
[ "BSD-3-Clause" ]
12
2020-05-13T03:50:11.000Z
2021-09-16T16:26:06.000Z
3rdParty/occa/src/lang/expr/leftUnaryOpNode.cpp
krowe-alcf/nekBench
d314ca6b942076620dd7dab8f11df97be977c5db
[ "BSD-3-Clause" ]
10
2020-03-02T15:55:02.000Z
2021-12-03T02:44:10.000Z
#include <occa/lang/expr/leftUnaryOpNode.hpp> namespace occa { namespace lang { leftUnaryOpNode::leftUnaryOpNode(token_t *token_, const unaryOperator_t &op_, const exprNode &value_) : exprOpNode(token_, op_), value(value_.clone()) {} leftUnaryOpNode::leftUnaryOpNode(const leftUnaryOpNode &node) : exprOpNode(node.token, node.op), value(node.value->clone()) {} leftUnaryOpNode::~leftUnaryOpNode() { delete value; } udim_t leftUnaryOpNode::type() const { return exprNodeType::leftUnary; } exprNode* leftUnaryOpNode::clone() const { return new leftUnaryOpNode(token, (const unaryOperator_t&) op, *value); } bool leftUnaryOpNode::canEvaluate() const { if (op.opType & (operatorType::dereference | operatorType::address)) { return false; } return value->canEvaluate(); } primitive leftUnaryOpNode::evaluate() const { primitive pValue = value->evaluate(); return ((unaryOperator_t&) op)(pValue); } exprNode* leftUnaryOpNode::endNode() { return value->endNode(); } void leftUnaryOpNode::setChildren(exprNodeRefVector &children) { children.push_back(&value); } variable_t* leftUnaryOpNode::getVariable() { return value->getVariable(); } void leftUnaryOpNode::print(printer &pout) const { pout << op << *value; } void leftUnaryOpNode::debugPrint(const std::string &prefix) const { printer pout(io::stderr); io::stderr << prefix << "|\n" << prefix << "|---["; pout << op; io::stderr << "] (leftUnary)\n"; value->childDebugPrint(prefix); } } }
27.220588
71
0.572663
krowe-alcf
9a081e4dc68491ed31f03c11bdf8d26f976b979c
521
hpp
C++
include/mi/NonCopyable.hpp
tmichi/mibase
0ab614901cfedeba523f48170c717da8b445d851
[ "MIT" ]
4
2017-11-24T13:28:52.000Z
2019-12-09T19:52:51.000Z
include/mi/NonCopyable.hpp
tmichi/mibase
0ab614901cfedeba523f48170c717da8b445d851
[ "MIT" ]
2
2015-07-09T09:53:04.000Z
2016-05-06T05:09:04.000Z
include/mi/NonCopyable.hpp
tmichi/mibase
0ab614901cfedeba523f48170c717da8b445d851
[ "MIT" ]
null
null
null
#ifndef MI_NON_COPYABLE_HPP #define MI_NON_COPYABLE_HPP 1 namespace mi { class NonCopyable { private: NonCopyable ( const NonCopyable& that ); void operator = ( const NonCopyable& that ); public: NonCopyable ( void ) { return; } virtual ~NonCopyable ( void ) { return; } }; } #endif //MI_NON_COPYABLE_HPP
23.681818
60
0.435701
tmichi
9a0ae489e808d4793bd16c35aaea7a3131034617
553
cc
C++
llvm-gcc-4.2-2.9/libjava/java/security/natVMAccessController.cc
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
1
2016-04-09T02:58:13.000Z
2016-04-09T02:58:13.000Z
llvm-gcc-4.2-2.9/libjava/java/security/natVMAccessController.cc
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
null
null
null
llvm-gcc-4.2-2.9/libjava/java/security/natVMAccessController.cc
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
null
null
null
// natVMAccessController.cc -- Native part of the VMAccessController class. /* Copyright (C) 2006 Free Software Foundation, Inc. This file is part of libgcj. This software is copyrighted work licensed under the terms of the Libgcj License. Please consult the file "LIBGCJ_LICENSE" for details. */ #include <config.h> #include <gcj/cni.h> #include <jvm.h> #include <java-stack.h> #include <java/security/VMAccessController.h> jobjectArray java::security::VMAccessController::getStack () { return _Jv_StackTrace::GetAccessControlStack (); }
23.041667
75
0.757685
vidkidz
9a0c25d34bf5a7b24684a5d245e5ca979b973bcb
5,116
hpp
C++
src/thirdparty/stlsoft/STLSoft/include/stlsoft/shims/logical/is_null.hpp
nneesshh/servercore
8aceb7c9d5b26976469645a708b4ab804864c03f
[ "MIT" ]
null
null
null
src/thirdparty/stlsoft/STLSoft/include/stlsoft/shims/logical/is_null.hpp
nneesshh/servercore
8aceb7c9d5b26976469645a708b4ab804864c03f
[ "MIT" ]
null
null
null
src/thirdparty/stlsoft/STLSoft/include/stlsoft/shims/logical/is_null.hpp
nneesshh/servercore
8aceb7c9d5b26976469645a708b4ab804864c03f
[ "MIT" ]
2
2020-11-04T03:07:09.000Z
2020-11-05T08:14:45.000Z
/* ///////////////////////////////////////////////////////////////////////// * File: stlsoft/shims/logical/is_null.hpp * * Purpose: Contains the is_null attribute shim. * * Created: 31st March 2007 * Updated: 19th February 2017 * * Home: http://stlsoft.org/ * * Copyright (c) 2007-2017, Matthew Wilson and Synesis Software * 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(s) of Matthew Wilson and Synesis Software nor the * names of any 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. * * ////////////////////////////////////////////////////////////////////// */ /** \file stlsoft/shims/logical/is_null.hpp * * \brief [C++] Primary include file for is_null collection logical shim * for standard and STLSoft types * (\ref group__concept__Shim__Logical__is_null "is_null Logical Shim"). */ #ifndef STLSOFT_INCL_STLSOFT_SHIMS_LOGICAL_HPP_IS_NULL #define STLSOFT_INCL_STLSOFT_SHIMS_LOGICAL_HPP_IS_NULL #ifndef STLSOFT_DOCUMENTATION_SKIP_SECTION # define STLSOFT_VER_STLSOFT_SHIMS_LOGICAL_HPP_IS_NULL_MAJOR 2 # define STLSOFT_VER_STLSOFT_SHIMS_LOGICAL_HPP_IS_NULL_MINOR 0 # define STLSOFT_VER_STLSOFT_SHIMS_LOGICAL_HPP_IS_NULL_REVISION 3 # define STLSOFT_VER_STLSOFT_SHIMS_LOGICAL_HPP_IS_NULL_EDIT 10 #endif /* !STLSOFT_DOCUMENTATION_SKIP_SECTION */ /* ///////////////////////////////////////////////////////////////////////// * includes */ #ifndef STLSOFT_INCL_STLSOFT_H_STLSOFT # include <stlsoft/stlsoft.h> #endif /* !STLSOFT_INCL_STLSOFT_H_STLSOFT */ #ifdef STLSOFT_TRACE_INCLUDE # pragma message(__FILE__) #endif /* STLSOFT_TRACE_INCLUDE */ #ifndef STLSOFT_INCL_STLSOFT_SHIMS_LOGICAL_IS_NULL_H_FWD # include <stlsoft/shims/logical/is_null/fwd.h> #endif /* !STLSOFT_INCL_STLSOFT_SHIMS_LOGICAL_IS_NULL_H_FWD */ #ifndef STLSOFT_INCL_STLSOFT_SHIMS_LOGICAL_IS_NULL_STD_H_POINTER # include <stlsoft/shims/logical/is_null/std/pointer.h> #endif /* !STLSOFT_INCL_STLSOFT_SHIMS_LOGICAL_IS_NULL_STD_H_POINTER */ #ifdef __cplusplus /* standard smart pointers */ # ifndef STLSOFT_INCL_STLSOFT_UTIL_STD_LIBRARY_DISCRIMINATOR # include <stlsoft/util/std/library_discriminator.hpp> # endif /* !STLSOFT_INCL_STLSOFT_UTIL_STD_LIBRARY_DISCRIMINATOR */ /* std::auto_ptr<> */ # ifndef _STLSOFT_PTR_ACCESS_NO_AUTO_PTR # ifndef STLSOFT_INCL_STLSOFT_SHIMS_LOGICAL_IS_NULL_STD_HPP_AUTO_PTR # include <stlsoft/shims/logical/is_null/std/auto_ptr.hpp> # endif /* !STLSOFT_INCL_STLSOFT_SHIMS_LOGICAL_IS_NULL_STD_HPP_AUTO_PTR */ # endif /* std::shared_ptr<> */ # if 0 || \ ( defined(STLSOFT_CF_STD_LIBRARY_DINKUMWARE_VC_VERSION) && \ STLSOFT_CF_STD_LIBRARY_DINKUMWARE_VC_VERSION >= STLSOFT_CF_DINKUMWARE_VC_VERSION_9_0) || \ 0 # ifndef STLSOFT_INCL_STLSOFT_SHIMS_LOGICAL_IS_NULL_STD_HPP_SHARED_PTR # include <stlsoft/shims/logical/is_null/std/shared_ptr.hpp> # endif /* !STLSOFT_INCL_STLSOFT_SHIMS_LOGICAL_IS_NULL_STD_HPP_SHARED_PTR */ # endif /* std::unique_ptr<> */ # if 0 || \ ( defined(STLSOFT_CF_STD_LIBRARY_DINKUMWARE_VC_VERSION) && \ STLSOFT_CF_STD_LIBRARY_DINKUMWARE_VC_VERSION >= STLSOFT_CF_DINKUMWARE_VC_VERSION_10_0) || \ 0 # ifndef STLSOFT_INCL_STLSOFT_SHIMS_LOGICAL_IS_NULL_STD_HPP_UNIQUE_PTR # include <stlsoft/shims/logical/is_null/std/unique_ptr.hpp> # endif /* !STLSOFT_INCL_STLSOFT_SHIMS_LOGICAL_IS_NULL_STD_HPP_UNIQUE_PTR */ # endif #endif /* __cplusplus */ /* ///////////////////////////////////////////////////////////////////////// * inclusion control */ #ifdef STLSOFT_CF_PRAGMA_ONCE_SUPPORT # pragma once #endif /* STLSOFT_CF_PRAGMA_ONCE_SUPPORT */ #endif /* !STLSOFT_INCL_STLSOFT_SHIMS_LOGICAL_HPP_IS_NULL */ /* ///////////////////////////// end of file //////////////////////////// */
39.96875
99
0.727326
nneesshh
9a0d9e1029a01184b64aa688766e80a2bc904903
393
cpp
C++
hedron-ui/src/hdrui/SandboxUIApp.cpp
Gabriel-Baril/hedron
5d4cad10c51e7c5e9c4919b089367560a8b3b1f3
[ "Apache-2.0" ]
null
null
null
hedron-ui/src/hdrui/SandboxUIApp.cpp
Gabriel-Baril/hedron
5d4cad10c51e7c5e9c4919b089367560a8b3b1f3
[ "Apache-2.0" ]
null
null
null
hedron-ui/src/hdrui/SandboxUIApp.cpp
Gabriel-Baril/hedron
5d4cad10c51e7c5e9c4919b089367560a8b3b1f3
[ "Apache-2.0" ]
null
null
null
#include <hedron.h> #include <Hedron/Core/entry_point.h> #include "SandboxUI.h" namespace hedron { class Sandbox : public Application { public: Sandbox(ApplicationCommandLineArgs args) : Application("Sandbox", args) { push_layer(new SandboxUI()); } ~Sandbox() { } }; Application* create_application(ApplicationCommandLineArgs args) { return new Sandbox(args); } }
15.72
65
0.704835
Gabriel-Baril
9a12f9e2dacf00922a37a060eb6e641f28ba8564
2,003
cpp
C++
RealVariable.cpp
Sarah-han/solver-a-b
5ac1f434dc7e3e0b1780d95bd2d6674366178045
[ "MIT" ]
null
null
null
RealVariable.cpp
Sarah-han/solver-a-b
5ac1f434dc7e3e0b1780d95bd2d6674366178045
[ "MIT" ]
null
null
null
RealVariable.cpp
Sarah-han/solver-a-b
5ac1f434dc7e3e0b1780d95bd2d6674366178045
[ "MIT" ]
null
null
null
#include "RealVariable.hpp" #include <math.h> solver::RealVariable solver::operator==(const solver::RealVariable &ls, const solver::RealVariable &rs) { return ls - rs; } // support only form (x)^2 solver::RealVariable solver::operator^(const solver::RealVariable &ls, const solver::RealVariable &rs) { if (ls._degree != 1 || ls._len != 1 || rs._degree != 0 || rs._len != 1 || rs._c != 2) { throw std::runtime_error("ERR: Function support only (bx)^2 form"); } double a, b, c; a = std::pow(ls._b, rs._c); b = 0; c = 0; return RealVariable(a, b, c); } // Done solver::RealVariable solver::operator*(const solver::RealVariable &ls, const solver::RealVariable &rs) { if (ls._degree + rs._degree > 2) throw std::runtime_error("ERR: Can't solve a function higher then a quadric function"); double a, b, c; a = ls._a * rs._c + ls._b * rs._b + ls._c * rs._a; b = ls._b * rs._c + ls._c * rs._b; c = ls._c * rs._c; return RealVariable(a, b, c); } // Done solver::RealVariable solver::operator-(const solver::RealVariable &ls, const solver::RealVariable &rs) { double a, b, c; a = ls._a - rs._a; b = ls._b - rs._b; c = ls._c - rs._c; return RealVariable(a, b, c); } // Done solver::RealVariable solver::operator+(const solver::RealVariable &ls, const solver::RealVariable &rs) { double a, b, c; a = ls._a + rs._a; b = ls._b + rs._b; c = ls._c + rs._c; return RealVariable(a, b, c); } // support only devision by double solver::RealVariable solver::operator/(const solver::RealVariable &ls, const solver::RealVariable &rs) { if (rs._degree != 0) { throw std::runtime_error("ERR: Function can divide only by a simple double"); } double a, b, c; a = ls._a / rs._c; b = ls._b / rs._c; c = ls._c / rs._c; return RealVariable(a, b, c); } // Done std::ostream &solver::operator<<(std::ostream &os, const solver::RealVariable &r) { return (os << r._a << "(x)^2 + " << r._b << "x + " << r._c); }
28.614286
103
0.61358
Sarah-han
9a137fcea951ae14652ec074252709c2f52eb4c2
21,636
cpp
C++
IPStreamingCPP/IPStreamingCPP/MainPage.xaml.cpp
srw2ho/IPStreaming
2a3345351f99c11fb69b2caedb3fd18ca7e5da73
[ "Apache-2.0" ]
2
2020-01-20T11:08:13.000Z
2020-09-01T17:35:56.000Z
IPStreamingCPP/IPStreamingCPP/MainPage.xaml.cpp
srw2ho/IPStreaming
2a3345351f99c11fb69b2caedb3fd18ca7e5da73
[ "Apache-2.0" ]
1
2020-08-20T01:24:57.000Z
2020-08-20T01:24:57.000Z
IPStreamingCPP/IPStreamingCPP/MainPage.xaml.cpp
srw2ho/IPStreaming
2a3345351f99c11fb69b2caedb3fd18ca7e5da73
[ "Apache-2.0" ]
1
2022-01-25T08:30:15.000Z
2022-01-25T08:30:15.000Z
// // MainPage.xaml.cpp // Implementation of the MainPage class. // #include "pch.h" #include "MainPage.xaml.h" #include "StreamingPageParam.h" #include "StreamingPage.xaml.h" using namespace IPStreamingCPP; using namespace AmcrestMotionDetection; using namespace FFmpegInteropExtRT; using namespace OnVifServicesRunTime; using namespace concurrency; using namespace Platform; using namespace Windows::System::Threading; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::Media::Core; using namespace Windows::Storage; using namespace Windows::Storage::Pickers; using namespace Windows::Storage::Streams; using namespace Windows::UI::Popups; using namespace Windows::UI::Core; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; using namespace Windows::Networking; using namespace Windows::Networking::Connectivity; using namespace Windows::UI::Xaml::Interop; // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 MainPage::MainPage() { InitializeComponent(); m_OnVifCameraViewModel = nullptr; m_displayRequest = ref new Windows::System::Display::DisplayRequest(); m_displayRequestCnt = 0; m_StreamingPageParamControl = ref new StreamingPageParamControl(); m_applicationSuspendingEventToken = Application::Current->Suspending += ref new SuspendingEventHandler(this, &MainPage::Application_Suspending); m_applicationResumingEventToken = Application::Current->Resuming += ref new EventHandler<Object^>(this, &MainPage::Application_Resuming); m_CodecReader = ref new FFmpegInteropExtRT::CodecReader(); // srw2ho: crashin case of first call, but only one computer m_CodecReader->ReadInstalledVideoDecoderCodecsAsync(); // readonly used Video codecs m_CodecReader->ReadUsedVideoDecoderCodecsAsync(); m_CodecReader->ReadUsedAudioDecoderCodecsAsync(); } MainPage::~MainPage() { Application::Current->Suspending -= m_applicationSuspendingEventToken; Application::Current->Resuming -= m_applicationResumingEventToken; // clearRecording(); // ReleaseAllRequestedDisplay(); delete m_StreamingPageParamControl; } void MainPage::PivotMediaLoaded(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { StreamingPageParam^ streamingPageParam = dynamic_cast<StreamingPageParam^>(PivotCameras->SelectedItem); if (streamingPageParam != nullptr) { MediaElement^ media = safe_cast<MediaElement^>(sender); if (media != nullptr) { streamingPageParam->MediaStreamElement = media; streamingPageParam->MediaCurrentStateChangedRegister = streamingPageParam->MediaStreamElement->CurrentStateChanged += ref new Windows::UI::Xaml::RoutedEventHandler(this, &MainPage::MediaElement_OnCurrentStateChanged); streamingPageParam->MediaFailedRegister = streamingPageParam->MediaStreamElement->MediaFailed += ref new Windows::UI::Xaml::ExceptionRoutedEventHandler(this, &MainPage::MediaElement_OnMediaFailed); } } } void MainPage::DisplayErrorMessage(Platform::String^ message) { // Display error message this->Dispatcher->RunAsync(CoreDispatcherPriority::High, ref new DispatchedHandler([this, message]() { auto errorDialog = ref new MessageDialog(message); errorDialog->ShowAsync(); })); } void MainPage::ActivateDisplay() { //create the request instance if needed //make request to put in active state m_displayRequest->RequestActive(); m_displayRequestCnt++; } void MainPage::ReleaseAllRequestedDisplay() { //must be same instance, so quit if it doesn't exist if (m_displayRequest == nullptr) return; while (m_displayRequestCnt > 0) { //undo the request m_displayRequest->RequestRelease(); m_displayRequestCnt--; } } void MainPage::ReleaseDisplay() { //must be same instance, so quit if it doesn't exist if (m_displayRequest == nullptr) return; if (m_displayRequestCnt > 0) { //undo the request m_displayRequest->RequestRelease(); m_displayRequestCnt--; } } void MainPage::WriteToAppData() { for each (auto var in this->m_StreamingPageParamControl->Items) { var->WriteToAppData(); } } void MainPage::Application_Suspending(Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e) { // Handle global application events only if this page is active if (Frame->CurrentSourcePageType.Name == Interop::TypeName(MainPage::typeid).Name) { this->ClearRessources(); this->clearRecording(); this->ReleaseAllRequestedDisplay(); this->WriteToAppData(); // write App data in case of Suspending } } void MainPage::Application_Resuming(Platform::Object^ sender, Platform::Object^ args) { // Handle global application events only if this page is active if (Frame->CurrentSourcePageType.Name == Interop::TypeName(MainPage::typeid).Name) { // this->ActivateDisplay(); } } void MainPage::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) { IPStreamingCPP::App^ app = safe_cast<IPStreamingCPP::App^>(e->Parameter); m_app = app; //OnVifCameraViewModel^ onVifCameraViewModel = safe_cast<OnVifCameraViewModel^>(e->Parameter); if (app != nullptr) { this->m_OnVifCameraViewModel = app->CameraViewModel; } if (this->m_OnVifCameraViewModel == nullptr) return; if (this->m_OnVifCameraViewModel->Cameras->Size == 0) // lesen aus local Storage { this->m_OnVifCameraViewModel->readDatafromLocalStorage(); } m_StreamingPageParamControl->ClearRessources(); // all previous events unregister m_StreamingPageParamControl->Items->Clear(); wchar_t buffer[200]; for (unsigned int ncount = 0; ncount < this->m_OnVifCameraViewModel->Cameras->Size; ncount++) //for each (auto var in this->m_OnVifCameraViewModel->Cameras) { OnVifCamera^ var = this->m_OnVifCameraViewModel->Cameras->GetAt(ncount); IPStreamingCPP::StreamingPageParam^ param = ref new StreamingPageParam(); swprintf(&buffer[0], sizeof(buffer) / sizeof(buffer[0]), L"Camera_%03d", ncount); param->createStreamingPageParam(ref new Platform::String(buffer), this->Frame); param->OnVifCamera = var; // OnVif-Camera param->PropertyChangedEventRegister = param->OnVifCamera->PropertyChanged += ref new PropertyChangedEventHandler(this, &MainPage::ScenarioPropertyChanged); param->CameraServerFailedRegister = param->CameraServer->Failed += ref new Windows::Foundation::TypedEventHandler<Platform::Object^, FFmpegInteropExtRT::CameraServerFailedEventArgs^>(this, &MainPage::CameraServerOnFailed); // Movement-Recording On param->OnStartMovementStreaming = param->MovementRecording->startStreaming += ref new Windows::Foundation::TypedEventHandler<Platform::Object^, Windows::Foundation::Collections::PropertySet^>(this, &IPStreamingCPP::MainPage::OnstartMovementStreaming); param->OnStopMovementStreaming = param->MovementRecording->stopStreaming += ref new Windows::Foundation::TypedEventHandler<Platform::Object^, Platform::String^>(this, &IPStreamingCPP::MainPage::OnStopMovementStreaming); param->OnChangeMovementStreaming = param->MovementRecording->ChangeMovement += ref new Windows::Foundation::TypedEventHandler<Platform::Object^, Windows::Foundation::Collections::PropertySet^>(this, &IPStreamingCPP::MainPage::OnChangeMovement); param->OnStartAMCRESEventStreaming = param->AmcrestMotion->startStreaming += ref new Windows::Foundation::TypedEventHandler<Platform::Object^, Windows::Foundation::Collections::PropertySet^>(this, &IPStreamingCPP::MainPage::OnstartMovementStreaming); param->OnStopAMCRESEventStreaming = param->AmcrestMotion->stopStreaming += ref new Windows::Foundation::TypedEventHandler<Platform::Object^, Platform::String^>(this, &IPStreamingCPP::MainPage::OnStopMovementStreaming); param->OnChangeAMCRESEventStreaming = param->AmcrestMotion->ChangeMovement += ref new Windows::Foundation::TypedEventHandler<Platform::Object^, Windows::Foundation::Collections::PropertySet^>(this, &IPStreamingCPP::MainPage::OnChangeMovement); param->MovementRecording->HostName = "WilliRaspiPlus"; param->MovementRecording->Port = 3000; param->CodecReader = this->m_CodecReader; // Movement-Recording On param->ScenarioView = ref new IPStreamingCPP::ScenarioViewControl(); Windows::UI::Xaml::Interop::TypeName tt = Windows::UI::Xaml::Interop::TypeName(StreamingPage::typeid); ScenarioItem^ item = ref new ScenarioItem("Streaming", tt, Symbol::AttachCamera, param); param->ScenarioView->Items->Append(item); tt = Windows::UI::Xaml::Interop::TypeName(OnVifServicesRunTime::OnVifSingleCameraPage::typeid); item = ref new ScenarioItem("OnVifCamera", tt, Symbol::Edit, param->OnVifCamera); param->ScenarioView->Items->Append(item); param->takeParametersFromCamera(); // Camera-Parameter werden übernommen m_StreamingPageParamControl->Items->Append(param); } m_StreamingPageParamControl->readSettingsfromLocalStorage(); if (this->m_StreamingPageParamControl->Items->Size == 0) m_StreamingPageParamControl->SelectedIndex = -1; else if (m_StreamingPageParamControl->SelectedIndex < 0) m_StreamingPageParamControl->SelectedIndex = 0; Page::OnNavigatedTo(e); } void MainPage::OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^ e) { this->ClearRessources(); this->clearRecording(); this->ReleaseAllRequestedDisplay(); this->WriteToAppData(); m_StreamingPageParamControl->writeSettingsToLocalStorage(); Page::OnNavigatingFrom(e); } void MainPage::startUriStreaming(Platform::Object^ sender, IPStreamingCPP::StreamingPageParam^ data) { IPStreamingCPP::StreamingPageParam^ streamingPageParam = safe_cast<IPStreamingCPP::StreamingPageParam^>(data); auto tsk= streamingPageParam->startUriStreaming(); Splitter->IsPaneOpen = false; } void MainPage::startFileStreaming(Platform::Object^ sender, IPStreamingCPP::StreamingPageParam^ data) { IPStreamingCPP::StreamingPageParam^ streamingPageParam = safe_cast<IPStreamingCPP::StreamingPageParam^>(data); auto boK = streamingPageParam->startFileStreaming(); Splitter->IsPaneOpen = false; } void MainPage::stopStreaming(Platform::Object^ sender, IPStreamingCPP::StreamingPageParam^ data) { IPStreamingCPP::StreamingPageParam^ streamingPageParam = safe_cast<IPStreamingCPP::StreamingPageParam^>(data); streamingPageParam->clearMediaElem(); streamingPageParam->stopStreaming(); } void MainPage::stopallRecording_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { auto tsk = clearRecordingAsync(); tsk.then([this]()->void { //this->Dispatcher->RunAsync(CoreDispatcherPriority::High, ref new DispatchedHandler([this]() { // for each (auto var in m_StreamingPageParamControl->Items) // { // StackPanel^ panel = getStackPanelByStreamingParam(var); // if (panel != nullptr) { // panel->Visibility = Windows::UI::Xaml::Visibility::Collapsed; // } // } // })); //return ; } ); } void MainPage::stopRecording_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { StreamingPageParam^ streamingPageParam = m_StreamingPageParamControl->getSelectedItem(); if (streamingPageParam != nullptr) { streamingPageParam->clearMediaElem(); streamingPageParam->stopStreaming(); } } void MainPage::startRecording_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { StreamingPageParam^ streamingPageParam = m_StreamingPageParamControl->getSelectedItem(); if (streamingPageParam != nullptr) { auto boK = streamingPageParam->startUriStreaming(); Splitter->IsPaneOpen = false; } } void MainPage::PivotCameras_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e) { Pivot^ pivot = dynamic_cast<Pivot^>(sender); // Pivot if (pivot != nullptr) { StreamingPageParam^ param = dynamic_cast<StreamingPageParam^>(pivot->SelectedItem); // Property-Changed by OnVifCamera-Page if (param != nullptr) { ScenarioControl->ItemsSource = param->ScenarioView->Items; ScenarioControl->SelectedIndex = 0; if (param->MovementRecording->IsMoment || param->AmcrestMotion->IsMoment) { this->detectMovement->Visibility = Windows::UI::Xaml::Visibility::Visible; } else { this->detectMovement->Visibility = Windows::UI::Xaml::Visibility::Collapsed; } } else { this->detectMovement->Visibility = Windows::UI::Xaml::Visibility::Collapsed; } } } void MainPage::ScenarioPropertyChanged(Platform::Object^ sender, Windows::UI::Xaml::Data::PropertyChangedEventArgs^ e) { OnVifCamera^ camera = dynamic_cast<OnVifCamera^>(sender); // Property-Changed by OnVifCamera-Page if (camera != nullptr) { if (e->PropertyName == "IsProfilesReaded") { if (camera->IsProfilesReaded) { // only when reading StreamingPageParam^ param = this->m_StreamingPageParamControl->getItemByOnVifCamera(camera); if (param != nullptr) { param->takeParametersFromCamera(); // Camera-Parameter werden übernommen } } } } } void MainPage::ScenarioControl_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e) { //NotifyUser(String.Empty, NotifyType.StatusMessage); ListView^ scenarioListBox = dynamic_cast<ListView^>(sender); ScenarioItem^ item = dynamic_cast<ScenarioItem^>(scenarioListBox->SelectedItem); if (item != nullptr) { // if (ScenarioFrame->CurrentSourcePageType.Name != item->TypeClassName.Name) { if (item->TypeClassName.Name == Windows::UI::Xaml::Interop::TypeName(OnVifSingleCameraPage::typeid).Name) { VisualStateManager::GoToState(this, "SetOpenPaneBig", true); } else { VisualStateManager::GoToState(this, "SetOpenPaneDefault", true); } ScenarioFrame->Navigate(item->TypeClassName, item->Object); StreamingPage^ page = dynamic_cast<StreamingPage^>(ScenarioFrame->Content); if (page != nullptr) { page->startUriStreaming += ref new Windows::Foundation::TypedEventHandler<Platform::Object^, IPStreamingCPP::StreamingPageParam^>(this, &MainPage::startUriStreaming); page->startFileStreaming += ref new Windows::Foundation::TypedEventHandler<Platform::Object^, IPStreamingCPP::StreamingPageParam^>(this, &MainPage::startFileStreaming); page->stopStreaming += ref new Windows::Foundation::TypedEventHandler<Platform::Object^, IPStreamingCPP::StreamingPageParam^>(this, &MainPage::stopStreaming); } } } } void MainPage::CameraServerOnFailed(Platform::Object^ sender, FFmpegInteropExtRT::CameraServerFailedEventArgs^ args) { Platform::String^ message = args->Message; DisplayErrorMessage(message); // throw ref new Platform::NotImplementedException(); } void MainPage::MediaElement_OnCurrentStateChanged(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { MediaElement^ mediaElement = (MediaElement^)sender; if (mediaElement != nullptr && mediaElement->IsAudioOnly == false) { if (mediaElement->CurrentState == Windows::UI::Xaml::Media::MediaElementState::Playing) { this->ActivateDisplay(); } else // CurrentState is Buffering, Closed, Opening, Paused, or Stopped. { bool bRelease = true; if (mediaElement->CurrentState == Windows::UI::Xaml::Media::MediaElementState::Opening) { bRelease = false; } if (mediaElement->CurrentState == Windows::UI::Xaml::Media::MediaElementState::Paused) { } if (mediaElement->CurrentState == Windows::UI::Xaml::Media::MediaElementState::Closed) { } if (mediaElement->CurrentState == Windows::UI::Xaml::Media::MediaElementState::Stopped) { } if (mediaElement->CurrentState == Windows::UI::Xaml::Media::MediaElementState::Buffering) { bRelease = false; } if (bRelease) { this->ReleaseDisplay(); } } } // throw ref new Platform::NotImplementedException(); } void MainPage::MediaElement_OnMediaFailed(Platform::Object^ sender, Windows::UI::Xaml::ExceptionRoutedEventArgs^ e) { if (m_displayRequest != nullptr) { // Deactivate the display request and set the var to null. this->ReleaseDisplay(); } Platform::String^ message = e->ErrorMessage; DisplayErrorMessage(message); // throw ref new Platform::NotImplementedException(); } void MainPage::clearRecording() { for each (auto var in this->m_StreamingPageParamControl->Items) { auto tsk = var->clearRecording(); } } concurrency::task<void> MainPage::clearRecordingAsync() { for each (auto var in this->m_StreamingPageParamControl->Items) { var->clearMediaElem(); } auto tsk = create_task([this]()->void { try { for each (auto var in this->m_StreamingPageParamControl->Items) { auto tsk = var->clearRecording(); tsk.wait(); } } catch (Exception^ exception) { bool bexception = true; } }); return tsk; // this->detectMovement->Visibility = Windows::UI::Xaml::Visibility::Collapsed; } void MainPage::ClearRessources() { m_StreamingPageParamControl->ClearRessources(); // all previous events unregister } void IPStreamingCPP::MainPage::OnStopMovementStreaming(Platform::Object^ sender, Platform::String^ args) { AmcrestMotion^ Amcrestrecording = dynamic_cast<AmcrestMotion^>(sender); RecordingListener::Recording^ recording = dynamic_cast<RecordingListener::Recording^>(sender); if (args != nullptr) { // stop movement with error Platform::String^ message = "undefinded Watcher: " + args; if (Amcrestrecording) { message = "AMCREST-Event Watcher: " + args; } else { message = "Movement-Watcher: " + args; } DisplayErrorMessage(message); } // throw ref new Platform::NotImplementedException(); } void IPStreamingCPP::MainPage::OnstartMovementStreaming(Platform::Object^ sender, Windows::Foundation::Collections::PropertySet^ args) { // throw ref new Platform::NotImplementedException(); } //void IPStreamingCPP::MainPage::OnStopAMCRESTEventStreaming(Platform::Object^ sender, Platform::String^ args) //{ // if (args != nullptr) { // stop movement with error // Platform::String^ message = "AMCREST-Event Watcher: " + args; // DisplayErrorMessage(message); // } // //} void IPStreamingCPP::MainPage::OnChangeMovement(Platform::Object^ sender, Windows::Foundation::Collections::PropertySet^ args) { //AmcrestMotion^ recording = dynamic_cast<AmcrestMotion^>(sender); bool dodetect = false; //if (recording != nullptr) { StreamingPageParam^ streamingPageParam = m_StreamingPageParamControl->getSelectedItem(); if (streamingPageParam != nullptr) { //if (streamingPageParam->AmcrestMotion == recording) { Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync( CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this, streamingPageParam, args]() { bool IsMoment = (streamingPageParam->MovementRecording->IsMoment || streamingPageParam->AmcrestMotion->IsMoment); if (IsMoment) { this->detectMovement->Visibility = Windows::UI::Xaml::Visibility::Visible; } else { this->detectMovement->Visibility = Windows::UI::Xaml::Visibility::Collapsed; } // not activated checkForEvents(streamingPageParam); })); } } } } bool IPStreamingCPP::MainPage::checkForEvents(StreamingPageParam^ streamingPageParam) { Platform::String^ eventset = ref new Platform::String(L""); Windows::Foundation::Collections::IObservableVector<Platform::String^ >^ events = streamingPageParam->AmcrestMotion->Events; for (unsigned int i = 0; i < events->Size; i++) { eventset = events->GetAt(i); eventset+= "\\r\\n"; } if (eventset->Length() > 0) { DisplayErrorMessage(eventset); } return (events->Size>0); } //bool IPStreamingCPP::MainPage::checkForMovement(Windows::Foundation::Collections::PropertySet^ args) { // // if (args->HasKey("m_MovementActiv") && args->HasKey("m_MovementActivated") && args->HasKey("m_RecordingActivTimeinSec")) { // Platform::Object^ isActivvalue = args->Lookup("m_MovementActiv"); // //Platform::Object^ isActatedvalue = args->Lookup("m_MovementActivated"); // Platform::Object^ RecordingTime = args->Lookup("m_RecordingActivTimeinSec"); // bool isActiv = safe_cast<IPropertyValue^>(isActivvalue)->GetBoolean(); // // int isActived = safe_cast<IPropertyValue^>(isActatedvalue)->GetInt32(); // //if (isActived > 0) // { // return (isActiv); // } // } // // return false; // //} // //void IPStreamingCPP::MainPage::OnChangeMovement(Platform::Object^ sender, Windows::Foundation::Collections::PropertySet^ args) //{ // // RecordingListener::Recording^ recording = dynamic_cast<RecordingListener::Recording^>(sender); // bool dodetect = false; // if (recording != nullptr) { // StreamingPageParam^ streamingPageParam = m_StreamingPageParamControl->getSelectedItem(); // if (streamingPageParam != nullptr) { // if (streamingPageParam->MovementRecording == recording) // { // Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync( // CoreDispatcherPriority::Normal, // ref new Windows::UI::Core::DispatchedHandler([this, recording, args]() // { // bool IsMoment = recording->IsMoment; // // // checkForMovement(args); // if (IsMoment) { // this->detectMovement->Visibility = Windows::UI::Xaml::Visibility::Visible; // } // else // { // this->detectMovement->Visibility = Windows::UI::Xaml::Visibility::Collapsed; // } // // })); // // } // } // } // //}
30.008322
253
0.742235
srw2ho
9a147a08302fe45eddfb77567e7489f88065ce5c
644
hpp
C++
smart_tales_ii/game/ui/informationcard.hpp
TijmenUU/smarttalesii
c3a9c90bc2385e21e6fe4aa1cfda550edf6e20ba
[ "CC-BY-3.0", "CC-BY-4.0" ]
null
null
null
smart_tales_ii/game/ui/informationcard.hpp
TijmenUU/smarttalesii
c3a9c90bc2385e21e6fe4aa1cfda550edf6e20ba
[ "CC-BY-3.0", "CC-BY-4.0" ]
11
2018-02-08T14:50:16.000Z
2022-01-21T19:54:24.000Z
smart_tales_ii/game/ui/informationcard.hpp
TijmenUU/smarttalesii
c3a9c90bc2385e21e6fe4aa1cfda550edf6e20ba
[ "CC-BY-3.0", "CC-BY-4.0" ]
null
null
null
/* informationcard.hpp Simple helper class used in winoverlay.hpp / .cpp. Counts down its timeout and after that it starts fading in the subtitle and image. */ #pragma once #include <SFML/Graphics.hpp> class InformationCard : public sf::Drawable { private: float fadeTimeOut; int colorValue; sf::Sprite image; sf::Text subtitle; protected: void draw(sf::RenderTarget & target, sf::RenderStates states) const override; public: void Update(const sf::Time & elapsed); void SetPosition(const float x, const float y); InformationCard(const std::string & textureFile, const std::string & description, const float _fadeTimeOut); };
21.466667
109
0.75
TijmenUU
9a14e84c937df5ce584001d2231706c81e90f695
1,211
cpp
C++
basic/inherit/singleInherit.cpp
Marveliu/learn-cpp
e1f121fb1d5d7decc5712817a3f4751f43fea1b8
[ "Apache-2.0" ]
null
null
null
basic/inherit/singleInherit.cpp
Marveliu/learn-cpp
e1f121fb1d5d7decc5712817a3f4751f43fea1b8
[ "Apache-2.0" ]
null
null
null
basic/inherit/singleInherit.cpp
Marveliu/learn-cpp
e1f121fb1d5d7decc5712817a3f4751f43fea1b8
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; class Animal //定义基类 { public: Animal(int con_weight, int con_age); //声明带参构造函数 ~Animal() { cout << "Animal destructor!" << endl; } int get_age() { return m_nAge; } //获取m_nAge属性值 void speak() { cout << "animal language!" << endl; } private: int m_nWeight, m_nAge; }; Animal::Animal(int con_weight, int con_age) //定义基类带参构造函数 { m_nWeight = con_weight; m_nAge = con_age; cout << "Animal constructor with param!" << endl; } class Cat : public Animal { //定义派生类 public: //声明带参构造函数 Cat(string con_name, int con_weight, int con_age); ~Cat() { cout << "Cat destructor!" << endl; } //定义析构函数 void speak() { cout << "cat language: miaomiao!" << endl; } private: string m_strName; }; //定义派生类带参的构造函数 Cat::Cat(string con_name, int con_weight, int con_age) : Animal(con_weight, con_age) { m_strName = con_name; cout << "Cat constructor with param!" << endl; } int main() { Cat cat("Persian", 3, 4); //定义派生类对象 cout << "cat age = " << cat.get_age() << endl; //调用get_age()函数 cat.speak(); //通过派生类调用speak()函数 cat.Animal::speak(); //调用基类同名函数 return 0; }
22.849057
84
0.601156
Marveliu
9a177211feed7e22ba2a45509653d9bd2010a525
2,248
hpp
C++
src/libbsn/include/libbsn/configuration/SensorConfiguration.hpp
gabrielevi10/bsn
2d42aa006933caf75365bb327fd7d79ae30c88b7
[ "MIT" ]
8
2020-01-26T15:26:27.000Z
2022-01-05T15:38:07.000Z
src/libbsn/include/libbsn/configuration/SensorConfiguration.hpp
gabrielevi10/bsn
2d42aa006933caf75365bb327fd7d79ae30c88b7
[ "MIT" ]
50
2019-08-29T23:52:43.000Z
2021-01-24T19:09:54.000Z
src/libbsn/include/libbsn/configuration/SensorConfiguration.hpp
gabrielevi10/bsn
2d42aa006933caf75365bb327fd7d79ae30c88b7
[ "MIT" ]
4
2019-06-15T17:23:57.000Z
2020-10-16T20:09:41.000Z
#ifndef SENSORCONFIGURATION_HPP #define SENSORCONFIGURATION_HPP #include <string> #include <math.h> #include <iostream> #include <array> #include <sstream> #include "libbsn/range/Range.hpp" namespace bsn { namespace configuration { class SensorConfiguration { public: SensorConfiguration(); SensorConfiguration(int32_t i, bsn::range::Range, std::array<bsn::range::Range, 2>, std::array<bsn::range::Range, 2>, std::array<bsn::range::Range, 3>); SensorConfiguration(const SensorConfiguration & /*obj*/); SensorConfiguration &operator=(const SensorConfiguration & /*obj*/); private: int32_t id; bsn::range::Range lowRisk; std::array<bsn::range::Range, 2> mediumRisk; std::array<bsn::range::Range, 2> highRisk; bsn::range::Range lowPercentage, midPercentage, highPercentage; public: // Retorna o estado de risco a partir dos intervalos double evaluateNumber(double number); // Retorna o quão deslocado do meio um valor está double getDisplacement(bsn::range::Range, double, std::string ); // Converte para o percentual final( {var}_percentage ) double convertRealPercentage(bsn::range::Range range, double number); // Verifica se valor passado é de baixo risco bool isLowRisk(double/*val*/); // Verifica se valor passado é de médio risco bool isMediumRisk(double/*val*/); // Verifica se valor passado é de alto risco bool isHighRisk(double/*val*/); int32_t getId() const; void setId(const int32_t); bsn::range::Range getLowRisk() const; void setLowRisk(const bsn::range::Range); std::array<bsn::range::Range, 2> getMediumRisk() const; void setMediumRisk(const std::array<bsn::range::Range, 2>); std::array<bsn::range::Range, 2> getHighRisk() const; void setHighRisk(const std::array<bsn::range::Range, 2>); bsn::range::Range getLowPercentage() const; void setLowPercentage(const bsn::range::Range); bsn::range::Range getMidPercentage() const; void setMidPercentage(const bsn::range::Range); bsn::range::Range getHighPercentage() const; void setHighPercentage(const bsn::range::Range); const std::string toString() ; }; } } #endif
27.084337
73
0.683274
gabrielevi10
9a17d0c7f6a0cf1624878b9d909425202934b4f2
380
cpp
C++
turtlebot2/kobuki_base/kobuki_ros/kobuki_node/src/kobuki_ros_node.cpp
RoboticsLabURJC/2021-tfg-carlos-caminero
e23991616cb971b9a0bd95b653789c54f571a930
[ "Apache-2.0" ]
null
null
null
turtlebot2/kobuki_base/kobuki_ros/kobuki_node/src/kobuki_ros_node.cpp
RoboticsLabURJC/2021-tfg-carlos-caminero
e23991616cb971b9a0bd95b653789c54f571a930
[ "Apache-2.0" ]
null
null
null
turtlebot2/kobuki_base/kobuki_ros/kobuki_node/src/kobuki_ros_node.cpp
RoboticsLabURJC/2021-tfg-carlos-caminero
e23991616cb971b9a0bd95b653789c54f571a930
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <memory> #include <rclcpp/rclcpp.hpp> #include "kobuki_node/kobuki_ros.hpp" int main(int argc, char** argv) { // Configures stdout stream for no buffering setvbuf(stdout, nullptr, _IONBF, BUFSIZ); rclcpp::init(argc, argv); rclcpp::spin(std::make_shared<kobuki_node::KobukiRos>(rclcpp::NodeOptions())); rclcpp::shutdown(); return 0; }
18.095238
80
0.707895
RoboticsLabURJC
9a17d0d1b9b617d436b632b8c6f300204c4853ae
1,798
cpp
C++
src/Game/CPlayer.cpp
kenluck2001/2DGameFrameWork
4064b0397240f66250099995157e65f2ee3ecff9
[ "MIT" ]
1
2016-07-22T17:32:38.000Z
2016-07-22T17:32:38.000Z
src/Game/CPlayer.cpp
kenluck2001/2DGameFrameWork
4064b0397240f66250099995157e65f2ee3ecff9
[ "MIT" ]
null
null
null
src/Game/CPlayer.cpp
kenluck2001/2DGameFrameWork
4064b0397240f66250099995157e65f2ee3ecff9
[ "MIT" ]
null
null
null
// ============================= // SDL Programming // Name: ODOH KENNETH EMEKA // Student id: 0902024 // Task 18 // ============================= #include "CPlayer.h" #include <CImageAlpha.h> #include "CSpaceAttacker.h" //////////////////////////////////////////////////////////////////////////////// CPlayer::CPlayer( CSpaceAttacker *pGame ) { takeshot = false; m_pGame = pGame; m_AeroPlane.Load("pics/plane.bmp"); m_AeroPlane.SetColorKey(0,67,171); GetBoundingRectangle().SetDimensions( m_AeroPlane.GetSurface()->w, m_AeroPlane.GetSurface()->h); // create bounding box } //////////////////////////////////////////////////////////////////////////////// void CPlayer::Fire() { takeshot = true; if (takeshot) { m_pGame->GetSoundServer()->Play("fire"); // find first bullet outside screen for(int i=0;i<MAX_BULLETS;i++) { if( m_Bullets[i].IsAvailable() ) // if found, set to plane coordinates so they will move forth. { m_Bullets[i].SetPosition( GetPosition() ); break; } } } } //////////////////////////////////////////////////////////////////////////////// void CPlayer::Update( float fSeconds ) { takeshot = false; GetBoundingRectangle().SetPosition(GetPosition()); } //////////////////////////////////////////////////////////////////////////////// CProjectile * CPlayer::GetBullets() { return m_Bullets; } //////////////////////////////////////////////////////////////////////////////// void CPlayer::Render( CRenderer & r ) { r.Render( &m_AeroPlane, GetX() - m_AeroPlane.GetSurface()->w/2, GetY() - m_AeroPlane.GetSurface()->h/2);//align the aeroplane exactly in the center of the screen considering the widht and height of the images itself } ////////////////////////////////////////////////////////////////////////////////
29
156
0.477753
kenluck2001
9a20107c36410583cd9701568f1da690d1b6aa45
4,072
cpp
C++
Socket.cpp
marcaddeo/MAMClient
c3d91a55e25a70347401071fd9d5a26afacfe361
[ "MIT" ]
null
null
null
Socket.cpp
marcaddeo/MAMClient
c3d91a55e25a70347401071fd9d5a26afacfe361
[ "MIT" ]
null
null
null
Socket.cpp
marcaddeo/MAMClient
c3d91a55e25a70347401071fd9d5a26afacfe361
[ "MIT" ]
null
null
null
/* * Socket.cpp * MAMClient * * Created by Marc Addeo on 10/7/08. * Copyright 2008 __MyCompanyName__. All rights reserved. * */ #include "Socket.h" Socket::Socket( CryptoStuff *crypt ) : m_sock( -1 ) { memset( &this->m_addr, 0, sizeof( this->m_addr ) ); this->crypto = crypt; } Socket::~Socket( void ) { } bool Socket::create( void ) { int on = 1; this->m_sock = socket( AF_INET, SOCK_STREAM, IPPROTO_IP ); if ( !this->is_valid() ) return false; if ( setsockopt( this->m_sock, SOL_SOCKET, SO_REUSEADDR, ( const char * )&on, sizeof( on ) ) == -1 ) return false; return true; } bool Socket::connect( const char *host, const int port ) { int status; if ( !this->create() ) return false; if ( !this->is_valid() ) return false; this->m_addr.sin_family = AF_INET; this->m_addr.sin_port = htons( port ); status = inet_pton( AF_INET, host, &this->m_addr.sin_addr ); if ( errno == EAFNOSUPPORT ) return false; status = ::connect( this->m_sock, ( sockaddr * )&this->m_addr, sizeof( this->m_addr ) ); if ( status == 0 ) return true; return false; } void Socket::select( void ) { struct timeval tv; tv.tv_sec = 30; tv.tv_usec = 0; FD_ZERO( &this->readfds ); FD_SET( this->m_sock, &this->readfds ); ::select( this->m_sock + 1, &this->readfds, NULL, NULL, &tv ); } bool Socket::is_readable( void ) { if ( FD_ISSET( this->m_sock, &this->readfds ) ) return true; return false; } bool Socket::send( const char *data, int size ) const { int status; int nSent = 0; while ( nSent < size ) { status = ::send( this->m_sock, data + nSent, size - nSent, 0 ); if ( status == -1 ) break; nSent += status; } if ( status == -1 ) return false; return true; } int Socket::read( const char *buffer, int size ) const { int status; char rBuffer[0x1000]; int nRecieved = 0; memset( rBuffer, 0, 0x1000 ); while ( nRecieved < size ) { status = ::recv( this->m_sock, rBuffer + nRecieved, size - nRecieved, 0 ); if ( status == -1 ) break; nRecieved += status; } if ( status == -1 || status == 0 ) return status; memcpy( ( void * )buffer, ( void * )rBuffer, size ); return status; } CPacket Socket::read_packet( void ) { CPacket packet; char pHeader[4]; int status; status = this->read( pHeader, sizeof( pHeader ) ); if ( status == 0 ) { std::cout << "Error in read_packet() ... Empty packet..." << std::endl; packet.header.size = 0; packet.header.id = 0; return packet; } if ( status == -1 ) std::cout << "Error in read_packet() ... " << errno << std::endl; this->crypto->incoming( pHeader, sizeof( pHeader ) ); packet.header = *( CPacketHeader * )pHeader; if ( packet.header.size < 0 || packet.header.size > MAXPACKETSIZE ) { packet.header.size = 0; packet.header.id = 0; return packet; } status = this->read( packet.data, ( packet.header.size - sizeof( CPacketHeader ) ) ); this->crypto->incoming( packet.data, ( packet.header.size - sizeof( CPacketHeader ) ) ); return packet; } bool Socket::send_packet( CPacket packet ) { char buffer[MAXPACKETSIZE]; bool sent; printf("Send_packet Packet %s: ", packet.data); hexdump( ( void * )packet.data, ( packet.header.size - sizeof( CPacketHeader ) ) ); memcpy( ( void * )buffer, ( void * )&packet, packet.header.size ); printf("Send_packet Buffer %s: ", buffer); hexdump( ( void * )buffer, 52); this->crypto->outgoing( buffer, packet.header.size ); sent = this->send( buffer, packet.header.size ); if ( !sent ) std::cout << "Error in send_packet() ... " << errno << std::endl; return sent; }
21.775401
104
0.5528
marcaddeo
9a2278aac1d423e8c0a5a693d8435a1c88f9a1da
2,871
cc
C++
services/service_manager/public/cpp/service_executable/service_executable_environment.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
services/service_manager/public/cpp/service_executable/service_executable_environment.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
services/service_manager/public/cpp/service_executable/service_executable_environment.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/service_manager/public/cpp/service_executable/service_executable_environment.h" #include "base/command_line.h" #include "base/logging.h" #include "base/message_loop/message_loop_current.h" #include "base/message_loop/message_pump_type.h" #include "base/synchronization/waitable_event.h" #include "base/task/thread_pool/thread_pool_instance.h" #include "build/build_config.h" #include "mojo/core/embedder/embedder.h" #include "mojo/public/cpp/platform/platform_channel.h" #include "mojo/public/cpp/system/invitation.h" #include "mojo/public/cpp/system/message_pipe.h" #include "services/service_manager/public/cpp/service_executable/switches.h" #include "services/service_manager/sandbox/sandbox.h" #include "services/service_manager/sandbox/switches.h" #if defined(OS_LINUX) #include "base/rand_util.h" #include "base/system/sys_info.h" #include "services/service_manager/sandbox/linux/sandbox_linux.h" #endif namespace service_manager { ServiceExecutableEnvironment::ServiceExecutableEnvironment() : ipc_thread_("IPC Thread") { DCHECK(!base::MessageLoopCurrent::Get()); #if defined(OS_LINUX) const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kServiceSandboxType)) { // Warm parts of base in the copy of base in the mojo runner. base::RandUint64(); base::SysInfo::AmountOfPhysicalMemory(); base::SysInfo::NumberOfProcessors(); // Repeat steps normally performed by the zygote. SandboxLinux::Options sandbox_options; sandbox_options.engage_namespace_sandbox = true; Sandbox::Initialize( UtilitySandboxTypeFromString( command_line.GetSwitchValueASCII(switches::kServiceSandboxType)), SandboxLinux::PreSandboxHook(), sandbox_options); } #endif mojo::core::Init(); base::ThreadPoolInstance::CreateAndStartWithDefaultParams( "StandaloneService"); ipc_thread_.StartWithOptions( base::Thread::Options(base::MessagePumpType::IO, 0)); ipc_support_.emplace(ipc_thread_.task_runner(), mojo::core::ScopedIPCSupport::ShutdownPolicy::CLEAN); } ServiceExecutableEnvironment::~ServiceExecutableEnvironment() = default; mojom::ServiceRequest ServiceExecutableEnvironment::TakeServiceRequestFromCommandLine() { auto invitation = mojo::IncomingInvitation::Accept( mojo::PlatformChannel::RecoverPassedEndpointFromCommandLine( *base::CommandLine::ForCurrentProcess())); return mojom::ServiceRequest(invitation.ExtractMessagePipe( base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kServiceRequestAttachmentName))); } } // namespace service_manager
36.807692
98
0.768373
sarang-apps
9a28121384bcfd15bf5c3fe13b8b406e6bc1fa18
8,072
cpp
C++
lammps-master/src/nbin_standard.cpp
rajkubp020/helloword
4bd22691de24b30a0f5b73821c35a7ac0666b034
[ "MIT" ]
null
null
null
lammps-master/src/nbin_standard.cpp
rajkubp020/helloword
4bd22691de24b30a0f5b73821c35a7ac0666b034
[ "MIT" ]
null
null
null
lammps-master/src/nbin_standard.cpp
rajkubp020/helloword
4bd22691de24b30a0f5b73821c35a7ac0666b034
[ "MIT" ]
null
null
null
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ #include "nbin_standard.h" #include "neighbor.h" #include "atom.h" #include "group.h" #include "domain.h" #include "comm.h" #include "update.h" #include "error.h" using namespace LAMMPS_NS; #define SMALL 1.0e-6 #define CUT2BIN_RATIO 100 /* ---------------------------------------------------------------------- */ NBinStandard::NBinStandard(LAMMPS *lmp) : NBin(lmp) {} /* ---------------------------------------------------------------------- setup neighbor binning geometry bin numbering in each dimension is global: 0 = 0.0 to binsize, 1 = binsize to 2*binsize, etc nbin-1,nbin,etc = bbox-binsize to bbox, bbox to bbox+binsize, etc -1,-2,etc = -binsize to 0.0, -2*binsize to -binsize, etc code will work for any binsize since next(xyz) and stencil extend as far as necessary binsize = 1/2 of cutoff is roughly optimal for orthogonal boxes: a dim must be filled exactly by integer # of bins in periodic, procs on both sides of PBC must see same bin boundary in non-periodic, coord2bin() still assumes this by use of nbin xyz for triclinic boxes: tilted simulation box cannot contain integer # of bins stencil & neigh list built differently to account for this mbinlo = lowest global bin any of my ghost atoms could fall into mbinhi = highest global bin any of my ghost atoms could fall into mbin = number of bins I need in a dimension ------------------------------------------------------------------------- */ void NBinStandard::setup_bins(int style) { // bbox = size of bbox of entire domain // bsubbox lo/hi = bounding box of my subdomain extended by comm->cutghost // for triclinic: // bbox bounds all 8 corners of tilted box // subdomain is in lamda coords // include dimension-dependent extension via comm->cutghost // domain->bbox() converts lamda extent to box coords and computes bbox double bbox[3],bsubboxlo[3],bsubboxhi[3]; double *cutghost = comm->cutghost; if (triclinic == 0) { bsubboxlo[0] = domain->sublo[0] - cutghost[0]; bsubboxlo[1] = domain->sublo[1] - cutghost[1]; bsubboxlo[2] = domain->sublo[2] - cutghost[2]; bsubboxhi[0] = domain->subhi[0] + cutghost[0]; bsubboxhi[1] = domain->subhi[1] + cutghost[1]; bsubboxhi[2] = domain->subhi[2] + cutghost[2]; } else { double lo[3],hi[3]; lo[0] = domain->sublo_lamda[0] - cutghost[0]; lo[1] = domain->sublo_lamda[1] - cutghost[1]; lo[2] = domain->sublo_lamda[2] - cutghost[2]; hi[0] = domain->subhi_lamda[0] + cutghost[0]; hi[1] = domain->subhi_lamda[1] + cutghost[1]; hi[2] = domain->subhi_lamda[2] + cutghost[2]; domain->bbox(lo,hi,bsubboxlo,bsubboxhi); } bbox[0] = bboxhi[0] - bboxlo[0]; bbox[1] = bboxhi[1] - bboxlo[1]; bbox[2] = bboxhi[2] - bboxlo[2]; // optimal bin size is roughly 1/2 the cutoff // for BIN style, binsize = 1/2 of max neighbor cutoff // for MULTI style, binsize = 1/2 of min neighbor cutoff // special case of all cutoffs = 0.0, binsize = box size double binsize_optimal; if (binsizeflag) binsize_optimal = binsize_user; else if (style == Neighbor::BIN) binsize_optimal = 0.5*cutneighmax; else binsize_optimal = 0.5*cutneighmin; if (binsize_optimal == 0.0) binsize_optimal = bbox[0]; double binsizeinv = 1.0/binsize_optimal; // test for too many global bins in any dimension due to huge global domain if (bbox[0]*binsizeinv > MAXSMALLINT || bbox[1]*binsizeinv > MAXSMALLINT || bbox[2]*binsizeinv > MAXSMALLINT) error->all(FLERR,"Domain too large for neighbor bins"); // create actual bins // always have one bin even if cutoff > bbox // for 2d, nbinz = 1 nbinx = static_cast<int> (bbox[0]*binsizeinv); nbiny = static_cast<int> (bbox[1]*binsizeinv); if (dimension == 3) nbinz = static_cast<int> (bbox[2]*binsizeinv); else nbinz = 1; if (nbinx == 0) nbinx = 1; if (nbiny == 0) nbiny = 1; if (nbinz == 0) nbinz = 1; // compute actual bin size for nbins to fit into box exactly // error if actual bin size << cutoff, since will create a zillion bins // this happens when nbin = 1 and box size << cutoff // typically due to non-periodic, flat system in a particular dim // in that extreme case, should use NSQ not BIN neighbor style binsizex = bbox[0]/nbinx; binsizey = bbox[1]/nbiny; binsizez = bbox[2]/nbinz; bininvx = 1.0 / binsizex; bininvy = 1.0 / binsizey; bininvz = 1.0 / binsizez; if (binsize_optimal*bininvx > CUT2BIN_RATIO || binsize_optimal*bininvy > CUT2BIN_RATIO || binsize_optimal*bininvz > CUT2BIN_RATIO) error->all(FLERR,"Cannot use neighbor bins - box size << cutoff"); // mbinlo/hi = lowest and highest global bins my ghost atoms could be in // coord = lowest and highest values of coords for my ghost atoms // static_cast(-1.5) = -1, so subract additional -1 // add in SMALL for round-off safety int mbinxhi,mbinyhi,mbinzhi; double coord; coord = bsubboxlo[0] - SMALL*bbox[0]; mbinxlo = static_cast<int> ((coord-bboxlo[0])*bininvx); if (coord < bboxlo[0]) mbinxlo = mbinxlo - 1; coord = bsubboxhi[0] + SMALL*bbox[0]; mbinxhi = static_cast<int> ((coord-bboxlo[0])*bininvx); coord = bsubboxlo[1] - SMALL*bbox[1]; mbinylo = static_cast<int> ((coord-bboxlo[1])*bininvy); if (coord < bboxlo[1]) mbinylo = mbinylo - 1; coord = bsubboxhi[1] + SMALL*bbox[1]; mbinyhi = static_cast<int> ((coord-bboxlo[1])*bininvy); if (dimension == 3) { coord = bsubboxlo[2] - SMALL*bbox[2]; mbinzlo = static_cast<int> ((coord-bboxlo[2])*bininvz); if (coord < bboxlo[2]) mbinzlo = mbinzlo - 1; coord = bsubboxhi[2] + SMALL*bbox[2]; mbinzhi = static_cast<int> ((coord-bboxlo[2])*bininvz); } // extend bins by 1 to insure stencil extent is included // for 2d, only 1 bin in z mbinxlo = mbinxlo - 1; mbinxhi = mbinxhi + 1; mbinx = mbinxhi - mbinxlo + 1; mbinylo = mbinylo - 1; mbinyhi = mbinyhi + 1; mbiny = mbinyhi - mbinylo + 1; if (dimension == 3) { mbinzlo = mbinzlo - 1; mbinzhi = mbinzhi + 1; } else mbinzlo = mbinzhi = 0; mbinz = mbinzhi - mbinzlo + 1; bigint bbin = ((bigint) mbinx) * ((bigint) mbiny) * ((bigint) mbinz) + 1; if (bbin > MAXSMALLINT) error->one(FLERR,"Too many neighbor bins"); mbins = bbin; } /* ---------------------------------------------------------------------- bin owned and ghost atoms ------------------------------------------------------------------------- */ void NBinStandard::bin_atoms() { int i,ibin; last_bin = update->ntimestep; for (i = 0; i < mbins; i++) binhead[i] = -1; // bin in reverse order so linked list will be in forward order // also puts ghost atoms at end of list, which is necessary double **x = atom->x; int *mask = atom->mask; int nlocal = atom->nlocal; int nall = nlocal + atom->nghost; if (includegroup) { int bitmask = group->bitmask[includegroup]; for (i = nall-1; i >= nlocal; i--) { if (mask[i] & bitmask) { ibin = coord2bin(x[i]); atom2bin[i] = ibin; bins[i] = binhead[ibin]; binhead[ibin] = i; } } for (i = atom->nfirst-1; i >= 0; i--) { ibin = coord2bin(x[i]); atom2bin[i] = ibin; bins[i] = binhead[ibin]; binhead[ibin] = i; } } else { for (i = nall-1; i >= 0; i--) { ibin = coord2bin(x[i]); atom2bin[i] = ibin; bins[i] = binhead[ibin]; binhead[ibin] = i; } } }
34.643777
77
0.612983
rajkubp020
9a3086bfcbea92e16f880f88b1a15e046b21ce41
11,633
cpp
C++
TicTacToeVsCPU.cpp
anubhawbhalotia/TicTacToe-Vs-CPU
2bb37dbfbd20075196ad859c5309e77c61d1e8f7
[ "MIT" ]
null
null
null
TicTacToeVsCPU.cpp
anubhawbhalotia/TicTacToe-Vs-CPU
2bb37dbfbd20075196ad859c5309e77c61d1e8f7
[ "MIT" ]
null
null
null
TicTacToeVsCPU.cpp
anubhawbhalotia/TicTacToe-Vs-CPU
2bb37dbfbd20075196ad859c5309e77c61d1e8f7
[ "MIT" ]
null
null
null
#include<stdio.h> #include<windows.h> #include<stdlib.h> #include<time.h> void ar(int*); void tictctoe(int,int*,char,char); int checkwin(int*,int); void cpuplay(int*,char); int checkcpunextmove(int*); int checkplayernextmove(int*); int checknextmove(int*); int checkcpunextmoveadv(int*); int checknextmoveadv(int*); int clone(int*,int); int checktwozeroone(int*,int); int playerplay(int*,char); void add(int,char); void gotoxy(int anubhaw, int y) { COORD c; c.X = anubhaw; c.Y = y; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c); } void ar(int *a) { int anubhaw=50,y=2,i,j; for(i=0;i<=2;i++) { gotoxy(anubhaw,y); for(j=0;j<=2;j++) { printf("%d ",*(a+(3*i)+j)); } y++; printf("\n"); } } void tictactoe(int t,int *a,char s1,char s2) { int z,i,j,win0,win1; for(i=t;;i++) { //ar(a); if(i%2==0) cpuplay(a,s2); else { z=playerplay(a,s1); if(z==0) { i=0; continue; } } win0=checkwin(a,0); win1=checkwin(a,1); if(win1==1) { gotoxy(23,17); printf("You Won"); break; } else if(win0==1) { gotoxy(22,17); printf("You lose"); break; } for(j=0;j<=8;j++) { if(*(a+j)==2) break; } if(j>8) { gotoxy(24,17); printf("Draw"); break; } //ar(a); } } int checkwin(int *a,int fn) { int i,j,d; //printf("\ninside checkwin"); for(i=0;i<=2;i++) { for(j=0;j<=2;j++) { if(*(a+(3*i)+j)!=fn) break; } if(j>2) return 1; // printf("not in rows\n"); } for(i=0;i<=2;i++) { for(j=0;j<=2;j++) { if(*(a+(3*j)+i)!=fn) break; } if(j>2) return 1; // printf("not in columns\n"); } for(i=0;i<=2;i++) { if(*(a+(3*i)+i)!=fn) break; } if(i>2) return 1; //printf("not in leading diagonal\n"); if(*(a+2)==fn && *(a+4)==fn && *(a+6)==fn) return 1; //printf("not in other diagonal\n"); return 0; } void cpuplay(int *a,char s2) { int d,p,i; p=checktwozeroone(a,0); //checks for direct winning case finds single empty box to put 0 (banana) if(p<10) goto c; p=checktwozeroone(a,1); //finds single emppty box to put 0 (bigadna) if(p<10) goto c; p=checknextmoveadv(a); //checks whether in the next chance, player doesn't win clarly if(p<10) goto c; p=checkcpunextmoveadv(a); //checks whether in next chance cpu can win clearly if(p<10) goto c; p=checknextmove(a); //checks whether in next chance if(p<10) goto c; p=checkplayernextmove(a); //keeps 1 check form or not. keeps 0 check form or not if(p<10) goto c; p=checkcpunextmove(a); //keeps 0 and check cpu form or not if(p<10) goto c; d=rand(); for(i=0;i<=4;i++) { if(d%5==i) { if(*(a+(2*i))==2) { p=(2*i)+1; break; } } } if(i<=4) goto c; if(*(a+4)==2) { p=5; goto c; } for(i=0;;i++) { if(*(a+i)==2) { //printf("general\n"); p=i+1; break; } } c: //printf(" value of p after cpu play : %d\n",p); *(a+p-1)=0; add(p,s2); } int checkcpunextmove(int *a) { int i,b[9],count=0; for(i=0;i<=8;i++) b[i]=*(a+i); if(b[4]==2) { b[4]=0; count=clone(b,0); b[4]=2; if(count>0) return 5; } for(i=0;i<=8;i++) { count=0; if(b[i]==2) { b[i]=0; count=clone(b,0); b[i]=2; if(count>0) { //printf("\ncheckcpunextmove\n"); return i+1; } } } return 10; } int checkplayernextmove(int *a) { int i,b[9],count=0; for(i=0;i<=8;i++) b[i]=*(a+i); if(b[4]==2) { b[4]=1; count=clone(b,1); b[4]=2; if(count>0) return 5; } for(i=0;i<=8;i++) { count=0; if(b[i]==2) { b[i]=1; count=clone(b,1); b[i]=2; if(count>0) { //printf("\ncheckplayernextmove\n"); return i+1; } } } return 10; } int checknextmove(int *a) { int i,b[9],count1=0,count0=0; for(i=0;i<=8;i++) b[i]=*(a+i); if(b[4]==2) { b[4]=1; count1=clone(b,1); b[4]=0; count0=clone(b,0); b[4]=2; if(count1>0 && count0>0) return 5; } for(i=0;i<=8;i++) { count1=0; count0=0; if(b[i]==2) { b[i]=1; count1=clone(b,1); b[i]=0; count0=clone(b,0); b[i]=2; if(count1>0 && count0>0) { //printf("\nchecknextmove\n"); return i+1; } } } return 10; } int checkcpunextmoveadv(int *a) { int i,b[9],count; for(i=0;i<=8;i++) b[i]=*(a+i); for(i=0;i<=8;i++) { count=0; if(b[i]==2) { b[i]=0; count=clone(b,0); b[i]=2; if(count>1) { //printf("\ncheckcpunextmoveadv\n"); return i+1; } } } return 10; } int checknextmoveadv(int *a) { int i,b[9],count; for(i=0;i<=8;i++) b[i]=*(a+i); for(i=0;i<=8;i++) { count=0; if(b[i]==2) { b[i]=1; count=clone(b,1); b[i]=2; if(count>1) { //printf("\nchecknextmoveadv"); return i+1; } } } return 10; } int clone(int *b,int fn) { int i,j,empty,zero,count=0,p; for(i=0;i<=2;i++) { empty=0; zero=0; for(j=0;j<=2;j++) { if(*(b+(3*i)+j)==2) empty++; if(*(b+(3*i)+j)==fn) zero++; } if(empty==1 && zero==2) count++; } for(i=0;i<=2;i++) { empty=0; zero=0; for(j=0;j<=2;j++) { if(*(b+(3*j)+i)==2) empty++; if(*(b+(3*j)+i)==fn) zero++; } if(empty==1 && zero==2) count++; } empty=0; zero=0; for(i=0;i<=2;i++) { if(*(b+(3*i)+i)==2) { p=(3*i)+i+1; empty++; } if(*(b+(3*i)+i)==fn) zero++; } if(empty==1 && zero==2) count++; empty=0; zero=0; for(i=0;i<=2;i++) { for(j=0;j<=2;j++) { if(i+j==2) { if(*(b+(3*i)+j)==2) { p=(3*i)+j+1; empty++; } if(*(b+(3*i)+j)==fn) zero++; } } } if(empty==1 && zero==2) count++; return count; } int checktwozeroone(int *a,int fn) { int i,j,empty,zero,p; for(i=0;i<=2;i++) { empty=0; zero=0; for(j=0;j<=2;j++) { if(*(a+(3*i)+j)==2) { p=(3*i)+j+1; empty++; } if(*(a+(3*i)+j)==fn) zero++; } if(empty==1 && zero==2) return p; } for(i=0;i<=2;i++) { empty=0; zero=0; for(j=0;j<=2;j++) { if(*(a+(3*j)+i)==2) { p=(3*j)+i+1; empty++; } if(*(a+(3*j)+i)==fn) zero++; } if(empty==1 && zero==2) return p; } empty=0; zero=0; for(i=0;i<=2;i++) { if(*(a+(3*i)+i)==2) { p=(3*i)+i+1; empty++; } if(*(a+(3*i)+i)==fn) zero++; } if(empty==1 && zero==2) return p; empty=0; zero=0; for(i=0;i<=2;i++) { for(j=0;j<=2;j++) { if(i+j==2) { if(*(a+(3*i)+j)==2) { p=(3*i)+j+1; empty++; } if(*(a+(3*i)+j)==fn) zero++; } } } if(empty==1 && zero==2) return p; return 10; } int playerplay(int *a,char s1) { int p; gotoxy(84,17); printf(" "); gotoxy(86,17); //printf("Make your play"); fflush(stdin); scanf("%d",&p); if(p<1 || p>9) { gotoxy(82,5); printf("Invalid Input\n"); return 0; } gotoxy(82,5); printf(" "); if(*(a+p-1)==2) *(a+p-1)=1; else { gotoxy(82,5); printf("Wrong move\n"); return 0; } add(p,s1); gotoxy(84,17); return 1; } void add(int p,char c) { int anubhaw,y; //printf("Adding at : %d",p); anubhaw=47+((p-1)%3)*7; y=15+((p-1)/3)*3; gotoxy(anubhaw,y); printf("%c%c%c",c,c,c); gotoxy(anubhaw,y+1); printf("%c%c%c",c,c,c); } int main() { int i,t,a[9],anubhaw=50,y=5,j,z=1; printf("Developer - Anubhaw Bhalotia"); d: gotoxy(52,0); printf("TIC-TAC-TOE"); gotoxy(50,1); printf("---------------"); gotoxy(0,3); for(i=0;i<=8;i++) a[i]=2; char s1,s2,toss; srand(time(NULL)); printf("Choose your symbol (X or O) : "); fflush(stdin); scanf("%c",&s1); if(s1!='X' && s1!='x' && s1!='O' && s1!='o' && s1!='0') { printf("\nInvalid Character"); printf("\nType any character and press 'Enter' to continue\n"); fflush(stdin); scanf("%c",&toss); fflush(stdin); system("cls"); goto d; } if(s1=='x') s1='X'; if(s1=='o' || s1=='0') s1='O'; (s1=='X')?s2='O':(s2='X'); printf("\n\nEnter any Character to begin Toss : "); fflush(stdin); scanf("%c",&toss); if(rand()%2==0) { printf("\n\nYou won the toss"); t=1; } else { printf("\n\nYou lose the toss"); t=0; } for(i=0;i<=2;i++) { gotoxy(anubhaw,y); for(j=0;j<=2;j++) { printf("%d ",z); z++; } y+=2; } for(i=6;i<=8;i=i+2) { gotoxy(48,i); printf("----------------"); } for(i=53;i<=60;i=i+4) { for(j=4;j<=10;j++) { gotoxy(i,j); printf("|"); } } for(i=17;i<=21;i=i+3) { gotoxy(45,i); printf("---------------------"); } for(i=52;i<=60;i=i+6) { for(j=14;j<=23;j++) { gotoxy(i,j); printf("|"); } } gotoxy(80,14); printf("Make your Move(1-9)"); gotoxy(83,16); printf("--------"); for(i=16;i<=18;i++) { gotoxy(82,i); printf("|"); gotoxy(82+9,i); printf("|"); } gotoxy(83,18); printf("--------"); gotoxy(0,4); tictactoe(t,a,s1,s2); gotoxy(17,16); printf("-----------------"); gotoxy(17,18); printf("-----------------"); for(i=16;i<=18;i++) { gotoxy(17,i); printf("|"); gotoxy(33,i); printf("|"); } gotoxy(0,25); printf("Type any Character and press 'Enter' to exit : "); fflush(stdin); scanf("%c",&toss); }
18.494436
101
0.376945
anubhawbhalotia
9a34a83de7464a3f9e10ed962cec0cf28f8fcd2c
381
cpp
C++
src/stkdata/ColumnDefInt.cpp
s-takeuchi/YaizuComLib
de1c881a4b743bafec22f7ea2d263572c474cbfe
[ "MIT" ]
4
2017-02-21T23:25:23.000Z
2022-01-30T20:17:22.000Z
src/stkdata/ColumnDefInt.cpp
Aekras1a/YaizuComLib
470d33376add0d448002221b75f7efd40eec506f
[ "MIT" ]
161
2015-05-16T14:26:36.000Z
2021-11-25T05:07:56.000Z
src/stkdata/ColumnDefInt.cpp
Aekras1a/YaizuComLib
470d33376add0d448002221b75f7efd40eec506f
[ "MIT" ]
1
2019-12-06T10:24:45.000Z
2019-12-06T10:24:45.000Z
#include "stkdata.h" #include "../stkpl/StkPl.h" // Constructor ColumnDefInt::ColumnDefInt() { } // Constructor ColumnDefInt::ColumnDefInt(const wchar_t* ColumnName) { StkPlWcsNCpy(m_ColumnName, COLUMN_NAME_SIZE, ColumnName, COLUMN_NAME_SIZE - 1); m_ColumnName[COLUMN_NAME_SIZE - 1] = L'\0'; m_ColumnType = COLUMN_TYPE_INT; } // Destructor ColumnDefInt::~ColumnDefInt() { }
18.142857
80
0.745407
s-takeuchi
9a39d79751778014da3e9ac19d7e7ca4a3feed88
8,704
cpp
C++
tool-dfxcli/src/ConfigCommand.cpp
nuralogix/dfx-api-client-cpp
6b45307ddf4b0036c107eebd7e8915f6c501c3b0
[ "MIT" ]
null
null
null
tool-dfxcli/src/ConfigCommand.cpp
nuralogix/dfx-api-client-cpp
6b45307ddf4b0036c107eebd7e8915f6c501c3b0
[ "MIT" ]
null
null
null
tool-dfxcli/src/ConfigCommand.cpp
nuralogix/dfx-api-client-cpp
6b45307ddf4b0036c107eebd7e8915f6c501c3b0
[ "MIT" ]
null
null
null
// Copyright (c) Nuralogix. All rights reserved. Licensed under the MIT license. // See LICENSE.txt in the project root for license information. #include "dfx/api/cli/ConfigCommand.hpp" #include "nlohmann/json.hpp" using nlohmann::json; ConfigViewCommand::ConfigViewCommand(CLI::App* config, std::shared_ptr<Options> options, DFXExitCode& result) : DFXAppCommand(std::move(options)), full(false) { cmd = config->add_subcommand("view", "Display current configuration"); cmd->alias("show"); cmd->add_flag("-f,--full", full, "Show full details without obfuscation")->capture_default_str(); cmd->callback([&]() { result = DFXAppCommand::execute(loadConfig()); }); } DFXExitCode ConfigViewCommand::execute() { json response = {{"context", config.contextID}, {"transport-type", config.transportType}, {"host", config.serverHost}, {"port", config.serverPort}, {"secure", config.secure}, {"skip-verify", config.skipVerify}}; if (!config.authEmail.empty()) { response["auth-email"] = config.authEmail; } if (!config.authPassword.empty()) { response["auth-password"] = (full ? config.authPassword : "OBFUSCATED"); } if (!config.authOrg.empty()) { response["auth-org"] = config.authOrg; } if (!config.license.empty()) { response["license"] = (full ? config.license : "OBFUSCATED"); } if (!config.studyID.empty()) { response["study-id"] = config.studyID; } if (!config.authToken.empty()) { response["auth-token"] = (full ? config.authToken : "OBFUSCATED"); } if (!config.deviceToken.empty()) { response["device-token"] = (full ? config.deviceToken : "OBFUSCATED"); } if (!config.rootCA.empty()) { response["root-ca"] = config.rootCA; } response["list-limit"] = config.listLimit; response["timeout"] = config.timeoutMillis; outputResponse(response); return DFXExitCode::SUCCESS; } ConfigListCommand::ConfigListCommand(CLI::App* config, std::shared_ptr<Options> options, DFXExitCode& result) : DFXAppCommand(std::move(options)) { cmd = config->add_subcommand("list", "List available config contexts"); cmd->alias("ls"); cmd->callback([&]() { result = execute(); }); } DFXExitCode ConfigListCommand::execute() { std::string defaultContext; std::vector<std::string> contextNames; auto status = dfx::api::getAvailableContexts(options->configFilePath, defaultContext, contextNames); if (!status.OK()) { outputError(status); return DFXExitCode::FAILURE; } // If user is overloading on the command line, mark that context as the default CLI::App* app = cmd; while (app && app->get_parent()) { app = app->get_parent(); } auto contextOpt = app->get_option_no_throw("--context"); if (contextOpt != nullptr && contextOpt->count() > 0) { defaultContext = options->context; } json response = json::array(); for (auto& name : contextNames) { json context = {{"context", name}}; context["default"] = name.compare(defaultContext) == 0; response.push_back(context); } outputResponse(response); return DFXExitCode::SUCCESS; } ConfigSampleCommand::ConfigSampleCommand(CLI::App* config, std::shared_ptr<Options> options, DFXExitCode& result) : DFXAppCommand(std::move(options)), advanced(false) { cmd = config->add_subcommand("sample", "Write sample YAML config to stdout"); cmd->add_flag("-a,--advanced", advanced, "Show an advanced sample format with multiple contexts"); cmd->callback([&]() { result = execute(); }); } DFXExitCode ConfigSampleCommand::execute() { if (!advanced) { // Basic example format std::cout << "# DFX Sample YAML Configuration File (basic)\n" << "# Save this default to: ~/.dfxcloud.yaml\n" << "\n" << "# This file contains only one configuration, to use multiple look at\n" << "# the advanced configuration layout example.\n" << "\n" << "host: api.deepaffex.ai\n" << "\n" << "auth-email: your-email-id\n" << "auth-password: your-password\n" << "auth-org: your-org-identifier\n" << "license: your-license\n" << "study-id: study-id # (Optional) Used for operations requiring\n" << "\n" << "# If the below tokens are present, you do not require email, password, org, license\n" << "#auth-token: your-auth-token # (Optional) Reusable from ./dfxcli login\n" << "#device-token: your-device-token # (Optional) Reusable from ./dfxcli register\n" << std::endl; } else { std::cout << "# DFX Sample YAML Configuration File (advanced)\n" << "# Save this default to: ~/.dfxcloud.yaml\n" << "\n" << "# This file can contain multiple contexts and this provides the default context\n" << "# name to use when loading. Context can be overridden on command line with --context.\n" << "context: rest # default context name to use\n" << "\n" << "# Place defaults here which apply to all services or contexts and\n" << "# explicitly override as needed for individual services or contexts\n" << "verbose: 2\n" << "timeout: 3000 # 3 seconds\n" << "list-limit: 25 # Maximum number of records returned for list calls. Default: 25\n" << "auth-email: your-email-id # defining below is optional if here\n" << "\n" << "# Services define the end-point hosts and can be cloud instances or\n" << "# standalone devices. They are used by contexts to provide host/port details.\n" << "services:\n" << " - name: v2-rest\n" << " host: api.deepaffex.ai\n" << " transport-type: REST\n" << " - name: v2-websocket\n" << " host: api.deepaffex.ai\n" << " #skip-verify: true # If TLS/SSL handshake can skip verification. Default: false\n" << " transport-type: WEBSOCKET\n" << " - name: v3-grpc\n" << " host: local-server.deepaffex.ai\n" << " port: 8443\n" << " transport-type: GRPC\n" << "\n" << "# Contexts provide the authentication details and link to the service hosts\n" << "contexts:\n" << " - name: rest\n" << " service: v2-rest # links to service host/port name above\n" << " auth-email: your-email-id\n" << " auth-password: your-secret-password\n" << " auth-org: your-org-identifier\n" << " license: your-license\n" << " study-id: study-id # (Optional) Used for operations requiring\n" << "\n" << " # Tokens can be cached in config to avoid login/register/unregister/logout on every request\n" << " # if provided, auth-email, auth-password, auth-org, license are optional\n" << " #auth-token: your-auth-token # (Optional) Reusable from ./dfxcli login\n" << " #device-token: your-device-token # (Optional) Reusable from ./dfxcli register\n" << "\n" << " - name: websocket\n" << " service: v2-websocket\n" << " auth-email: your-email-id\n" << " auth-password: your-secret-password\n" << " auth-org: your-org-identifier\n" << " license: your-license\n" << " study-id: study-id\n" << "\n" << " - name: grpc\n" << " service: v3-grpc\n" << " auth-email: your-email-id\n" << " auth-password: your-secret-password\n" << " auth-org: your-org-identifier\n" << " license: your-license\n" << " study-id: study-id\n"; } return DFXExitCode::SUCCESS; }
46.05291
120
0.534352
nuralogix
9a429a6662ec32856578f6b9347a6c613aa54248
5,250
cc
C++
src/remote_adapter/remote_adapter_client/hmi_adapter/lua_lib/hmi_adapter_client_lua_wrapper.cc
LuxoftSDL/sdl_atf
454487dafdc422db724cceb02827a6738e93203b
[ "BSD-3-Clause" ]
6
2016-03-04T20:27:37.000Z
2021-11-06T08:05:00.000Z
src/remote_adapter/remote_adapter_client/hmi_adapter/lua_lib/hmi_adapter_client_lua_wrapper.cc
smartdevicelink/sdl_atf
08354ae6633169513639a3d9257acd1229a5caa2
[ "BSD-3-Clause" ]
122
2016-03-09T20:03:50.000Z
2022-01-31T14:26:36.000Z
src/remote_adapter/remote_adapter_client/hmi_adapter/lua_lib/hmi_adapter_client_lua_wrapper.cc
smartdevicelink/sdl_atf
08354ae6633169513639a3d9257acd1229a5caa2
[ "BSD-3-Clause" ]
41
2016-03-10T09:34:00.000Z
2020-12-01T09:08:24.000Z
#include "hmi_adapter/lua_lib/hmi_adapter_client_lua_wrapper.h" #include <iostream> #include "common/constants.h" #include "hmi_adapter/hmi_adapter_client.h" #include "rpc/detail/log.h" namespace lua_lib { RPCLIB_CREATE_LOG_CHANNEL(HmiAdapterClientLuaWrapper) int HmiAdapterClientLuaWrapper::create_SDLRemoteTestAdapter(lua_State *L) { LOG_INFO("{0}", __func__); luaL_checktype(L, 1, LUA_TTABLE); // Index -1(top) - table shm_params_array // Index -2 - table out_params // Index -3 - table in_params // Index -4 - RemoteClient instance // index -5 - Library table auto tcp_params = build_TCPParams(L); lua_pop(L, 1); // Remove value from the top of the stack // Index -1(top) - table in_params // Index -2 - RemoteClient instance // Index -3 - Library table RemoteClient **user_data = reinterpret_cast<RemoteClient **>(luaL_checkudata(L, 2, "RemoteClient")); if (nullptr == user_data) { std::cout << "RemoteClient was not found" << std::endl; return 0; } RemoteClient *client = *user_data; lua_pop(L, 1); // Remove value from the top of the stack // Index -1(top) - Library table try { HmiAdapterClient *qt_client = new HmiAdapterClient(client, tcp_params); // Allocate memory for a pointer to client object HmiAdapterClient **s = (HmiAdapterClient **)lua_newuserdata(L, sizeof(HmiAdapterClient *)); // Index -1(top) - instance userdata // Index -2 - Library table *s = qt_client; } catch (std::exception &e) { std::cout << "Exception occurred: " << e.what() << std::endl; lua_pushnil(L); // Index -1(top) - nil // Index -2 - Library table return 1; } HmiAdapterClientLuaWrapper::registerSDLRemoteTestAdapter(L); // Index -1 (top) - registered SDLRemoteTestAdapter metatable // Index -2 - instance userdata // Index -3 - Library table lua_setmetatable(L, -2); // Set class table as metatable for instance userdata // Index -1(top) - instance table // Index -2 - Library table return 1; } int HmiAdapterClientLuaWrapper::destroy_SDLRemoteTestAdapter(lua_State *L) { LOG_INFO("{0}", __func__); auto instance = get_instance(L); delete instance; return 0; } void HmiAdapterClientLuaWrapper::registerSDLRemoteTestAdapter(lua_State *L) { LOG_INFO("{0}", __func__); static const luaL_Reg SDLRemoteTestAdapterFunctions[] = { {"connect", HmiAdapterClientLuaWrapper::lua_connect}, {"write", HmiAdapterClientLuaWrapper::lua_write}, {NULL, NULL}}; luaL_newmetatable(L, "HmiAdapterClient"); // Index -1(top) - SDLRemoteTestAdapter metatable lua_newtable(L); // Index -1(top) - created table // Index -2 : SDLRemoteTestAdapter metatable luaL_setfuncs(L, SDLRemoteTestAdapterFunctions, 0); // Index -1(top) - table with SDLRemoteTestAdapterFunctions // Index -2 : SDLRemoteTestAdapter metatable lua_setfield(L, -2, "__index"); // Setup created table as index lookup for metatable // Index -1(top) - SDLRemoteTestAdapter metatable lua_pushcfunction(L, HmiAdapterClientLuaWrapper::destroy_SDLRemoteTestAdapter); // Index -1(top) - destroy_SDLRemoteTestAdapter function pointer // Index -2 - SDLRemoteTestAdapter metatable lua_setfield(L, -2, "__gc"); // Set garbage collector function to metatable // Index -1(top) - SDLRemoteTestAdapter metatable } HmiAdapterClient *HmiAdapterClientLuaWrapper::get_instance(lua_State *L) { LOG_INFO("{0}", __func__); // Index 1 - lua instance HmiAdapterClient **user_data = reinterpret_cast<HmiAdapterClient **>( luaL_checkudata(L, 1, "HmiAdapterClient")); if (nullptr == user_data) { return nullptr; } return *user_data; //*((HmiAdapterClient**)ud); } std::vector<parameter_type> HmiAdapterClientLuaWrapper::build_TCPParams(lua_State *L) { LOG_INFO("{0}", __func__); // Index -1(top) - table params lua_getfield(L, -1, "host"); // Pushes onto the stack the value params[host] // Index -1(top) - string host // Index -2 - table params const char *host = lua_tostring(L, -1); lua_pop(L, 1); // remove value from the top of the stack // Index -1(top) - table params lua_getfield(L, -1, "port"); // Pushes onto the stack the value params[port] // Index -1(top) - number port // Index -2 - table params const int port = lua_tointeger(L, -1); lua_pop(L, 1); // Remove value from the top of the stack // Index -1(top) - table params std::vector<parameter_type> TCPParams; TCPParams.push_back( std::make_pair(std::string(host), constants::param_types::STRING)); TCPParams.push_back( std::make_pair(std::to_string(port), constants::param_types::INT)); return TCPParams; } int HmiAdapterClientLuaWrapper::lua_connect(lua_State *L) { LOG_INFO("{0}", __func__); // Index -1(top) - table instance auto instance = get_instance(L); instance->connect(); return 0; } int HmiAdapterClientLuaWrapper::lua_write(lua_State *L) { LOG_INFO("{0}", __func__); // Index -1(top) - string data // Index -2 - table instance auto instance = get_instance(L); auto data = lua_tostring(L, -1); int result = instance->send(data); lua_pushinteger(L, result); return 1; } } // namespace lua_lib
29.829545
80
0.689714
LuxoftSDL
9a42ac97df0ae6638139917df1c1e016a5242ca4
10,106
cpp
C++
hi_scripting/scripting/scriptnode/api/DspHelpers.cpp
romsom/HISE
73e0e299493ce9236e6fafa7938d3477fcc36a4a
[ "Intel" ]
null
null
null
hi_scripting/scripting/scriptnode/api/DspHelpers.cpp
romsom/HISE
73e0e299493ce9236e6fafa7938d3477fcc36a4a
[ "Intel" ]
null
null
null
hi_scripting/scripting/scriptnode/api/DspHelpers.cpp
romsom/HISE
73e0e299493ce9236e6fafa7938d3477fcc36a4a
[ "Intel" ]
null
null
null
/* =========================================================================== * * This file is part of HISE. * Copyright 2016 Christoph Hart * * HISE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HISE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HISE. If not, see <http://www.gnu.org/licenses/>. * * Commercial licenses for using HISE in an closed source project are * available on request. Please visit the project's website to get more * information about commercial licensing: * * http://www.hise.audio/ * * HISE is based on the JUCE library, * which also must be licensed for commercial applications: * * http://www.juce.com * * =========================================================================== */ namespace scriptnode { using namespace juce; using namespace hise; void DspHelpers::increaseBuffer(AudioSampleBuffer& b, const PrepareSpecs& specs) { auto numChannels = specs.numChannels; auto numSamples = specs.blockSize; if (numChannels != b.getNumChannels() || b.getNumSamples() < numSamples) { b.setSize(numChannels, numSamples); } } scriptnode::DspHelpers::ParameterCallback DspHelpers::getFunctionFrom0To1ForRange(NormalisableRange<double> range, bool inverted, const ParameterCallback& originalFunction) { if (RangeHelpers::isIdentity(range)) { if (!inverted) return originalFunction; else { return [originalFunction](double normalisedValue) { originalFunction(1.0 - normalisedValue); }; } } if (inverted) { return [range, originalFunction](double normalisedValue) { normalisedValue = 1.0 - normalisedValue; auto v = range.convertFrom0to1(normalisedValue); originalFunction(v); }; } else { return [range, originalFunction](double normalisedValue) { auto v = range.convertFrom0to1(normalisedValue); originalFunction(v); }; } } double DspHelpers::ConverterFunctions::decibel2Gain(double input) { return Decibels::decibelsToGain(input); } double DspHelpers::ConverterFunctions::gain2Decibel(double input) { return Decibels::gainToDecibels(input); } double DspHelpers::ConverterFunctions::dryAmount(double input) { auto invGain = jlimit(0.0, 1.0, 1.0 - input); auto invDb = Decibels::gainToDecibels(invGain); return invDb; } double DspHelpers::ConverterFunctions::wetAmount(double input) { return Decibels::gainToDecibels(input); } double DspHelpers::ConverterFunctions::subtractFromOne(double input) { return jlimit(0.0, 1.0, 1.0 - input); } DspHelpers::ConverterFunction DspHelpers::ConverterFunctions::getFunction(const Identifier& id) { if (id.isNull() || id == ConverterIds::Identity) return {}; if (id == ConverterIds::Decibel2Gain) return decibel2Gain; if (id == ConverterIds::Gain2Decibel) return gain2Decibel; if (id == ConverterIds::SubtractFromOne) return subtractFromOne; if (id == ConverterIds::DryAmount) return dryAmount; if (id == ConverterIds::WetAmount) return wetAmount; return {}; } scriptnode::DspHelpers::ParameterCallback DspHelpers::wrapIntoConversionLambda(const Identifier& converterId, const ParameterCallback& originalFunction, NormalisableRange<double> range, bool inverted) { using namespace ConverterIds; if (converterId == Identity || converterId.isNull()) return getFunctionFrom0To1ForRange(range, inverted, originalFunction); if (converterId == SubtractFromOne) { auto withRange = getFunctionFrom0To1ForRange(range, false, originalFunction); return [withRange](double normedValue) { double v = ConverterFunctions::subtractFromOne(normedValue); withRange(v); }; } if (auto cf = ConverterFunctions::getFunction(converterId)) { return [originalFunction, cf](double newValue) { originalFunction(cf(newValue)); }; } else return originalFunction; } double DspHelpers::findPeak(const ProcessData& data) { double max = 0.0; for (auto channel : data) { auto r = FloatVectorOperations::findMinAndMax(channel, data.size); auto thisMax = jmax<float>(std::abs(r.getStart()), std::abs(r.getEnd())); max = jmax(max, (double)thisMax); } return max; } void ProcessData::copyToFrameDynamic(float* frame) const { jassert(modifyPointersAllowed); for (int i = 0; i < numChannels; i++) frame[i] = *data[i]; } void ProcessData::copyFromFrameAndAdvanceDynamic(const float* frame) { jassert(modifyPointersAllowed); for (int i = 0; i < numChannels; i++) *data[i]++ = frame[i]; } void ProcessData::advanceChannelPointers(int sampleAmount/*=1*/) { jassert(modifyPointersAllowed); for (int i = 0; i < numChannels; i++) data[i] += sampleAmount; } scriptnode::ProcessData ProcessData::copyToRawArray(float** channelData, float* uninitialisedData, bool clearArray/*=true*/) { for (int i = 0; i < numChannels; i++) { channelData[i] = uninitialisedData; if (clearArray) memset(channelData[i], 0, sizeof(float)*size); uninitialisedData += size; } ProcessData rd(channelData, numChannels, size); rd.eventBuffer = eventBuffer; return rd; } scriptnode::ProcessData ProcessData::copyTo(AudioSampleBuffer& buffer, int index) { auto channelOffset = index * numChannels; int numChannelsToCopy = jmin(buffer.getNumChannels() - channelOffset, numChannels); int numSamplesToCopy = jmin(buffer.getNumSamples(), size); for (int i = 0; i < numChannelsToCopy; i++) buffer.copyFrom(i + channelOffset, 0, data[i], numSamplesToCopy); return referTo(buffer, index); } scriptnode::ProcessData ProcessData::referTo(AudioSampleBuffer& buffer, int index) const { ProcessData d; auto channelOffset = index * numChannels; d.numChannels = jmin(buffer.getNumChannels() - channelOffset, numChannels); d.size = jmin(buffer.getNumSamples(), size); d.data = buffer.getArrayOfWritePointers() + channelOffset; d.eventBuffer = eventBuffer; return d; } scriptnode::ProcessData& ProcessData::operator+=(const ProcessData& other) { jassert(numChannels == other.numChannels); jassert(size == other.size); for (int i = 0; i < numChannels; i++) FloatVectorOperations::add(data[i], other.data[i], size); return *this; } juce::String CodeHelpers::createIncludeFile(File targetDirectory) { if (!targetDirectory.isDirectory()) return {}; auto includeFile = targetDirectory.getChildFile("includes.cpp"); Array<File> cppFiles = targetDirectory.findChildFiles(File::findFiles, false, "*.cpp"); String s; if(targetDirectory == projectIncludeDirectory) s << "#include \"JuceHeader.h\n\n\""; for (auto cppFile : cppFiles) { if (cppFile == includeFile) continue; auto fileName = s << "#include \"" << cppFile.getFileName().replaceCharacter('\\', '/') << "\"\n"; } String nl = "\n"; if (targetDirectory == projectIncludeDirectory) { s << "// project factory" << nl; s << "namespace scriptnode" << nl; s << "{" << nl; s << "using namespace hise;" << nl; s << "using namespace juce;" << nl; s << "namespace project" << nl; s << "{" << nl; s << "DEFINE_FACTORY_FOR_NAMESPACE;" << nl; s << "}" << nl; s << "}" << nl; } includeFile.replaceWithText(s); String hc; hc << "#include \"" << includeFile.getFullPathName().replaceCharacter('\\', '/') << "\""; return hc; } void CodeHelpers::addFileInternal(const String& filename, const String& content, File targetDirectory) { auto file = targetDirectory.getChildFile(filename).withFileExtension(".cpp"); bool isProjectTarget = targetDirectory == projectIncludeDirectory; String namespaceId = isProjectTarget ? "project" : "custom"; String code; code << "/* Autogenerated code. Might get overwritten, so don't edit it. */\n"; code << "using namespace juce;\n"; code << "using namespace hise;\n\n"; code << CppGen::Emitter::wrapIntoNamespace(content, namespaceId); file.replaceWithText(CppGen::Emitter::wrapIntoNamespace(code, "scriptnode")); if (targetDirectory == getIncludeDirectory()) PresetHandler::showMessageWindow("Node exported to Global Node Directory", "The node was exported as C++ class as 'custom." + filename + "'. Recompile HISE to use the hardcoded version."); else PresetHandler::showMessageWindow("Node exported to Project Directory", "The node was exported as C++ class as 'project." + filename + "'. Export your plugin to use the hardcoded version."); createIncludeFile(targetDirectory); } File CodeHelpers::includeDirectory; File CodeHelpers::projectIncludeDirectory; void CodeHelpers::setIncludeDirectory(String filePath) { if (filePath.isNotEmpty() && File::isAbsolutePath(filePath)) includeDirectory = File(filePath); else includeDirectory = File(); } juce::File CodeHelpers::getIncludeDirectory() { return includeDirectory; } void CodeHelpers::initCustomCodeFolder(Processor* p) { auto s = dynamic_cast<GlobalSettingManager*>(p->getMainController())->getSettingsObject().getSetting(HiseSettings::Compiler::CustomNodePath); setIncludeDirectory(s); #if HI_ENABLE_CUSTOM_NODE_LOCATION projectIncludeDirectory = GET_PROJECT_HANDLER(p).getSubDirectory(FileHandlerBase::AdditionalSourceCode).getChildFile("CustomNodes"); if (!projectIncludeDirectory.isDirectory()) projectIncludeDirectory.createDirectory(); #endif } bool CodeHelpers::customFolderIsDefined() { return includeDirectory.isDirectory(); } bool CodeHelpers::projectFolderIsDefined() { return projectIncludeDirectory.isDirectory(); } void CodeHelpers::addFileToCustomFolder(const String& filename, const String& content) { addFileInternal(filename, content, includeDirectory); } void CodeHelpers::addFileToProjectFolder(const String& filename, const String& content) { addFileInternal(filename, content, projectIncludeDirectory); } }
25.979434
200
0.717396
romsom
9a439480d07ff2ce1005fdfe3f100cd885ec6c87
94
cpp
C++
unittests/data/ctypes/templates/templates.cpp
electronicvisions/pyplusplus
4d88bb8754d22654a61202ae8adc222807953e38
[ "BSL-1.0" ]
9
2016-06-07T19:14:53.000Z
2020-02-28T09:06:19.000Z
unittests/data/ctypes/templates/templates.cpp
electronicvisions/pyplusplus
4d88bb8754d22654a61202ae8adc222807953e38
[ "BSL-1.0" ]
1
2018-08-15T11:33:40.000Z
2018-08-15T11:33:40.000Z
unittests/data/ctypes/templates/templates.cpp
electronicvisions/pyplusplus
4d88bb8754d22654a61202ae8adc222807953e38
[ "BSL-1.0" ]
5
2016-06-23T09:37:00.000Z
2019-12-18T13:51:29.000Z
#include "templates.h" void EXPORT_SYMBOL init( value_t<int>& x){ x.value = 2009; }
15.666667
43
0.62766
electronicvisions