blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
2b13a37dee353cd7fbeec79d4b9e80f10a74dd87
29800b8eb0f5ed053b0620184f1e1b40540db76a
/P-HeChangTuan/main.cc
ca0c1e493b073c2742b0f8f0c7b06059cd730e19
[]
no_license
coolsuperman/Practice-Cpp
de332c1ae5e5d355536171adbd3efe7a415e920b
f041487aec9a8aabe6d5352e00a7ddf4ee90f8b1
refs/heads/master
2020-05-03T13:51:08.735231
2019-09-13T12:23:16
2019-09-13T12:23:16
178,662,726
0
2
null
null
null
null
UTF-8
C++
false
false
897
cc
#include<iostream> #include<vector> using namespace std; int main(){ int num; while(cin>>num){ vector<int> stus(num); int k,d; for(int i=0;i<num;i++){ cin>>stus[i]; } cin>>k>>d; vector<vector<long> > dp_max(num+1,vector<long>(k+1,0)); vector<vector<long> > dp_min(num+1,vector<long>(k+1,0)); for(int i = 0;i<num;i++){ dp_max[i+1][1]=stus[i]; dp_min[i+1][1]=stus[i]; } for(int i=1;i<=num;i++){ for(int j=2;j<=k;j++){ for(int pre=i-1;pre>0&&i-pre<=d;pre--){ dp_max[i][j]=max(dp_max[i][j],max(dp_max[pre][j-1]*stus[i],dp_min[pre][j-1]*stus[i])); dp_min[i][j]=min(dp_min[i][j],min(dp_max[pre][j-1]*stus[i],dp_min[pre][j-1]*stus[i])); } } } long mul=dp_max[k][k]; for(int i=k+1;i<=num;i++){ mul=max(mul,dp_max[i][k]); } cout<<mul<<endl; } return 0; }
[ "846069147@qq.com" ]
846069147@qq.com
1122a60778c97a726824cd7d9f5a4eb668422151
805d9859e85321e6b0a87b3f6fd4b2bf765bc8ee
/Data Structures and Algorithms/Data Structures/inversion_count.cpp
0c0e92bb7e5af21092aef1e6e403b16d6f48d304
[]
no_license
aaka2409/HacktoberFest2020
eb6b312555b046b6382cee106b7869d5a36cfe9d
f348e60c2c58c99c20207094b8351aa15b319285
refs/heads/master
2023-08-26T01:19:49.058021
2021-10-25T09:48:24
2021-10-25T09:48:24
420,963,776
1
0
null
null
null
null
UTF-8
C++
false
false
947
cpp
#include<iostream> using namespace std; int merg(int a[], int s, int e){ int mid = (s+e)/2; int temp[1000]; int cnt = 0; int i = s; int j = mid+1; int k = s; while(i<=mid && j<=e){ if(a[i]<=a[j]){ temp[k++] = a[i++]; } else{ temp[k++] = a[j++]; cnt += mid - i + 1; } } while(i<=mid){ temp[k++] = a[i++]; } while(j<=e){ temp[k++] = a[j++]; } for(int i=0; i<=e; i++) a[i] = temp[i]; return cnt; } int inversionSort(int a[], int s, int e){ if(s>=e) return 0; int mid = (s+e)/2; int x = inversionSort(a,s,mid); int y = inversionSort(a,mid+1,e); int z = merg(a,s,e); return x+y+z; } int main(){ int n; int a[1000]; cin>>n; for (int i = 0; i < n; ++i) cin>>a[i]; // no. of cross invertions are .... cout<<"No. of Inversions it will take "; cout<< inversionSort(a,0,n-1); cout<<endl; for(int i=0; i<n; i++) cout<<a[i]<< " "; return 0; }
[ "noreply@github.com" ]
aaka2409.noreply@github.com
12228d76b06073c3d49bf5b892305a8ec446c7a0
4baa62e54b5ad336d989cb0554ae422c591f73af
/1100/1149.cpp
b76ebfd1973fc1fd8201190c824583c45e8b5ba1
[]
no_license
shikgom2/Codeup
219283fc487c2da781ba562bda4fcba40cfe7c46
111243633fbec7116e52e609b01415d6d2cbba99
refs/heads/master
2020-06-13T06:56:56.586964
2019-07-09T07:50:19
2019-07-09T07:50:19
194,578,627
7
3
null
null
null
null
UTF-8
C++
false
false
111
cpp
#include <stdio.h> int main() { int a, b; scanf("%d %d", &a, &b); printf("%d", a > b ? a : b); return 0; }
[ "noreply@github.com" ]
shikgom2.noreply@github.com
5591e721b54944eb328dcb582d5242d5e0229fe9
85cff448cf544746dd275d6e5afc924d34b2c177
/app/dtkCreator/dtkCreatorMainWindow.h
736dba4f5968cf2d506d986ea3c6cc7431d3c49f
[]
no_license
NicolasSchnitzler/dtk
ab8eb2ee37121b86afb38ee07683f3be59800395
a85dabef4f89e08d0af2de8cae5373aba019f143
refs/heads/master
2021-01-12T22:08:24.278316
2016-01-27T08:27:12
2016-01-27T08:27:12
37,517,231
0
0
null
2015-06-16T08:17:25
2015-06-16T08:17:25
null
UTF-8
C++
false
false
1,412
h
/* dtkCreatorMainWindow.h --- * * Author: Julien Wintz * Copyright (C) 2008 - Julien Wintz, Inria. * Created: Mon Aug 3 17:38:47 2009 (+0200) * Version: $Id$ * Last-Updated: Tue Jun 25 09:44:56 2013 (+0200) * By: Selim Kraria * Update #: 70 */ /* Commentary: * */ /* Change log: * */ #ifndef DTKCREATORMAINWINDOW_H #define DTKCREATORMAINWINDOW_H #include <dtkComposer/dtkComposerWriter.h> #include <QtWidgets> class dtkAbstractView; class dtkCreatorMainWindowPrivate; class dtkCreatorMainWindow : public QMainWindow { Q_OBJECT public: dtkCreatorMainWindow(QWidget *parent = 0); ~dtkCreatorMainWindow(void); void readSettings(void); void writeSettings(void); public slots: bool compositionOpen(void); bool compositionOpen(const QString& file); bool compositionSave(void); bool compositionSaveAs(void); bool compositionSaveAs(const QString& file, dtkComposerWriter::Type type = dtkComposerWriter::Ascii); bool compositionInsert(void); bool compositionInsert(const QString& file); protected slots: void switchToCompo(void); void switchToDstrb(void); void switchToDebug(void); void switchToView(void); protected slots: void showControls(void); void onViewFocused(dtkAbstractView *view); protected: void closeEvent(QCloseEvent *event); private: dtkCreatorMainWindowPrivate *d; }; #endif
[ "Nicolas.Niclausse@inria.fr" ]
Nicolas.Niclausse@inria.fr
f6f1e115564f38ea021cb8c69fc32ca7911c5660
1e3e058b6dc7d5f337db4f42b280eb055086ab3c
/SW_Test/Prescription.h
157bf50a44dba78ff642796f6a9d8e6df274a79b
[]
no_license
jg8643/Hospital-manager
00d4bb11b62e66dd4a07fb3581066ed9cfa19f42
f53125ca814491d61e0fc0b96291ae2379d58f35
refs/heads/master
2020-05-25T15:31:29.666962
2019-05-27T11:47:42
2019-05-27T11:47:42
187,868,891
0
0
null
null
null
null
UHC
C++
false
false
344
h
#pragma once #include "SW_TestDlg.h" #include "Setting.h" #include "predata.h" class Prescription { public: Prescription(Setting *); ~Prescription(); Setting *set; CSWTestDlg *myswdlg; int tcount; // 진료 완료 환자 수 predata *pre_data[100]; // 진료 완료 환자 void CreatePre(CString *, CString (*str)[2]); };
[ "wjdrb8643@naver.com" ]
wjdrb8643@naver.com
d90a82bce103621e861e70f00bfcd12fd9d8192f
a3f206af3878e2fff0437863a5c0d2d800295814
/solutions/prob11053/solution_c++.cc
ba21b35b75cf0bf1eab0ba8d9b6c0d22ee8bf7b3
[]
no_license
soarhigh03/baekjoon-solutions
0cdcec30825a00074a982b380ae2f2ddee5e3f54
8161cdda184e4e354be4eafe2b4fa2bd48635fa4
refs/heads/master
2023-01-04T10:42:32.882285
2020-10-24T02:20:48
2020-10-24T02:20:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
562
cc
/* * Baekjoon Online Judge #11053 * https://www.acmicpc.net/problem/11053 */ #include <bits/stdc++.h> using namespace std; int N, A[1001], dp[1001]; int lis() { memset(dp, 0, sizeof dp); dp[0] = 1; for (int i = 1; i < N; ++i) { dp[i] = 1; for (int j = 0; j < i; ++j) if (A[i] > A[j] && dp[i] < dp[j] + 1) dp[i] = dp[j] + 1; } return *max_element(dp, dp + N); } int main() { scanf("%d", &N); for (int i = 0; i < N; ++i) scanf("%d", &A[i]); printf("%d\n", lis()); return 0; }
[ "loop.infinitely@gmail.com" ]
loop.infinitely@gmail.com
d57f5b309a05886f32efcbbe0fd87b4799d01976
66f49f3ac2e509339521fa6e8b63d7ba281cfacb
/AlgorithmicEngagement/2009/Cakes/Cakes.cpp
b83c0b4e487839933b52a6bf5ca06e42d42b3f1b
[]
no_license
catupper/POIsolutions
c6a691ec841603f1a8f55d28d8da52f696aab974
15532c62307d8384865de24b9f39de1406b28948
refs/heads/master
2020-12-30T11:15:19.646025
2015-03-13T11:31:47
2015-03-13T11:31:47
18,140,795
4
2
null
2015-03-13T11:31:47
2014-03-26T14:24:59
C++
UTF-8
C++
false
false
1,199
cpp
#include<iostream> #include<algorithm> #include<map> #include<set> #include<vector> #include<cstdio> using namespace std; typedef pair<int, int> P; int n, m; long long res; int p[108000]; int a[108000]; int cnt[108000]; int deg[108000]; vector<int> edge[108000]; vector<P> edges; bool cmp(const int &a, const int &b){ if(deg[a] == deg[b])return a < b; return deg[a] < deg[b]; } int main(){ cin >> n >> m; for(int i = 0;i < n;i++)cin >> p[i]; for(int i = 0;i < m;i++){ int a, b; scanf("%d%d", &a, &b); a--,b--; deg[a]++; deg[b]++; edges.push_back(P(a, b)); } for(int i = 0;i < m;i++){ int a = edges[i].first; int b = edges[i].second; if(cmp(b, a))swap(a, b); edge[a].push_back(b); } sort(a, a + n, cmp); for(int i = 0;i < m;i++){ int a = edges[i].first; int b = edges[i].second; if(cmp(b, a))swap(a, b); for(int j = 0;j < edge[a].size();j++){ cnt[edge[a][j]]++; } for(int j = 0;j < edge[b].size();j++){ if(cnt[edge[b][j]]){ res += max(p[edge[b][j]], max(p[a], p[b])); } } for(int j = 0;j < edge[a].size();j++){ cnt[edge[a][j]] = 0; } } printf("%lld\n", res); return 0; }
[ "nekarugo628@gmail.com" ]
nekarugo628@gmail.com
3f7b44e239ed6fc69bf29006617f950f84f8115f
7e11872c2c5cb8ce78a0492c935f98fd48cd5844
/Perg/src/Perg/LayerStack.cpp
efe8a4c19592f82d09a89cc967a0342860b74c78
[ "Apache-2.0" ]
permissive
oktembaris77/Perg
c775043ecf07e9f1e1f6714fc5b61f47530521cd
ebe15fe1ee6e453514c3351ce951ce152e1a292e
refs/heads/main
2023-01-28T15:29:41.406383
2020-12-10T16:00:03
2020-12-10T16:00:03
315,937,200
0
0
null
null
null
null
UTF-8
C++
false
false
772
cpp
#include "pepch.h" #include "LayerStack.h" namespace Perg { LayerStack::LayerStack() { } LayerStack::~LayerStack() { for (Layer* layer : m_Layers) delete layer; } void LayerStack::PushLayer(Layer* layer) { m_Layers.emplace(m_Layers.begin() + m_LayerInsertIndex, layer); m_LayerInsertIndex++; } void LayerStack::PushOverlay(Layer* overlay) { m_Layers.emplace_back(overlay); } void LayerStack::PopLayer(Layer* layer) { auto it = std::find(m_Layers.begin(), m_Layers.end(), layer); if (it != m_Layers.end()) { m_Layers.erase(it); m_LayerInsertIndex--; } } void LayerStack::PopOverlay(Layer* overlay) { auto it = std::find(m_Layers.begin(), m_Layers.end(), overlay); if (it != m_Layers.end()) m_Layers.erase(it); } }
[ "oktembaris77@gmail.com" ]
oktembaris77@gmail.com
cd1aa560dc5c03b43b29faab90a4baf50682b96a
104a6ad30a0fd936ff0bd72e3cf963e4b934fdc5
/GameEngineX/Source/PlayerComponents/PlayerComponent.cpp
ac7f8fab84da5215aa55306f162b86220b18e04d
[ "MIT" ]
permissive
GeorgeHanna/BarebonesGameEngine
8c3cb06695e645e47f966dde61e478c37f11a9af
39a122832a4b050fff117114d1ba37bbd72edd42
refs/heads/master
2022-12-09T06:35:15.834901
2020-09-16T10:39:28
2020-09-16T10:39:28
295,979,297
0
0
null
null
null
null
UTF-8
C++
false
false
1,386
cpp
// // PlayerComponent.cpp // GameEngineX // // Created by George Hanna on 18/07/16. // Copyright © 2016 George Hanna. All rights reserved. // #include "PlayerComponent.hpp" void PlayerComponent::Initialize() { _playerphysics = std::static_pointer_cast<PhysicsBody2DCircleComponent>(_parent->_components[PhysicsBody2DCircleComponent::GetType_s()]); Resources::GetPhysicsWorld("1")->_collisionlistener->AddCollisionEventListener(std::bind(&PlayerComponent::OnCollision, this, std::placeholders::_1)); InputHandler::AddPressDownEventListener(std::bind(&PlayerComponent::OnPressDown, this, std::placeholders::_1)); InputHandler::AddPressUpEventListener(std::bind(&PlayerComponent::OnPressUp, this, std::placeholders::_1)); } void PlayerComponent::Update(Timer *timer) { Component::Update(timer); } void PlayerComponent::OnCollision(Contact *contact) { } void PlayerComponent::OnPressDown(InputHandler::InputPosition *position) { _startpos = position->_position; //printf("Press down - x:%f, y:%f", _startpos.x,_startpos.y); } void PlayerComponent::OnPressUp(InputHandler::InputPosition *position) { _endpos = position->_position; glm::vec2 delta = _startpos-_endpos; _playerphysics->_body->ApplyForce({-delta.x,delta.y}, _playerphysics->_body->GetWorldCenter(), true); //printf("Press up - x:%f, y:%f", _endpos.x,_endpos.y); }
[ "george.hanna8@icloud.com" ]
george.hanna8@icloud.com
a583ba8c88f60d470042ea42a8506a824e267c57
96b621c20c50bff6f87b1d5cf6634c49ace2990a
/src/bind.h
7a025a9cae024315d91ad434df4aca8e63f4a39f
[ "MIT" ]
permissive
Forestryks/libsbox
a937831b349bd0e2d0adbf4cdf1b2c3201bae406
f7ee6264a628b4e16c8782a43fe55c91f072058d
refs/heads/master
2021-08-07T14:02:25.587446
2020-05-21T12:22:38
2020-05-21T12:22:38
180,595,702
3
4
MIT
2019-12-10T09:51:52
2019-04-10T14:09:32
C++
UTF-8
C++
false
false
923
h
/* * Copyright (c) 2019 Andrei Odintsov <forestryks1@gmail.com> */ #ifndef LIBSBOX_BIND_H_ #define LIBSBOX_BIND_H_ #include "task_data.h" #include <filesystem> #include <vector> namespace fs = std::filesystem; class Bind { public: enum Rules { RW = 1, DEV = 2, NOEXEC = 4, SUID = 8, OPT = 16 }; Bind(fs::path inside, fs::path outside, int flags); explicit Bind(const BindData *bind_data); void mount(const fs::path &root_dir, const fs::path &work_dir); void umount_if_mounted(); static void apply_standard_rules(const fs::path &root_dir, const fs::path &work_dir); private: fs::path inside_; fs::path outside_; int flags_; bool mounted_ = false; fs::path from_; fs::path to_; void set_paths(const fs::path &root_dir, const fs::path &work_dir); static std::vector<Bind> standard_binds; }; #endif //LIBSBOX_BIND_H_
[ "forestryks1@gmail.com" ]
forestryks1@gmail.com
f6746acf83fca05a3242aac9dc3552d00d5d0354
de8c2e562e8d0ebd3e6d7469f41741c06d4c60bf
/code/Common/GSPSDK-V3/src/TestwxWidget/MainApp.cpp
40593f3c4148cf8cfef87a3d5ff10e5e612550c3
[]
no_license
dongdong-2009/Bull
c95da575597414e85b161ac1397f5b12d6df3bb2
ab10bef10d3422d37c36475c1b0a0fd2ab360004
refs/heads/master
2021-05-27T11:30:20.586457
2014-06-06T10:32:34
2014-06-06T10:32:34
null
0
0
null
null
null
null
GB18030
C++
false
false
3,424
cpp
///////////////////////////////////////////////////////////////////////////// // Name: MainApp.cpp // Author: XX // Created: XX/XX/XX // Copyright: XX ///////////////////////////////////////////////////////////////////////////// #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) #pragma implementation "MainApp.cpp" #endif // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wx.h" #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #include "TestServer.h" #include "TestClient.h" #include "MainApp.h" namespace GSP { extern void GSPModuleInit(void); extern void GSPModuleUnint(void); } //end namespace GSP // WDR: class implementations //---------------------------------------------------------------------------- // CMainApp //---------------------------------------------------------------------------- IMPLEMENT_APP(CMainApp) CMainApp *g_pMainApp = NULL; // WDR: event table for MainApp CMainApp::CMainApp() { m_pMainWindow = NULL; g_pMainApp = this; } // WDR: handler implementations for CMainApp bool CMainApp::OnInit(void) { GSPModuleInit(); GSP::GSPModuleInit(); srand((int)time(NULL)); wxApp::OnInit(); m_csLocal.Init(); m_csLocal.AddCatalog("wxDemo"); m_pMainWindow = new CMainFrame( NULL, -1, "GSS Stack Test", wxPoint(0,0), wxSize(800,600) ); m_pMainWindow->CentreOnScreen(); m_pMainWindow->Show( TRUE ); // m_pMainWindow->ShowFullScreen(TRUE,wxFULLSCREEN_NOBORDER ); // 键盘输入不了 return true; } int CMainApp::OnExit(void) { GSP::GSPModuleUnint(); GSPModuleUnint(); return 0; } void CMainApp::GetGridSelectRows( wxGrid* pGrid, wxArrayInt &vResult ) { vResult.Clear(); int iRows = pGrid->GetRows(); for( int i = 0 ; i<iRows; i++) { if( pGrid->IsInSelection(i, 0) ) { vResult.Add(i); } } } //---------------------------------------------------------------------------- // CMainFrame //---------------------------------------------------------------------------- // WDR: event table for CMainFrame BEGIN_EVENT_TABLE(CMainFrame,wxFrame) EVT_MENU( ID_MENU_SERVER, CMainFrame::OnMenuServerClick ) EVT_MENU( ID_MENU_TEST, CMainFrame::OnMenuClientClient ) EVT_MENU( ID_MENU_ASSERT, CMainFrame::OnMenuAssertClick ) END_EVENT_TABLE() CMainFrame::CMainFrame( wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &position, const wxSize& size, long style ) : wxFrame( parent, id, title, position, size, style ) { // WDR: dialog function MainFrameDialog for CMainFrame MainFrameDialog( this, TRUE ); wxMenuBar *pMenuBar = MyMenuBarFunc(); SetMenuBar(pMenuBar); } // WDR: handler implementations for CMainFrame void CMainFrame::OnMenuClientClient( wxCommandEvent &event ) { //启动客户端测试 CTestClientDialog *pDialog = new CTestClientDialog(this, -1, "Test Client"); //, wxPoint(0,0), wxSize(800,600)) pDialog->CentreOnScreen(); pDialog->Show(TRUE); } void CMainFrame::OnMenuServerClick( wxCommandEvent &event ) { //启动服务器端测试 CTestSrvDialog *pDialog = new CTestSrvDialog(this, -1, "Test Server"); //, wxPoint(0,0), wxSize(800,600)) pDialog->CentreOnScreen(); pDialog->Show(TRUE); } void CMainFrame::OnMenuAssertClick( wxCommandEvent &event ) { GS_ASSERT(0); }
[ "7922375@qq.com" ]
7922375@qq.com
f6759087a5452aaeda62b04bce5d0ab93eb75e73
e7594dd55dcbf2e54cc14491e554611fb3f96fec
/practica/practica_08/tp/ej06/code/sumarPotenciaHasta.cpp
73b3037a264e09b73209016bc584748d3508d8ce
[]
no_license
NicoKc/algo1
5b66bdb8009752cf5ba16c84a1812ae8de767083
57a34a225d299e1d7eb4e4d457c0740f35b04242
refs/heads/master
2022-11-29T23:26:57.334479
2020-08-17T16:18:13
2020-08-17T16:18:13
256,615,834
1
0
null
null
null
null
UTF-8
C++
false
false
278
cpp
int sumarPotenciaHasta(int n) { int res = 0; //1 int i = 1; //1 while(i < n) { //1 + n/2 * ( res = res + i; //2 i = i * 2; //2 } return res; } // = 3 + n/2 *(4) = 3 + 2n
[ "nicolaskinaschuk@gmail.com" ]
nicolaskinaschuk@gmail.com
a01b2a409b5024d632381cad703779756b586f06
094de465233cc34e82d02df5e4c57261deec8b68
/src/broker.cpp
292a82f039d08dd9f99138571917a30853218e5d
[]
no_license
davidkellis/stocktrader_cpp
7f1a047adb45f7463c915417b017edd7ea0f2f56
e30cd90c5fedf0066a6236d888cba7021aa71256
refs/heads/master
2016-08-05T08:09:27.661115
2009-10-02T16:24:03
2009-10-02T16:24:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,291
cpp
#include "broker.h" // This has to go here because C++ considers it a circular dependency problem if implemented in the class definition. double Account::value(ULL timestamp) { double stock_value = 0; map<string,int>::iterator it; for(it = portfolio.begin(); it != portfolio.end(); it++) { // stock_value += quote(ticker, timestamp) * share_count stock_value += broker->exchange->quote((*it).first, timestamp, 0.0) * (*it).second; } return stock_value + cash; } int Account::buy(string ticker, int shares, ULL timestamp, bool on_margin) { return broker->buy((*this), ticker, shares, timestamp, on_margin); } int Account::buy_amap(string ticker, ULL timestamp, double amount) { return broker->buy_amap((*this), ticker, timestamp, amount); } int Account::sell(string ticker, int shares, ULL timestamp) { return broker->sell((*this), ticker, shares, timestamp); } int Account::sell_short(string ticker, int shares, ULL timestamp) { return broker->sell_short((*this), ticker, shares, timestamp); } int Account::sell_short_amt(string ticker, ULL timestamp, double amount) { return broker->sell_short_amt((*this), ticker, timestamp, amount); } int Account::sell_all(string ticker, ULL timestamp) { return broker->sell_all((*this), ticker, timestamp); }
[ "davidkellis@gmail.com" ]
davidkellis@gmail.com
ba5a5e692233f75da41fe10411bebf263a0f4033
98b345594e6fa0ad9910bc0c20020827bbb62c53
/re110_1/processor18/80/phi
c680971ddc58b03401b8d9e45e55efc6a088ec22
[]
no_license
carsumptive/coe-of2
e9027de48e42546ca4df1c104dcc8d04725954f2
fc3e0426696f42fbbbdce7c027df9ee8ced4ccd0
refs/heads/master
2023-04-04T06:09:23.093717
2021-04-06T06:47:14
2021-04-06T06:47:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,713
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 7 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class surfaceScalarField; location "80"; object phi; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 3 -1 0 0 0 0]; internalField nonuniform List<scalar> 272 ( 2.47462e-05 -0.000185959 9.45516e-05 -0.000625204 0.00020429 -0.00113534 0.000344078 -0.0016894 -0.00224946 2.61567e-05 -0.000212115 9.83238e-05 -0.000697371 0.000209293 -0.00124631 0.000347097 -0.0018272 0.000496192 -0.00239855 0.000640894 -0.00292082 0.000769004 -0.00336704 0.000873819 -0.00372738 0.000954073 -0.00400715 0.00101246 -0.00422125 -0.00438798 2.7378e-05 -0.000239493 0.000101231 -0.000771224 0.000212222 -0.0013573 0.000346469 -0.00196145 0.000487485 -0.00253957 0.000620002 -0.00305334 0.000733318 -0.00348036 0.000822605 -0.00381666 0.000888188 -0.00407274 0.000933718 -0.00426678 0.000964203 -0.00441846 0.000984521 -0.00454487 0.00099863 -0.00465878 0.00100935 -0.00476871 0.00101854 -0.00487982 0.00102731 -0.00499502 0.00103634 -0.00511583 0.001046 -0.00524281 -0.00537593 2.83787e-05 0.000103191 0.000212992 0.000342231 0.000473894 0.000593519 0.000692058 0.000766462 0.000818396 0.000852184 0.000872897 0.000885085 0.000892215 0.000896632 0.000899802 0.000902596 0.000905523 0.000908868 0.000912761 0.000917201 0.000922177 0.000839602 0.00554866 0.00083052 0.00569794 0.00585046 0.000820873 3.02825e-05 0.000202687 0.000111263 0.000696095 0.0002314 0.00127102 0.00037406 0.00188506 0.000520406 0.00248662 0.000654084 0.00302969 0.000764696 0.00348577 0.000848602 0.00384738 0.00090751 0.00412398 0.000946138 0.00433439 0.000970019 0.0044996 0.000984064 0.00463803 0.000991938 0.0047634 0.000996051 0.00488476 0.000997848 0.00500749 0.000998157 0.00513448 0.000997455 0.00526716 0.000996015 0.00540597 0.000993979 0.000991361 0.000988178 2.90882e-05 0.000173599 0.000108801 0.000616382 0.000230014 0.0011498 0.000378064 0.00173701 0.000534772 0.00232991 0.000682878 0.00288159 0.000810058 0.00335859 0.000910606 0.00374683 0.000984695 0.00404989 0.00103629 0.0042828 0.00107087 0.00109374 0.00110912 0.00111994 0.00112804 0.00113449 0.00113991 2.76525e-05 0.000145946 0.000105287 0.000538748 0.00022621 0.00102888 0.000378005 0.00158521 0.000543661 0.000705468 0.00084936 0.00096744 0.00105803 2.60116e-05 0.000100816 0.00022008 0.000236165 -0.0193207 0.000200189 -0.0192492 0.000166318 -0.0192265 0.000131973 -0.0191603 9.83834e-05 -0.0191377 6.49014e-05 -0.0191037 3.30431e-05 -0.0191101 -0.0190786 0.000794799 0.000699567 0.000626111 0.000563237 0.00050782 0.000459309 0.000414427 0.000372722 0.000334993 0.000300374 0.00026787 0.000236564 0.000206752 0.000178538 0.000150869 0.000125375 9.9284e-05 7.38445e-05 4.85063e-05 2.49441e-05 0.000658127 0.0226006 0.00053423 0.0218688 0.000442661 0.0214676 0.000371527 0.0210435 0.000316106 0.0207461 0.00027096 0.0204507 0.000233171 0.0202138 0.000202262 0.0200148 0.000176137 0.0198513 0.000152195 0.019676 0.000132537 0.0195815 0.000113325 0.0194374 9.77091e-05 0.0193856 8.22233e-05 0.0192744 6.96364e-05 0.0192481 5.62707e-05 0.019162 4.38961e-05 0.0191345 3.21506e-05 0.0190958 2.16749e-05 0.019088 1.11933e-05 0.0190662 0.0190464 0.00081935 0.000687972 0.00058921 0.000509971 0.000446491 0.000393147 0.000347337 0.000308307 0.000273984 0.000241985 0.000214168 0.000186904 0.000163141 0.000139501 0.000118649 9.71197e-05 7.66745e-05 5.67679e-05 3.80237e-05 1.92892e-05 ) ; boundaryField { inlet { type calculated; value nonuniform 0(); } outlet { type calculated; value nonuniform 0(); } cylinder { type calculated; value uniform 0; } top { type symmetryPlane; value uniform 0; } bottom { type symmetryPlane; value uniform 0; } defaultFaces { type empty; value nonuniform 0(); } procBoundary18to17 { type processor; value nonuniform List<scalar> 85 ( -0.000267872 -0.000846036 -0.0014671 -0.00209069 -0.00267123 -0.00317296 -0.0035789 -0.00389107 -0.00412467 -0.00430057 -0.00443917 -0.00455706 -0.00466591 -0.00477312 -0.00488299 -0.00499782 -0.00511876 -0.00524616 -0.00537982 -0.00551903 -0.00566216 -0.00554024 -0.00568886 -0.00584082 -0.00023297 -0.000777075 -0.00139115 -0.00202772 -0.00263297 -0.00316337 -0.00359638 -0.00393128 -0.00418289 -0.00437302 -0.00452349 -0.00465207 -0.00477127 -0.00488888 -0.00500929 -0.00513479 -0.00526646 -0.000848026 -0.00540453 -0.0218466 -0.021124 -0.0207782 -0.020467 -0.0202394 -0.020076 -0.0199154 -0.0197785 -0.0196863 -0.019598 -0.0195068 -0.0194178 -0.0193419 -0.0192925 -0.0192215 -0.019201 -0.0191342 -0.0191122 -0.0190784 -0.0190865 -0.0190537 -0.0224379 -0.0217449 -0.0213761 -0.0209724 -0.0206907 -0.0204056 -0.020176 -0.0199839 -0.0198251 -0.019652 -0.0195618 -0.0194182 -0.0193699 -0.0192589 -0.0192355 -0.0191486 -0.0191221 -0.0190841 -0.0190775 -0.0190558 -0.0190352 ) ; } procBoundary18to19 { type processor; value nonuniform List<scalar> 91 ( 0.000161212 0.000555399 0.0010256 0.00154961 0.00209381 0.000499722 0.00277612 0.00323893 0.00362256 0.0039269 0.00416286 0.00434674 0.00105369 0.00452455 0.00464467 0.00475798 0.00487063 0.00498625 0.0051068 0.00523315 0.00536546 0.00105647 0.00551459 0.00565718 0.00555069 0.00570056 0.00585365 0.00446502 0.00461516 0.00474802 0.00487394 0.00499939 0.00512803 0.00526174 0.00114465 0.00540123 0.00216426 0.00271978 0.00321469 0.00362875 0.00395931 0.00112398 0.00421684 0.000119935 0.000463943 0.000909617 0.000373828 0.00143146 0.0193573 0.0192852 0.0192604 0.0191946 0.0191712 0.0191372 0.0191419 0.0191117 0.021974 0.0212193 0.0208517 0.0205299 0.0202948 0.0201245 0.0199603 0.0198202 0.019724 0.0196327 0.0195393 0.0194491 -0.000272732 0.0193717 0.0227695 0.0220002 0.0215664 0.0211228 0.0208096 0.0205041 0.0202596 0.0200539 0.0198856 0.019708 0.0196093 0.0194646 0.0194093 0.019298 0.0192689 0.0191835 0.0191549 0.0191158 0.0191068 0.019085 0.0190657 ) ; } } // ************************************************************************* //
[ "chaseguy15" ]
chaseguy15
54e65bd15d6cd6d142e6ad48fefac8236ed8a14c
27db000c97e2079fa7acfcf3b41a32e2b3c9ffe9
/solvers/geneticalgorithm.h
6bb199cf8359b03ab6eca02237446e7993a4a916
[ "MIT" ]
permissive
tingyingwu2010/heurisko
d9ee68e3052136c31b6fff2a6708ed88ff236b2a
ff5d3e26fa53a3ca8b3fbf3a88df27eecaf20fb5
refs/heads/master
2022-11-05T19:26:41.379184
2020-06-24T14:00:36
2020-06-24T14:00:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,799
h
#ifndef GENETICALGORITHM_H #define GENETICALGORITHM_H #include "../entities/problem.h" #include "globalsolver.h" #include <iostream> #include <memory> enum CrossoverType { UNIFORM, ONE_POINT, TWO_POINT, SIMULATED_BINARY }; enum SelectionType { FITNESS_PROPORTIONATE, TOURNAMENT }; enum MutationType { RANDOM_MUTATION, POLYNOMIAL, SWAP_MUTATION, SCRAMBLE_MUTATION }; template <class T> class GeneticAlgorithm : public GlobalSolver<T> { public: GeneticAlgorithm(int numberOfIndividuals, float crossoverRate, float mutationRate, CrossoverType crossoverType, SelectionType selectionType, MutationType mutationType, std::shared_ptr<Problem<T>> prob) : GlobalSolver<T>(numberOfIndividuals, prob) { if (this->numberOfAgents < 2) { std::cerr << "The number of individuals needs to be equal or higher than 2" << std::endl; exit(EXIT_FAILURE); } this->crossoverRate = crossoverRate; this->mutationRate = mutationRate; this->crossoverType = crossoverType; this->selectionType = selectionType; this->mutationType = mutationType; puts("Genetic Algorithm instantiated"); } void solve() { if (this->maxIterations == 0 && this->runningTime == 0) { std::cerr << "Use \"setMaxIterations(int)\" or \"setRunningTime(double)\" to " "define a stopping criteria!" << std::endl; exit(EXIT_FAILURE); } else std::cout << "Starting Genetic Algorithm search procedure" << std::endl; if (this->mutationType == MutationType::POLYNOMIAL && this->etaM == -FLT_MIN) { std::cerr << "You must set the polynomial mutation index through " "\"setEtaM(float)\" function" << std::endl; exit(EXIT_FAILURE); } else if (this->crossoverType == CrossoverType::SIMULATED_BINARY && this->etaC == -FLT_MIN) { std::cerr << "You must set the SBX operator index through \"setEtaC(float)\" " "function" << std::endl; exit(EXIT_FAILURE); } utils::startTimeCounter(); // Current population std::vector<std::vector<double>> individuals(this->numberOfAgents); #pragma omp parallel for for (int i = 0; i < this->numberOfAgents; i++) this->problem->fillRandomDecisionVariables(individuals[i]); // Stores the objective value of each individual std::vector<double> individualsFitness(this->numberOfAgents); #pragma omp parallel for for (int i = 0; i < this->numberOfAgents; i++) { switch (this->problem->getRepType()) { case RepresentationType::DIRECT: individualsFitness[i] = this->problem->evaluate(individuals[i]); break; case RepresentationType::INDIRECT: std::shared_ptr<Solution<T>> sol = this->problem->construct(individuals[i]); individualsFitness[i] = sol->getFitness(); break; } #pragma omp critical this->updateGlobalBest(individuals[i], individualsFitness[i], true); } // Container to store the offspring after the crossover (child1 at newIndividuals1 // and child2 at newIndividuals2) std::vector<std::vector<double>> newIndividuals1 = individuals; std::vector<std::vector<double>> newIndividuals2 = individuals; // Objective values for the offspring std::vector<double> newIndividuals1Fitness = individualsFitness; std::vector<double> newIndividuals2Fitness = individualsFitness; int iteration = -1; while (iteration++ < this->maxIterations || utils::getCurrentTime() < this->runningTime) { #pragma omp parallel for for (int i = 0; i < this->numberOfAgents; i++) { // Select two individuals int indexParent1, indexParent2; selection(indexParent1, indexParent2, individualsFitness); if (utils::getRandom() <= this->crossoverRate) { // Perform crossover crossover(individuals[indexParent1], individuals[indexParent2], newIndividuals1[i], newIndividuals2[i]); // Mutate the new individuals mutate(newIndividuals1[i], newIndividuals2[i]); } else { newIndividuals1[i] = individuals[indexParent1]; newIndividuals2[i] = individuals[indexParent2]; } } #pragma omp parallel for for (int i = 0; i < this->numberOfAgents; i++) { // Evaluate child1 switch (this->problem->getRepType()) { case RepresentationType::DIRECT: newIndividuals1Fitness[i] = this->problem->evaluate(newIndividuals1[i]); newIndividuals2Fitness[i] = this->problem->evaluate(newIndividuals2[i]); break; case RepresentationType::INDIRECT: std::shared_ptr<Solution<T>> sol1 = this->problem->construct(newIndividuals1[i]); newIndividuals1Fitness[i] = sol1->getFitness(); std::shared_ptr<Solution<T>> sol2 = this->problem->construct(newIndividuals2[i]); newIndividuals2Fitness[i] = sol2->getFitness(); if (utils::getCurrentTime() > 30) { sol1->localSearch(); sol2->localSearch(); } break; } #pragma omp critical { this->updateGlobalBest(newIndividuals1[i], newIndividuals1Fitness[i], true); this->updateGlobalBest(newIndividuals2[i], newIndividuals2Fitness[i], true); } } // Pick the best individuals in the offspring to be the next generation switch (this->problem->getStrategy()) { case OptimizationStrategy::MINIMIZE: { #pragma omp parallel for for (int i = 0; i < this->numberOfAgents; i++) { if (newIndividuals1Fitness[i] < newIndividuals2Fitness[i] && newIndividuals1Fitness[i] < individualsFitness[i]) { individuals[i] = newIndividuals1[i]; } else if (newIndividuals2Fitness[i] < newIndividuals1Fitness[i] && newIndividuals2Fitness[i] < individualsFitness[i]) { individuals[i] = newIndividuals2[i]; } } } break; case OptimizationStrategy::MAXIMIZE: { #pragma omp parallel for for (int i = 0; i < this->numberOfAgents; i++) { if (newIndividuals1Fitness[i] > newIndividuals2Fitness[i] && newIndividuals1Fitness[i] > individualsFitness[i]) { individuals[i] = newIndividuals1[i]; } else if (newIndividuals2Fitness[i] > newIndividuals1Fitness[i] && newIndividuals2Fitness[i] > individualsFitness[i]) { individuals[i] = newIndividuals2[i]; } } } break; } } std::cout << "Best solution " << this->globalBestFitness << " Running time: " << utils::getCurrentTime() << std::endl << "Best solution decision variables: "; utils::printVector(this->globalBest); } void crossover(std::vector<T> const &parent1, std::vector<T> const &parent2, std::vector<T> &child1, std::vector<T> &child2) { switch (this->crossoverType) { case CrossoverType::UNIFORM: uniformCrossover(parent1, parent2, child1, child2); break; case CrossoverType::SIMULATED_BINARY: simulatedBinaryCrossover(parent1, parent2, child1, child2); break; case CrossoverType::ONE_POINT: std::cout << "One Point Crossover" << std::endl; break; } } void simulatedBinaryCrossover(const std::vector<T> &parent1, const std::vector<T> &parent2, std::vector<T> &child1, std::vector<T> &child2) { double EPS = 1.0e-14; // y1 stores the value for the 1st child; y2 the value for the 2nd child; yl (notice // it's an L not a 1) holds the lower limit for the variable yu holds the upper // limit double y1, y2, yl, yu; // betaq, in the paper, is the symbol beta with a line above double alpha, beta, betaq; if (utils::getRandom() <= this->crossoverRate) // roll the dices. Should we apply a crossover? { // Crossover operations for the MS crossover for (int i = 0; i < this->problem->getDimension(); i++) // for each variable of a solution (individual) { // according to the paper, each variable in a solution has a 50% // chance of changing its value. This should be removed when dealing // with one-dimensional solutions. if (utils::getRandom() <= 0.5) { // the following if/else block puts the lowest value between // parent1 and parent2 in y1 and the other in y2. if (parent1[i] < parent2[i]) { y1 = parent1[i]; y2 = parent2[i]; } else { y1 = parent2[i]; y2 = parent1[i]; } // if the value in parent1 is not the same of parent2 if (fabs(parent1[i] - parent2[i]) > EPS) { yl = this->problem->getLb()[i]; // lower limit of the i-th // variable of an individual. // Note that yl != y1. yu = this->problem->getUb()[i]; // upper limit of the i-th // variable of an individual // Calculation for the first child double rand = utils::getRandom(); beta = 1.0 + (2.0 * (y1 - yl) / (y2 - y1)); // it differs from the paper here. The // paper uses one value of beta for // calculating both children. Here, we // use one beta for each child. alpha = 2.0 - pow(beta, -(etaC + 1.0)); // calculation of alpha as // described in the paper // calculation of betaq as described in the paper if (rand <= (1.0 / alpha)) { betaq = pow((rand * alpha), (1.0 / (etaC + 1.0))); } else { betaq = pow((1.0 / (2.0 - rand * alpha)), (1.0 / (etaC + 1.0))); } child1[i] = 0.5 * ((y1 + y2) - betaq * (y2 - y1)); // calculation of the first child as // described in the paper // Calculations for the second child beta = 1.0 + (2.0 * (yu - y2) / (y2 - y1)); // differs from the paper. The // second value of beta uses the // upper limit (yu) and the maximum // between parent1 and parent2 (y2) alpha = 2.0 - pow(beta, -(etaC + 1.0)); // calculation of alpha as // described in the paper // calculation of betaq as described in the paper if (rand <= (1.0 / alpha)) { betaq = pow((rand * alpha), (1.0 / (etaC + 1.0))); } else { betaq = pow((1.0 / (2.0 - rand * alpha)), (1.0 / (etaC + 1.0))); } child2[i] = 0.5 * ((y1 + y2) + betaq * (y2 - y1)); // calculation of the second child // as described in the paper ensures // the value of both children are in // the correct bounds [yl, yu]. // According to the paper, this // should not be needed. } // if the i-th variable has the same value in both parents else { child1[i] = parent1[i]; child2[i] = parent2[i]; } } else // 50% chance of changing values. In the case random > 0.5, // the children should have the same value as the parents { child1[i] = parent1[i]; child2[i] = parent2[i]; } } } else { child1 = parent1; child2 = parent2; } } void uniformCrossover(const std::vector<T> &parent1, const std::vector<T> &parent2, std::vector<T> &child1, std::vector<T> &child2) { for (size_t i = 0; i < this->problem->getDimension(); i++) { if (utils::getRandom() <= 0.5) { child1[i] = parent1[i]; child2[i] = parent2[i]; } else { child1[i] = parent2[i]; child2[i] = parent1[i]; } } } void selection(int &indexParent1, int &indexParent2, const std::vector<double> &individualsFitness) { switch (this->selectionType) { case SelectionType::FITNESS_PROPORTIONATE: { std::cout << "Fitness proportionate" << std::endl; } break; case SelectionType::TOURNAMENT: { indexParent1 = tournamentSelection(individualsFitness); indexParent2 = tournamentSelection(individualsFitness); } break; } } int tournamentSelection(const std::vector<double> &individualsFitness) { int indexIndividual1 = utils::getRandom(this->numberOfAgents - 1); int indexIndividual2 = utils::getRandom(this->numberOfAgents - 2); if (indexIndividual2 >= indexIndividual1) indexIndividual2++; if (individualsFitness[indexIndividual1] > individualsFitness[indexIndividual2]) return indexIndividual1; else return indexIndividual2; } void mutate(std::vector<double> &child1, std::vector<double> &child2) { switch (this->mutationType) { case MutationType::RANDOM_MUTATION: { randomMutation(child1); randomMutation(child1); } break; case MutationType::POLYNOMIAL: { polynomialMutation(child1); polynomialMutation(child2); } break; } } void randomMutation(std::vector<double> &individual) { for (int i = 0; i < this->problem->getDimension(); i++) if (utils::getRandom() <= mutationRate) individual[i] = this->problem->getRandomDecisionVariableAt(i); } void polynomialMutation(std::vector<double> &individual) { for (int i = 0; i < this->problem->getDimension(); i++) { if (utils::getRandom() <= mutationRate) { double rand = utils::getRandom(); if (rand <= 0.5) { double leftValue = individual[i] - this->problem->getLb()[i]; double sigma_l = pow(2 * rand, 1. / (1 + etaM)) - 1; individual[i] = individual[i] + (sigma_l * leftValue); } else { double rightValue = this->problem->getUb()[i] - individual[i]; // 1 is the upper bound // for the ith variable double sigma_r = 1 - pow(2 * (1 - rand), 1. / (1 + etaM)); individual[i] = individual[i] + (sigma_r * rightValue); } } } } void setEtaM(float value) { etaM = value; } void setEtaC(float value) { etaC = value; } private: float crossoverRate; float mutationRate; float etaM = -FLT_MIN; float etaC = -FLT_MIN; CrossoverType crossoverType; SelectionType selectionType; MutationType mutationType; }; #endif // GENETICALGORITHM_H
[ "williantessarolunardi@gmail.com" ]
williantessarolunardi@gmail.com
c9ab9ee7a82104ff07a85994a9e33f956e66e5bf
7c7ca9efe5869a805a3c5238425be185758a71ce
/marsksim/boost/atomic/detail/ops_gcc_x86.hpp
fc50666a8ebda9bb9deb45ed45d0670b1e23720d
[]
no_license
cansou/MyCustomMars
f332e6a1332eed9184838200d21cd36f5b57d3c9
fb62f268a1913a70c39df329ef39df6034baac60
refs/heads/master
2022-10-20T18:53:22.220235
2020-06-12T08:46:25
2020-06-12T08:46:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,818
hpp
/* * 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) * * Copyright (c) 2009 Helge Bahmann * Copyright (c) 2012 Tim Blechmann * Copyright (c) 2014 Andrey Semashev */ /*! * \file atomic/detail/ops_gcc_x86.hpp * * This header contains implementation of the \c operations template. */ #ifndef BOOST_ATOMIC_DETAIL_OPS_GCC_X86_HPP_INCLUDED_ #define BOOST_ATOMIC_DETAIL_OPS_GCC_X86_HPP_INCLUDED_ #include <boost/memory_order.hpp> #include <boost/atomic/detail/config.hpp> #include <boost/atomic/detail/storage_type.hpp> #include <boost/atomic/detail/operations_fwd.hpp> #include <boost/atomic/capabilities.hpp> #if defined(BOOST_ATOMIC_DETAIL_X86_HAS_CMPXCHG8B) || defined(BOOST_ATOMIC_DETAIL_X86_HAS_CMPXCHG16B) #include <boost/atomic/detail/ops_gcc_x86_dcas.hpp> #include <boost/atomic/detail/ops_cas_based.hpp> #endif #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif #if defined(__x86_64__) #define BOOST_ATOMIC_DETAIL_TEMP_CAS_REGISTER "rdx" #else #define BOOST_ATOMIC_DETAIL_TEMP_CAS_REGISTER "edx" #endif namespace mars_boost_ksim {} namespace boost_ksim = mars_boost_ksim; namespace mars_boost_ksim { namespace atomics { namespace detail { struct gcc_x86_operations_base { static BOOST_FORCEINLINE void fence_before(memory_order order) BOOST_NOEXCEPT { if ((order & memory_order_release) != 0) __asm__ __volatile__ ("" ::: "memory"); } static BOOST_FORCEINLINE void fence_after(memory_order order) BOOST_NOEXCEPT { if ((order & memory_order_acquire) != 0) __asm__ __volatile__ ("" ::: "memory"); } }; template< typename T, typename Derived > struct gcc_x86_operations : public gcc_x86_operations_base { typedef T storage_type; static BOOST_FORCEINLINE void store(storage_type volatile& storage, storage_type v, memory_order order) BOOST_NOEXCEPT { if (order != memory_order_seq_cst) { fence_before(order); storage = v; fence_after(order); } else { Derived::exchange(storage, v, order); } } static BOOST_FORCEINLINE storage_type load(storage_type const volatile& storage, memory_order order) BOOST_NOEXCEPT { storage_type v = storage; fence_after(order); return v; } static BOOST_FORCEINLINE storage_type fetch_sub(storage_type volatile& storage, storage_type v, memory_order order) BOOST_NOEXCEPT { return Derived::fetch_add(storage, -v, order); } static BOOST_FORCEINLINE bool compare_exchange_weak( storage_type volatile& storage, storage_type& expected, storage_type desired, memory_order success_order, memory_order failure_order) BOOST_NOEXCEPT { return Derived::compare_exchange_strong(storage, expected, desired, success_order, failure_order); } static BOOST_FORCEINLINE bool test_and_set(storage_type volatile& storage, memory_order order) BOOST_NOEXCEPT { return !!Derived::exchange(storage, (storage_type)1, order); } static BOOST_FORCEINLINE void clear(storage_type volatile& storage, memory_order order) BOOST_NOEXCEPT { store(storage, (storage_type)0, order); } static BOOST_FORCEINLINE bool is_lock_free(storage_type const volatile&) BOOST_NOEXCEPT { return true; } }; template< bool Signed > struct operations< 1u, Signed > : public gcc_x86_operations< typename make_storage_type< 1u, Signed >::type, operations< 1u, Signed > > { typedef gcc_x86_operations< typename make_storage_type< 1u, Signed >::type, operations< 1u, Signed > > base_type; typedef typename base_type::storage_type storage_type; typedef typename make_storage_type< 1u, Signed >::aligned aligned_storage_type; static BOOST_FORCEINLINE storage_type fetch_add(storage_type volatile& storage, storage_type v, memory_order) BOOST_NOEXCEPT { __asm__ __volatile__ ( "lock; xaddb %0, %1" : "+q" (v), "+m" (storage) : : BOOST_ATOMIC_DETAIL_ASM_CLOBBER_CC_COMMA "memory" ); return v; } static BOOST_FORCEINLINE storage_type exchange(storage_type volatile& storage, storage_type v, memory_order) BOOST_NOEXCEPT { __asm__ __volatile__ ( "xchgb %0, %1" : "+q" (v), "+m" (storage) : : "memory" ); return v; } static BOOST_FORCEINLINE bool compare_exchange_strong( storage_type volatile& storage, storage_type& expected, storage_type desired, memory_order, memory_order) BOOST_NOEXCEPT { storage_type previous = expected; bool success; __asm__ __volatile__ ( "lock; cmpxchgb %3, %1\n\t" "sete %2" : "+a" (previous), "+m" (storage), "=q" (success) : "q" (desired) : BOOST_ATOMIC_DETAIL_ASM_CLOBBER_CC_COMMA "memory" ); expected = previous; return success; } #define BOOST_ATOMIC_DETAIL_CAS_LOOP(op, argument, result)\ __asm__ __volatile__\ (\ "xor %%" BOOST_ATOMIC_DETAIL_TEMP_CAS_REGISTER ", %%" BOOST_ATOMIC_DETAIL_TEMP_CAS_REGISTER "\n\t"\ ".align 16\n\t"\ "1: movb %[arg], %%dl\n\t"\ op " %%al, %%dl\n\t"\ "lock; cmpxchgb %%dl, %[storage]\n\t"\ "jne 1b"\ : [res] "+a" (result), [storage] "+m" (storage)\ : [arg] "q" (argument)\ : BOOST_ATOMIC_DETAIL_ASM_CLOBBER_CC_COMMA BOOST_ATOMIC_DETAIL_TEMP_CAS_REGISTER, "memory"\ ) static BOOST_FORCEINLINE storage_type fetch_and(storage_type volatile& storage, storage_type v, memory_order) BOOST_NOEXCEPT { storage_type res = storage; BOOST_ATOMIC_DETAIL_CAS_LOOP("andb", v, res); return res; } static BOOST_FORCEINLINE storage_type fetch_or(storage_type volatile& storage, storage_type v, memory_order) BOOST_NOEXCEPT { storage_type res = storage; BOOST_ATOMIC_DETAIL_CAS_LOOP("orb", v, res); return res; } static BOOST_FORCEINLINE storage_type fetch_xor(storage_type volatile& storage, storage_type v, memory_order) BOOST_NOEXCEPT { storage_type res = storage; BOOST_ATOMIC_DETAIL_CAS_LOOP("xorb", v, res); return res; } #undef BOOST_ATOMIC_DETAIL_CAS_LOOP }; template< bool Signed > struct operations< 2u, Signed > : public gcc_x86_operations< typename make_storage_type< 2u, Signed >::type, operations< 2u, Signed > > { typedef gcc_x86_operations< typename make_storage_type< 2u, Signed >::type, operations< 2u, Signed > > base_type; typedef typename base_type::storage_type storage_type; typedef typename make_storage_type< 2u, Signed >::aligned aligned_storage_type; static BOOST_FORCEINLINE storage_type fetch_add(storage_type volatile& storage, storage_type v, memory_order) BOOST_NOEXCEPT { __asm__ __volatile__ ( "lock; xaddw %0, %1" : "+q" (v), "+m" (storage) : : BOOST_ATOMIC_DETAIL_ASM_CLOBBER_CC_COMMA "memory" ); return v; } static BOOST_FORCEINLINE storage_type exchange(storage_type volatile& storage, storage_type v, memory_order) BOOST_NOEXCEPT { __asm__ __volatile__ ( "xchgw %0, %1" : "+q" (v), "+m" (storage) : : "memory" ); return v; } static BOOST_FORCEINLINE bool compare_exchange_strong( storage_type volatile& storage, storage_type& expected, storage_type desired, memory_order, memory_order) BOOST_NOEXCEPT { storage_type previous = expected; bool success; __asm__ __volatile__ ( "lock; cmpxchgw %3, %1\n\t" "sete %2" : "+a" (previous), "+m" (storage), "=q" (success) : "q" (desired) : BOOST_ATOMIC_DETAIL_ASM_CLOBBER_CC_COMMA "memory" ); expected = previous; return success; } #define BOOST_ATOMIC_DETAIL_CAS_LOOP(op, argument, result)\ __asm__ __volatile__\ (\ "xor %%" BOOST_ATOMIC_DETAIL_TEMP_CAS_REGISTER ", %%" BOOST_ATOMIC_DETAIL_TEMP_CAS_REGISTER "\n\t"\ ".align 16\n\t"\ "1: movw %[arg], %%dx\n\t"\ op " %%ax, %%dx\n\t"\ "lock; cmpxchgw %%dx, %[storage]\n\t"\ "jne 1b"\ : [res] "+a" (result), [storage] "+m" (storage)\ : [arg] "q" (argument)\ : BOOST_ATOMIC_DETAIL_ASM_CLOBBER_CC_COMMA BOOST_ATOMIC_DETAIL_TEMP_CAS_REGISTER, "memory"\ ) static BOOST_FORCEINLINE storage_type fetch_and(storage_type volatile& storage, storage_type v, memory_order) BOOST_NOEXCEPT { storage_type res = storage; BOOST_ATOMIC_DETAIL_CAS_LOOP("andw", v, res); return res; } static BOOST_FORCEINLINE storage_type fetch_or(storage_type volatile& storage, storage_type v, memory_order) BOOST_NOEXCEPT { storage_type res = storage; BOOST_ATOMIC_DETAIL_CAS_LOOP("orw", v, res); return res; } static BOOST_FORCEINLINE storage_type fetch_xor(storage_type volatile& storage, storage_type v, memory_order) BOOST_NOEXCEPT { storage_type res = storage; BOOST_ATOMIC_DETAIL_CAS_LOOP("xorw", v, res); return res; } #undef BOOST_ATOMIC_DETAIL_CAS_LOOP }; template< bool Signed > struct operations< 4u, Signed > : public gcc_x86_operations< typename make_storage_type< 4u, Signed >::type, operations< 4u, Signed > > { typedef gcc_x86_operations< typename make_storage_type< 4u, Signed >::type, operations< 4u, Signed > > base_type; typedef typename base_type::storage_type storage_type; typedef typename make_storage_type< 4u, Signed >::aligned aligned_storage_type; static BOOST_FORCEINLINE storage_type fetch_add(storage_type volatile& storage, storage_type v, memory_order) BOOST_NOEXCEPT { __asm__ __volatile__ ( "lock; xaddl %0, %1" : "+r" (v), "+m" (storage) : : BOOST_ATOMIC_DETAIL_ASM_CLOBBER_CC_COMMA "memory" ); return v; } static BOOST_FORCEINLINE storage_type exchange(storage_type volatile& storage, storage_type v, memory_order) BOOST_NOEXCEPT { __asm__ __volatile__ ( "xchgl %0, %1" : "+r" (v), "+m" (storage) : : "memory" ); return v; } static BOOST_FORCEINLINE bool compare_exchange_strong( storage_type volatile& storage, storage_type& expected, storage_type desired, memory_order, memory_order) BOOST_NOEXCEPT { storage_type previous = expected; bool success; __asm__ __volatile__ ( "lock; cmpxchgl %3, %1\n\t" "sete %2" : "+a" (previous), "+m" (storage), "=q" (success) : "r" (desired) : BOOST_ATOMIC_DETAIL_ASM_CLOBBER_CC_COMMA "memory" ); expected = previous; return success; } #define BOOST_ATOMIC_DETAIL_CAS_LOOP(op, argument, result)\ __asm__ __volatile__\ (\ "xor %%" BOOST_ATOMIC_DETAIL_TEMP_CAS_REGISTER ", %%" BOOST_ATOMIC_DETAIL_TEMP_CAS_REGISTER "\n\t"\ ".align 16\n\t"\ "1: movl %[arg], %%edx\n\t"\ op " %%eax, %%edx\n\t"\ "lock; cmpxchgl %%edx, %[storage]\n\t"\ "jne 1b"\ : [res] "+a" (result), [storage] "+m" (storage)\ : [arg] "r" (argument)\ : BOOST_ATOMIC_DETAIL_ASM_CLOBBER_CC_COMMA BOOST_ATOMIC_DETAIL_TEMP_CAS_REGISTER, "memory"\ ) static BOOST_FORCEINLINE storage_type fetch_and(storage_type volatile& storage, storage_type v, memory_order) BOOST_NOEXCEPT { storage_type res = storage; BOOST_ATOMIC_DETAIL_CAS_LOOP("andl", v, res); return res; } static BOOST_FORCEINLINE storage_type fetch_or(storage_type volatile& storage, storage_type v, memory_order) BOOST_NOEXCEPT { storage_type res = storage; BOOST_ATOMIC_DETAIL_CAS_LOOP("orl", v, res); return res; } static BOOST_FORCEINLINE storage_type fetch_xor(storage_type volatile& storage, storage_type v, memory_order) BOOST_NOEXCEPT { storage_type res = storage; BOOST_ATOMIC_DETAIL_CAS_LOOP("xorl", v, res); return res; } #undef BOOST_ATOMIC_DETAIL_CAS_LOOP }; #if defined(BOOST_ATOMIC_DETAIL_X86_HAS_CMPXCHG8B) template< bool Signed > struct operations< 8u, Signed > : public cas_based_operations< gcc_dcas_x86< Signed > > { }; #elif defined(__x86_64__) template< bool Signed > struct operations< 8u, Signed > : public gcc_x86_operations< typename make_storage_type< 8u, Signed >::type, operations< 8u, Signed > > { typedef gcc_x86_operations< typename make_storage_type< 8u, Signed >::type, operations< 8u, Signed > > base_type; typedef typename base_type::storage_type storage_type; typedef typename make_storage_type< 8u, Signed >::aligned aligned_storage_type; static BOOST_FORCEINLINE storage_type fetch_add(storage_type volatile& storage, storage_type v, memory_order) BOOST_NOEXCEPT { __asm__ __volatile__ ( "lock; xaddq %0, %1" : "+r" (v), "+m" (storage) : : BOOST_ATOMIC_DETAIL_ASM_CLOBBER_CC_COMMA "memory" ); return v; } static BOOST_FORCEINLINE storage_type exchange(storage_type volatile& storage, storage_type v, memory_order) BOOST_NOEXCEPT { __asm__ __volatile__ ( "xchgq %0, %1" : "+r" (v), "+m" (storage) : : "memory" ); return v; } static BOOST_FORCEINLINE bool compare_exchange_strong( storage_type volatile& storage, storage_type& expected, storage_type desired, memory_order, memory_order) BOOST_NOEXCEPT { storage_type previous = expected; bool success; __asm__ __volatile__ ( "lock; cmpxchgq %3, %1\n\t" "sete %2" : "+a" (previous), "+m" (storage), "=q" (success) : "r" (desired) : BOOST_ATOMIC_DETAIL_ASM_CLOBBER_CC_COMMA "memory" ); expected = previous; return success; } #define BOOST_ATOMIC_DETAIL_CAS_LOOP(op, argument, result)\ __asm__ __volatile__\ (\ "xor %%" BOOST_ATOMIC_DETAIL_TEMP_CAS_REGISTER ", %%" BOOST_ATOMIC_DETAIL_TEMP_CAS_REGISTER "\n\t"\ ".align 16\n\t"\ "1: movq %[arg], %%rdx\n\t"\ op " %%rax, %%rdx\n\t"\ "lock; cmpxchgq %%rdx, %[storage]\n\t"\ "jne 1b"\ : [res] "+a" (result), [storage] "+m" (storage)\ : [arg] "r" (argument)\ : BOOST_ATOMIC_DETAIL_ASM_CLOBBER_CC_COMMA BOOST_ATOMIC_DETAIL_TEMP_CAS_REGISTER, "memory"\ ) static BOOST_FORCEINLINE storage_type fetch_and(storage_type volatile& storage, storage_type v, memory_order) BOOST_NOEXCEPT { storage_type res = storage; BOOST_ATOMIC_DETAIL_CAS_LOOP("andq", v, res); return res; } static BOOST_FORCEINLINE storage_type fetch_or(storage_type volatile& storage, storage_type v, memory_order) BOOST_NOEXCEPT { storage_type res = storage; BOOST_ATOMIC_DETAIL_CAS_LOOP("orq", v, res); return res; } static BOOST_FORCEINLINE storage_type fetch_xor(storage_type volatile& storage, storage_type v, memory_order) BOOST_NOEXCEPT { storage_type res = storage; BOOST_ATOMIC_DETAIL_CAS_LOOP("xorq", v, res); return res; } #undef BOOST_ATOMIC_DETAIL_CAS_LOOP }; #endif #if defined(BOOST_ATOMIC_DETAIL_X86_HAS_CMPXCHG16B) template< bool Signed > struct operations< 16u, Signed > : public cas_based_operations< gcc_dcas_x86_64< Signed > > { }; #endif // defined(BOOST_ATOMIC_DETAIL_X86_HAS_CMPXCHG16B) BOOST_FORCEINLINE void thread_fence(memory_order order) BOOST_NOEXCEPT { if (order == memory_order_seq_cst) { __asm__ __volatile__ ( #if defined(__x86_64__) || defined(__SSE2__) "mfence\n" #else "lock; addl $0, (%%esp)\n" #endif ::: "memory" ); } else if ((order & (memory_order_acquire | memory_order_release)) != 0) { __asm__ __volatile__ ("" ::: "memory"); } } BOOST_FORCEINLINE void signal_fence(memory_order order) BOOST_NOEXCEPT { if (order != memory_order_relaxed) __asm__ __volatile__ ("" ::: "memory"); } } // namespace detail } // namespace atomics } // namespace mars_boost_ksim #undef BOOST_ATOMIC_DETAIL_TEMP_CAS_REGISTER #endif // BOOST_ATOMIC_DETAIL_OPS_GCC_X86_HPP_INCLUDED_
[ "" ]
1e4d029d0ca2e313b7c46dd0c199f5c9e6d44ee2
80a0035888aebec883c76be5c45129ebd4b5cf77
/maaaaaaaze/main.cpp
24cecb290bb61128f2b47f00283007f7bea3db0e
[]
no_license
seoyechan/back16985
938e01e4704a1b8f066daaa2e83b1e24efd9a6e7
96d512ecc94624bd0fc6f13de7cb0421e775ca51
refs/heads/master
2022-04-24T19:06:12.633329
2020-04-17T05:29:48
2020-04-17T05:29:48
256,409,698
0
0
null
null
null
null
UHC
C++
false
false
2,665
cpp
#include <iostream> #include <algorithm> #include <queue> #define _CRT_SECURE_NO_WARNINGS #pragma warning(disable:4996) using namespace std; typedef struct qube{ int arr[4][5][5]; }; typedef struct pos{ int layer, x, y, count; }; qube filed[5]; int select_arr[5]; int nRet; int nx[] = { 0, 1, 0, -1 }; int ny[] = { -1, 0, 1, 0 }; int nlayer[] = { -1, 1 }; int bfs() { queue <pos> que; que.push({ 0, 0, 0, 0}); int visit[5][5][5] = { 0, }; visit[0][0][0] = 1; while (!que.empty()) { pos temp = que.front(); que.pop(); if (temp.x == 4 && temp.y == 4 && temp.layer == 4) { return temp.count; } int tempx = 0; int tempy = 0; int templayer = 0; int tempcount = 0; for (int i = 0; i < 6; i++) // 위 오른쪽 아래 왼쪽 위 아래 { if ((temp.layer == 0 && i == 4) || (temp.layer == 4 && i == 5)) continue; if (i < 4) { tempx = temp.x + nx[i]; tempy = temp.y + ny[i]; if (tempx >= 0 && tempy >= 0 && tempx < 5 && tempy < 5) { if (!visit[templayer][tempy][tempx] && filed[templayer].arr[select_arr[templayer]][tempy][tempx]) { tempcount = temp.count + 1; que.push({ templayer, tempx, tempy, tempcount }); visit[templayer][tempy][tempx] = 1; } } } else { templayer = temp.layer + nlayer[i - 4]; if (!visit[templayer][temp.y][temp.x] && filed[templayer].arr[select_arr[templayer]][temp.y][temp.x]) { tempcount = temp.count + 1; que.push({ templayer, temp.x, temp.y, tempcount }); visit[templayer][temp.y][temp.x] = 1; } } } } return 987654322; } void dfs(int cnt) { if (cnt == 5) { nRet = min(nRet, bfs()); return; } for (int k = 0; k < 5; k++) { select_arr[cnt] = k; dfs(cnt + 1); } } int main() { int t; int test_case; freopen("input.txt", "r", stdin); cin >> t; for (test_case = 1; test_case <= t; ++test_case) { for (int k = 0; k < 5; k++){ for (int i = 0; i < 5; i++){ for (int j = 0; j < 5; j++){ cin >> filed[k].arr[0][i][j]; } } } ///회전 후 결과 저장 for (int k = 0; k < 5; k++){ for (int i = 0; i < 5; i++){ for (int j = 0; j < 5; j++) { filed[k].arr[1][i][j] = filed[k].arr[0][4 - j][i]; } } for (int i = 0; i < 5; i++){ for (int j = 0; j < 5; j++) { filed[k].arr[2][i][j] = filed[k].arr[0][4 - i][4 - j]; } } for (int i = 0; i < 5; i++){ for (int j = 0; j < 5; j++) { filed[k].arr[3][i][j] = filed[k].arr[0][j][4 - i]; } } } nRet = 987654321; dfs(0); if (nRet == 987654321) cout << -1 << "\n"; else cout << nRet << "\n"; } return 0; }
[ "seoyechan@naver.com" ]
seoyechan@naver.com
150d57b51918909828a491090061a2e0133e1d43
c851236c2a3f08f99a1760043080b0a664cf3d92
/mergesortforalinkedlist.cpp
c184acf8228bf69f2601ed2dc0af3231d3767aeb
[]
no_license
Anubhav12345678/competitive-programming
121ba61645f1edc329edb41515e951b9e510958f
702cd59a159eafacabc705b218989349572421f9
refs/heads/master
2023-01-20T08:12:54.008789
2020-11-18T10:23:42
2020-11-18T10:23:42
313,863,914
1
0
null
null
null
null
UTF-8
C++
false
false
2,238
cpp
#include <bits/stdc++.h> using namespace std; #define ll long long //merge sort of a single link list // typedef struct node* nptr struct node { int data; struct node* next; }; struct node* SortedMerge(struct node* a, struct node* b) { struct node* result = NULL; /* Base cases */ if (a == NULL) return (b); else if (b == NULL) return (a); /* Pick either a or b, and recur */ if (a->data <= b->data) { result = a; result->next = SortedMerge(a->next, b); } else { result = b; result->next = SortedMerge(a, b->next); } return (result); } void partition(struct node *head,struct node **a,struct node **b) { //a is front ref // b is back ref // head is a copy of the pointer to the head of the main link list struct node *fast,*slow; fast = head; slow = head; while(fast!=NULL) { fast = fast->next; if(fast!=NULL) { fast = fast->next; slow = slow->next; } }//now fast is null and slow pointer is at the mid or just after that *a = head; *b = slow->next; slow->next=NULL; } void Mergesort(struct node **headref) { struct node* head = *headref; struct node *a; struct node *b; if(head==NULL||head->next==NULL)//if len of list ==1||0 return; partition(head,&a,&b); Mergesort(&a); Mergesort(&b); *headref = SortedMerge(a,b); } void push(struct node **headref,int data) { // struct node *head = *headref; struct node *nep = new node(); nep->data = data; nep->next = *headref; *headref = nep; } void printList(struct node *head) { if(head!=NULL) { while(head!=NULL) { cout<<head->data<<" "; head = head->next; } } } int main() { /* Start with the empty list */ struct node* res = NULL; struct node* a = NULL; /* Let us create a unsorted linked lists to test the functions Created lists shall be a: 2->3->20->5->10->15 */ push(&a, 15); push(&a, 10); push(&a, 5); push(&a, 20); push(&a, 3); push(&a, 2); /* Sort the above created Linked List */ Mergesort(&a); cout << "Sorted Linked List is: \n"; printList(a); return 0; }
[ "anubhavgupta408@gmail.com" ]
anubhavgupta408@gmail.com
d139d7284335992aad90a464d86a0a078ca8f95c
59b6d5314fe3e866e7f6d5267ea8dba40e4bea41
/tests/Unit/SharedLibrary/shared_library2.cpp
2e58ca0ae67b4c4ce41886f7b9636ec0e189f4f3
[ "LicenseRef-scancode-unknown-license-reference", "NCSA" ]
permissive
scchan/hcc
5534d4fe896b8a5dd3fc3272259af8ac959a588d
33e60e8635c58e772d2aa51d57b853f2bc1e1e5d
refs/heads/master
2021-01-19T15:47:55.209519
2016-07-15T16:48:56
2016-07-15T16:48:56
54,526,106
1
0
null
2016-11-25T21:06:43
2016-03-23T02:55:00
C++
UTF-8
C++
false
false
1,975
cpp
// XFAIL: Linux // RUN: %hc -fPIC -Wl,-Bsymbolic -shared -DSHARED_LIBRARY_1 %s -o %T/libtest2_foo.so // RUN: %hc -fPIC -Wl,-Bsymbolic -shared -DSHARED_LIBRARY_2 %s -o %T/libtest2_bar.so // RUN: %clang -std=c++11 %s -o %t.out -ldl && LD_LIBRARY_PATH=%T %t.out // kernels built as multiple shared libraries // loaded dynamically via dlopen() #if SHARED_LIBRARY_1 #include <hc.hpp> extern "C" int foo(int grid_size) { using namespace hc; extent<1> ex(grid_size); array_view<int, 1> av(grid_size); parallel_for_each(ex, [=](index<1>& idx) [[hc]] { av(idx) = 1; }).wait(); int ret = 0; for (int i = 0; i < grid_size; ++i) { ret += av[i]; } return ret; } #else #if SHARED_LIBRARY_2 #include <hc.hpp> extern "C" int bar(int grid_size) { using namespace hc; extent<1> ex(grid_size); array_view<int, 1> av(grid_size); parallel_for_each(ex, [=](index<1>& idx) [[hc]] { av(idx) = 2; }).wait(); int ret = 0; for (int i = 0; i < grid_size; ++i) { ret += av[i]; } return ret; } #else #include <dlfcn.h> int main() { bool ret = true; int (*foo_handle)(int) = nullptr; int (*bar_handle)(int) = nullptr; void* libfoo_handle = dlopen("libtest2_foo.so", RTLD_LAZY); ret &= (libfoo_handle != nullptr); void* libbar_handle = dlopen("libtest2_bar.so", RTLD_LAZY); ret &= (libbar_handle != nullptr); if (libfoo_handle) { foo_handle = (int(*)(int)) dlsym(libfoo_handle, "foo"); ret &= (foo_handle != nullptr); } if (libbar_handle) { bar_handle = (int(*)(int)) dlsym(libbar_handle, "bar"); ret &= (bar_handle != nullptr); } if (foo_handle && bar_handle) { for (int i = 0; i < 16; ++i) { ret &= (foo_handle(i) == i); ret &= (bar_handle(i * 2) == (i * 4)); } } if (libfoo_handle) { dlclose(libfoo_handle); } if (libbar_handle) { dlclose(libbar_handle); } return !(ret == true); } #endif // if SHARED_LIBRARY_2 #endif // if SHARED_LIBRARY_1
[ "jack@multicorewareinc.com" ]
jack@multicorewareinc.com
1570965bb5f87c06e11962b42c5e0adc149a7067
dda0a106fea97cfbcfaf82bd77eaa4056a62b2df
/吉田学園情報ビジネス専門学校 早川樹綺也/00_制作ゲーム/02_COMMANDKNIGHT/00_プロジェクト/loadfilefunction.h
30bfa51159c134b0dd224f2476b0918d7a904600
[]
no_license
JukiyaHayakawa-1225/Yoshidagakuen_HayakawaJukiya
1b9c9a25fb3b1e707a61a27db84df0eca876c484
8d3f88fb7cd13f2a57b55e2eda782a8d93737a3f
refs/heads/master
2020-08-14T15:05:41.388077
2019-10-15T02:37:10
2019-10-15T02:37:10
187,962,297
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,602
h
//============================================================================= // // ファイルを読み込む際の関数[loadfilefunction.h] // Auther:Jukiya Hayakawa // //============================================================================= #ifndef _LOADFILEFUNCTION_H_ #define _LOADFILEFUNCTION_H_ //***************************************************************************** // インクルードファイル //***************************************************************************** #include "main.h" //***************************************************************************** // マクロ定義 //***************************************************************************** #define TEXT_NUM_MODEL "NUM_MODEL = " #define TEXT_FILENAME_MODEL "MODEL_FILENAME = " #define TEXT_NUM_PARTS "NUM_PARTS = " #define TEXT_CHARASET "CHARACTERSET" #define TEXT_END_CHARASET "END_CHARACTERSET" #define TEXT_PARTSSET "PARTSSET" #define TEXT_END_PARTSSET "END_PARTSSET" #define TEXT_INDEX "INDEX = " #define TEXT_PARENT "PARENT = " #define TEXT_POS "POS = " #define TEXT_ROT "ROT = " #define TEXT_MOTIONSET "MOTIONSET" #define TEXT_END_MOTIONSET "END_MOTIONSET" #define TEXT_LOOP "LOOP = " #define TEXT_FRAME "FRAME = " #define TEXT_NUM_KEY "NUM_KEY = " #define TEXT_KEYSET "KEYSET" #define TEXT_END_KEYSET "END_KEYSET" #define TEXT_KEY "KEY" #define TEXT_END_KEY "END_KEY" #define TEXT_MODELSET "MODELSET" #define TEXT_END_MODELSET "END_MODELSET" #define TEXT_TYPE "TYPE = " #define TEXT_SIZE "SIZE = " #define TEXT_TAB "\t" #define TEXT_ENTER "\n" #define TEXT_SPACE " " #define TEXT_COMMENT "#" #define TEXT_SCRIPT "SCRIPT" #define TEXT_END_SCRIPT "END_SCRIPT" #define TEXT_COLLISION "COLLISION = " #define TEXT_HIT "HIT = " //***************************************************************************** // クラスの定義 //***************************************************************************** class CLoadFileFunction { public: // 誰からもアクセス可能 CLoadFileFunction(); ~CLoadFileFunction(); static char *ReadLine(FILE *pFile, char *pDst); static char *GetLineTop(char *pScr); static char *HeadPutout(char *pDest, char *pHead); static char *ReadString(char *pScr, char *pDest, char *pHead); static int Memcmp(char *pScr, char *pCmp); static int PopString(char *pScr, char *pDst); static int ReadInt(char *pScr, char *pHead); static float ReadFloat(char *pScr, char *pHead); static bool ReadBool(char *pScr, char *pHead); static D3DXVECTOR3 ReadVector3(char *pScr, char *pHead); }; #endif
[ "jb2017029@stu.yoshida-g.ac.jp" ]
jb2017029@stu.yoshida-g.ac.jp
d8a1f0b67b2419e94697ca635a1c837449908104
9b4f4ad42b82800c65f12ae507d2eece02935ff6
/src/Sync/ThreadW_CPP.cpp
33d62c3bfb93fb53ccee4502b12339679f9bfffd
[]
no_license
github188/SClass
f5ef01247a8bcf98d64c54ee383cad901adf9630
ca1b7efa6181f78d6f01a6129c81f0a9dd80770b
refs/heads/main
2023-07-03T01:25:53.067293
2021-08-06T18:19:22
2021-08-06T18:19:22
393,572,232
0
1
null
2021-08-07T03:57:17
2021-08-07T03:57:16
null
UTF-8
C++
false
false
748
cpp
#include "Stdafx.h" #include "MyMemory.h" #include <windows.h> #include <intrin.h> #if defined(CPU_X86_32) || defined(CPU_X86_64) extern "C" void Thread_NanoSleep(Int64 clk) { UInt64 endTime = __rdtsc() + clk; while (true) { YieldProcessor(); YieldProcessor(); YieldProcessor(); YieldProcessor(); if (__rdtsc() >= endTime) break; } } #else extern "C" void Thread_NanoSleep(Int64 clk) { UInt64 endTime; LARGE_INTEGER liCurr; QueryPerformanceCounter(&liCurr); endTime = liCurr.QuadPart + clk; while (true) { YieldProcessor(); YieldProcessor(); YieldProcessor(); YieldProcessor(); QueryPerformanceCounter(&liCurr); if ((UInt64)liCurr.QuadPart >= endTime) break; } } #endif
[ "sswroom@yahoo.com" ]
sswroom@yahoo.com
2fb94f2628b186856cd706cb83c50685500d7d5f
39642ce6ce555dd9f29680141ceefd9383089baf
/src/count_and_say.h
95e40d801a8395bd36c18881511c6e108056e3d6
[]
no_license
windie/leetcode
a6003a3e17706bbf5afd20f181673f8ea290f9f6
8c86190e98ebfaa7948648b9a677b593699e88a0
refs/heads/master
2021-01-22T09:58:24.202640
2015-05-11T03:13:29
2015-05-11T03:13:29
13,387,232
0
0
null
null
null
null
UTF-8
C++
false
false
2,029
h
class Solution { public: string countAndSay(int n) { vector<string> f(n); if(n==0){ return ""; } f[0] = "1"; for(int i = 1; i<n; i++){ string res=""; int ch = f[i-1][0]; int cnt = 1; for(int j = 1; j < f[i-1].size(); j++){ if(f[i-1][j] == ch){ cnt++; }else{ res.push_back(cnt+'0'); res.push_back(ch); ch = f[i-1][j]; cnt = 1; } } res.push_back(cnt+'0'); res.push_back(ch); f[i] = res; } return f[n-1]; } }; //class Solution { // string f(int n){ // if(n==0){ // return ""; // } // if(n==1){ // return "1"; // } // string s = f(n-1); // string res = ""; // int cnt = 1; // char ch = s[0]; // for(int i=1; i<s.size(); i++){ // if(s[i] == ch){ // cnt++; // }else{ // res += (cnt+'0'); // res += ch; // ch = s[i]; // cnt = 1; // } // } // res += (cnt + '0'); // res += ch; // return res; // } // //public: // string countAndSay(int n) { // return f(n); // } //}; //#include <iostream> //using namespace std; // //class Solution { // string next(string s) { // char ch = s[0]; // int cnt = 1; // string res = ""; // for (int i = 1; i < s.length(); i++) { // if (s[i] == ch) { // cnt++; // } else { // res.push_back(cnt + '0'); // res.push_back(ch); // cnt = 1; // ch = s[i]; // } // } // res.push_back(cnt + '0'); // res.push_back(ch); // return res; // } //public: // string countAndSay(int n) { // if (n == 0) { // return ""; // } // string rs = "1"; // for (int i = 1; i < n; i++) { // rs = next(rs); // } // return rs; // } //};
[ "linxiaoyan18@gmail.com" ]
linxiaoyan18@gmail.com
83424cf47742234985e7f52480d12421e1b9bb72
9039a8155241712d7a69402d3d9e8d85d19e562a
/lib/include/recti/recti.hpp
7ede1f59af2048deea6ae6b3329af04eea0dbb91
[ "MIT" ]
permissive
blockspacer/physdes
fb3558f20c6823659d22c315ce3a487cf21e0d4a
f41e24e8c885940f05d6ebad13d40549041dfb32
refs/heads/master
2022-09-25T23:36:53.367601
2020-06-02T12:40:08
2020-06-02T12:40:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,644
hpp
#pragma once // #include <boost/operators.hpp> #include "vector2.hpp" #include <boost/operators.hpp> #include <cassert> #include <tuple> // import std::tie() namespace recti { /** * @brief 2D point * * @tparam T1 * @tparam T2 */ template <typename T1, typename T2 = T1> class point { protected: T1 _x; //!< x coordinate T2 _y; //!< y coordinate public: /** * @brief Construct a new point object * * @param x * @param y */ constexpr point(T1 x, T2 y) : _x {std::move(x)} , _y {std::move(y)} { } /** * @brief * * @return const T1& */ constexpr auto x() const -> const T1& { return this->_x; } /** * @brief * * @return const T2& */ constexpr auto y() const -> const T2& { return this->_y; } /** * @brief * * @param rhs * @return constexpr point& */ constexpr point& operator+=(const vector2<T1>& rhs) { this->_x += rhs.x(); this->_y += rhs.y(); return *this; } /** * @brief * * @param rhs * @return constexpr point& */ constexpr point& operator-=(const vector2<T1>& rhs) { this->_x -= rhs.x(); this->_y -= rhs.y(); return *this; } /** * @brief * * @tparam U1 * @tparam U2 * @param rhs * @return true * @return false */ template <typename U1, typename U2> constexpr bool operator<(const point<U1, U2>& rhs) const { return std::tie(this->x(), this->y()) < std::tie(rhs.x(), rhs.y()); } /** * @brief * * @tparam U1 * @tparam U2 * @param rhs * @return true * @return false */ template <typename U1, typename U2> constexpr bool operator>(const point<U1, U2>& rhs) const { return std::tie(this->x(), this->y()) > std::tie(rhs.x(), rhs.y()); } /** * @brief * * @tparam U1 * @tparam U2 * @param rhs * @return true * @return false */ template <typename U1, typename U2> constexpr bool operator<=(const point<U1, U2>& rhs) const { return std::tie(this->x(), this->y()) <= std::tie(rhs.x(), rhs.y()); } /** * @brief * * @tparam U1 * @tparam U2 * @param rhs * @return true * @return false */ template <typename U1, typename U2> constexpr bool operator>=(const point<U1, U2>& rhs) const { return std::tie(this->x(), this->y()) >= std::tie(rhs.x(), rhs.y()); } /** * @brief * * @tparam U1 * @tparam U2 * @param rhs * @return true * @return false */ template <typename U1, typename U2> constexpr bool operator==(const point<U1, U2>& rhs) const { return std::tie(this->x(), this->y()) == std::tie(rhs.x(), rhs.y()); } /** * @brief * * @tparam U1 * @tparam U2 * @param rhs * @return true * @return false */ template <typename U1, typename U2> constexpr bool operator!=(const point<U1, U2>& rhs) const { return !(*this == rhs); } /** * @brief * * @return point<T2, T1> */ constexpr auto flip() const -> point<T2, T1> { return {this->y(), this->x()}; } }; /** * @brief 2D point * * @tparam T1 * @tparam T2 */ template <typename T1, typename T2 = T1> class dualpoint : public point<T1, T2> { public: /** * @brief * * @return const T1& */ constexpr const T1& y() const // override intentionally { return this->_x; } /** * @brief * * @return const T2& */ constexpr const T2& x() const // override intentionally { return this->_y; } }; /** * @brief * * @tparam Stream * @tparam T1 * @tparam T2 * @param out * @param p * @return Stream& */ template <class Stream, typename T1, typename T2> Stream& operator<<(Stream& out, const point<T1, T2>& p) { out << '(' << p.x() / 100.0 << ", " << p.y() / 100.0 << ')'; return out; } /** * @brief Interval * * @tparam T */ template <typename T> class interval : boost::totally_ordered<interval<T>> { private: T _lower; //> lower bound T _upper; //> upper bound public: /** * @brief Construct a new interval object * * @param lower * @param upper */ constexpr interval(T lower, T upper) : _lower {std::move(lower)} , _upper {std::move(upper)} { assert(!(_upper < _lower)); } /** * @brief * * @return const T& */ constexpr const T& lower() const { return this->_lower; } /** * @brief * * @return const T& */ constexpr const T& upper() const { return this->_upper; } /** * @brief * * @return constexpr T */ constexpr T len() const { return this->upper() - this->lower(); } /** * @brief * * @param rhs * @return true * @return false */ constexpr bool operator==(const interval& rhs) const { return this->lower() == rhs.lower() && this->upper() == rhs.upper(); } /** * @brief * * @param rhs * @return true * @return false */ constexpr bool operator<(const interval& rhs) const { return this->upper() < rhs.lower(); } /** * @brief * * @tparam U * @param a * @return true * @return false */ template <typename U> constexpr bool contains(const interval<U>& a) const { return !(a.lower() < this->lower() || this->upper() < a.upper()); } /** * @brief * * @param x * @return true * @return false */ constexpr bool contains(const T& a) const { return !(a < this->lower() || this->upper() < a); } }; /** * @brief Rectangle (Rectilinear) * * @tparam T */ template <typename T> struct rectangle : point<interval<T>> { /** * @brief Construct a new rectangle object * * @param x * @param y */ constexpr rectangle(interval<T> x, interval<T> y) : point<interval<T>> {std::move(x), std::move(y)} { } /** * @brief * * @param rhs * @return true * @return false */ constexpr bool contains(const point<T>& rhs) const { return this->x().contains(rhs.x()) && this->y().contains(rhs.y()); } /** * @brief * * @return point<T> */ constexpr point<T> lower() const { return {this->x().lower(), this->y().lower()}; } /** * @brief * * @return point<T> */ constexpr point<T> upper() const { return {this->x().upper(), this->y().upper()}; } /** * @brief * * @return constexpr T */ constexpr T area() const { return this->x().len() * this->y().len(); } }; /** * @brief * * @tparam Stream * @tparam T * @param out * @param r * @return Stream& */ template <class Stream, typename T> Stream& operator<<(Stream& out, const rectangle<T>& r) { out << r.lower() << " rectangle " << r.upper(); return out; } /** * @brief Horizontal Line Segment * * @tparam T */ template <typename T> struct hsegment : point<interval<T>, T> { /** * @brief Construct a new hsegment object * * @param x * @param y */ constexpr hsegment(interval<T> x, T y) : point<interval<T>, T> {std::move(x), std::move(y)} { } /** * @brief * * @tparam U * @param rhs * @return true * @return false */ template <typename U> constexpr bool contains(const point<U>& rhs) const { return this->y() == rhs.y() && this->x().contains(rhs.x()); } }; /** * @brief vsegment Line Segment * * @tparam T */ template <typename T> struct vsegment : point<T, interval<T>> { /** * @brief Construct a new vsegment object * * @param x * @param y */ constexpr vsegment(T x, interval<T> y) : point<T, interval<T>> {std::move(x), std::move(y)} { } /** * @brief * * @tparam U * @param rhs * @return true * @return false */ template <typename U> constexpr bool contains(const point<U>& rhs) const { return this->x() == rhs.x() && this->y().contains(rhs.y()); } }; } // namespace recti
[ "luk036@gmail.com" ]
luk036@gmail.com
c8a6f0b39210672d98b64ec50336a1210d69f0f1
ec42c36d8c5ff4c6c7590d954dd46630de85901b
/2019/241 NWEN/Ass/NWEN241_A3/databaseCollection/t7test.cc
d20dc196ba620fe2c9bf64dc0e28274b2168c524
[]
no_license
eisendaniel/uni
08c770c56638ee40b429eba3c0dab8363bed1934
aba7b1d60275d990e9cfa63e2ea61473a9079d84
refs/heads/master
2021-11-13T13:29:23.307458
2021-11-08T19:38:06
2021-11-08T19:38:06
248,628,666
0
0
null
null
null
null
UTF-8
C++
false
false
2,557
cc
/** * t7test.cc * Sample test program for Task 7 * The test program assumes that you have already implemented the show() and add() functions. * * To compile with your implementation: * g++ t7test.cc dbms.cc -o t7test * * If successful, executable file t7test should have been * created. */ #include <iostream> #include "dbms.hh" using namespace std; using namespace dbms; struct album albums1[] = { {10, "The Dark Side of the Moon", 1973, "Pink Floyd"}, {14, "Back in Black", 1980, "AC/DC"}, {23, "Their Greatest Hits", 1976, "Eagles"} }; struct album albums2[] = { {37, "Falling into You", 1996, "Celine Dion"}, {43, "Come Away With Me", 2002, "Norah Jones"}, {55, "21", 2001, "Adele"} }; void addAlbum1(DbTable *db) { for (unsigned long i = 0; i < sizeof(albums1) / sizeof(album); i++) { db->add(albums1[i]); } } void addAlbum2(DbTable *db) { for (unsigned long i = 0; i < sizeof(albums2) / sizeof(album); i++) { db->add(albums2[i]); } } int main(void) { DbTable *db; cout << "The test program assumes that you have already implemented the show() and add() functions." << endl; cout << "Instantiating DbTable..." << endl; db = new DbTable(); cout << "Adding 6 entries..." << endl; addAlbum1(db); addAlbum2(db); cout << "Removing entry with id=100 [not in table]..." << endl; bool r = db->remove(100); cout << "Expected return value: 0" << endl; cout << "Actual return value : " << r << endl; cout << "Expected : rowsUsed = 6, rowsTotal = 10" << endl; cout << "From DbTable: rowsUsed = " << db->rows() << ", rowsTotal = " << db->allocated() << endl << endl; cout << "Removing entry with id=37..." << endl; r = db->remove(37); cout << "Expected return value: 1" << endl; cout << "Actual return value : " << r << endl; cout << "Expected : rowsUsed = 5, rowsTotal = 5" << endl; cout << "From DbTable: rowsUsed = " << db->rows() << ", rowsTotal = " << db->allocated() << endl << endl; cout << "Removing entry with id=14..." << endl; r = db->remove(14); cout << "Expected return value: 1" << endl; cout << "Actual return value : " << r << endl; cout << "Expected : rowsUsed = 4, rowsTotal = 5" << endl; cout << "From DbTable: rowsUsed = " << db->rows() << ", rowsTotal = " << db->allocated() << endl << endl; for (int i = 0; i < 4; i++) { cout << "Invoking show(" << i << ")..." << endl; bool r = db->show(i); cout << "Expected return value: 1" << endl; cout << "Actual return value : " << r << endl << endl; } cout << "Freeing DbTable..." << endl; delete db; return 0; }
[ "danieleisen99@gmail.com" ]
danieleisen99@gmail.com
c86e639c64ae48506a43f3315a913e1254a068a2
b9418eaf0d9c4760b139afc7a683f5d2dc98e3b2
/src/GUI/selection_list_item.cpp
fe535d32b8f3c3eb41e147ff2e4529748a36fe1d
[]
no_license
heathharrelson/PerfTrack
42cd538f287040d18cf177337aeef8b13bc21168
62e7ef947cb154f3f0068db9bc940554ecf01553
refs/heads/master
2020-04-16T11:45:31.002789
2013-08-16T19:03:25
2013-08-16T19:03:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,309
cpp
// selection_list_item.cpp // John May, 28 October 2004 /***************************************************************** * PerfTrack Version 1.0 (September 2005) * * For information on PerfTrack, please contact John May * (johnmay@llnl.gov) or Karen Karavanic (karavan@cs.pdx.edu). * * See COPYRIGHT AND LICENSE information at the end of this file. * *****************************************************************/ #include "selection_list_item.h" SelectionListItem:: SelectionListItem( Q3ListView * parent, QString value, QString type, QString reslist, QString resNames, bool expandable, bool selectable ) : Q3ListViewItem( parent, value, type ), children_fetched( false ), attributes_fetched( false ), execution_resources_fetched( false ), resources( reslist ), resourceNames( resNames ) { setExpandable( expandable ); setSelectable( selectable ); } SelectionListItem:: SelectionListItem( SelectionListItem * parent, QString value, QString type, QString reslist, QString resNames, bool expandable, bool selectable ) : Q3ListViewItem( parent, value, type ), children_fetched( false ), attributes_fetched( false ), execution_resources_fetched( false ), resources( reslist ), resourceNames( resNames ) { setExpandable( expandable ); setSelectable( selectable ); } /**************************************************************************** COPYRIGHT AND LICENSE Copyright (c) 2005, Regents of the University of California and Portland State University. Produced at the Lawrence Livermore National Laboratory and Portland State University. UCRL-CODE-2005-155998 All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of California or Portland State Univeristy nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ACKNOWLEDGMENT 1. This notice is required to be provided under our contract with the U.S. Department of Energy (DOE). This work was produced at the University of California, Lawrence Livermore National Laboratory under Contract No. W-7405-ENG-48 with the DOE. 2. Neither the United States Government nor the University of California nor any of their employees, makes any warranty, express or implied, or assumes any liability or responsibility for the accuracy, completeness, or usefulness of any information, apparatus, product, or process disclosed, or represents that its use would not infringe privately-owned rights. 3. Also, reference herein to any specific commercial products, process, or services by trade name, trademark, manufacturer or otherwise does not necessarily constitute or imply its endorsement, recommendation, or favoring by the United States Government or the University of California. The views and opinions of authors expressed herein do not necessarily state or reflect those of the United States Government or the University of California, and shall not be used for advertising or product endorsement purposes. ****************************************************************************/
[ "crzysdrs@gmail.com" ]
crzysdrs@gmail.com
f0ead38d6de7328efee518f9161954ec1723dd76
cc0f632f56c572bd4f50c141f048b0bc7fad4055
/UVA/10491.cpp
30541201198be976346561d32bb873ffcf7f1da0
[]
no_license
AbuHorairaTarif/UvaProject
78517e585c668a83b99866be19b84a0a120bc617
b0688f97a7226bdd692c9ceb29e7b0c406b8a15a
refs/heads/master
2021-05-04T08:19:46.607485
2016-11-11T14:26:23
2016-11-11T14:26:23
70,333,668
0
0
null
null
null
null
UTF-8
C++
false
false
162
cpp
#include <cstdio> int main() { double a,b,c; while(scanf("%lf%lf%lf",&a,&b,&c)==3) printf("%.5lf\n",(a*b+b*b-b)/(a+b)/(a+b-c-1)); return 0; }
[ "horaira_cse13@yahoo.com" ]
horaira_cse13@yahoo.com
c615e16512c3c34e63a150c2c23be9b102b7afb5
283b945850fdcc78977995451d51c2c0cea63ffa
/include/network/utils.hh
5757d387435ace8a69e91ba7503a0164d75e05d5
[ "BSD-2-Clause" ]
permissive
adegroote/hyper
fafae29db75afd9293c258b174f3c3865bbef643
11b442f4d4a6a8098723652d3711ebd8e8dccf45
refs/heads/master
2016-09-05T12:08:58.591421
2013-11-19T15:17:22
2013-11-19T15:17:22
4,157,374
1
1
null
null
null
null
UTF-8
C++
false
false
571
hh
#ifndef _HYPER_NETWORK_UTILS_HH_ #define _HYPER_NETWORK_UTILS_HH_ #include <boost/mpl/assert.hpp> #include <boost/mpl/reverse_fold.hpp> #include <boost/mpl/transform.hpp> #include <boost/mpl/vector.hpp> #include <boost/tuple/tuple.hpp> #include <boost/type_traits/is_same.hpp> namespace hyper { namespace network { template <typename Seq> struct to_tuple { typedef typename boost::mpl::reverse_fold<Seq, boost::tuples::null_type, boost::tuples::cons<boost::mpl::_2, boost::mpl::_1> >::type type; }; } } #endif /* _HYPER_NETWORK_UTILS_HH_ */
[ "arnaud.degroote@laas.fr" ]
arnaud.degroote@laas.fr
bd1998c0d275f7b51d76ce440b28d1622f7c1ec0
691c0cfafba387cf5dfa62eb7fb0f6a4fde2b0ed
/toggle string.cpp
c5cf7b4b4d74eaf6a31261ae0d6a80d5882dbfa7
[]
no_license
SubhaDas2001/Hackerearth_solutions
d20c0f66b34102cd68bef67e0c0ac60533c1023d
0b1f12ba297dc85b63ff05a13c717361a8de29f2
refs/heads/main
2023-02-05T17:40:27.333058
2020-12-30T13:36:48
2020-12-30T13:36:48
323,820,284
0
0
null
null
null
null
UTF-8
C++
false
false
200
cpp
#include<stdio.h> int main() { int i; char s[100]; gets(s); for (i=0;s[i]!='\0';i++) { if (s[i]>='a' && s[i] <='z') s[i]=s[i]-32; else s[i]=s[i]+32; } printf ("%s",s); }
[ "noreply@github.com" ]
SubhaDas2001.noreply@github.com
800b8af31071d749a13e5448092bd3f528c3041e
175e724e9cc27fe3000326c816c6c8a2e8ed5e48
/jma-receipt.r_5_1_branch/cobol/copy/HCM2K.INC
9a970232127f43bbef7046e7a58944b6d9356d8e
[]
no_license
Hiroaki-Inomata/ORCA-5-1
8ddb025ed0a9f7d4ca43503dff093722508207bf
15c648029770cfd9b3af60ae004c65819af6b4b1
refs/heads/master
2022-11-08T13:33:19.410136
2020-06-25T13:35:13
2020-06-25T13:35:13
274,871,265
0
1
null
null
null
null
UTF-8
C++
false
false
1,438
inc
01 HCM2K. 02 HCM2K-PRTYM PIC X(16). 02 HCM2K-SEIYMD PIC X(22). 02 HCM2K-HOSPCD PIC X(20). 02 HCM2K-ADRS PIC X(100). 02 HCM2K-HOSPNAME PIC X(100). 02 HCM2K-KAISETUNAME PIC X(30). 02 HCM2K-IHO-TBL1 OCCURS 11 TIMES. 03 HCM2K-KENSU1 PIC X(6). 03 HCM2K-NISSU1 PIC X(6). 03 HCM2K-TENSU1 PIC X(10). 03 HCM2K-ITBFTN1 PIC X(9). 02 HCM2K-IHO-TBL2 OCCURS 9 TIMES. 03 HCM2K-KENSU2 PIC X(6). 03 HCM2K-NISSU2 PIC X(6). 03 HCM2K-TENSU2 PIC X(10). 03 HCM2K-ITBFTN2 PIC X(9). 02 HCM2K-IHO-TBL3 OCCURS 12 TIMES. 03 HCM2K-KENSU3 PIC X(6). 03 HCM2K-NISSU3 PIC X(6). 03 HCM2K-TENSU3 PIC X(10). 02 HCM2K-ITBFTN3 PIC X(9). 02 HCM2K-IHO-TBL4 OCCURS 9 TIMES. 03 HCM2K-KENSU4 PIC X(6). 03 HCM2K-NISSU4 PIC X(6). 03 HCM2K-TENSU4 PIC X(10). 02 HCM2K-IHO-TBL5 OCCURS 9 TIMES. 03 HCM2K-KENSU5 PIC X(6). 03 HCM2K-NISSU5 PIC X(6). 03 HCM2K-TENSU5 PIC X(10). 02 HCM2K-KENSUG PIC X(6). 02 HCM2K-TITLE PIC X(50).
[ "air.h.128k.il@gmail.com" ]
air.h.128k.il@gmail.com
82977b4a68391c5345f07f6eb3781473f4dc3fec
cdc18670c82b47628f8894b97b0ffa75d1a54f32
/rb_tree.h
50c6dac4886bec34edf0abdde855d7a9f3b28df5
[]
no_license
fangwater/Red_black_tree
ac417c303dfc67af07b40d46feb4014b857c927b
f6bccf03d5bf14ca335361e3c04aa65d8ca8d26e
refs/heads/master
2021-01-01T19:33:08.862478
2018-01-08T06:47:50
2018-01-08T06:47:50
98,613,261
0
0
null
null
null
null
UTF-8
C++
false
false
7,589
h
#ifndef RB_TREE_H #define RB_TREE_H #include <iostream> #define red 0 #define black 1 #define onright(x) (x->parent->rchild == x) #define onleft(x) (x->parent->lchild == x) template <typename T> struct node{ int color = 0;/*red for 0 ,black for 1*/ T data; node<T>* parent = NULL; node<T>* lchild = NULL; node<T>* rchild = NULL; node<T>* succ(){ node<T>* s = this; if(lchild){ s = rchild; while(s->lchild!=NULL){s = s->lchild;} } else{ while (onright(s)){s = s->parent;} s = s->parent; } return s; } }; template <typename T> class redblack{ public: node<T>* root; node<T>* now; int size = 0; void travIn( node<T>* x) { if(!x)return; travIn(x->lchild); std::cout<<x->data<<std::endl; travIn(x->rchild); } void solve_double_red(node<T>* hot); void solve_double_black(node<T>* hot); node<T>* removeat(node<T>* x,node<T>* now){ node<T>* w = x; //used to instead node<T>* succed = NULL; int tag = 0; if(onleft(x)){ tag = 1; } //if this pointer have no left child if(!(x->lchild)){ succed = x->rchild; } else if(!(x->rchild)){ succed = x->lchild; } else{ w = w->succ(); T temp=x->data; x->data = w->data; w->data = temp; node<T>* u = w->parent; ((u==x)?u->rchild:u->lchild) = succed = w->rchild; } now = w->parent; if(succed){ succed->parent = now; if(tag){ now->lchild = succed; } else{ now->rchild = succed; } } delete(w); return succed; } node<T>*& FromParentTo(node<T>* hot){ if(hot == root){ return root; } else{ return (onleft(hot)) ? hot->parent->lchild:hot->parent->rchild; } } node<T>* uncle(node<T>* hot){ node<T>* grandfather = hot->parent->parent; if(grandfather->lchild == hot->parent){ return grandfather->rchild;} return grandfather->lchild; } node<T>* connect34(node<T>* a,node<T>* b,node<T>* c,node<T>* t0,node<T>* t1,node<T>* t2,node<T>* t3){ a->lchild = t0; if(t0 != NULL)t0->parent = a; a->rchild = t1; if(t1 != NULL)t1->parent = a; c->lchild = t2; if(t2 != NULL)t2->parent = c; c->rchild = t3; if(t3 != NULL)t3->parent = c; b->lchild = a; if(a != NULL)a->parent = b; b->rchild = c; c->parent = b; return b; } node<T>* rotate(node<T>* v){ node<T>* p = v->parent; node<T>* g = p->parent; if(onleft(p)){ if(onleft(v)){//zig zig return connect34(v,p,g,v->lchild,v->rchild,p->rchild,g->rchild); } else{//zig zag v->parent = g->parent; return connect34(p,v,g,p->lchild,v->lchild,v->rchild,g->rchild); } } else{ if(onright(v)){ //zag zag p->parent = g->parent; return connect34(g,p,v,g->lchild,p->lchild,v->lchild,v->rchild); } else{ v->parent = g->parent; return connect34(g,v,p,g->lchild,v->lchild,v->rchild,p->rchild); } } } public: node<T>* insert(const T data); bool remove(T data); node<T>* search(const T data,node<T>* temp); }; template <typename T> bool redblack<T>::remove(T data) { node<T>* x = search(data,root); if(!x) return false; node<T>* r = removeat(x,now); if(!(--size))return true; if(!now){ root->color = black; return true; } if(r == NULL){ return true; } if(r->color == red){ r->color = black; return true; } solve_double_black(r); return true; } template <typename T> void redblack<T>::solve_double_black(node<T> *hot) { node<T>* parent = hot->parent; if(parent == nullptr){ return; } node<T>* brother = (hot == parent->lchild)?parent->rchild:parent->lchild; //如果兄弟节点为黑色 if(brother->color == black){ node<T>* t = nullptr; if(brother->rchild->color == red) t = brother->rchild;//借走右侄子 if(brother->lchild->color == red) t = brother->rchild;//借走左侄子 if(t){ //说明有红色的侄子 int precolor = parent->color; //备份其颜色 node<T>* &b = FromParentTo(parent); b = rotate(t); if(b->lchild){b->lchild->color = black;} if(b->rchild){b->rchild->color = black;} b->color = precolor; } else{ //借不出红侄子 brother->color = red;//兄弟染红 if(parent->color == red){ parent->color = black; } else{ solve_double_black(parent); } } } else{ brother->color = black; parent->color =red; node<T>* t = onleft(brother) ? brother->lchild : brother->rchild; now = parent; node<T>* &temp = FromParentTo(parent); temp = rotate(t); solve_double_black(t); } } template <typename T> void redblack<T>::solve_double_red(node<T> *hot) { //如果递归到树根,那么树根染成黑色,黑高度增加 if(hot == root){ root->color = black;return; } //如果点的父亲是黑色的,不存在需要修正的问题 if(hot->parent->color == black){return;} node<T>* father = hot->parent; //如果p的父亲存在,而且p是红色的,那么p一定有父亲存在 node<T>* grand = father->parent; node<T>* uncl = uncle(hot); //根据uncle的颜色进行处理 //如果叔叔为black int tag = 0; if(uncl == NULL){ tag = 1; } else if(uncl->color == black){ tag = 1; } if(tag){ //如果节点和父亲同侧 if((onleft(hot)) == (onleft(father))){ //染红 father->color = black; } else{ hot->color = black; grand->color = red; node<T>* gg = grand->parent; node<T>* &r = FromParentTo(grand); r = rotate(hot); r->parent = gg; } } //叔叔为red else{ father->color = black; uncl->color = black; if(grand != root){ grand->color = red; } solve_double_red(grand); } } template <typename T> node<T>* redblack<T>::insert(const T data) { if(size == 0){ root = new node<T>(); root->data = data; root->color = black; size++; return root; } node<T>* x = search(data,root); if(x) return x; x = new node<T>; x->parent = now;x->color = red;size++;x->data = data; if(now->data > data){ now->lchild = x; } else{ now->rchild = x; } solve_double_red(x); return x; } template <typename T> node<T>* redblack<T>::search(T data,node<T>* temp) { if(temp == nullptr){ return nullptr;} if(data == temp->data){return temp;} now = temp; if(data<temp->data){ return search(data,temp->lchild);} return search(data,temp->rchild); } #endif // RB_TREE_H
[ "fanghaizhou0611@gmail.com" ]
fanghaizhou0611@gmail.com
94eed40852dd90e64b6f98982515c1af0557467a
e949b67f3d8a5758817b4861783c6136e33d8c99
/c++tsts/l3/FXString.h
f73b3ae04464687bec448ca649c570c82ce51bc9
[]
no_license
edt11x/edt-jnk
1976c6b4cbb1cfe38db731bd520a3d1eb31995bf
e9ceb4fa645c2513b7699cea9fcb31944476efba
refs/heads/master
2023-08-17T11:15:20.938437
2023-08-16T18:53:47
2023-08-16T18:53:47
20,622,874
0
0
null
null
null
null
UTF-8
C++
false
false
8,422
h
/* *=========================================================================== */ /** \file FXString.h * * */ /*=========================================================================== * * Goodrich Avionics Systems, Inc. * 4029 Executive Drive * Beavercreek, OH 45430-1062 * (937)426-1700 * *=========================================================================== * * This file contains proprietary information. This file shall not be * duplicated, used, modified, or disclosed in whole or in part without the * express written consent of Goodrich Avionics Systems, Incorporated. * * Copyright (c), Goodrich Avionics Systems, Incorporated. * All rights reserved. * *=========================================================================== * * $Workfile: FXString.h $ * * $Archive: T:/SmartDeck/archives/Flight_Display/Development/Projects/Libraries/UtilToolBox/Headers/FXString.h-arc $ * * $Revision: 2.0 $ * * $Date: Sep 03 2003 15:48:52 $ * * $Author: JohnsT $ * *=========================================================================== */ /** \class FXString.h * * This class provides the methods necessary for manipulating a variable- <br> * length string with a fixed maximum length. The FXString class can not be <br> * instantiated; only classes that inherit from FXString can actually be <br> * instantiated. * *=========================================================================== */ // Protect against multiple includes #ifndef __FXSTRING_H__ #define __FXSTRING_H__ // System Header File(s) #include <string.h> //B4I #include <ctype.h> //B4I #include <stdio.h> //B4I // Standard Header File(s) #include "StdIncl.h" // User-Defined Header(s) // None // Symbolic Constant(s) // None // Pre-ErrorCode Definitions #define EFXS_EXCEEDS_MAX_LENGTH 1 #define EFXS_NULL_POINTER 2 #define EFXS_NULL_CHARACTER 3 // Macro Define(s) // Enumerated Type(s) // Class definition class FXString { // Public, Protected, and Private Attributes Section public: // None private: char szComment[MAX_CHARS_LINE]; /**< NOTE: removed from methods for optimization purposes */ char *pcCurToken; /**< keeps track of the current token for strTok */ static char *pszVCSId; /**< Source ID Track Number */ protected: char *pszBuffer; uint16 ui2MaxLength; uint16 ui2Length; /**< i2MaxLength - 1 or max length excluding the NULL character */ // Public, Protected, and Private Methods Section public: ~FXString(); // accessors const char *getBuffer ( void ) const; uint16 getFixedLength( void ) const; uint16 length ( void ) const; // case altering methods tStdReturn toUp ( void ); tStdReturn toLow( void ); // copy methods tStdReturn copy ( const FXString &fxStr ); tStdReturn copy ( const char *pszString ); tStdReturn copy ( char cCharacter ); tStdReturn copyN( const FXString &fxStr, int16 i2Count ); tStdReturn copyN( const char *pszString, int16 i2Count ); // concat methods tStdReturn concat ( const FXString &fxStr ); tStdReturn concat ( const char *pszString ); tStdReturn concat ( char cCharacter ); tStdReturn concatN( const FXString &fxStr, int16 i2Count ); tStdReturn concatN( const char *pszString, int16 i2Count ); // compare methods -> Case-Sensitive int16 compare ( const FXString &fxStr ) const; int16 compare ( const char *pszString ) const; int16 compare ( char cCharacter ) const; int16 compareN( const FXString &fxStr, int16 i2Count ) const; int16 compareN( const char *pszString, int16 i2Count ) const; // compare methods -> NoT cAsE-sEnSiTiVe int16 compareI ( const FXString &fxStr ) const; int16 compareI ( const char *pszString ) const; int16 compareI ( char cCharacter ) const; int16 compareNI( const FXString &fxStr, int16 i2Count ) const; int16 compareNI( const char *pszString, int16 i2Count ) const; // methods to find a substring int inStr( const FXString &fxStr, uint16 i2Position = 0 ) const; int inStr( const char *pszString, uint16 i2Position = 0 ) const; int inStr( char cCharacter, uint16 i2Position = 0 ) const; // substring methods tStdReturn left( uint16 ui2LeftLength ); tStdReturn left( uint16 ui2LeftLength, const char* pszStr ); tStdReturn left( uint16 ui2LeftLength, const FXString &fxStr ); tStdReturn right( uint16 ui2RightLength ); tStdReturn right( uint16 ui2RightLength, const char* pszStr ); tStdReturn right( uint16 ui2RightLength, const FXString &fxStr ); tStdReturn mid( uint16 ui2Start, uint16 ui2MidLength ); tStdReturn mid( uint16 ui2Start, uint16 ui2MidLength, const char* pszStr ); tStdReturn mid( uint16 ui2Start, uint16 ui2MidLength, const FXString &fxStr ); // conversion methods tStdReturn getBoolean( bool *pbValue ) const; tStdReturn getDouble( double *pdValue ) const; tStdReturn getHex( int *piValue ) const; tStdReturn getInt( int *piValue ) const; tStdReturn getLong( long int *pliValue ) const; tStdReturn setBoolean( bool bValue ); tStdReturn setDouble( double dValue, char *pszFormat = "" ); tStdReturn setHex( int iValue, char *pszFormat = "" ); tStdReturn setInt( int iValue, char *pszFormat = "" ); tStdReturn setLong( long int liValue, char *pszFormat ); // separate string by token tStdReturn strTok( char* pszThisToken, const char* pszDelim ); void resetTok( void ); // miscellaneous methods void clearBuffer(); // clears the buffer space void reverse(); char getAt( uint16 ui2Location ) const; tStdReturn setAt( uint16 ui2Location, char cCharacter ); FXString& operator=( const FXString &rhs); // data conversion methods int32 atoi() const; tStdReturn itoa( int32 i4IntegerToConvert ); private: protected: FXString(); // NOTE: This will prohibit instances of FXString from being created }; #endif // __FXSTRING_H__ /*=========================================================================== * * $Log: T:/SmartDeck/archives/Flight_Display/Development/Projects/Libraries/UtilToolBox/Headers/FXString.h-arc $ * * Rev 2.0 Sep 03 2003 15:48:52 JohnsT * Rolling Revision number to 2.0. No changes, just new baseline. * * Rev 1.0 Sep 03 2003 15:41:58 JohnsT * Initial revision. * * Rev 1.2 Mar 28 2003 16:08:28 ParsoT * Integrity safer. Todd last week. * * Rev 1.1 Feb 21 2003 14:01:16 ParsoT * Updated / merged from FDS * * Rev 1.6 Nov 12 2002 13:19:22 McCluR * Added getLong and setLong conversions. The ConfigReader classes needed them. * * Rev 1.5 Nov 07 2002 15:45:12 McCluR * fixed default params in the conversion methods. * * Rev 1.4 Nov 06 2002 12:28:30 McCluR * Added conversion methods. * Fixed bugs found in reverse(), concat, copyN. * Fixed concat and copyN to not copy self. * Updated Doxygenation. * Resolution for 113: Add Coversion Methods to FXString * Resolution for 128: The FXString classes need these updates * Resolution for 129: FXString needs rework * * Rev 1.3 Nov 05 2002 11:55:46 McCluR * Added additional left, mid and right methods. * Fixed inStr to return an index instead of a pointer. * Removed clean() method. Made the clearBuffer method pulbic. should use that now. * Removed the base copy constructor. Couldn't be called anyway. * * Rev 1.2 Nov 01 2002 14:56:58 McCluR * added a copy constructor and a const char * constructor * * Rev 1.1 Oct 23 2002 09:26:00 MccluJ * changing header to include doxygen code * * Rev 1.0 Jul 24 2002 15:04:00 GeisD * Initial Revision * *=========================================================================== ***** END of HEADER ***** */
[ "edt11x@gmail.com" ]
edt11x@gmail.com
8e196143608f055fa55d7747269c2a205fb048b5
d0c44dd3da2ef8c0ff835982a437946cbf4d2940
/cmake-build-debug/programs_tiling/function14409/function14409_schedule_5/function14409_schedule_5_wrapper.cpp
29f1aad9ab0d4ef00bc3f60e3cad95a23b341552
[]
no_license
IsraMekki/tiramisu_code_generator
8b3f1d63cff62ba9f5242c019058d5a3119184a3
5a259d8e244af452e5301126683fa4320c2047a3
refs/heads/master
2020-04-29T17:27:57.987172
2019-04-23T16:50:32
2019-04-23T16:50:32
176,297,755
1
2
null
null
null
null
UTF-8
C++
false
false
1,207
cpp
#include "Halide.h" #include "function14409_schedule_5_wrapper.h" #include "tiramisu/utils.h" #include <cstdlib> #include <iostream> #include <time.h> #include <fstream> #include <chrono> #define MAX_RAND 200 int main(int, char **){ Halide::Buffer<int32_t> buf00(64, 128); Halide::Buffer<int32_t> buf01(64, 64, 64); Halide::Buffer<int32_t> buf02(64, 64); Halide::Buffer<int32_t> buf03(64, 128, 64); Halide::Buffer<int32_t> buf04(64); Halide::Buffer<int32_t> buf0(64, 128, 64, 64); init_buffer(buf0, (int32_t)0); auto t1 = std::chrono::high_resolution_clock::now(); function14409_schedule_5(buf00.raw_buffer(), buf01.raw_buffer(), buf02.raw_buffer(), buf03.raw_buffer(), buf04.raw_buffer(), buf0.raw_buffer()); auto t2 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> diff = t2 - t1; std::ofstream exec_times_file; exec_times_file.open("../data/programs/function14409/function14409_schedule_5/exec_times.txt", std::ios_base::app); if (exec_times_file.is_open()){ exec_times_file << diff.count() * 1000000 << "us" <<std::endl; exec_times_file.close(); } return 0; }
[ "ei_mekki@esi.dz" ]
ei_mekki@esi.dz
ab1983b3ef47b3fac548d9447afbf4b1358a7bc5
b19d6db8c2297b438f951c0813a4875191397cb6
/fwk4gps 2012/iCoordinator.h
5f70663860b4ff143a3150b12117495b8096e012
[]
no_license
cathyatseneca/gam671-astar
7f9eaf943b4e364fc4d9de5de7d2d3b3d8aa99e0
d25545526dc67b8627b0db0ea00b71f1191c5917
refs/heads/master
2020-04-28T00:18:24.304942
2012-04-04T19:27:09
2012-04-04T19:27:09
3,930,363
1
0
null
null
null
null
UTF-8
C++
false
false
2,588
h
#ifndef _I_COORDINATOR_H_ #define _I_COORDINATOR_H_ /* Coordinator Interface - Modelling Layer * * iCoordinator.h * fwk4gps version 3.0 * gam666/dps901/gam670/dps905 * January 14 2012 * copyright (c) 2012 Chris Szalwinski * distributed under TPL - see ../Licenses.txt */ #include "Base.h" // for the Base class definition //-------------------------------- iCoordinator ------------------------------------- // // iCoordinator is the Interface to the Coordinator class // class iObject; class iTexture; class iLight; class iCamera; class iSound; class iText; class iHUD; class iGraphic; enum Action; enum ModelSound; class iCoordinator : public Base { public: // initialization virtual void initialize() = 0; virtual void add(iObject* o) = 0; virtual void add(iTexture* t) = 0; virtual void add(iLight* l) = 0; virtual void add(iCamera* c) = 0; virtual void add(iSound* s) = 0; virtual void add(iGraphic* v) = 0; virtual void add(iText* t) = 0; virtual void add(iHUD* h) = 0; virtual void reset() = 0; // execution virtual void update() = 0; virtual bool pressed(Action a) const = 0; virtual bool ptrPressed() const = 0; virtual bool ctrPressed() const = 0; virtual int change(Action a) const = 0; virtual void resize() = 0; virtual int run() = 0; // termination virtual void remove(iObject* o) = 0; virtual void remove(iTexture* t) = 0; virtual void remove(iLight* l) = 0; virtual void remove(iCamera* c) = 0; virtual void remove(iSound* s) = 0; virtual void remove(iGraphic* v) = 0; virtual void remove(iText* t) = 0; virtual void remove(iHUD* h) = 0; }; iCoordinator* CoordinatorAddress(); #endif
[ "cathyatseneca@gmail.com" ]
cathyatseneca@gmail.com
8090f91d005241f6f0df2e6aa4c0e5585837eef7
8722d44a37a52777055e56cc8e931f7aa1dfdeb7
/LockfreeQueue/stdafx.cpp
1521ab66bc6c632c4f1b05deda377a018eb7c54c
[]
no_license
twangjie/ipc
492c53edad0e55fc35cb51e62bdcf890f66a50c1
1920b7b20d554bfc56711929b6b17adc71a5b089
refs/heads/master
2020-03-29T01:49:22.850062
2018-09-19T07:14:21
2018-09-19T07:14:21
149,408,077
0
0
null
null
null
null
UTF-8
C++
false
false
292
cpp
// stdafx.cpp : source file that includes just the standard includes // LockfreeQueue.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "twangjie@qq.com" ]
twangjie@qq.com
f07c326d1da78efe84a84f36d94c513615f819af
1e5e1c653ea9df9b52a1032207d97a57bb2ab688
/Lesson03-variables/usingConstExpr.cpp
9892e100ecf1eaf29be6394d28bbc81c6999126d
[]
no_license
harveylabis/SamsTeachCplusplus
ac3c8c744b94aa8416ece4211a6a40aced07bfba
46d72b88a382443c794038db91a972e715c5fe21
refs/heads/main
2023-07-09T08:48:29.201982
2021-08-20T01:24:07
2021-08-20T01:24:07
386,963,711
0
0
null
null
null
null
UTF-8
C++
false
false
401
cpp
#include <iostream> constexpr double GetPi() { return 22.0 / 7; } constexpr double TwicePi() { return 2 * GetPi(); } int main() { using namespace std; const double pi = 22.0 / 7; cout << "constant pi contains value " << pi << endl; cout << "constexpr GetPi() returns value " << GetPi() << endl; cout << "constexpr TwicePi() returns value " << TwicePi() << endl; return 0; }
[ "harveyabiagador@gmail.com" ]
harveyabiagador@gmail.com
257234cacaa03e129859f4ec995d7ee44790ad60
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/collectd/old_hunk_170.cpp
b58a0b376ed5f935c934bdf9c7e53ed84a89fd4d
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
657
cpp
NULL, &plugin, NULL, &host, &time, &interval, &meta)) return -1; if (type[0] != 0 && plugin_get_ds(type) == NULL) { PyErr_Format(PyExc_TypeError, "Dataset %s not found", type); return -1; } sstrncpy(self->data.host, host, sizeof(self->data.host)); sstrncpy(self->data.plugin, plugin, sizeof(self->data.plugin)); sstrncpy(self->data.plugin_instance, plugin_instance, sizeof(self->data.plugin_instance)); sstrncpy(self->data.type, type, sizeof(self->data.type)); sstrncpy(self->data.type_instance, type_instance, sizeof(self->data.type_instance)); self->data.time = time; if (values == NULL) { values = PyList_New(0); PyErr_Clear();
[ "993273596@qq.com" ]
993273596@qq.com
9c3e061721e15819d8ba23721a6db925359b7d33
22aea1204c257db7e1bf190bce6a2337b53d62f0
/src/DataStructure.cpp
87f29bd100192122d14d91ffab7a8cea298c3b9a
[]
no_license
hongchh/predict-entity
4ebb23a4badc90dfeed0427de6293dc9df77d873
22340e1f964dfddf7a70dd5f29594af2338eb768
refs/heads/master
2021-01-20T20:36:13.252411
2017-04-23T09:10:52
2017-04-23T09:10:52
63,426,580
1
0
null
null
null
null
UTF-8
C++
false
false
930
cpp
#include "headers.h" void Vector::init(const int& dimision) { this->dimision = dimision; if (dimision <= 0) { dim = NULL; } else { dim = new float[dimision]; } } Vector::~Vector() { if (dim != NULL) delete [] dim; } float Vector::operator*(const Vector& v) const { if (dimision != v.dimision) { printf("[Vector] operator*(), dimision error.\n"); exit(0); } float val = 0.0; for (int i = 0; i < dimision; ++i) val += dim[i] * v.dim[i]; return val; } float Vector::distance(const Vector& v) const { if (dimision != v.dimision) { printf("[Vector] distance(), dimision error.\n"); exit(0); } float dist = 0.0; for (int i = 0; i < dimision; ++i) dist += (dim[i] - v.dim[i]) * (dim[i] - v.dim[i]); return sqrt(dist); } bool Buffer::operator<(const Buffer& buff) const { return val < buff.val; }
[ "hongchh_sysu@qq.com" ]
hongchh_sysu@qq.com
fcf508fe3cef70a63a64d3cc715531c00869e105
8a5ea0aa4e755820ac82ab494acd7db3c49eddce
/JanneRemesEngine/Engine/jni/Debug.h
eef2c9b4648678eac03cde45906d1c57e8508287
[]
no_license
JanneRemes/janityengine
88a9e4aa28030b987e1ffb98411daf6f1efb6fd1
27dbdb73bdd8b122171cbd8a36b2a15a25956bb6
refs/heads/master
2021-01-23T18:50:53.547422
2014-05-20T11:55:05
2014-05-20T11:55:05
19,489,551
2
0
null
null
null
null
UTF-8
C++
false
false
488
h
#pragma once #ifndef DEBUG #define DEBUG #include <assert.h> #include <AL\al.h> #include <AL\alc.h> #include <Win32toAndroid.h> namespace JanityEngine { class Debug { public: Debug(); ~Debug(); static void PrintGLString(const char *name, GLenum s); static void CheckGlError(const char* op); static void CheckALError(const char* op); static void Win32Assert(int expression); static void WriteLog(const char* text, ...); private: Debug(const Debug&); }; } #endif
[ "tti12sjanner@outlook.com" ]
tti12sjanner@outlook.com
6dd57aff6ad2519429847a9ed32dd139619cbd8e
7df33fbf07e9ea691f0adaf6a76dda4f40f36f52
/src/ip.cpp
42e6c708ae8aa475b31e28082b11d3ce72e77637
[ "MIT" ]
permissive
wilbertom/maproute
5c64f62ed3d5b006b6e579c2a4c4cfcf3d446bc7
2400d48923d8da9d4c4baea7f40042570ee6265c
refs/heads/master
2021-01-10T02:20:08.200049
2015-11-25T15:52:12
2015-11-25T15:52:12
46,868,443
0
0
null
null
null
null
UTF-8
C++
false
false
722
cpp
#ifndef MR_IP_C #define MR_IP_C #include <maproute/ip.hpp> IPV4::IPV4( ipv4_component x, ipv4_component y, ipv4_component a, ipv4_component b ) { this->set_x(x); this->set_y(y); this->set_a(a); this->set_b(b); } ipv4_component IPV4::get_x() const { return this->x; } ipv4_component IPV4::get_y() const { return this->y; } ipv4_component IPV4::get_a() const { return this->a; } ipv4_component IPV4::get_b() const { return this->b; } void IPV4::set_x(ipv4_component c) { this->x = c; } void IPV4::set_y(ipv4_component c) { this->y = c; } void IPV4::set_a(ipv4_component c) { this->a = c; } void IPV4::set_b(ipv4_component c) { this->b = c; } #endif
[ "wilbertomorales777@gmail.com" ]
wilbertomorales777@gmail.com
8fcf159e8ee2c3bc705647cb01347f3700ee8536
a64fec82446091643600d748cee8609162f768b9
/0511_UDP_chat/UDP_chat/UDP_chatDlg.cpp
70280c336f7736226cbdfca72b84870f5d414601
[]
no_license
chia56028/NCTU-EE-OOP
c29f10926a182014d4e58983403bd6e606a1b183
f1b45ef2155f8f80768fb6aed7234b019fd1ffdf
refs/heads/main
2023-04-27T19:16:16.205638
2021-05-11T11:55:05
2021-05-11T11:55:05
343,736,490
2
0
null
null
null
null
UTF-8
C++
false
false
5,798
cpp
 // UDP_chatDlg.cpp: 實作檔案 // #include "pch.h" #include "framework.h" #include "UDP_chat.h" #include "UDP_chatDlg.h" #include "afxdialogex.h" #ifdef _DEBUG #define new DEBUG_NEW #endif #define SEVENT (WM_USER+100) // Server Event #define CEVENT (WM_USER+200) // Client Event #include "tcpip_async.cpp" SOCKET SSock, CSock; // Internet Connection Code sockaddr_in CAddr; // Save Remote Info (IP+Port) char IP[100] = { "192.168.13.255" }; //x.x.x.255 for broadcast // 對 App About 使用 CAboutDlg 對話方塊 class CAboutDlg : public CDialogEx { public: CAboutDlg(); // 對話方塊資料 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_ABOUTBOX }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支援 // 程式碼實作 protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // CUDPchatDlg 對話方塊 CUDPchatDlg::CUDPchatDlg(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_UDP_CHAT_DIALOG, pParent) , m_Edit1(_T("")) , m_Edit2(_T("")) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CUDPchatDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_EDIT1, m_Edit1); DDX_Text(pDX, IDC_EDIT2, m_Edit2); DDX_Control(pDX, IDC_EDIT1, m_Edit11); } BEGIN_MESSAGE_MAP(CUDPchatDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BUTTON1, &CUDPchatDlg::OnBnClickedButton1) ON_EN_CHANGE(IDC_EDIT1, &CUDPchatDlg::OnEnChangeEdit1) END_MESSAGE_MAP() // CUDPchatDlg 訊息處理常式 BOOL CUDPchatDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 將 [關於...] 功能表加入系統功能表。 // IDM_ABOUTBOX 必須在系統命令範圍之中。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != nullptr) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 設定此對話方塊的圖示。當應用程式的主視窗不是對話方塊時, // 框架會自動從事此作業 SetIcon(m_hIcon, TRUE); // 設定大圖示 SetIcon(m_hIcon, FALSE); // 設定小圖示 // TODO: 在此加入額外的初始設定 // Set up UDP Client (Receive Message) Start_UDP_Server(&SSock, 6000, SEVENT, m_hWnd); // Set up UDP Server (Send Message) Start_UDP_Client(&CSock, &CAddr, 6000, IP, CEVENT, m_hWnd); UpdateData(1); m_Edit1 = L"Successfully start UDP"; UpdateData(0); return TRUE; // 傳回 TRUE,除非您對控制項設定焦點 } void CUDPchatDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } // 如果將最小化按鈕加入您的對話方塊,您需要下列的程式碼, // 以便繪製圖示。對於使用文件/檢視模式的 MFC 應用程式, // 框架會自動完成此作業。 void CUDPchatDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 繪製的裝置內容 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 將圖示置中於用戶端矩形 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 描繪圖示 dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } // 當使用者拖曳最小化視窗時, // 系統呼叫這個功能取得游標顯示。 HCURSOR CUDPchatDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } // Client send the string in the windows to Server void CUDPchatDlg::OnBnClickedButton1() { // 1. Declare variables int i, Len = sizeof(sockaddr); char S1[2000] = { "Hello World" }; wchar_t *S11; // 2. Capture string UpdateData(1); S11 = (wchar_t *)m_Edit2.GetBuffer(); UpdateData(0); // 3. Data transform UniCodeToBig5(S11, S1, sizeof(S1)-2); // bug here // 4. Client send datas to Server sendto(CSock, S1, strlen(S1), 0, (sockaddr *)&CAddr, Len); } void CUDPchatDlg::OnEnChangeEdit1() { // TODO: 如果這是 RICHEDIT 控制項,控制項將不會 // 傳送此告知,除非您覆寫 CDialogEx::OnInitDialog() // 函式和呼叫 CRichEditCtrl().SetEventMask() // 讓具有 ENM_CHANGE 旗標 ORed 加入遮罩。 // TODO: 在此加入控制項告知處理常式程式碼 } LRESULT CUDPchatDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { int i, len=sizeof(sockaddr); char S1[2000], S2[2000]; // One-Byte Character wchar_t S11[200]; // Two-Bytes UninCode String sockaddr Addr; sockaddr_in Addr1; // UDP Server: Receive Message from Client if (message == SEVENT) { i = recvfrom(wParam, S1, sizeof(S1) - 1, 0, (sockaddr *)&Addr1, &len); if (i > 0) { // end of string S1[i] = 0; sprintf_s(S2, sizeof(S2) - 1, "(%d,%d,%d,%d) say: %s\r\n", (Addr1.sin_addr.s_addr >> 0) & 0xFF, (Addr1.sin_addr.s_addr >> 8) & 0xFF, (Addr1.sin_addr.s_addr >> 16) & 0xFF, (Addr1.sin_addr.s_addr >> 24) & 0xFF, S1, sizeof(S1)-1); // transform Big5ToUniCode(S2, S11, strlen(S2)+1); // display string UpdateData(1); m_Edit1 += S11; m_Edit1 += L"\r\n"; UpdateData(0); // auto scroll m_Edit11.LineScroll(m_Edit11.GetLineCount()); } } return CDialogEx::WindowProc(message, wParam, lParam); }
[ "chia56028@gmail.com" ]
chia56028@gmail.com
deca3021072a6528aa0279ff57c9e48947c85c22
88b991fc54265c13f62710393169839676f2ffd2
/Test/JobTest/MultiProcessCalc.cpp
5079ef28070c48fae13ee71e1147102f31a44393
[]
no_license
RATime360/Code
4b51c6af12e73bd77becf44067aee8d0c97101fe
6694bfd7c71d0247911d02ab6e0c3c41e3479900
refs/heads/master
2023-01-14T10:01:53.356289
2020-11-18T06:41:46
2020-11-18T06:41:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
370
cpp
#include "MultiProcessCalc.h" bool MultiProcessCalc::DoJob() { QString params = QString::fromLatin1(CurrentJobData()); int circles = params.toInt(); for (int i = CurrentJobIterFrom(); i <= CurrentJobIterTo(); i++) { mCalc.CalcCircles(i, circles); } return true; } MultiProcessCalc::MultiProcessCalc(const Db& _Db) : JobImp(_Db) { }
[ "DevilCCCP@gmail.com" ]
DevilCCCP@gmail.com
e37d6ddda02eb1b3ec843b8a7547ae7b22aaab4a
253b1380a3c2749668e199069f858f1a5a0f8773
/src/vulpecula/responders/StarResp.h
d86c730f35982ac5d4926032771a6923daf6056f
[]
no_license
Shanghai-/3DGameEnginesFinal
c0396f5fd1c56ddf89208be84d400c28e8bd153b
266038deb7782e16023d957a5b68c2cab6356593
refs/heads/master
2022-01-10T18:40:05.294450
2019-05-11T22:52:42
2019-05-11T22:52:42
175,902,211
0
0
null
null
null
null
UTF-8
C++
false
false
568
h
#ifndef STARRESP_H #define STARRESP_H #include "engine/components/responders/CollisionResponse.h" #include "engine/components/CAudioSource.h" class StarResp : public CollisionResponse { public: StarResp(std::shared_ptr<GameObject> star, std::shared_ptr<GameObject> zone, GameWorld *gw); ~StarResp(); void onCollide(std::shared_ptr<GameObject> other); void onCollisionEnd(std::shared_ptr<GameObject> other); private: std::shared_ptr<GameObject> m_star, m_zone; GameWorld *m_gw; }; #endif // STARRESP_H
[ "bwalsh1@cs.brown.edu" ]
bwalsh1@cs.brown.edu
83df9869c32d70f85533e38f9f6a03c0866a6097
348e80a3b8c0c0a16fc36ef2d1034eac06da97aa
/PeraConfigTool/BCGCBPro/BCGPFullScreenImpl.h
d58a384c40a097a50c86a5c7338d126ac5600eba
[]
no_license
wyrover/WorkPlatForm
0e2c9127ccb6828857532eb11f96be3efc061fe9
f14a8cdd2bc3772ea4bd37a0381f5f8305a0a2c2
refs/heads/master
2021-01-16T21:16:13.672343
2016-01-17T08:59:01
2016-01-17T08:59:01
62,207,103
0
1
null
2016-06-29T07:56:29
2016-06-29T07:56:28
null
UTF-8
C++
false
false
2,132
h
//******************************************************************************* // COPYRIGHT NOTES // --------------- // This is a part of BCGControlBar Library Professional Edition // Copyright (C) 1998-2011 BCGSoft Ltd. // All rights reserved. // // This source code can be used, distributed or modified // only under terms and conditions // of the accompanying license agreement. //******************************************************************************* // // BCGPFullScreenImpl.h: interface for the BCGPFullScreenImpl class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_BCGPFULLSCREENIMPL_H__6FBF448A_6F12_4008_97C1_6682B67ECE10__INCLUDED_) #define AFX_BCGPFULLSCREENIMPL_H__6FBF448A_6F12_4008_97C1_6682B67ECE10__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CBCGPToolBar; class CBCGPFrameImpl; #include "BCGCBPro.h" class BCGCBPRODLLEXPORT CBCGPFullScreenImpl { friend class CBCGPFrameImpl; public: CBCGPFullScreenImpl(CBCGPFrameImpl* pFrameImpl); virtual ~CBCGPFullScreenImpl(); void ShowFullScreen(); void ShowFullScreen(CFrameWnd* pFrame); void RestoreState(CFrameWnd* pFrame); CRect GetFullScreenRect() const { return m_rectFullScreenWindow; } BOOL IsFullScreen() const { return m_bFullScreen; } void EnableMainMenu(BOOL bShow = TRUE) { m_bShowMenu = bShow; } void SetFullScreenID(UINT uiFullScreenID) { m_uiFullScreenID = uiFullScreenID; } void EnableTabsArea(BOOL bShowTabs) { m_bTabsArea = bShowTabs; } CBCGPToolBar* GetFullScreenBar () const { return m_pwndFullScreenBar; } void OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI); protected: CRect m_rectFullScreenWindow; CBCGPToolBar* m_pwndFullScreenBar; BOOL m_bFullScreen; BOOL m_bShowMenu; BOOL m_bMenuBarWasVisible; CRect m_rectFramePrev; CBCGPFrameImpl* m_pImpl; UINT m_uiFullScreenID; BOOL m_bTabsArea; CString m_strRegSection; protected: void UnDockAndHideControlBars(CFrameWnd* pFrame); }; #endif // !defined(AFX_BCGPFULLSCREENIMPL_H__6FBF448A_6F12_4008_97C1_6682B67ECE10__INCLUDED_)
[ "cugxiangzhenwei@sina.cn" ]
cugxiangzhenwei@sina.cn
54c17901b0cf6dc484741c09e4587c64a7303ba0
e108376881e3e9e51b5d03aed334b01ebce87a9e
/gen/Jd2ya_VConstraint_Swing.hh
ae5184db873b5772c87604def993d5f44b5ab006
[]
no_license
Emungai/ThreeLinkRobot_Frost
f217c0d791c1989f277e91e1fceede9a2d8efea9
89f745627ed2e2f2658695636a6fdf2cdcc3469a
refs/heads/master
2023-01-03T21:12:51.160008
2022-12-22T04:18:45
2022-12-22T04:18:45
99,365,552
0
0
null
null
null
null
UTF-8
C++
false
false
951
hh
/* * Automatically Generated from Mathematica. * Wed 2 Aug 2017 16:38:24 GMT-04:00 */ #ifndef JD2YA_VCONSTRAINT_SWING_HH #define JD2YA_VCONSTRAINT_SWING_HH #ifdef MATLAB_MEX_FILE // No need for external definitions #else // MATLAB_MEX_FILE #include "math2mat.hpp" #include "mdefs.hpp" namespace SymFunction { void Jd2ya_VConstraint_Swing_raw(double *p_output1, const double *var1,const double *var2); inline void Jd2ya_VConstraint_Swing(Eigen::MatrixXd &p_output1, const Eigen::VectorXd &var1,const Eigen::VectorXd &var2) { // Check // - Inputs assert_size_matrix(var1, 5, 1); assert_size_matrix(var2, 5, 1); // - Outputs assert_size_matrix(p_output1, 2, 10); // set zero the matrix p_output1.setZero(); // Call Subroutine with raw data Jd2ya_VConstraint_Swing_raw(p_output1.data(), var1.data(),var2.data()); } } #endif // MATLAB_MEX_FILE #endif // JD2YA_VCONSTRAINT_SWING_HH
[ "mungam@umich.edu" ]
mungam@umich.edu
1ce7b0f947e5eb19d492f818f9fc19e92c9b9631
99992a66fd0256ca383579adf5ffa962eb7b8052
/CppTestApp/tagtype.cpp
e1cd5ddf0e3229853240c6a9b6ba92d01b24647d
[]
no_license
zizi0308/StudyCplusplus21
ffe81cbb8a0194a417ec0d3c3f98e58b30f8cbf6
fa572f83a4eea9fdc5911d1e9b95a9986fbf6979
refs/heads/main
2023-07-05T00:59:06.207610
2021-08-10T11:59:41
2021-08-10T11:59:41
371,536,638
0
0
null
null
null
null
UHC
C++
false
false
371
cpp
#include <stdio.h> int main() { enum origin {EAST, WEST, SOUTH, NORTH}; enum origin mark = WEST; printf("%d방향\n", mark); struct SHuman // typedef 생략가능 { char name[12]; int age; double height; }; // 뒤에 태그명 생략가능 struct SHuman kim = { "김상형", 29, 181.4 }; printf("이름 = %s, 나이 = %d\n", kim.name, kim.age); }
[ "whgmlwl222@naver.com" ]
whgmlwl222@naver.com
6c84f380c3ba4c0b3c23b4f5bfc7eaf1a00a3b99
fd2216a22c4974a915eefce2a4d851c4cbaf128c
/src/src.ino
477932193ed0a4ffaefdc82eb0e76fd21c030adc
[ "MIT" ]
permissive
tolysz/iec62056-mqtt
f9380d76911c543e848f75ff7147cb9737212867
ea4d1a32bd2ce1ca5ab42d32e7fdd30422eefcc1
refs/heads/master
2023-04-02T17:07:22.778479
2021-04-03T22:22:21
2021-04-03T22:22:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
45
ino
// Dummy file to allow opening in Arduino IDE
[ "piortwjo@gmail.com" ]
piortwjo@gmail.com
bbbf095fb93e87ee4e3eaf0686cd1a61a6cce940
e3c03bb58f899934b555f75eec50ca3a93bd2227
/below2.1/timebomb.cc
d7f12b3b2312ce1b80f6b8ed4e48d1877d3374c2
[ "Apache-2.0" ]
permissive
notwatermango/Kattis-Problem-Archive
62ab0ab85abc2d86d8b3c96ca6cf652eb9242c0a
bce1929d654b1bceb104f96d68c74349273dd1ff
refs/heads/main
2023-07-30T09:52:55.535275
2021-09-22T13:24:03
2021-09-22T13:24:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,388
cc
#include <iostream> using namespace std; int main(){ string arr[5]; for (int i = 0; i < 5; i++) { getline(cin,arr[i]); } int digits = (arr[0].length()+1)/4; string res = ""; bool sad = false; for (int j = 0; j < arr[0].length(); j+=4) { if(arr[0][j] == '*' && arr[0][j+1] == '*' && arr[0][j+2] == '*' && arr[1][j] == '*' && arr[1][j+1] == ' ' && arr[1][j+2] == '*' && arr[2][j] == '*' && arr[2][j+1] == ' ' && arr[2][j+2] == '*' && arr[3][j] == '*' && arr[3][j+1] == ' ' && arr[3][j+2] == '*' && arr[4][j] == '*' && arr[4][j+1] == '*' && arr[4][j+2] == '*' ){ res+="0"; } else if(arr[0][j] == ' ' && arr[0][j+1] == ' ' && arr[0][j+2] == '*' && arr[1][j] == ' ' && arr[1][j+1] == ' ' && arr[1][j+2] == '*' && arr[2][j] == ' ' && arr[2][j+1] == ' ' && arr[2][j+2] == '*' && arr[3][j] == ' ' && arr[3][j+1] == ' ' && arr[3][j+2] == '*' && arr[4][j] == ' ' && arr[4][j+1] == ' ' && arr[4][j+2] == '*' ){ res+="1"; } else if(arr[0][j] == '*' && arr[0][j+1] == '*' && arr[0][j+2] == '*' && arr[1][j] == ' ' && arr[1][j+1] == ' ' && arr[1][j+2] == '*' && arr[2][j] == '*' && arr[2][j+1] == '*' && arr[2][j+2] == '*' && arr[3][j] == '*' && arr[3][j+1] == ' ' && arr[3][j+2] == ' ' && arr[4][j] == '*' && arr[4][j+1] == '*' && arr[4][j+2] == '*' ){ res+="2"; } else if(arr[0][j] == '*' && arr[0][j+1] == '*' && arr[0][j+2] == '*' && arr[1][j] == ' ' && arr[1][j+1] == ' ' && arr[1][j+2] == '*' && arr[2][j] == '*' && arr[2][j+1] == '*' && arr[2][j+2] == '*' && arr[3][j] == ' ' && arr[3][j+1] == ' ' && arr[3][j+2] == '*' && arr[4][j] == '*' && arr[4][j+1] == '*' && arr[4][j+2] == '*' ){ res+="3"; } else if(arr[0][j] == '*' && arr[0][j+1] == ' ' && arr[0][j+2] == '*' && arr[1][j] == '*' && arr[1][j+1] == ' ' && arr[1][j+2] == '*' && arr[2][j] == '*' && arr[2][j+1] == '*' && arr[2][j+2] == '*' && arr[3][j] == ' ' && arr[3][j+1] == ' ' && arr[3][j+2] == '*' && arr[4][j] == ' ' && arr[4][j+1] == ' ' && arr[4][j+2] == '*' ){ res+="4"; } else if(arr[0][j] == '*' && arr[0][j+1] == '*' && arr[0][j+2] == '*' && arr[1][j] == '*' && arr[1][j+1] == ' ' && arr[1][j+2] == ' ' && arr[2][j] == '*' && arr[2][j+1] == '*' && arr[2][j+2] == '*' && arr[3][j] == ' ' && arr[3][j+1] == ' ' && arr[3][j+2] == '*' && arr[4][j] == '*' && arr[4][j+1] == '*' && arr[4][j+2] == '*' ){ res+="5"; } else if(arr[0][j] == '*' && arr[0][j+1] == '*' && arr[0][j+2] == '*' && arr[1][j] == '*' && arr[1][j+1] == ' ' && arr[1][j+2] == ' ' && arr[2][j] == '*' && arr[2][j+1] == '*' && arr[2][j+2] == '*' && arr[3][j] == '*' && arr[3][j+1] == ' ' && arr[3][j+2] == '*' && arr[4][j] == '*' && arr[4][j+1] == '*' && arr[4][j+2] == '*' ){ res+="6"; } else if(arr[0][j] == '*' && arr[0][j+1] == '*' && arr[0][j+2] == '*' && arr[1][j] == ' ' && arr[1][j+1] == ' ' && arr[1][j+2] == '*' && arr[2][j] == ' ' && arr[2][j+1] == ' ' && arr[2][j+2] == '*' && arr[3][j] == ' ' && arr[3][j+1] == ' ' && arr[3][j+2] == '*' && arr[4][j] == ' ' && arr[4][j+1] == ' ' && arr[4][j+2] == '*' ){ res+="7"; } else if(arr[0][j] == '*' && arr[0][j+1] == '*' && arr[0][j+2] == '*' && arr[1][j] == '*' && arr[1][j+1] == ' ' && arr[1][j+2] == '*' && arr[2][j] == '*' && arr[2][j+1] == '*' && arr[2][j+2] == '*' && arr[3][j] == '*' && arr[3][j+1] == ' ' && arr[3][j+2] == '*' && arr[4][j] == '*' && arr[4][j+1] == '*' && arr[4][j+2] == '*' ){ res+="8"; } else if(arr[0][j] == '*' && arr[0][j+1] == '*' && arr[0][j+2] == '*' && arr[1][j] == '*' && arr[1][j+1] == ' ' && arr[1][j+2] == '*' && arr[2][j] == '*' && arr[2][j+1] == '*' && arr[2][j+2] == '*' && arr[3][j] == ' ' && arr[3][j+1] == ' ' && arr[3][j+2] == '*' && arr[4][j] == '*' && arr[4][j+1] == '*' && arr[4][j+2] == '*' ){ res+="9"; } else{ sad = true; } } if(stoi(res)%6!=0){ sad = true; } if(sad){ cout<<"BOOM!!"; } else{ cout<<"BEER!!"; } return 0; }
[ "67574872+danzel-py@users.noreply.github.com" ]
67574872+danzel-py@users.noreply.github.com
1261b66ae5da6f9c95c44f7a6466d898207885e2
08cd4570572284811cca31491e6863adff32a6f5
/Programs/MIdsPractice/main.cpp
9d17f0ccf8c215b8c696c02e5818c942cff56ca8
[]
no_license
smusman/CSE-102_Computer-Programming
f8aff9d627ac33a96fa4082e10c650d1e0a1df2a
dd5ec695035a77646d02f8e5099e690bba324547
refs/heads/master
2020-05-09T17:41:21.597008
2019-07-28T18:12:35
2019-07-28T18:12:35
181,319,528
0
0
null
null
null
null
UTF-8
C++
false
false
729
cpp
#include <iostream> using namespace std; int main() { int row,num,i,j, k; cout<<"Please Enter Number of Stars in first Row> "; loop: cin>>num; if (num%2==0 || num<0) { cout<<"Invalid Entry, enter an odd positive number> "; goto loop; } else{ row=(num+1)/2; for(i=1; i<=row; i++) { for(j=1; j<=i; j++) { cout<<" "; } for (k=num; k>=1; k--) { cout<<"*"; } num=num-2; cout<<endl; } } return 0; } //row=number of rows //i=specific row //num=num of stars in first row //j=spaces before pattern //k=number of stars in a row
[ "noreply@github.com" ]
smusman.noreply@github.com
567b469336ceb0deab8a33cecefb3e2f91c0492a
d67a1704b15d2d6646fd35426fef4b09d8b39651
/problem3/NOMAD/nomad.cpp
8ccd2ab371561911d499915c40fde0d1b144d93c
[]
no_license
shubhangid/mop
3cce679d53093db3aa15078aea772cc4b51f8abe
81ee90dc72fffaf98f0cf1e222a6c8bf8f1d84eb
refs/heads/master
2021-01-10T21:43:23.648874
2013-10-22T14:06:16
2013-10-22T14:06:16
11,132,007
0
1
null
null
null
null
UTF-8
C++
false
false
3,599
cpp
/*---------------------------------*/ /* FORTRAN and the NOMAD library */ /* (see readme.txt) */ /*---------------------------------*/ #include "nomad.hpp" using namespace std; using namespace NOMAD; extern "C" { void nomad_ ( int * n , int * m , double * x , double * lb , double * ub , int * max_bbe , int * display_degree ); void bb_ ( double x[20] , double fx[1] ); } /*----------------------------------------*/ /* The problem: the evaluation is made */ /* by calling a FORTRAN routine */ /*----------------------------------------*/ class My_Evaluator : public Evaluator { public: My_Evaluator ( const Parameters & p ) : Evaluator ( p ) {} ~My_Evaluator ( void ) {} bool eval_x ( Eval_Point & x , const Double & h_max , bool & count_eval ) const { int n = x.size(); int m = x.get_bb_outputs().size(); int i; double * xx = new double [n]; double * fx = new double [m]; for ( i = 0 ; i < x.size() ; ++i ) xx[i] = x[i].value(); // call the FORTRAN routine: bb_ ( xx , fx ); for ( i = 0 ; i < m ; ++i ) x.set_bb_output ( i , fx[i] ); count_eval = true; // count a black-box evaluation return true; // the evaluation succeeded } }; /*---------------------------------------*/ /* this routine launches NOMAD and can */ /* be called from a FORTRAN program */ /*---------------------------------------*/ void nomad_ ( int * n , // # of variables int * m , // # of outputs (obj + m-1 constraints) double * x , // starting point (IN) / solution (OUT) double * lb , // lower bounds for each variable double * ub , // upper bounds int * max_bbe , // max # of evaluations (-1: not considered) int * display_degree ) { // display_degree (0-4; 0: no display) // display: Display out ( std::cout ); out.precision ( DISPLAY_PRECISION_STD ); try { int i; // parameters creation: Parameters p ( out ); p.set_DIMENSION (*n); // number of variables vector<bb_output_type> bbot (*m); // definition of output types: bbot[0] = OBJ; // first output : objective value to minimize for ( i = 1 ; i < *m ; ++i ) // other outputs: constraints cj <= 0 bbot[i] = PB; p.set_BB_OUTPUT_TYPE ( bbot ); // starting point and bounds: Point px0 ( *n ); Point plb ( *n ); Point pub ( *n ); for ( i = 0 ; i < *n ; ++i ) { px0[i] = x [i]; //if ( lb[i] > -1e20 ) plb[i] = lb[i]; //if ( ub[i] < 1e20 ) pub[i] = ub[i]; } p.set_X0 ( px0 ); p.set_LOWER_BOUND ( plb ); p.set_UPPER_BOUND ( pub ); // p.set_LH_SEARCH( 200,20 ); // maximum number of black-box evaluations: if ( *max_bbe > 0 ) p.set_MAX_BB_EVAL ( *max_bbe ); // display degree: p.set_DISPLAY_DEGREE ( *display_degree ); // parameters validation: p.check(); // custom evaluator creation: My_Evaluator ev ( p ); // algorithm creation and execution: Mads mads ( p , &ev ); mads.run(); // get the solution: const Eval_Point * bf = mads.get_best_feasible(); if ( bf ) for ( i = 0 ; i < *n ; ++i ) x[i] = (*bf)[i].value(); } catch ( exception & e ) { cerr << "\nNOMAD has been interrupted (" << e.what() << ")\n\n"; } }
[ "shubhangi@shubhangi-ThinkPad-Edge" ]
shubhangi@shubhangi-ThinkPad-Edge
b02efbe1f03e5ed4b9afb6d9081c619334d3ebc0
3674ff26e1fe0cdb552e8ced32a8d2c7e751d6e4
/algo/minmax1.cpp
f4e88194d848cd7f7266906e08b74c75f0d4403f
[]
no_license
liyustar/Cpp-Standard-Library-Tutorial
f7232a2a86e8793de2b198763a53da7e8166bdf9
83ecb86d23068e6c41fcf8b2703e8c9f58897a8f
refs/heads/master
2021-01-15T23:07:50.734839
2012-09-21T18:55:58
2012-09-21T18:55:58
5,553,826
0
1
null
2020-09-30T20:52:51
2012-08-25T18:19:56
C++
UTF-8
C++
false
false
1,056
cpp
#include <cstdlib> #include "algostuff.hpp" using namespace std; bool absLess (int elem1, int elem2) { return abs(elem1) < abs(elem2); } int main() { deque<int> coll; INSERT_ELEMENTS(coll,2,6); INSERT_ELEMENTS(coll,-3,6); PRINT_ELEMENTS(coll); // process and print minimum and maximum cout << "minimum: " << *min_element(coll.cbegin(), coll.cend()) << endl; cout << "Maximum: " << *max_element(coll.cbegin(), coll.cend()) << endl; // print min and max and their distance using minmax_element() auto mm = minmax_element (coll.cbegin(), coll.cend()); cout << "min: " << *(mm.first) << endl; // print minimum cout << "max: " << *(mm.second) << endl; // print maximum cout << "distance: " << distance(mm.first, mm.second) << endl; // process and print minimum and maximum of absolute values cout << "minimum of absolute values: " << *min_element(coll.cbegin(), coll.cend(), absLess) << endl; cout << "maximum of absolute values: " << *max_element(coll.cbegin(), coll.cend(), absLess) << endl; }
[ "liyustar@gmail.com" ]
liyustar@gmail.com
de088f0ece5ef3512860ad3b4d9847e74f477bab
d932716790743d0e2ae7db7218fa6d24f9bc85dc
/mojo/public/cpp/bindings/associated_binding.h
bb3c40506363ee0b404f12007ecf80615cb22b1d
[ "BSD-3-Clause" ]
permissive
vade/chromium
c43f0c92fdede38e8a9b858abd4fd7c2bb679d9c
35c8a0b1c1a76210ae000a946a17d8979b7d81eb
refs/heads/Syphon
2023-02-28T00:10:11.977720
2017-05-24T16:38:21
2017-05-24T16:38:21
80,049,719
19
3
null
2017-05-24T19:05:34
2017-01-25T19:31:53
null
UTF-8
C++
false
false
6,032
h
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MOJO_PUBLIC_CPP_BINDINGS_ASSOCIATED_BINDING_H_ #define MOJO_PUBLIC_CPP_BINDINGS_ASSOCIATED_BINDING_H_ #include <memory> #include <string> #include <utility> #include "base/bind.h" #include "base/callback.h" #include "base/logging.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "mojo/public/cpp/bindings/associated_interface_ptr_info.h" #include "mojo/public/cpp/bindings/associated_interface_request.h" #include "mojo/public/cpp/bindings/bindings_export.h" #include "mojo/public/cpp/bindings/connection_error_callback.h" #include "mojo/public/cpp/bindings/interface_endpoint_client.h" #include "mojo/public/cpp/bindings/raw_ptr_impl_ref_traits.h" #include "mojo/public/cpp/bindings/scoped_interface_endpoint_handle.h" namespace mojo { class MessageReceiver; // Base class used to factor out code in AssociatedBinding<T> expansions, in // particular for Bind(). class MOJO_CPP_BINDINGS_EXPORT AssociatedBindingBase { public: AssociatedBindingBase(); ~AssociatedBindingBase(); // Adds a message filter to be notified of each incoming message before // dispatch. If a filter returns |false| from Accept(), the message is not // dispatched and the pipe is closed. Filters cannot be removed. void AddFilter(std::unique_ptr<MessageReceiver> filter); // Closes the associated interface. Puts this object into a state where it can // be rebound. void Close(); // Similar to the method above, but also specifies a disconnect reason. void CloseWithReason(uint32_t custom_reason, const std::string& description); // Sets an error handler that will be called if a connection error occurs. // // This method may only be called after this AssociatedBinding has been bound // to a message pipe. The error handler will be reset when this // AssociatedBinding is unbound or closed. void set_connection_error_handler(const base::Closure& error_handler); void set_connection_error_with_reason_handler( const ConnectionErrorWithReasonCallback& error_handler); // Indicates whether the associated binding has been completed. bool is_bound() const { return !!endpoint_client_; } // Sends a message on the underlying message pipe and runs the current // message loop until its response is received. This can be used in tests to // verify that no message was sent on a message pipe in response to some // stimulus. void FlushForTesting(); protected: void BindImpl(ScopedInterfaceEndpointHandle handle, MessageReceiverWithResponderStatus* receiver, std::unique_ptr<MessageReceiver> payload_validator, bool expect_sync_requests, scoped_refptr<base::SingleThreadTaskRunner> runner, uint32_t interface_version); std::unique_ptr<InterfaceEndpointClient> endpoint_client_; }; // Represents the implementation side of an associated interface. It is similar // to Binding, except that it doesn't own a message pipe handle. // // When you bind this class to a request, optionally you can specify a // base::SingleThreadTaskRunner. This task runner must belong to the same // thread. It will be used to dispatch incoming method calls and connection // error notification. It is useful when you attach multiple task runners to a // single thread for the purposes of task scheduling. Please note that incoming // synchrounous method calls may not be run from this task runner, when they // reenter outgoing synchrounous calls on the same thread. template <typename Interface, typename ImplRefTraits = RawPtrImplRefTraits<Interface>> class AssociatedBinding : public AssociatedBindingBase { public: using ImplPointerType = typename ImplRefTraits::PointerType; // Constructs an incomplete associated binding that will use the // implementation |impl|. It may be completed with a subsequent call to the // |Bind| method. explicit AssociatedBinding(ImplPointerType impl) { stub_.set_sink(std::move(impl)); } // Constructs a completed associated binding of |impl|. |impl| must outlive // the binding. AssociatedBinding(ImplPointerType impl, AssociatedInterfaceRequest<Interface> request, scoped_refptr<base::SingleThreadTaskRunner> runner = base::ThreadTaskRunnerHandle::Get()) : AssociatedBinding(std::move(impl)) { Bind(std::move(request), std::move(runner)); } ~AssociatedBinding() {} // Sets up this object as the implementation side of an associated interface. void Bind(AssociatedInterfaceRequest<Interface> request, scoped_refptr<base::SingleThreadTaskRunner> runner = base::ThreadTaskRunnerHandle::Get()) { BindImpl(request.PassHandle(), &stub_, base::WrapUnique(new typename Interface::RequestValidator_()), Interface::HasSyncMethods_, std::move(runner), Interface::Version_); } // Unbinds and returns the associated interface request so it can be // used in another context, such as on another thread or with a different // implementation. Puts this object into a state where it can be rebound. AssociatedInterfaceRequest<Interface> Unbind() { DCHECK(endpoint_client_); AssociatedInterfaceRequest<Interface> request( endpoint_client_->PassHandle()); endpoint_client_.reset(); return request; } // Returns the interface implementation that was previously specified. Interface* impl() { return ImplRefTraits::GetRawPointer(&stub_.sink()); } private: typename Interface::template Stub_<ImplRefTraits> stub_; DISALLOW_COPY_AND_ASSIGN(AssociatedBinding); }; } // namespace mojo #endif // MOJO_PUBLIC_CPP_BINDINGS_ASSOCIATED_BINDING_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
1ee5cca6ea3f820c70ab86f66b25c31d16c4863f
8a87f5b889a9ce7d81421515f06d9c9cbf6ce64a
/3rdParty/boost/1.78.0/boost/preprocessor/iteration/detail/iter/limits/reverse2_256.hpp
521bd249beaa86098311c17ec42355a9fd8db048
[ "Apache-2.0", "BSD-3-Clause", "ICU", "Zlib", "GPL-1.0-or-later", "OpenSSL", "ISC", "LicenseRef-scancode-gutenberg-2020", "MIT", "GPL-2.0-only", "CC0-1.0", "BSL-1.0", "LicenseRef-scancode-autoconf-simple-exception", "LicenseRef-scancode-pcre", "Bison-exception-2.2", "LicenseRef-scancode...
permissive
arangodb/arangodb
0980625e76c56a2449d90dcb8d8f2c485e28a83b
43c40535cee37fc7349a21793dc33b1833735af5
refs/heads/devel
2023-08-31T09:34:47.451950
2023-08-31T07:25:02
2023-08-31T07:25:02
2,649,214
13,385
982
Apache-2.0
2023-09-14T17:02:16
2011-10-26T06:42:00
C++
UTF-8
C++
false
false
48,331
hpp
# /* ************************************************************************** # * * # * (C) Copyright Paul Mensonides 2002. # * 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) # * * # ************************************************************************** */ # # /* See http://www.boost.org for most recent version. */ # # if BOOST_PP_ITERATION_FINISH_2 <= 256 && BOOST_PP_ITERATION_START_2 >= 256 # define BOOST_PP_ITERATION_2 256 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 255 && BOOST_PP_ITERATION_START_2 >= 255 # define BOOST_PP_ITERATION_2 255 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 254 && BOOST_PP_ITERATION_START_2 >= 254 # define BOOST_PP_ITERATION_2 254 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 253 && BOOST_PP_ITERATION_START_2 >= 253 # define BOOST_PP_ITERATION_2 253 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 252 && BOOST_PP_ITERATION_START_2 >= 252 # define BOOST_PP_ITERATION_2 252 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 251 && BOOST_PP_ITERATION_START_2 >= 251 # define BOOST_PP_ITERATION_2 251 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 250 && BOOST_PP_ITERATION_START_2 >= 250 # define BOOST_PP_ITERATION_2 250 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 249 && BOOST_PP_ITERATION_START_2 >= 249 # define BOOST_PP_ITERATION_2 249 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 248 && BOOST_PP_ITERATION_START_2 >= 248 # define BOOST_PP_ITERATION_2 248 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 247 && BOOST_PP_ITERATION_START_2 >= 247 # define BOOST_PP_ITERATION_2 247 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 246 && BOOST_PP_ITERATION_START_2 >= 246 # define BOOST_PP_ITERATION_2 246 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 245 && BOOST_PP_ITERATION_START_2 >= 245 # define BOOST_PP_ITERATION_2 245 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 244 && BOOST_PP_ITERATION_START_2 >= 244 # define BOOST_PP_ITERATION_2 244 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 243 && BOOST_PP_ITERATION_START_2 >= 243 # define BOOST_PP_ITERATION_2 243 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 242 && BOOST_PP_ITERATION_START_2 >= 242 # define BOOST_PP_ITERATION_2 242 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 241 && BOOST_PP_ITERATION_START_2 >= 241 # define BOOST_PP_ITERATION_2 241 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 240 && BOOST_PP_ITERATION_START_2 >= 240 # define BOOST_PP_ITERATION_2 240 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 239 && BOOST_PP_ITERATION_START_2 >= 239 # define BOOST_PP_ITERATION_2 239 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 238 && BOOST_PP_ITERATION_START_2 >= 238 # define BOOST_PP_ITERATION_2 238 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 237 && BOOST_PP_ITERATION_START_2 >= 237 # define BOOST_PP_ITERATION_2 237 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 236 && BOOST_PP_ITERATION_START_2 >= 236 # define BOOST_PP_ITERATION_2 236 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 235 && BOOST_PP_ITERATION_START_2 >= 235 # define BOOST_PP_ITERATION_2 235 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 234 && BOOST_PP_ITERATION_START_2 >= 234 # define BOOST_PP_ITERATION_2 234 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 233 && BOOST_PP_ITERATION_START_2 >= 233 # define BOOST_PP_ITERATION_2 233 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 232 && BOOST_PP_ITERATION_START_2 >= 232 # define BOOST_PP_ITERATION_2 232 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 231 && BOOST_PP_ITERATION_START_2 >= 231 # define BOOST_PP_ITERATION_2 231 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 230 && BOOST_PP_ITERATION_START_2 >= 230 # define BOOST_PP_ITERATION_2 230 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 229 && BOOST_PP_ITERATION_START_2 >= 229 # define BOOST_PP_ITERATION_2 229 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 228 && BOOST_PP_ITERATION_START_2 >= 228 # define BOOST_PP_ITERATION_2 228 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 227 && BOOST_PP_ITERATION_START_2 >= 227 # define BOOST_PP_ITERATION_2 227 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 226 && BOOST_PP_ITERATION_START_2 >= 226 # define BOOST_PP_ITERATION_2 226 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 225 && BOOST_PP_ITERATION_START_2 >= 225 # define BOOST_PP_ITERATION_2 225 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 224 && BOOST_PP_ITERATION_START_2 >= 224 # define BOOST_PP_ITERATION_2 224 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 223 && BOOST_PP_ITERATION_START_2 >= 223 # define BOOST_PP_ITERATION_2 223 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 222 && BOOST_PP_ITERATION_START_2 >= 222 # define BOOST_PP_ITERATION_2 222 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 221 && BOOST_PP_ITERATION_START_2 >= 221 # define BOOST_PP_ITERATION_2 221 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 220 && BOOST_PP_ITERATION_START_2 >= 220 # define BOOST_PP_ITERATION_2 220 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 219 && BOOST_PP_ITERATION_START_2 >= 219 # define BOOST_PP_ITERATION_2 219 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 218 && BOOST_PP_ITERATION_START_2 >= 218 # define BOOST_PP_ITERATION_2 218 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 217 && BOOST_PP_ITERATION_START_2 >= 217 # define BOOST_PP_ITERATION_2 217 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 216 && BOOST_PP_ITERATION_START_2 >= 216 # define BOOST_PP_ITERATION_2 216 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 215 && BOOST_PP_ITERATION_START_2 >= 215 # define BOOST_PP_ITERATION_2 215 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 214 && BOOST_PP_ITERATION_START_2 >= 214 # define BOOST_PP_ITERATION_2 214 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 213 && BOOST_PP_ITERATION_START_2 >= 213 # define BOOST_PP_ITERATION_2 213 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 212 && BOOST_PP_ITERATION_START_2 >= 212 # define BOOST_PP_ITERATION_2 212 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 211 && BOOST_PP_ITERATION_START_2 >= 211 # define BOOST_PP_ITERATION_2 211 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 210 && BOOST_PP_ITERATION_START_2 >= 210 # define BOOST_PP_ITERATION_2 210 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 209 && BOOST_PP_ITERATION_START_2 >= 209 # define BOOST_PP_ITERATION_2 209 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 208 && BOOST_PP_ITERATION_START_2 >= 208 # define BOOST_PP_ITERATION_2 208 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 207 && BOOST_PP_ITERATION_START_2 >= 207 # define BOOST_PP_ITERATION_2 207 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 206 && BOOST_PP_ITERATION_START_2 >= 206 # define BOOST_PP_ITERATION_2 206 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 205 && BOOST_PP_ITERATION_START_2 >= 205 # define BOOST_PP_ITERATION_2 205 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 204 && BOOST_PP_ITERATION_START_2 >= 204 # define BOOST_PP_ITERATION_2 204 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 203 && BOOST_PP_ITERATION_START_2 >= 203 # define BOOST_PP_ITERATION_2 203 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 202 && BOOST_PP_ITERATION_START_2 >= 202 # define BOOST_PP_ITERATION_2 202 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 201 && BOOST_PP_ITERATION_START_2 >= 201 # define BOOST_PP_ITERATION_2 201 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 200 && BOOST_PP_ITERATION_START_2 >= 200 # define BOOST_PP_ITERATION_2 200 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 199 && BOOST_PP_ITERATION_START_2 >= 199 # define BOOST_PP_ITERATION_2 199 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 198 && BOOST_PP_ITERATION_START_2 >= 198 # define BOOST_PP_ITERATION_2 198 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 197 && BOOST_PP_ITERATION_START_2 >= 197 # define BOOST_PP_ITERATION_2 197 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 196 && BOOST_PP_ITERATION_START_2 >= 196 # define BOOST_PP_ITERATION_2 196 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 195 && BOOST_PP_ITERATION_START_2 >= 195 # define BOOST_PP_ITERATION_2 195 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 194 && BOOST_PP_ITERATION_START_2 >= 194 # define BOOST_PP_ITERATION_2 194 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 193 && BOOST_PP_ITERATION_START_2 >= 193 # define BOOST_PP_ITERATION_2 193 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 192 && BOOST_PP_ITERATION_START_2 >= 192 # define BOOST_PP_ITERATION_2 192 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 191 && BOOST_PP_ITERATION_START_2 >= 191 # define BOOST_PP_ITERATION_2 191 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 190 && BOOST_PP_ITERATION_START_2 >= 190 # define BOOST_PP_ITERATION_2 190 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 189 && BOOST_PP_ITERATION_START_2 >= 189 # define BOOST_PP_ITERATION_2 189 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 188 && BOOST_PP_ITERATION_START_2 >= 188 # define BOOST_PP_ITERATION_2 188 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 187 && BOOST_PP_ITERATION_START_2 >= 187 # define BOOST_PP_ITERATION_2 187 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 186 && BOOST_PP_ITERATION_START_2 >= 186 # define BOOST_PP_ITERATION_2 186 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 185 && BOOST_PP_ITERATION_START_2 >= 185 # define BOOST_PP_ITERATION_2 185 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 184 && BOOST_PP_ITERATION_START_2 >= 184 # define BOOST_PP_ITERATION_2 184 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 183 && BOOST_PP_ITERATION_START_2 >= 183 # define BOOST_PP_ITERATION_2 183 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 182 && BOOST_PP_ITERATION_START_2 >= 182 # define BOOST_PP_ITERATION_2 182 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 181 && BOOST_PP_ITERATION_START_2 >= 181 # define BOOST_PP_ITERATION_2 181 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 180 && BOOST_PP_ITERATION_START_2 >= 180 # define BOOST_PP_ITERATION_2 180 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 179 && BOOST_PP_ITERATION_START_2 >= 179 # define BOOST_PP_ITERATION_2 179 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 178 && BOOST_PP_ITERATION_START_2 >= 178 # define BOOST_PP_ITERATION_2 178 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 177 && BOOST_PP_ITERATION_START_2 >= 177 # define BOOST_PP_ITERATION_2 177 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 176 && BOOST_PP_ITERATION_START_2 >= 176 # define BOOST_PP_ITERATION_2 176 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 175 && BOOST_PP_ITERATION_START_2 >= 175 # define BOOST_PP_ITERATION_2 175 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 174 && BOOST_PP_ITERATION_START_2 >= 174 # define BOOST_PP_ITERATION_2 174 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 173 && BOOST_PP_ITERATION_START_2 >= 173 # define BOOST_PP_ITERATION_2 173 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 172 && BOOST_PP_ITERATION_START_2 >= 172 # define BOOST_PP_ITERATION_2 172 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 171 && BOOST_PP_ITERATION_START_2 >= 171 # define BOOST_PP_ITERATION_2 171 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 170 && BOOST_PP_ITERATION_START_2 >= 170 # define BOOST_PP_ITERATION_2 170 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 169 && BOOST_PP_ITERATION_START_2 >= 169 # define BOOST_PP_ITERATION_2 169 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 168 && BOOST_PP_ITERATION_START_2 >= 168 # define BOOST_PP_ITERATION_2 168 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 167 && BOOST_PP_ITERATION_START_2 >= 167 # define BOOST_PP_ITERATION_2 167 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 166 && BOOST_PP_ITERATION_START_2 >= 166 # define BOOST_PP_ITERATION_2 166 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 165 && BOOST_PP_ITERATION_START_2 >= 165 # define BOOST_PP_ITERATION_2 165 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 164 && BOOST_PP_ITERATION_START_2 >= 164 # define BOOST_PP_ITERATION_2 164 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 163 && BOOST_PP_ITERATION_START_2 >= 163 # define BOOST_PP_ITERATION_2 163 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 162 && BOOST_PP_ITERATION_START_2 >= 162 # define BOOST_PP_ITERATION_2 162 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 161 && BOOST_PP_ITERATION_START_2 >= 161 # define BOOST_PP_ITERATION_2 161 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 160 && BOOST_PP_ITERATION_START_2 >= 160 # define BOOST_PP_ITERATION_2 160 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 159 && BOOST_PP_ITERATION_START_2 >= 159 # define BOOST_PP_ITERATION_2 159 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 158 && BOOST_PP_ITERATION_START_2 >= 158 # define BOOST_PP_ITERATION_2 158 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 157 && BOOST_PP_ITERATION_START_2 >= 157 # define BOOST_PP_ITERATION_2 157 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 156 && BOOST_PP_ITERATION_START_2 >= 156 # define BOOST_PP_ITERATION_2 156 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 155 && BOOST_PP_ITERATION_START_2 >= 155 # define BOOST_PP_ITERATION_2 155 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 154 && BOOST_PP_ITERATION_START_2 >= 154 # define BOOST_PP_ITERATION_2 154 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 153 && BOOST_PP_ITERATION_START_2 >= 153 # define BOOST_PP_ITERATION_2 153 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 152 && BOOST_PP_ITERATION_START_2 >= 152 # define BOOST_PP_ITERATION_2 152 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 151 && BOOST_PP_ITERATION_START_2 >= 151 # define BOOST_PP_ITERATION_2 151 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 150 && BOOST_PP_ITERATION_START_2 >= 150 # define BOOST_PP_ITERATION_2 150 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 149 && BOOST_PP_ITERATION_START_2 >= 149 # define BOOST_PP_ITERATION_2 149 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 148 && BOOST_PP_ITERATION_START_2 >= 148 # define BOOST_PP_ITERATION_2 148 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 147 && BOOST_PP_ITERATION_START_2 >= 147 # define BOOST_PP_ITERATION_2 147 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 146 && BOOST_PP_ITERATION_START_2 >= 146 # define BOOST_PP_ITERATION_2 146 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 145 && BOOST_PP_ITERATION_START_2 >= 145 # define BOOST_PP_ITERATION_2 145 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 144 && BOOST_PP_ITERATION_START_2 >= 144 # define BOOST_PP_ITERATION_2 144 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 143 && BOOST_PP_ITERATION_START_2 >= 143 # define BOOST_PP_ITERATION_2 143 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 142 && BOOST_PP_ITERATION_START_2 >= 142 # define BOOST_PP_ITERATION_2 142 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 141 && BOOST_PP_ITERATION_START_2 >= 141 # define BOOST_PP_ITERATION_2 141 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 140 && BOOST_PP_ITERATION_START_2 >= 140 # define BOOST_PP_ITERATION_2 140 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 139 && BOOST_PP_ITERATION_START_2 >= 139 # define BOOST_PP_ITERATION_2 139 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 138 && BOOST_PP_ITERATION_START_2 >= 138 # define BOOST_PP_ITERATION_2 138 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 137 && BOOST_PP_ITERATION_START_2 >= 137 # define BOOST_PP_ITERATION_2 137 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 136 && BOOST_PP_ITERATION_START_2 >= 136 # define BOOST_PP_ITERATION_2 136 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 135 && BOOST_PP_ITERATION_START_2 >= 135 # define BOOST_PP_ITERATION_2 135 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 134 && BOOST_PP_ITERATION_START_2 >= 134 # define BOOST_PP_ITERATION_2 134 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 133 && BOOST_PP_ITERATION_START_2 >= 133 # define BOOST_PP_ITERATION_2 133 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 132 && BOOST_PP_ITERATION_START_2 >= 132 # define BOOST_PP_ITERATION_2 132 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 131 && BOOST_PP_ITERATION_START_2 >= 131 # define BOOST_PP_ITERATION_2 131 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 130 && BOOST_PP_ITERATION_START_2 >= 130 # define BOOST_PP_ITERATION_2 130 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 129 && BOOST_PP_ITERATION_START_2 >= 129 # define BOOST_PP_ITERATION_2 129 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 128 && BOOST_PP_ITERATION_START_2 >= 128 # define BOOST_PP_ITERATION_2 128 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 127 && BOOST_PP_ITERATION_START_2 >= 127 # define BOOST_PP_ITERATION_2 127 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 126 && BOOST_PP_ITERATION_START_2 >= 126 # define BOOST_PP_ITERATION_2 126 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 125 && BOOST_PP_ITERATION_START_2 >= 125 # define BOOST_PP_ITERATION_2 125 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 124 && BOOST_PP_ITERATION_START_2 >= 124 # define BOOST_PP_ITERATION_2 124 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 123 && BOOST_PP_ITERATION_START_2 >= 123 # define BOOST_PP_ITERATION_2 123 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 122 && BOOST_PP_ITERATION_START_2 >= 122 # define BOOST_PP_ITERATION_2 122 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 121 && BOOST_PP_ITERATION_START_2 >= 121 # define BOOST_PP_ITERATION_2 121 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 120 && BOOST_PP_ITERATION_START_2 >= 120 # define BOOST_PP_ITERATION_2 120 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 119 && BOOST_PP_ITERATION_START_2 >= 119 # define BOOST_PP_ITERATION_2 119 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 118 && BOOST_PP_ITERATION_START_2 >= 118 # define BOOST_PP_ITERATION_2 118 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 117 && BOOST_PP_ITERATION_START_2 >= 117 # define BOOST_PP_ITERATION_2 117 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 116 && BOOST_PP_ITERATION_START_2 >= 116 # define BOOST_PP_ITERATION_2 116 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 115 && BOOST_PP_ITERATION_START_2 >= 115 # define BOOST_PP_ITERATION_2 115 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 114 && BOOST_PP_ITERATION_START_2 >= 114 # define BOOST_PP_ITERATION_2 114 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 113 && BOOST_PP_ITERATION_START_2 >= 113 # define BOOST_PP_ITERATION_2 113 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 112 && BOOST_PP_ITERATION_START_2 >= 112 # define BOOST_PP_ITERATION_2 112 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 111 && BOOST_PP_ITERATION_START_2 >= 111 # define BOOST_PP_ITERATION_2 111 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 110 && BOOST_PP_ITERATION_START_2 >= 110 # define BOOST_PP_ITERATION_2 110 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 109 && BOOST_PP_ITERATION_START_2 >= 109 # define BOOST_PP_ITERATION_2 109 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 108 && BOOST_PP_ITERATION_START_2 >= 108 # define BOOST_PP_ITERATION_2 108 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 107 && BOOST_PP_ITERATION_START_2 >= 107 # define BOOST_PP_ITERATION_2 107 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 106 && BOOST_PP_ITERATION_START_2 >= 106 # define BOOST_PP_ITERATION_2 106 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 105 && BOOST_PP_ITERATION_START_2 >= 105 # define BOOST_PP_ITERATION_2 105 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 104 && BOOST_PP_ITERATION_START_2 >= 104 # define BOOST_PP_ITERATION_2 104 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 103 && BOOST_PP_ITERATION_START_2 >= 103 # define BOOST_PP_ITERATION_2 103 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 102 && BOOST_PP_ITERATION_START_2 >= 102 # define BOOST_PP_ITERATION_2 102 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 101 && BOOST_PP_ITERATION_START_2 >= 101 # define BOOST_PP_ITERATION_2 101 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 100 && BOOST_PP_ITERATION_START_2 >= 100 # define BOOST_PP_ITERATION_2 100 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 99 && BOOST_PP_ITERATION_START_2 >= 99 # define BOOST_PP_ITERATION_2 99 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 98 && BOOST_PP_ITERATION_START_2 >= 98 # define BOOST_PP_ITERATION_2 98 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 97 && BOOST_PP_ITERATION_START_2 >= 97 # define BOOST_PP_ITERATION_2 97 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 96 && BOOST_PP_ITERATION_START_2 >= 96 # define BOOST_PP_ITERATION_2 96 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 95 && BOOST_PP_ITERATION_START_2 >= 95 # define BOOST_PP_ITERATION_2 95 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 94 && BOOST_PP_ITERATION_START_2 >= 94 # define BOOST_PP_ITERATION_2 94 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 93 && BOOST_PP_ITERATION_START_2 >= 93 # define BOOST_PP_ITERATION_2 93 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 92 && BOOST_PP_ITERATION_START_2 >= 92 # define BOOST_PP_ITERATION_2 92 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 91 && BOOST_PP_ITERATION_START_2 >= 91 # define BOOST_PP_ITERATION_2 91 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 90 && BOOST_PP_ITERATION_START_2 >= 90 # define BOOST_PP_ITERATION_2 90 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 89 && BOOST_PP_ITERATION_START_2 >= 89 # define BOOST_PP_ITERATION_2 89 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 88 && BOOST_PP_ITERATION_START_2 >= 88 # define BOOST_PP_ITERATION_2 88 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 87 && BOOST_PP_ITERATION_START_2 >= 87 # define BOOST_PP_ITERATION_2 87 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 86 && BOOST_PP_ITERATION_START_2 >= 86 # define BOOST_PP_ITERATION_2 86 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 85 && BOOST_PP_ITERATION_START_2 >= 85 # define BOOST_PP_ITERATION_2 85 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 84 && BOOST_PP_ITERATION_START_2 >= 84 # define BOOST_PP_ITERATION_2 84 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 83 && BOOST_PP_ITERATION_START_2 >= 83 # define BOOST_PP_ITERATION_2 83 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 82 && BOOST_PP_ITERATION_START_2 >= 82 # define BOOST_PP_ITERATION_2 82 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 81 && BOOST_PP_ITERATION_START_2 >= 81 # define BOOST_PP_ITERATION_2 81 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 80 && BOOST_PP_ITERATION_START_2 >= 80 # define BOOST_PP_ITERATION_2 80 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 79 && BOOST_PP_ITERATION_START_2 >= 79 # define BOOST_PP_ITERATION_2 79 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 78 && BOOST_PP_ITERATION_START_2 >= 78 # define BOOST_PP_ITERATION_2 78 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 77 && BOOST_PP_ITERATION_START_2 >= 77 # define BOOST_PP_ITERATION_2 77 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 76 && BOOST_PP_ITERATION_START_2 >= 76 # define BOOST_PP_ITERATION_2 76 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 75 && BOOST_PP_ITERATION_START_2 >= 75 # define BOOST_PP_ITERATION_2 75 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 74 && BOOST_PP_ITERATION_START_2 >= 74 # define BOOST_PP_ITERATION_2 74 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 73 && BOOST_PP_ITERATION_START_2 >= 73 # define BOOST_PP_ITERATION_2 73 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 72 && BOOST_PP_ITERATION_START_2 >= 72 # define BOOST_PP_ITERATION_2 72 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 71 && BOOST_PP_ITERATION_START_2 >= 71 # define BOOST_PP_ITERATION_2 71 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 70 && BOOST_PP_ITERATION_START_2 >= 70 # define BOOST_PP_ITERATION_2 70 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 69 && BOOST_PP_ITERATION_START_2 >= 69 # define BOOST_PP_ITERATION_2 69 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 68 && BOOST_PP_ITERATION_START_2 >= 68 # define BOOST_PP_ITERATION_2 68 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 67 && BOOST_PP_ITERATION_START_2 >= 67 # define BOOST_PP_ITERATION_2 67 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 66 && BOOST_PP_ITERATION_START_2 >= 66 # define BOOST_PP_ITERATION_2 66 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 65 && BOOST_PP_ITERATION_START_2 >= 65 # define BOOST_PP_ITERATION_2 65 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 64 && BOOST_PP_ITERATION_START_2 >= 64 # define BOOST_PP_ITERATION_2 64 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 63 && BOOST_PP_ITERATION_START_2 >= 63 # define BOOST_PP_ITERATION_2 63 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 62 && BOOST_PP_ITERATION_START_2 >= 62 # define BOOST_PP_ITERATION_2 62 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 61 && BOOST_PP_ITERATION_START_2 >= 61 # define BOOST_PP_ITERATION_2 61 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 60 && BOOST_PP_ITERATION_START_2 >= 60 # define BOOST_PP_ITERATION_2 60 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 59 && BOOST_PP_ITERATION_START_2 >= 59 # define BOOST_PP_ITERATION_2 59 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 58 && BOOST_PP_ITERATION_START_2 >= 58 # define BOOST_PP_ITERATION_2 58 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 57 && BOOST_PP_ITERATION_START_2 >= 57 # define BOOST_PP_ITERATION_2 57 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 56 && BOOST_PP_ITERATION_START_2 >= 56 # define BOOST_PP_ITERATION_2 56 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 55 && BOOST_PP_ITERATION_START_2 >= 55 # define BOOST_PP_ITERATION_2 55 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 54 && BOOST_PP_ITERATION_START_2 >= 54 # define BOOST_PP_ITERATION_2 54 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 53 && BOOST_PP_ITERATION_START_2 >= 53 # define BOOST_PP_ITERATION_2 53 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 52 && BOOST_PP_ITERATION_START_2 >= 52 # define BOOST_PP_ITERATION_2 52 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 51 && BOOST_PP_ITERATION_START_2 >= 51 # define BOOST_PP_ITERATION_2 51 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 50 && BOOST_PP_ITERATION_START_2 >= 50 # define BOOST_PP_ITERATION_2 50 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 49 && BOOST_PP_ITERATION_START_2 >= 49 # define BOOST_PP_ITERATION_2 49 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 48 && BOOST_PP_ITERATION_START_2 >= 48 # define BOOST_PP_ITERATION_2 48 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 47 && BOOST_PP_ITERATION_START_2 >= 47 # define BOOST_PP_ITERATION_2 47 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 46 && BOOST_PP_ITERATION_START_2 >= 46 # define BOOST_PP_ITERATION_2 46 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 45 && BOOST_PP_ITERATION_START_2 >= 45 # define BOOST_PP_ITERATION_2 45 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 44 && BOOST_PP_ITERATION_START_2 >= 44 # define BOOST_PP_ITERATION_2 44 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 43 && BOOST_PP_ITERATION_START_2 >= 43 # define BOOST_PP_ITERATION_2 43 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 42 && BOOST_PP_ITERATION_START_2 >= 42 # define BOOST_PP_ITERATION_2 42 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 41 && BOOST_PP_ITERATION_START_2 >= 41 # define BOOST_PP_ITERATION_2 41 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 40 && BOOST_PP_ITERATION_START_2 >= 40 # define BOOST_PP_ITERATION_2 40 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 39 && BOOST_PP_ITERATION_START_2 >= 39 # define BOOST_PP_ITERATION_2 39 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 38 && BOOST_PP_ITERATION_START_2 >= 38 # define BOOST_PP_ITERATION_2 38 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 37 && BOOST_PP_ITERATION_START_2 >= 37 # define BOOST_PP_ITERATION_2 37 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 36 && BOOST_PP_ITERATION_START_2 >= 36 # define BOOST_PP_ITERATION_2 36 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 35 && BOOST_PP_ITERATION_START_2 >= 35 # define BOOST_PP_ITERATION_2 35 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 34 && BOOST_PP_ITERATION_START_2 >= 34 # define BOOST_PP_ITERATION_2 34 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 33 && BOOST_PP_ITERATION_START_2 >= 33 # define BOOST_PP_ITERATION_2 33 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 32 && BOOST_PP_ITERATION_START_2 >= 32 # define BOOST_PP_ITERATION_2 32 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 31 && BOOST_PP_ITERATION_START_2 >= 31 # define BOOST_PP_ITERATION_2 31 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 30 && BOOST_PP_ITERATION_START_2 >= 30 # define BOOST_PP_ITERATION_2 30 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 29 && BOOST_PP_ITERATION_START_2 >= 29 # define BOOST_PP_ITERATION_2 29 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 28 && BOOST_PP_ITERATION_START_2 >= 28 # define BOOST_PP_ITERATION_2 28 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 27 && BOOST_PP_ITERATION_START_2 >= 27 # define BOOST_PP_ITERATION_2 27 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 26 && BOOST_PP_ITERATION_START_2 >= 26 # define BOOST_PP_ITERATION_2 26 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 25 && BOOST_PP_ITERATION_START_2 >= 25 # define BOOST_PP_ITERATION_2 25 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 24 && BOOST_PP_ITERATION_START_2 >= 24 # define BOOST_PP_ITERATION_2 24 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 23 && BOOST_PP_ITERATION_START_2 >= 23 # define BOOST_PP_ITERATION_2 23 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 22 && BOOST_PP_ITERATION_START_2 >= 22 # define BOOST_PP_ITERATION_2 22 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 21 && BOOST_PP_ITERATION_START_2 >= 21 # define BOOST_PP_ITERATION_2 21 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 20 && BOOST_PP_ITERATION_START_2 >= 20 # define BOOST_PP_ITERATION_2 20 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 19 && BOOST_PP_ITERATION_START_2 >= 19 # define BOOST_PP_ITERATION_2 19 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 18 && BOOST_PP_ITERATION_START_2 >= 18 # define BOOST_PP_ITERATION_2 18 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 17 && BOOST_PP_ITERATION_START_2 >= 17 # define BOOST_PP_ITERATION_2 17 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 16 && BOOST_PP_ITERATION_START_2 >= 16 # define BOOST_PP_ITERATION_2 16 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 15 && BOOST_PP_ITERATION_START_2 >= 15 # define BOOST_PP_ITERATION_2 15 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 14 && BOOST_PP_ITERATION_START_2 >= 14 # define BOOST_PP_ITERATION_2 14 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 13 && BOOST_PP_ITERATION_START_2 >= 13 # define BOOST_PP_ITERATION_2 13 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 12 && BOOST_PP_ITERATION_START_2 >= 12 # define BOOST_PP_ITERATION_2 12 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 11 && BOOST_PP_ITERATION_START_2 >= 11 # define BOOST_PP_ITERATION_2 11 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 10 && BOOST_PP_ITERATION_START_2 >= 10 # define BOOST_PP_ITERATION_2 10 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 9 && BOOST_PP_ITERATION_START_2 >= 9 # define BOOST_PP_ITERATION_2 9 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 8 && BOOST_PP_ITERATION_START_2 >= 8 # define BOOST_PP_ITERATION_2 8 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 7 && BOOST_PP_ITERATION_START_2 >= 7 # define BOOST_PP_ITERATION_2 7 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 6 && BOOST_PP_ITERATION_START_2 >= 6 # define BOOST_PP_ITERATION_2 6 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 5 && BOOST_PP_ITERATION_START_2 >= 5 # define BOOST_PP_ITERATION_2 5 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 4 && BOOST_PP_ITERATION_START_2 >= 4 # define BOOST_PP_ITERATION_2 4 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 3 && BOOST_PP_ITERATION_START_2 >= 3 # define BOOST_PP_ITERATION_2 3 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 2 && BOOST_PP_ITERATION_START_2 >= 2 # define BOOST_PP_ITERATION_2 2 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 1 && BOOST_PP_ITERATION_START_2 >= 1 # define BOOST_PP_ITERATION_2 1 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif # if BOOST_PP_ITERATION_FINISH_2 <= 0 && BOOST_PP_ITERATION_START_2 >= 0 # define BOOST_PP_ITERATION_2 0 # include BOOST_PP_FILENAME_2 # undef BOOST_PP_ITERATION_2 # endif
[ "jan@arangodb.com" ]
jan@arangodb.com
f48d969bbc4c162cd74af6c61ec45823e5f06058
f2612a3f38e4118b3587a57fedc346d834d0dde0
/src/obfuscation.cpp
701e387cf1c546d66b6dfdeba89568ff21395e5f
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
cryptotronxyz/audax
6721ccdbdd28d57966a8e0dab263d49db384d8d1
79f4da18e898befea9d652b5c296d715a85f13e3
refs/heads/master
2022-07-09T12:00:04.572010
2020-05-13T22:44:32
2020-05-13T22:44:32
259,174,313
0
0
MIT
2020-04-27T01:35:24
2020-04-27T01:35:24
null
UTF-8
C++
false
false
82,850
cpp
// Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "obfuscation.h" #include "coincontrol.h" #include "consensus/validation.h" #include "init.h" #include "main.h" #include "masternodeman.h" #include "script/sign.h" #include "swifttx.h" #include "ui_interface.h" #include "util.h" #include <boost/algorithm/string/replace.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <algorithm> #include <boost/assign/list_of.hpp> #include <openssl/rand.h> using namespace std; using namespace boost; // The main object for accessing Obfuscation CObfuscationPool obfuScationPool; // A helper object for signing messages from Masternodes CObfuScationSigner obfuScationSigner; // The current Obfuscations in progress on the network std::vector<CObfuscationQueue> vecObfuscationQueue; // Keep track of the used Masternodes std::vector<CTxIn> vecMasternodesUsed; // Keep track of the scanning errors I've seen map<uint256, CObfuscationBroadcastTx> mapObfuscationBroadcastTxes; // Keep track of the active Masternode CActiveMasternode activeMasternode; /* *** BEGIN OBFUSCATION MAGIC - AUDAX ********** Copyright (c) 2014-2015, Dash Developers eduffield - evan@dashpay.io udjinm6 - udjinm6@dashpay.io */ void CObfuscationPool::ProcessMessageObfuscation(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) { if (fLiteMode) return; //disable all Obfuscation/Masternode related functionality if (!masternodeSync.IsBlockchainSynced()) return; if (strCommand == NetMsgType::DSA) { //Obfuscation Accept Into Pool int errorID; if (pfrom->nVersion < ActiveProtocol()) { errorID = ERR_VERSION; LogPrintf("dsa -- incompatible version! \n"); pfrom->PushMessage(NetMsgType::DSSU, sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } if (!fMasterNode) { errorID = ERR_NOT_A_MN; LogPrintf("dsa -- not a Masternode! \n"); pfrom->PushMessage(NetMsgType::DSSU, sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } int nDenom; CTransaction txCollateral; vRecv >> nDenom >> txCollateral; CMasternode* pmn = mnodeman.Find(activeMasternode.vin); if (pmn == NULL) { errorID = ERR_MN_LIST; pfrom->PushMessage(NetMsgType::DSSU, sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } if (sessionUsers == 0) { if (pmn->nLastDsq != 0 && pmn->nLastDsq + mnodeman.CountEnabled(ActiveProtocol()) / 5 > mnodeman.nDsqCount) { LogPrintf("dsa -- last dsq too recent, must wait. %s \n", pfrom->addr.ToString()); errorID = ERR_RECENT; pfrom->PushMessage(NetMsgType::DSSU, sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } } if (!IsCompatibleWithSession(nDenom, txCollateral, errorID)) { LogPrintf("dsa -- not compatible with existing transactions! \n"); pfrom->PushMessage(NetMsgType::DSSU, sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } else { LogPrintf("dsa -- is compatible, please submit! \n"); pfrom->PushMessage(NetMsgType::DSSU, sessionID, GetState(), GetEntriesCount(), MASTERNODE_ACCEPTED, errorID); return; } } else if (strCommand == NetMsgType::DSQ) { //Obfuscation Queue TRY_LOCK(cs_obfuscation, lockRecv); if (!lockRecv) return; if (pfrom->nVersion < ActiveProtocol()) { return; } CObfuscationQueue dsq; vRecv >> dsq; CService addr; if (!dsq.GetAddress(addr)) return; if (!dsq.CheckSignature()) return; if (dsq.IsExpired()) return; CMasternode* pmn = mnodeman.Find(dsq.vin); if (pmn == NULL) return; // if the queue is ready, submit if we can if (dsq.ready) { if (!pSubmittedToMasternode) return; if ((CNetAddr)pSubmittedToMasternode->addr != (CNetAddr)addr) { LogPrintf("dsq - message doesn't match current Masternode - %s != %s\n", pSubmittedToMasternode->addr.ToString(), addr.ToString()); return; } if (state == POOL_STATUS_QUEUE) { LogPrint("obfuscation", "Obfuscation queue is ready - %s\n", addr.ToString()); PrepareObfuscationDenominate(); } } else { BOOST_FOREACH (CObfuscationQueue q, vecObfuscationQueue) { if (q.vin == dsq.vin) return; } LogPrint("obfuscation", "dsq last %d last2 %d count %d\n", pmn->nLastDsq, pmn->nLastDsq + mnodeman.size() / 5, mnodeman.nDsqCount); //don't allow a few nodes to dominate the queuing process if (pmn->nLastDsq != 0 && pmn->nLastDsq + mnodeman.CountEnabled(ActiveProtocol()) / 5 > mnodeman.nDsqCount) { LogPrint("obfuscation", "dsq -- Masternode sending too many dsq messages. %s \n", pmn->addr.ToString()); return; } mnodeman.nDsqCount++; pmn->nLastDsq = mnodeman.nDsqCount; pmn->allowFreeTx = true; LogPrint("obfuscation", "dsq - new Obfuscation queue object - %s\n", addr.ToString()); vecObfuscationQueue.push_back(dsq); dsq.Relay(); dsq.time = GetTime(); } } else if (strCommand == NetMsgType::DSI) { //ObfuScation vIn int errorID; if (pfrom->nVersion < ActiveProtocol()) { LogPrintf("dsi -- incompatible version! \n"); errorID = ERR_VERSION; pfrom->PushMessage(NetMsgType::DSSU, sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } if (!fMasterNode) { LogPrintf("dsi -- not a Masternode! \n"); errorID = ERR_NOT_A_MN; pfrom->PushMessage(NetMsgType::DSSU, sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } std::vector<CTxIn> in; CAmount nAmount; CTransaction txCollateral; std::vector<CTxOut> out; vRecv >> in >> nAmount >> txCollateral >> out; //do we have enough users in the current session? if (!IsSessionReady()) { LogPrintf("dsi -- session not complete! \n"); errorID = ERR_SESSION; pfrom->PushMessage(NetMsgType::DSSU, sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } //do we have the same denominations as the current session? if (!IsCompatibleWithEntries(out)) { LogPrintf("dsi -- not compatible with existing transactions! \n"); errorID = ERR_EXISTING_TX; pfrom->PushMessage(NetMsgType::DSSU, sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } //check it like a transaction { CAmount nValueIn = 0; CAmount nValueOut = 0; bool missingTx = false; CValidationState state; CMutableTransaction tx; BOOST_FOREACH (const CTxOut o, out) { nValueOut += o.nValue; tx.vout.push_back(o); if (o.scriptPubKey.size() != 25) { LogPrintf("dsi - non-standard pubkey detected! %s\n", o.scriptPubKey.ToString()); errorID = ERR_NON_STANDARD_PUBKEY; pfrom->PushMessage(NetMsgType::DSSU, sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } if (!o.scriptPubKey.IsNormalPaymentScript()) { LogPrintf("dsi - invalid script! %s\n", o.scriptPubKey.ToString()); errorID = ERR_INVALID_SCRIPT; pfrom->PushMessage(NetMsgType::DSSU, sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } } BOOST_FOREACH (const CTxIn i, in) { tx.vin.push_back(i); LogPrint("obfuscation", "dsi -- tx in %s\n", i.ToString()); CTransaction tx2; uint256 hash; if (GetTransaction(i.prevout.hash, tx2, hash, true)) { if (tx2.vout.size() > i.prevout.n) { nValueIn += tx2.vout[i.prevout.n].nValue; } } else { missingTx = true; } } if (nValueIn > OBFUSCATION_POOL_MAX) { LogPrintf("dsi -- more than Obfuscation pool max! %s\n", tx.ToString()); errorID = ERR_MAXIMUM; pfrom->PushMessage(NetMsgType::DSSU, sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } if (!missingTx) { if (nValueIn - nValueOut > nValueIn * .01) { LogPrintf("dsi -- fees are too high! %s\n", tx.ToString()); errorID = ERR_FEES; pfrom->PushMessage(NetMsgType::DSSU, sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } } else { LogPrintf("dsi -- missing input tx! %s\n", tx.ToString()); errorID = ERR_MISSING_TX; pfrom->PushMessage(NetMsgType::DSSU, sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } { LOCK(cs_main); if (!AcceptableInputs(mempool, state, CTransaction(tx), false, NULL, false, true)) { LogPrintf("dsi -- transaction not valid! \n"); errorID = ERR_INVALID_TX; pfrom->PushMessage(NetMsgType::DSSU, sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); return; } } } if (AddEntry(in, nAmount, txCollateral, out, errorID)) { pfrom->PushMessage(NetMsgType::DSSU, sessionID, GetState(), GetEntriesCount(), MASTERNODE_ACCEPTED, errorID); Check(); RelayStatus(sessionID, GetState(), GetEntriesCount(), MASTERNODE_RESET); } else { pfrom->PushMessage(NetMsgType::DSSU, sessionID, GetState(), GetEntriesCount(), MASTERNODE_REJECTED, errorID); } } else if (strCommand == NetMsgType::DSSU) { //Obfuscation status update if (pfrom->nVersion < ActiveProtocol()) { return; } if (!pSubmittedToMasternode) return; if ((CNetAddr)pSubmittedToMasternode->addr != (CNetAddr)pfrom->addr) { //LogPrintf("dssu - message doesn't match current Masternode - %s != %s\n", pSubmittedToMasternode->addr.ToString(), pfrom->addr.ToString()); return; } int sessionIDMessage; int state; int entriesCount; int accepted; int errorID; vRecv >> sessionIDMessage >> state >> entriesCount >> accepted >> errorID; LogPrint("obfuscation", "dssu - state: %i entriesCount: %i accepted: %i error: %s \n", state, entriesCount, accepted, GetMessageByID(errorID)); if ((accepted != 1 && accepted != 0) && sessionID != sessionIDMessage) { LogPrintf("dssu - message doesn't match current Obfuscation session %d %d\n", sessionID, sessionIDMessage); return; } StatusUpdate(state, entriesCount, accepted, errorID, sessionIDMessage); } else if (strCommand == NetMsgType::DSS) { //Obfuscation Sign Final Tx if (pfrom->nVersion < ActiveProtocol()) { return; } vector<CTxIn> sigs; vRecv >> sigs; bool success = false; int count = 0; BOOST_FOREACH (const CTxIn item, sigs) { if (AddScriptSig(item)) success = true; LogPrint("obfuscation", " -- sigs count %d %d\n", (int)sigs.size(), count); count++; } if (success) { obfuScationPool.Check(); RelayStatus(obfuScationPool.sessionID, obfuScationPool.GetState(), obfuScationPool.GetEntriesCount(), MASTERNODE_RESET); } } else if (strCommand == NetMsgType::DSF) { //Obfuscation Final tx if (pfrom->nVersion < ActiveProtocol()) { return; } if (!pSubmittedToMasternode) return; if ((CNetAddr)pSubmittedToMasternode->addr != (CNetAddr)pfrom->addr) { //LogPrintf("dsc - message doesn't match current Masternode - %s != %s\n", pSubmittedToMasternode->addr.ToString(), pfrom->addr.ToString()); return; } int sessionIDMessage; CTransaction txNew; vRecv >> sessionIDMessage >> txNew; if (sessionID != sessionIDMessage) { LogPrint("obfuscation", "dsf - message doesn't match current Obfuscation session %d %d\n", sessionID, sessionIDMessage); return; } //check to see if input is spent already? (and probably not confirmed) SignFinalTransaction(txNew, pfrom); } else if (strCommand == NetMsgType::DSC) { //Obfuscation Complete if (pfrom->nVersion < ActiveProtocol()) { return; } if (!pSubmittedToMasternode) return; if ((CNetAddr)pSubmittedToMasternode->addr != (CNetAddr)pfrom->addr) { //LogPrintf("dsc - message doesn't match current Masternode - %s != %s\n", pSubmittedToMasternode->addr.ToString(), pfrom->addr.ToString()); return; } int sessionIDMessage; bool error; int errorID; vRecv >> sessionIDMessage >> error >> errorID; if (sessionID != sessionIDMessage) { LogPrint("obfuscation", "dsc - message doesn't match current Obfuscation session %d %d\n", obfuScationPool.sessionID, sessionIDMessage); return; } obfuScationPool.CompletedTransaction(error, errorID); } } int randomizeList(int i) { return std::rand() % i; } void CObfuscationPool::Reset() { cachedLastSuccess = 0; lastNewBlock = 0; txCollateral = CMutableTransaction(); vecMasternodesUsed.clear(); UnlockCoins(); SetNull(); } void CObfuscationPool::SetNull() { // MN side sessionUsers = 0; vecSessionCollateral.clear(); // Client side entriesCount = 0; lastEntryAccepted = 0; countEntriesAccepted = 0; sessionFoundMasternode = false; // Both sides state = POOL_STATUS_IDLE; sessionID = 0; sessionDenom = 0; entries.clear(); finalTransaction.vin.clear(); finalTransaction.vout.clear(); lastTimeChanged = GetTimeMillis(); // -- seed random number generator (used for ordering output lists) unsigned int seed = 0; RAND_bytes((unsigned char*)&seed, sizeof(seed)); std::srand(seed); } bool CObfuscationPool::SetCollateralAddress(std::string strAddress) { CTxDestination dest = DecodeDestination(strAddress); if (dest.which() == 0) { LogPrintf("CObfuscationPool::SetCollateralAddress - Invalid Obfuscation collateral address\n"); return false; } collateralPubKey = GetScriptForDestination(dest); return true; } // // Unlock coins after Obfuscation fails or succeeds // void CObfuscationPool::UnlockCoins() { while (true) { TRY_LOCK(pwalletMain->cs_wallet, lockWallet); if (!lockWallet) { MilliSleep(50); continue; } BOOST_FOREACH (CTxIn v, lockedCoins) pwalletMain->UnlockCoin(v.prevout); break; } lockedCoins.clear(); } std::string CObfuscationPool::GetStatus() { static int showingObfuScationMessage = 0; showingObfuScationMessage += 10; std::string suffix = ""; if (chainActive.Tip()->nHeight - cachedLastSuccess < minBlockSpacing || !masternodeSync.IsBlockchainSynced()) { return strAutoDenomResult; } switch (state) { case POOL_STATUS_IDLE: return _("Obfuscation is idle."); case POOL_STATUS_ACCEPTING_ENTRIES: if (entriesCount == 0) { showingObfuScationMessage = 0; return strAutoDenomResult; } else if (lastEntryAccepted == 1) { if (showingObfuScationMessage % 10 > 8) { lastEntryAccepted = 0; showingObfuScationMessage = 0; } return _("Obfuscation request complete:") + " " + _("Your transaction was accepted into the pool!"); } else { std::string suffix = ""; if (showingObfuScationMessage % 70 <= 40) return strprintf(_("Submitted following entries to masternode: %u / %d"), entriesCount, GetMaxPoolTransactions()); else if (showingObfuScationMessage % 70 <= 50) suffix = "."; else if (showingObfuScationMessage % 70 <= 60) suffix = ".."; else if (showingObfuScationMessage % 70 <= 70) suffix = "..."; return strprintf(_("Submitted to masternode, waiting for more entries ( %u / %d ) %s"), entriesCount, GetMaxPoolTransactions(), suffix); } case POOL_STATUS_SIGNING: if (showingObfuScationMessage % 70 <= 40) return _("Found enough users, signing ..."); else if (showingObfuScationMessage % 70 <= 50) suffix = "."; else if (showingObfuScationMessage % 70 <= 60) suffix = ".."; else if (showingObfuScationMessage % 70 <= 70) suffix = "..."; return strprintf(_("Found enough users, signing ( waiting %s )"), suffix); case POOL_STATUS_TRANSMISSION: return _("Transmitting final transaction."); case POOL_STATUS_FINALIZE_TRANSACTION: return _("Finalizing transaction."); case POOL_STATUS_ERROR: return _("Obfuscation request incomplete:") + " " + lastMessage + " " + _("Will retry..."); case POOL_STATUS_SUCCESS: return _("Obfuscation request complete:") + " " + lastMessage; case POOL_STATUS_QUEUE: if (showingObfuScationMessage % 70 <= 30) suffix = "."; else if (showingObfuScationMessage % 70 <= 50) suffix = ".."; else if (showingObfuScationMessage % 70 <= 70) suffix = "..."; return strprintf(_("Submitted to masternode, waiting in queue %s"), suffix); ; default: return strprintf(_("Unknown state: id = %u"), state); } } // // Check the Obfuscation progress and send client updates if a Masternode // void CObfuscationPool::Check() { if (fMasterNode) LogPrint("obfuscation", "CObfuscationPool::Check() - entries count %lu\n", entries.size()); //printf("CObfuscationPool::Check() %d - %d - %d\n", state, anonTx.CountEntries(), GetTimeMillis()-lastTimeChanged); if (fMasterNode) { LogPrint("obfuscation", "CObfuscationPool::Check() - entries count %lu\n", entries.size()); // If entries is full, then move on to the next phase if (state == POOL_STATUS_ACCEPTING_ENTRIES && (int)entries.size() >= GetMaxPoolTransactions()) { LogPrint("obfuscation", "CObfuscationPool::Check() -- TRYING TRANSACTION \n"); UpdateState(POOL_STATUS_FINALIZE_TRANSACTION); } } // create the finalized transaction for distribution to the clients if (state == POOL_STATUS_FINALIZE_TRANSACTION) { LogPrint("obfuscation", "CObfuscationPool::Check() -- FINALIZE TRANSACTIONS\n"); UpdateState(POOL_STATUS_SIGNING); if (fMasterNode) { CMutableTransaction txNew; // make our new transaction for (unsigned int i = 0; i < entries.size(); i++) { BOOST_FOREACH (const CTxOut& v, entries[i].vout) txNew.vout.push_back(v); BOOST_FOREACH (const CTxDSIn& s, entries[i].sev) txNew.vin.push_back(s); } // shuffle the outputs for improved anonymity std::random_shuffle(txNew.vin.begin(), txNew.vin.end(), randomizeList); std::random_shuffle(txNew.vout.begin(), txNew.vout.end(), randomizeList); LogPrint("obfuscation", "Transaction 1: %s\n", txNew.ToString()); finalTransaction = txNew; // request signatures from clients RelayFinalTransaction(sessionID, finalTransaction); } } // If we have all of the signatures, try to compile the transaction if (fMasterNode && state == POOL_STATUS_SIGNING && SignaturesComplete()) { LogPrint("obfuscation", "CObfuscationPool::Check() -- SIGNING\n"); UpdateState(POOL_STATUS_TRANSMISSION); CheckFinalTransaction(); } // reset if we're here for 10 seconds if ((state == POOL_STATUS_ERROR || state == POOL_STATUS_SUCCESS) && GetTimeMillis() - lastTimeChanged >= 10000) { LogPrint("obfuscation", "CObfuscationPool::Check() -- timeout, RESETTING\n"); UnlockCoins(); SetNull(); if (fMasterNode) RelayStatus(sessionID, GetState(), GetEntriesCount(), MASTERNODE_RESET); } } void CObfuscationPool::CheckFinalTransaction() { if (!fMasterNode) return; // check and relay final tx only on masternode CWalletTx txNew = CWalletTx(pwalletMain, finalTransaction); LOCK2(cs_main, pwalletMain->cs_wallet); { LogPrint("obfuscation", "Transaction 2: %s\n", txNew.ToString()); // See if the transaction is valid if (!txNew.AcceptToMemoryPool(false, true, true)) { LogPrintf("CObfuscationPool::Check() - CommitTransaction : Error: Transaction not valid\n"); SetNull(); // not much we can do in this case UpdateState(POOL_STATUS_ACCEPTING_ENTRIES); RelayCompletedTransaction(sessionID, true, ERR_INVALID_TX); return; } LogPrintf("CObfuscationPool::Check() -- IS MASTER -- TRANSMITTING OBFUSCATION\n"); // sign a message int64_t sigTime = GetAdjustedTime(); std::string strMessage = txNew.GetHash().ToString() + std::to_string(sigTime); std::string strError = ""; std::vector<unsigned char> vchSig; CKey key2; CPubKey pubkey2; if (!obfuScationSigner.SetKey(strMasterNodePrivKey, strError, key2, pubkey2)) { LogPrintf("CObfuscationPool::Check() - ERROR: Invalid Masternodeprivkey: '%s'\n", strError); return; } if (!obfuScationSigner.SignMessage(strMessage, strError, vchSig, key2)) { LogPrintf("CObfuscationPool::Check() - Sign message failed\n"); return; } if (!obfuScationSigner.VerifyMessage(pubkey2, vchSig, strMessage, strError)) { LogPrintf("CObfuscationPool::Check() - Verify message failed\n"); return; } if (!mapObfuscationBroadcastTxes.count(txNew.GetHash())) { CObfuscationBroadcastTx dstx; dstx.tx = txNew; dstx.vin = activeMasternode.vin; dstx.vchSig = vchSig; dstx.sigTime = sigTime; mapObfuscationBroadcastTxes.insert(make_pair(txNew.GetHash(), dstx)); } CInv inv(MSG_DSTX, txNew.GetHash()); RelayInv(inv); // Tell the clients it was successful RelayCompletedTransaction(sessionID, false, MSG_SUCCESS); // Randomly charge clients ChargeRandomFees(); // Reset LogPrint("obfuscation", "CObfuscationPool::Check() -- COMPLETED -- RESETTING\n"); SetNull(); RelayStatus(sessionID, GetState(), GetEntriesCount(), MASTERNODE_RESET); } } // // Charge clients a fee if they're abusive // // Why bother? Obfuscation uses collateral to ensure abuse to the process is kept to a minimum. // The submission and signing stages in Obfuscation are completely separate. In the cases where // a client submits a transaction then refused to sign, there must be a cost. Otherwise they // would be able to do this over and over again and bring the mixing to a hault. // // How does this work? Messages to Masternodes come in via "dsi", these require a valid collateral // transaction for the client to be able to enter the pool. This transaction is kept by the Masternode // until the transaction is either complete or fails. // void CObfuscationPool::ChargeFees() { if (!fMasterNode) return; //we don't need to charge collateral for every offence. int offences = 0; int r = rand() % 100; if (r > 33) return; if (state == POOL_STATUS_ACCEPTING_ENTRIES) { BOOST_FOREACH (const CTransaction& txCollateral, vecSessionCollateral) { bool found = false; BOOST_FOREACH (const CObfuScationEntry& v, entries) { if (v.collateral == txCollateral) { found = true; } } // This queue entry didn't send us the promised transaction if (!found) { LogPrintf("CObfuscationPool::ChargeFees -- found uncooperative node (didn't send transaction). Found offence.\n"); offences++; } } } if (state == POOL_STATUS_SIGNING) { // who didn't sign? BOOST_FOREACH (const CObfuScationEntry v, entries) { BOOST_FOREACH (const CTxDSIn s, v.sev) { if (!s.fHasSig) { LogPrintf("CObfuscationPool::ChargeFees -- found uncooperative node (didn't sign). Found offence\n"); offences++; } } } } r = rand() % 100; int target = 0; //mostly offending? if (offences >= Params().PoolMaxTransactions() - 1 && r > 33) return; //everyone is an offender? That's not right if (offences >= Params().PoolMaxTransactions()) return; //charge one of the offenders randomly if (offences > 1) target = 50; //pick random client to charge r = rand() % 100; if (state == POOL_STATUS_ACCEPTING_ENTRIES) { BOOST_FOREACH (const CTransaction& txCollateral, vecSessionCollateral) { bool found = false; BOOST_FOREACH (const CObfuScationEntry& v, entries) { if (v.collateral == txCollateral) { found = true; } } // This queue entry didn't send us the promised transaction if (!found && r > target) { LogPrintf("CObfuscationPool::ChargeFees -- found uncooperative node (didn't send transaction). charging fees.\n"); CWalletTx wtxCollateral = CWalletTx(pwalletMain, txCollateral); // Broadcast if (!wtxCollateral.AcceptToMemoryPool(true)) { // This must not fail. The transaction has already been signed and recorded. LogPrintf("CObfuscationPool::ChargeFees() : Error: Transaction not valid"); } wtxCollateral.RelayWalletTransaction(); return; } } } if (state == POOL_STATUS_SIGNING) { // who didn't sign? BOOST_FOREACH (const CObfuScationEntry v, entries) { BOOST_FOREACH (const CTxDSIn s, v.sev) { if (!s.fHasSig && r > target) { LogPrintf("CObfuscationPool::ChargeFees -- found uncooperative node (didn't sign). charging fees.\n"); CWalletTx wtxCollateral = CWalletTx(pwalletMain, v.collateral); // Broadcast if (!wtxCollateral.AcceptToMemoryPool(false)) { // This must not fail. The transaction has already been signed and recorded. LogPrintf("CObfuscationPool::ChargeFees() : Error: Transaction not valid"); } wtxCollateral.RelayWalletTransaction(); return; } } } } } // charge the collateral randomly // - Obfuscation is completely free, to pay miners we randomly pay the collateral of users. void CObfuscationPool::ChargeRandomFees() { if (fMasterNode) { int i = 0; BOOST_FOREACH (const CTransaction& txCollateral, vecSessionCollateral) { int r = rand() % 100; /* Collateral Fee Charges: Being that Obfuscation has "no fees" we need to have some kind of cost associated with using it to stop abuse. Otherwise it could serve as an attack vector and allow endless transaction that would bloat Audax and make it unusable. To stop these kinds of attacks 1 in 10 successful transactions are charged. This adds up to a cost of 0.001 AUDAX per transaction on average. */ if (r <= 10) { LogPrintf("CObfuscationPool::ChargeRandomFees -- charging random fees. %u\n", i); CWalletTx wtxCollateral = CWalletTx(pwalletMain, txCollateral); // Broadcast if (!wtxCollateral.AcceptToMemoryPool(true)) { // This must not fail. The transaction has already been signed and recorded. LogPrintf("CObfuscationPool::ChargeRandomFees() : Error: Transaction not valid"); } wtxCollateral.RelayWalletTransaction(); } } } } // // Check for various timeouts (queue objects, Obfuscation, etc) // void CObfuscationPool::CheckTimeout() { if (!fMasterNode) return; // catching hanging sessions if (!fMasterNode) { switch (state) { case POOL_STATUS_TRANSMISSION: LogPrint("obfuscation", "CObfuscationPool::CheckTimeout() -- Session complete -- Running Check()\n"); Check(); break; case POOL_STATUS_ERROR: LogPrint("obfuscation", "CObfuscationPool::CheckTimeout() -- Pool error -- Running Check()\n"); Check(); break; case POOL_STATUS_SUCCESS: LogPrint("obfuscation", "CObfuscationPool::CheckTimeout() -- Pool success -- Running Check()\n"); Check(); break; } } // check Obfuscation queue objects for timeouts int c = 0; vector<CObfuscationQueue>::iterator it = vecObfuscationQueue.begin(); while (it != vecObfuscationQueue.end()) { if ((*it).IsExpired()) { LogPrint("obfuscation", "CObfuscationPool::CheckTimeout() : Removing expired queue entry - %d\n", c); it = vecObfuscationQueue.erase(it); } else ++it; c++; } int addLagTime = 0; if (!fMasterNode) addLagTime = 10000; //if we're the client, give the server a few extra seconds before resetting. if (state == POOL_STATUS_ACCEPTING_ENTRIES || state == POOL_STATUS_QUEUE) { c = 0; // check for a timeout and reset if needed vector<CObfuScationEntry>::iterator it2 = entries.begin(); while (it2 != entries.end()) { if ((*it2).IsExpired()) { LogPrint("obfuscation", "CObfuscationPool::CheckTimeout() : Removing expired entry - %d\n", c); it2 = entries.erase(it2); if (entries.size() == 0) { UnlockCoins(); SetNull(); } if (fMasterNode) { RelayStatus(sessionID, GetState(), GetEntriesCount(), MASTERNODE_RESET); } } else ++it2; c++; } if (GetTimeMillis() - lastTimeChanged >= (OBFUSCATION_QUEUE_TIMEOUT * 1000) + addLagTime) { UnlockCoins(); SetNull(); } } else if (GetTimeMillis() - lastTimeChanged >= (OBFUSCATION_QUEUE_TIMEOUT * 1000) + addLagTime) { LogPrint("obfuscation", "CObfuscationPool::CheckTimeout() -- Session timed out (%ds) -- resetting\n", OBFUSCATION_QUEUE_TIMEOUT); UnlockCoins(); SetNull(); UpdateState(POOL_STATUS_ERROR); lastMessage = _("Session timed out."); } if (state == POOL_STATUS_SIGNING && GetTimeMillis() - lastTimeChanged >= (OBFUSCATION_SIGNING_TIMEOUT * 1000) + addLagTime) { LogPrint("obfuscation", "CObfuscationPool::CheckTimeout() -- Session timed out (%ds) -- restting\n", OBFUSCATION_SIGNING_TIMEOUT); ChargeFees(); UnlockCoins(); SetNull(); UpdateState(POOL_STATUS_ERROR); lastMessage = _("Signing timed out."); } } // // Check for complete queue // void CObfuscationPool::CheckForCompleteQueue() { if (!fMasterNode) return; /* Check to see if we're ready for submissions from clients */ // // After receiving multiple dsa messages, the queue will switch to "accepting entries" // which is the active state right before merging the transaction // if (state == POOL_STATUS_QUEUE && sessionUsers == GetMaxPoolTransactions()) { UpdateState(POOL_STATUS_ACCEPTING_ENTRIES); CObfuscationQueue dsq; dsq.nDenom = sessionDenom; dsq.vin = activeMasternode.vin; dsq.time = GetTime(); dsq.ready = true; dsq.Sign(); dsq.Relay(); } } // check to see if the signature is valid bool CObfuscationPool::SignatureValid(const CScript& newSig, const CTxIn& newVin) { CMutableTransaction txNew; txNew.vin.clear(); txNew.vout.clear(); int found = -1; CScript sigPubKey = CScript(); unsigned int i = 0; CAmount zeroAmount = 0; BOOST_FOREACH (CObfuScationEntry& e, entries) { BOOST_FOREACH (const CTxOut& out, e.vout) txNew.vout.push_back(out); BOOST_FOREACH (const CTxDSIn& s, e.sev) { txNew.vin.push_back(s); if (s == newVin) { found = i; sigPubKey = s.prevPubKey; } i++; } } if (found >= 0) { //might have to do this one input at a time? int n = found; txNew.vin[n].scriptSig = newSig; LogPrint("obfuscation", "CObfuscationPool::SignatureValid() - Sign with sig %s\n", newSig.ToString().substr(0, 24)); if (!VerifyScript(txNew.vin[n].scriptSig, sigPubKey, NULL, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC, MutableTransactionSignatureChecker(&txNew, n, zeroAmount))) { LogPrint("obfuscation", "CObfuscationPool::SignatureValid() - Signing - Error signing input %u\n", n); return false; } } LogPrint("obfuscation", "CObfuscationPool::SignatureValid() - Signing - Successfully validated input\n"); return true; } // check to make sure the collateral provided by the client is valid bool CObfuscationPool::IsCollateralValid(const CTransaction& txCollateral) { if (txCollateral.vout.size() < 1) return false; if (txCollateral.nLockTime != 0) return false; int64_t nValueIn = 0; int64_t nValueOut = 0; bool missingTx = false; BOOST_FOREACH (const CTxOut o, txCollateral.vout) { nValueOut += o.nValue; if (!o.scriptPubKey.IsNormalPaymentScript()) { LogPrintf("CObfuscationPool::IsCollateralValid - Invalid Script %s\n", txCollateral.ToString()); return false; } } BOOST_FOREACH (const CTxIn i, txCollateral.vin) { CTransaction tx2; uint256 hash; if (GetTransaction(i.prevout.hash, tx2, hash, true)) { if (tx2.vout.size() > i.prevout.n) { nValueIn += tx2.vout[i.prevout.n].nValue; } } else { missingTx = true; } } if (missingTx) { LogPrint("obfuscation", "CObfuscationPool::IsCollateralValid - Unknown inputs in collateral transaction - %s\n", txCollateral.ToString()); return false; } //collateral transactions are required to pay out OBFUSCATION_COLLATERAL as a fee to the miners if (nValueIn - nValueOut < OBFUSCATION_COLLATERAL) { LogPrint("obfuscation", "CObfuscationPool::IsCollateralValid - did not include enough fees in transaction %d\n%s\n", nValueOut - nValueIn, txCollateral.ToString()); return false; } LogPrint("obfuscation", "CObfuscationPool::IsCollateralValid %s\n", txCollateral.ToString()); { LOCK(cs_main); CValidationState state; if (!AcceptableInputs(mempool, state, txCollateral, true, NULL)) { if (fDebug) LogPrintf("CObfuscationPool::IsCollateralValid - didn't pass IsAcceptable\n"); return false; } } return true; } // // Add a clients transaction to the pool // bool CObfuscationPool::AddEntry(const std::vector<CTxIn>& newInput, const CAmount& nAmount, const CTransaction& txCollateral, const std::vector<CTxOut>& newOutput, int& errorID) { if (!fMasterNode) return false; BOOST_FOREACH (CTxIn in, newInput) { if (in.prevout.IsNull() || nAmount < 0) { LogPrint("obfuscation", "CObfuscationPool::AddEntry - input not valid!\n"); errorID = ERR_INVALID_INPUT; sessionUsers--; return false; } } if (!IsCollateralValid(txCollateral)) { LogPrint("obfuscation", "CObfuscationPool::AddEntry - collateral not valid!\n"); errorID = ERR_INVALID_COLLATERAL; sessionUsers--; return false; } if ((int)entries.size() >= GetMaxPoolTransactions()) { LogPrint("obfuscation", "CObfuscationPool::AddEntry - entries is full!\n"); errorID = ERR_ENTRIES_FULL; sessionUsers--; return false; } BOOST_FOREACH (CTxIn in, newInput) { LogPrint("obfuscation", "looking for vin -- %s\n", in.ToString()); BOOST_FOREACH (const CObfuScationEntry& v, entries) { BOOST_FOREACH (const CTxDSIn& s, v.sev) { if ((CTxIn)s == in) { LogPrint("obfuscation", "CObfuscationPool::AddEntry - found in vin\n"); errorID = ERR_ALREADY_HAVE; sessionUsers--; return false; } } } } CObfuScationEntry v; v.Add(newInput, nAmount, txCollateral, newOutput); entries.push_back(v); LogPrint("obfuscation", "CObfuscationPool::AddEntry -- adding %s\n", newInput[0].ToString()); errorID = MSG_ENTRIES_ADDED; return true; } bool CObfuscationPool::AddScriptSig(const CTxIn& newVin) { LogPrint("obfuscation", "CObfuscationPool::AddScriptSig -- new sig %s\n", newVin.scriptSig.ToString().substr(0, 24)); BOOST_FOREACH (const CObfuScationEntry& v, entries) { BOOST_FOREACH (const CTxDSIn& s, v.sev) { if (s.scriptSig == newVin.scriptSig) { LogPrint("obfuscation", "CObfuscationPool::AddScriptSig - already exists\n"); return false; } } } if (!SignatureValid(newVin.scriptSig, newVin)) { LogPrint("obfuscation", "CObfuscationPool::AddScriptSig - Invalid Sig\n"); return false; } LogPrint("obfuscation", "CObfuscationPool::AddScriptSig -- sig %s\n", newVin.ToString()); BOOST_FOREACH (CTxIn& vin, finalTransaction.vin) { if (newVin.prevout == vin.prevout && vin.nSequence == newVin.nSequence) { vin.scriptSig = newVin.scriptSig; vin.prevPubKey = newVin.prevPubKey; LogPrint("obfuscation", "CObfuScationPool::AddScriptSig -- adding to finalTransaction %s\n", newVin.scriptSig.ToString().substr(0, 24)); } } for (unsigned int i = 0; i < entries.size(); i++) { if (entries[i].AddSig(newVin)) { LogPrint("obfuscation", "CObfuScationPool::AddScriptSig -- adding %s\n", newVin.scriptSig.ToString().substr(0, 24)); return true; } } LogPrintf("CObfuscationPool::AddScriptSig -- Couldn't set sig!\n"); return false; } // Check to make sure everything is signed bool CObfuscationPool::SignaturesComplete() { BOOST_FOREACH (const CObfuScationEntry& v, entries) { BOOST_FOREACH (const CTxDSIn& s, v.sev) { if (!s.fHasSig) return false; } } return true; } // // Execute a Obfuscation denomination via a Masternode. // This is only ran from clients // void CObfuscationPool::SendObfuscationDenominate(std::vector<CTxIn>& vin, std::vector<CTxOut>& vout, CAmount amount) { if (fMasterNode) { LogPrintf("CObfuscationPool::SendObfuscationDenominate() - Obfuscation from a Masternode is not supported currently.\n"); return; } if (txCollateral == CMutableTransaction()) { LogPrintf("CObfuscationPool:SendObfuscationDenominate() - Obfuscation collateral not set"); return; } // lock the funds we're going to use BOOST_FOREACH (CTxIn in, txCollateral.vin) lockedCoins.push_back(in); BOOST_FOREACH (CTxIn in, vin) lockedCoins.push_back(in); //BOOST_FOREACH(CTxOut o, vout) // LogPrintf(" vout - %s\n", o.ToString()); // we should already be connected to a Masternode if (!sessionFoundMasternode) { LogPrintf("CObfuscationPool::SendObfuscationDenominate() - No Masternode has been selected yet.\n"); UnlockCoins(); SetNull(); return; } if (!CheckDiskSpace()) { UnlockCoins(); SetNull(); LogPrintf("CObfuscationPool::SendObfuscationDenominate() - Not enough disk space, disabling Obfuscation.\n"); return; } UpdateState(POOL_STATUS_ACCEPTING_ENTRIES); LogPrintf("CObfuscationPool::SendObfuscationDenominate() - Added transaction to pool.\n"); ClearLastMessage(); //check it against the memory pool to make sure it's valid { CAmount nValueOut = 0; CValidationState state; CMutableTransaction tx; BOOST_FOREACH (const CTxOut& o, vout) { nValueOut += o.nValue; tx.vout.push_back(o); } BOOST_FOREACH (const CTxIn& i, vin) { tx.vin.push_back(i); LogPrint("obfuscation", "dsi -- tx in %s\n", i.ToString()); } LogPrintf("Submitting tx %s\n", tx.ToString()); while (true) { TRY_LOCK(cs_main, lockMain); if (!lockMain) { MilliSleep(50); continue; } if (!AcceptableInputs(mempool, state, CTransaction(tx), false, NULL, false, true)) { LogPrintf("dsi -- transaction not valid! %s \n", tx.ToString()); UnlockCoins(); SetNull(); return; } break; } } // store our entry for later use CObfuScationEntry e; e.Add(vin, amount, txCollateral, vout); entries.push_back(e); RelayIn(entries[0].sev, entries[0].amount, txCollateral, entries[0].vout); Check(); } // Incoming message from Masternode updating the progress of Obfuscation // newAccepted: -1 mean's it'n not a "transaction accepted/not accepted" message, just a standard update // 0 means transaction was not accepted // 1 means transaction was accepted bool CObfuscationPool::StatusUpdate(int newState, int newEntriesCount, int newAccepted, int& errorID, int newSessionID) { if (fMasterNode) return false; if (state == POOL_STATUS_ERROR || state == POOL_STATUS_SUCCESS) return false; UpdateState(newState); entriesCount = newEntriesCount; if (errorID != MSG_NOERR) strAutoDenomResult = _("Masternode:") + " " + GetMessageByID(errorID); if (newAccepted != -1) { lastEntryAccepted = newAccepted; countEntriesAccepted += newAccepted; if (newAccepted == 0) { UpdateState(POOL_STATUS_ERROR); lastMessage = GetMessageByID(errorID); } if (newAccepted == 1 && newSessionID != 0) { sessionID = newSessionID; LogPrintf("CObfuscationPool::StatusUpdate - set sessionID to %d\n", sessionID); sessionFoundMasternode = true; } } if (newState == POOL_STATUS_ACCEPTING_ENTRIES) { if (newAccepted == 1) { LogPrintf("CObfuscationPool::StatusUpdate - entry accepted! \n"); sessionFoundMasternode = true; //wait for other users. Masternode will report when ready UpdateState(POOL_STATUS_QUEUE); } else if (newAccepted == 0 && sessionID == 0 && !sessionFoundMasternode) { LogPrintf("CObfuscationPool::StatusUpdate - entry not accepted by Masternode \n"); UnlockCoins(); UpdateState(POOL_STATUS_ACCEPTING_ENTRIES); DoAutomaticDenominating(); //try another Masternode } if (sessionFoundMasternode) return true; } return true; } // // After we receive the finalized transaction from the Masternode, we must // check it to make sure it's what we want, then sign it if we agree. // If we refuse to sign, it's possible we'll be charged collateral // bool CObfuscationPool::SignFinalTransaction(CTransaction& finalTransactionNew, CNode* node) { if (fMasterNode) return false; finalTransaction = finalTransactionNew; LogPrintf("CObfuscationPool::SignFinalTransaction %s", finalTransaction.ToString()); vector<CTxIn> sigs; //make sure my inputs/outputs are present, otherwise refuse to sign BOOST_FOREACH (const CObfuScationEntry e, entries) { BOOST_FOREACH (const CTxDSIn s, e.sev) { /* Sign my transaction and all outputs */ int mine = -1; CScript prevPubKey = CScript(); CTxIn vin = CTxIn(); for (unsigned int i = 0; i < finalTransaction.vin.size(); i++) { if (finalTransaction.vin[i] == s) { mine = i; prevPubKey = s.prevPubKey; vin = s; break; } } if (mine >= 0) { //might have to do this one input at a time? int foundOutputs = 0; CAmount nValue1 = 0; CAmount nValue2 = 0; for (unsigned int i = 0; i < finalTransaction.vout.size(); i++) { BOOST_FOREACH (const CTxOut& o, e.vout) { if (finalTransaction.vout[i] == o) { foundOutputs++; nValue1 += finalTransaction.vout[i].nValue; } } } BOOST_FOREACH (const CTxOut o, e.vout) nValue2 += o.nValue; int targetOuputs = e.vout.size(); if (foundOutputs < targetOuputs || nValue1 != nValue2) { // in this case, something went wrong and we'll refuse to sign. It's possible we'll be charged collateral. But that's // better then signing if the transaction doesn't look like what we wanted. LogPrintf("CObfuscationPool::Sign - My entries are not correct! Refusing to sign. %d entries %d target. \n", foundOutputs, targetOuputs); UnlockCoins(); SetNull(); return false; } const CKeyStore& keystore = *pwalletMain; LogPrint("obfuscation", "CObfuscationPool::Sign - Signing my input %i\n", mine); if (!SignSignature(keystore, prevPubKey, finalTransaction, mine, nValue1, SIGHASH_ALL)) { // changes scriptSig LogPrint("obfuscation", "CObfuscationPool::Sign - Unable to sign my own transaction! \n"); // not sure what to do here, it will timeout...? } sigs.push_back(finalTransaction.vin[mine]); LogPrint("obfuscation", " -- dss %d %d %s\n", mine, (int)sigs.size(), finalTransaction.vin[mine].scriptSig.ToString()); } } LogPrint("obfuscation", "CObfuscationPool::Sign - txNew:\n%s", finalTransaction.ToString()); } // push all of our signatures to the Masternode if (sigs.size() > 0 && node != NULL) node->PushMessage(NetMsgType::DSS, sigs); return true; } void CObfuscationPool::NewBlock() { LogPrint("obfuscation", "CObfuscationPool::NewBlock \n"); //we we're processing lots of blocks, we'll just leave if (GetTime() - lastNewBlock < 10) return; lastNewBlock = GetTime(); obfuScationPool.CheckTimeout(); } // Obfuscation transaction was completed (failed or successful) void CObfuscationPool::CompletedTransaction(bool error, int errorID) { if (fMasterNode) return; if (error) { LogPrintf("CompletedTransaction -- error \n"); UpdateState(POOL_STATUS_ERROR); Check(); UnlockCoins(); SetNull(); } else { LogPrintf("CompletedTransaction -- success \n"); UpdateState(POOL_STATUS_SUCCESS); UnlockCoins(); SetNull(); // To avoid race conditions, we'll only let DS run once per block cachedLastSuccess = chainActive.Tip()->nHeight; } lastMessage = GetMessageByID(errorID); } void CObfuscationPool::ClearLastMessage() { lastMessage = ""; } // // Passively run Obfuscation in the background to anonymize funds based on the given configuration. // // This does NOT run by default for daemons, only for QT. // bool CObfuscationPool::DoAutomaticDenominating(bool fDryRun) { return false; // Disabled until Obfuscation is completely removed if (fMasterNode) return false; if (state == POOL_STATUS_ERROR || state == POOL_STATUS_SUCCESS) return false; if (GetEntriesCount() > 0) { strAutoDenomResult = _("Mixing in progress..."); return false; } TRY_LOCK(cs_obfuscation, lockDS); if (!lockDS) { strAutoDenomResult = _("Lock is already in place."); return false; } if (!masternodeSync.IsBlockchainSynced()) { strAutoDenomResult = _("Can't mix while sync in progress."); return false; } if (!fDryRun && pwalletMain->IsLocked()) { strAutoDenomResult = _("Wallet is locked."); return false; } if (chainActive.Tip()->nHeight - cachedLastSuccess < minBlockSpacing) { LogPrintf("CObfuscationPool::DoAutomaticDenominating - Last successful Obfuscation action was too recent\n"); strAutoDenomResult = _("Last successful Obfuscation action was too recent."); return false; } if (mnodeman.size() == 0) { LogPrint("obfuscation", "CObfuscationPool::DoAutomaticDenominating - No Masternodes detected\n"); strAutoDenomResult = _("No Masternodes detected."); return false; } // ** find the coins we'll use std::vector<CTxIn> vCoins; CAmount nValueMin = CENT; CAmount nValueIn = 0; CAmount nOnlyDenominatedBalance; CAmount nBalanceNeedsDenominated; // should not be less than fees in OBFUSCATION_COLLATERAL + few (lets say 5) smallest denoms CAmount nLowestDenom = OBFUSCATION_COLLATERAL + obfuScationDenominations[obfuScationDenominations.size() - 1] * 5; // if there are no OBF collateral inputs yet if (!pwalletMain->HasCollateralInputs()) // should have some additional amount for them nLowestDenom += OBFUSCATION_COLLATERAL * 4; CAmount nBalanceNeedsAnonymized = nAnonymizeAudaxAmount * COIN - pwalletMain->GetAnonymizedBalance(); // if balanceNeedsAnonymized is more than pool max, take the pool max if (nBalanceNeedsAnonymized > OBFUSCATION_POOL_MAX) nBalanceNeedsAnonymized = OBFUSCATION_POOL_MAX; // if balanceNeedsAnonymized is more than non-anonymized, take non-anonymized CAmount nAnonymizableBalance = pwalletMain->GetAnonymizableBalance(); if (nBalanceNeedsAnonymized > nAnonymizableBalance) nBalanceNeedsAnonymized = nAnonymizableBalance; if (nBalanceNeedsAnonymized < nLowestDenom) { LogPrintf("DoAutomaticDenominating : No funds detected in need of denominating \n"); strAutoDenomResult = _("No funds detected in need of denominating."); return false; } LogPrint("obfuscation", "DoAutomaticDenominating : nLowestDenom=%d, nBalanceNeedsAnonymized=%d\n", nLowestDenom, nBalanceNeedsAnonymized); if (fDryRun) return true; nOnlyDenominatedBalance = pwalletMain->GetDenominatedBalance(true) + pwalletMain->GetDenominatedBalance() - pwalletMain->GetAnonymizedBalance(); nBalanceNeedsDenominated = nBalanceNeedsAnonymized - nOnlyDenominatedBalance; //check if we have should create more denominated inputs if (nBalanceNeedsDenominated > nOnlyDenominatedBalance) return CreateDenominated(nBalanceNeedsDenominated); //check if we have the collateral sized inputs if (!pwalletMain->HasCollateralInputs()) return !pwalletMain->HasCollateralInputs(false) && MakeCollateralAmounts(); std::vector<CTxOut> vOut; // initial phase, find a Masternode if (!sessionFoundMasternode) { // Clean if there is anything left from previous session UnlockCoins(); SetNull(); int nUseQueue = rand() % 100; UpdateState(POOL_STATUS_ACCEPTING_ENTRIES); if (pwalletMain->GetDenominatedBalance(true) > 0) { //get denominated unconfirmed inputs LogPrintf("DoAutomaticDenominating -- Found unconfirmed denominated outputs, will wait till they confirm to continue.\n"); strAutoDenomResult = _("Found unconfirmed denominated outputs, will wait till they confirm to continue."); return false; } //check our collateral nad create new if needed std::string strReason; CValidationState state; if (txCollateral == CMutableTransaction()) { if (!pwalletMain->CreateCollateralTransaction(txCollateral, strReason)) { LogPrintf("% -- create collateral error:%s\n", __func__, strReason); return false; } } else { if (!IsCollateralValid(txCollateral)) { LogPrintf("%s -- invalid collateral, recreating...\n", __func__); if (!pwalletMain->CreateCollateralTransaction(txCollateral, strReason)) { LogPrintf("%s -- create collateral error: %s\n", __func__, strReason); return false; } } } //if we've used 90% of the Masternode list then drop all the oldest first int nThreshold = (int)(mnodeman.CountEnabled(ActiveProtocol()) * 0.9); LogPrint("obfuscation", "Checking vecMasternodesUsed size %d threshold %d\n", (int)vecMasternodesUsed.size(), nThreshold); while ((int)vecMasternodesUsed.size() > nThreshold) { vecMasternodesUsed.erase(vecMasternodesUsed.begin()); LogPrint("obfuscation", " vecMasternodesUsed size %d threshold %d\n", (int)vecMasternodesUsed.size(), nThreshold); } //don't use the queues all of the time for mixing if (nUseQueue > 33) { // Look through the queues and see if anything matches BOOST_FOREACH (CObfuscationQueue& dsq, vecObfuscationQueue) { CService addr; if (dsq.time == 0) continue; if (!dsq.GetAddress(addr)) continue; if (dsq.IsExpired()) continue; int protocolVersion; if (!dsq.GetProtocolVersion(protocolVersion)) continue; if (protocolVersion < ActiveProtocol()) continue; //non-denom's are incompatible if ((dsq.nDenom & (1 << 4))) continue; bool fUsed = false; //don't reuse Masternodes BOOST_FOREACH (CTxIn usedVin, vecMasternodesUsed) { if (dsq.vin == usedVin) { fUsed = true; break; } } if (fUsed) continue; std::vector<CTxIn> vTempCoins; std::vector<COutput> vTempCoins2; // Try to match their denominations if possible if (!pwalletMain->SelectCoinsByDenominations(dsq.nDenom, nValueMin, nBalanceNeedsAnonymized, vTempCoins, vTempCoins2, nValueIn, 0, 5)) { LogPrintf("DoAutomaticDenominating --- Couldn't match denominations %d\n", dsq.nDenom); continue; } CMasternode* pmn = mnodeman.Find(dsq.vin); if (pmn == NULL) { LogPrintf("DoAutomaticDenominating --- dsq vin %s is not in masternode list!", dsq.vin.ToString()); continue; } LogPrintf("DoAutomaticDenominating --- attempt to connect to masternode from queue %s\n", pmn->addr.ToString()); lastTimeChanged = GetTimeMillis(); // connect to Masternode and submit the queue request CNode* pnode = ConnectNode((CAddress)addr, NULL, true); if (pnode != NULL) { pSubmittedToMasternode = pmn; vecMasternodesUsed.push_back(dsq.vin); sessionDenom = dsq.nDenom; pnode->PushMessage(NetMsgType::DSA, sessionDenom, txCollateral); LogPrintf("DoAutomaticDenominating --- connected (from queue), sending dsa for %d - %s\n", sessionDenom, pnode->addr.ToString()); strAutoDenomResult = _("Mixing in progress..."); dsq.time = 0; //remove node return true; } else { LogPrintf("DoAutomaticDenominating --- error connecting \n"); strAutoDenomResult = _("Error connecting to Masternode."); dsq.time = 0; //remove node continue; } } } // do not initiate queue if we are a liquidity proveder to avoid useless inter-mixing if (nLiquidityProvider) return false; int i = 0; // otherwise, try one randomly while (i < 10) { CMasternode* pmn = mnodeman.FindRandomNotInVec(vecMasternodesUsed, ActiveProtocol()); if (pmn == NULL) { LogPrintf("DoAutomaticDenominating --- Can't find random masternode!\n"); strAutoDenomResult = _("Can't find random Masternode."); return false; } if (pmn->nLastDsq != 0 && pmn->nLastDsq + mnodeman.CountEnabled(ActiveProtocol()) / 5 > mnodeman.nDsqCount) { i++; continue; } lastTimeChanged = GetTimeMillis(); LogPrintf("DoAutomaticDenominating --- attempt %d connection to Masternode %s\n", i, pmn->addr.ToString()); CNode* pnode = ConnectNode((CAddress)pmn->addr, NULL, true); if (pnode != NULL) { pSubmittedToMasternode = pmn; vecMasternodesUsed.push_back(pmn->vin); std::vector<CAmount> vecAmounts; pwalletMain->ConvertList(vCoins, vecAmounts); // try to get a single random denom out of vecAmounts while (sessionDenom == 0) sessionDenom = GetDenominationsByAmounts(vecAmounts); pnode->PushMessage(NetMsgType::DSA, sessionDenom, txCollateral); LogPrintf("DoAutomaticDenominating --- connected, sending dsa for %d\n", sessionDenom); strAutoDenomResult = _("Mixing in progress..."); return true; } else { vecMasternodesUsed.push_back(pmn->vin); // postpone MN we wasn't able to connect to i++; continue; } } strAutoDenomResult = _("No compatible Masternode found."); return false; } strAutoDenomResult = _("Mixing in progress..."); return false; } bool CObfuscationPool::PrepareObfuscationDenominate() { std::string strError = ""; // Submit transaction to the pool if we get here // Try to use only inputs with the same number of rounds starting from lowest number of rounds possible for (int i = 0; i < 5; i++) { strError = pwalletMain->PrepareObfuscationDenominate(i, i + 1); LogPrintf("DoAutomaticDenominating : Running Obfuscation denominate for %d rounds. Return '%s'\n", i, strError); if (strError == "") return true; } // We failed? That's strange but let's just make final attempt and try to mix everything strError = pwalletMain->PrepareObfuscationDenominate(0, 5); LogPrintf("DoAutomaticDenominating : Running Obfuscation denominate for all rounds. Return '%s'\n", strError); if (strError == "") return true; // Should never actually get here but just in case strAutoDenomResult = strError; LogPrintf("DoAutomaticDenominating : Error running denominate, %s\n", strError); return false; } bool CObfuscationPool::SendRandomPaymentToSelf() { int64_t nBalance = pwalletMain->GetBalance(); int64_t nPayment = (nBalance * 0.35) + (rand() % nBalance); if (nPayment > nBalance) nPayment = nBalance - (0.1 * COIN); // make our change address CReserveKey reservekey(pwalletMain); CScript scriptChange; CPubKey vchPubKey; assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptChange = GetScriptForDestination(vchPubKey.GetID()); CWalletTx wtx; CAmount nFeeRet = 0; std::string strFail = ""; vector<pair<CScript, CAmount> > vecSend; // ****** Add fees ************ / vecSend.push_back(make_pair(scriptChange, nPayment)); CCoinControl* coinControl = NULL; bool success = pwalletMain->CreateTransaction(vecSend, wtx, reservekey, nFeeRet, strFail, coinControl, ONLY_DENOMINATED); if (!success) { LogPrintf("SendRandomPaymentToSelf: Error - %s\n", strFail); return false; } pwalletMain->CommitTransaction(wtx, reservekey); LogPrintf("SendRandomPaymentToSelf Success: tx %s\n", wtx.GetHash().GetHex()); return true; } // Split up large inputs or create fee sized inputs bool CObfuscationPool::MakeCollateralAmounts() { CWalletTx wtx; CAmount nFeeRet = 0; std::string strFail = ""; vector<pair<CScript, CAmount> > vecSend; CCoinControl coinControl; coinControl.fAllowOtherInputs = false; coinControl.fAllowWatchOnly = false; // make our collateral address CReserveKey reservekeyCollateral(pwalletMain); // make our change address CReserveKey reservekeyChange(pwalletMain); CScript scriptCollateral; CPubKey vchPubKey; assert(reservekeyCollateral.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptCollateral = GetScriptForDestination(vchPubKey.GetID()); vecSend.push_back(make_pair(scriptCollateral, OBFUSCATION_COLLATERAL * 4)); // try to use non-denominated and not mn-like funds bool success = pwalletMain->CreateTransaction(vecSend, wtx, reservekeyChange, nFeeRet, strFail, &coinControl, ONLY_NONDENOMINATED_NOT150000IFMN); if (!success) { // if we failed (most likeky not enough funds), try to use all coins instead - // MN-like funds should not be touched in any case and we can't mix denominated without collaterals anyway CCoinControl* coinControlNull = NULL; LogPrintf("MakeCollateralAmounts: ONLY_NONDENOMINATED_NOT150000IFMN Error - %s\n", strFail); success = pwalletMain->CreateTransaction(vecSend, wtx, reservekeyChange, nFeeRet, strFail, coinControlNull, ONLY_NOT150000IFMN); if (!success) { LogPrintf("MakeCollateralAmounts: ONLY_NOT150000IFMN Error - %s\n", strFail); reservekeyCollateral.ReturnKey(); return false; } } reservekeyCollateral.KeepKey(); LogPrintf("MakeCollateralAmounts: tx %s\n", wtx.GetHash().GetHex()); // use the same cachedLastSuccess as for DS mixinx to prevent race if (!pwalletMain->CommitTransaction(wtx, reservekeyChange)) { LogPrintf("MakeCollateralAmounts: CommitTransaction failed!\n"); return false; } cachedLastSuccess = chainActive.Tip()->nHeight; return true; } // Create denominations bool CObfuscationPool::CreateDenominated(CAmount nTotalValue) { CWalletTx wtx; CAmount nFeeRet = 0; std::string strFail = ""; vector<pair<CScript, CAmount> > vecSend; CAmount nValueLeft = nTotalValue; // make our collateral address CReserveKey reservekeyCollateral(pwalletMain); // make our change address CReserveKey reservekeyChange(pwalletMain); // make our denom addresses CReserveKey reservekeyDenom(pwalletMain); CScript scriptCollateral; CPubKey vchPubKey; assert(reservekeyCollateral.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptCollateral = GetScriptForDestination(vchPubKey.GetID()); // ****** Add collateral outputs ************ / if (!pwalletMain->HasCollateralInputs()) { vecSend.push_back(make_pair(scriptCollateral, OBFUSCATION_COLLATERAL * 4)); nValueLeft -= OBFUSCATION_COLLATERAL * 4; } // ****** Add denoms ************ / BOOST_REVERSE_FOREACH (CAmount v, obfuScationDenominations) { int nOutputs = 0; // add each output up to 10 times until it can't be added again while (nValueLeft - v >= OBFUSCATION_COLLATERAL && nOutputs <= 10) { CScript scriptDenom; CPubKey vchPubKey; //use a unique change address assert(reservekeyDenom.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptDenom = GetScriptForDestination(vchPubKey.GetID()); // TODO: do not keep reservekeyDenom here reservekeyDenom.KeepKey(); vecSend.push_back(make_pair(scriptDenom, v)); //increment outputs and subtract denomination amount nOutputs++; nValueLeft -= v; LogPrintf("CreateDenominated1 %d\n", nValueLeft); } if (nValueLeft == 0) break; } LogPrintf("CreateDenominated2 %d\n", nValueLeft); // if we have anything left over, it will be automatically send back as change - there is no need to send it manually CCoinControl* coinControl = NULL; bool success = pwalletMain->CreateTransaction(vecSend, wtx, reservekeyChange, nFeeRet, strFail, coinControl, ONLY_NONDENOMINATED_NOT150000IFMN); if (!success) { LogPrintf("CreateDenominated: Error - %s\n", strFail); // TODO: return reservekeyDenom here reservekeyCollateral.ReturnKey(); return false; } // TODO: keep reservekeyDenom here reservekeyCollateral.KeepKey(); // use the same cachedLastSuccess as for DS mixinx to prevent race if (pwalletMain->CommitTransaction(wtx, reservekeyChange)) cachedLastSuccess = chainActive.Tip()->nHeight; else LogPrintf("CreateDenominated: CommitTransaction failed!\n"); LogPrintf("CreateDenominated: tx %s\n", wtx.GetHash().GetHex()); return true; } bool CObfuscationPool::IsCompatibleWithEntries(std::vector<CTxOut>& vout) { if (GetDenominations(vout) == 0) return false; BOOST_FOREACH (const CObfuScationEntry v, entries) { LogPrintf(" IsCompatibleWithEntries %d %d\n", GetDenominations(vout), GetDenominations(v.vout)); /* BOOST_FOREACH(CTxOut o1, vout) LogPrintf(" vout 1 - %s\n", o1.ToString()); BOOST_FOREACH(CTxOut o2, v.vout) LogPrintf(" vout 2 - %s\n", o2.ToString()); */ if (GetDenominations(vout) != GetDenominations(v.vout)) return false; } return true; } bool CObfuscationPool::IsCompatibleWithSession(int64_t nDenom, CTransaction txCollateral, int& errorID) { if (nDenom == 0) return false; LogPrintf("CObfuscationPool::IsCompatibleWithSession - sessionDenom %d sessionUsers %d\n", sessionDenom, sessionUsers); if (!unitTest && !IsCollateralValid(txCollateral)) { LogPrint("obfuscation", "CObfuscationPool::IsCompatibleWithSession - collateral not valid!\n"); errorID = ERR_INVALID_COLLATERAL; return false; } if (sessionUsers < 0) sessionUsers = 0; if (sessionUsers == 0) { sessionID = 1 + (rand() % 999999); sessionDenom = nDenom; sessionUsers++; lastTimeChanged = GetTimeMillis(); if (!unitTest) { //broadcast that I'm accepting entries, only if it's the first entry through CObfuscationQueue dsq; dsq.nDenom = nDenom; dsq.vin = activeMasternode.vin; dsq.time = GetTime(); dsq.Sign(); dsq.Relay(); } UpdateState(POOL_STATUS_QUEUE); vecSessionCollateral.push_back(txCollateral); return true; } if ((state != POOL_STATUS_ACCEPTING_ENTRIES && state != POOL_STATUS_QUEUE) || sessionUsers >= GetMaxPoolTransactions()) { if ((state != POOL_STATUS_ACCEPTING_ENTRIES && state != POOL_STATUS_QUEUE)) errorID = ERR_MODE; if (sessionUsers >= GetMaxPoolTransactions()) errorID = ERR_QUEUE_FULL; LogPrintf("CObfuscationPool::IsCompatibleWithSession - incompatible mode, return false %d %d\n", state != POOL_STATUS_ACCEPTING_ENTRIES, sessionUsers >= GetMaxPoolTransactions()); return false; } if (nDenom != sessionDenom) { errorID = ERR_DENOM; return false; } LogPrintf("CObfuScationPool::IsCompatibleWithSession - compatible\n"); sessionUsers++; lastTimeChanged = GetTimeMillis(); vecSessionCollateral.push_back(txCollateral); return true; } //create a nice string to show the denominations void CObfuscationPool::GetDenominationsToString(int nDenom, std::string& strDenom) { // Function returns as follows: // // bit 0 - 100AUDAX+1 ( bit on if present ) // bit 1 - 10AUDAX+1 // bit 2 - 1AUDAX+1 // bit 3 - .1AUDAX+1 // bit 3 - non-denom strDenom = ""; if (nDenom & (1 << 0)) { if (strDenom.size() > 0) strDenom += "+"; strDenom += "100"; } if (nDenom & (1 << 1)) { if (strDenom.size() > 0) strDenom += "+"; strDenom += "10"; } if (nDenom & (1 << 2)) { if (strDenom.size() > 0) strDenom += "+"; strDenom += "1"; } if (nDenom & (1 << 3)) { if (strDenom.size() > 0) strDenom += "+"; strDenom += "0.1"; } } int CObfuscationPool::GetDenominations(const std::vector<CTxDSOut>& vout) { std::vector<CTxOut> vout2; BOOST_FOREACH (CTxDSOut out, vout) vout2.push_back(out); return GetDenominations(vout2); } // return a bitshifted integer representing the denominations in this list int CObfuscationPool::GetDenominations(const std::vector<CTxOut>& vout, bool fSingleRandomDenom) { std::vector<pair<int64_t, int> > denomUsed; // make a list of denominations, with zero uses BOOST_FOREACH (int64_t d, obfuScationDenominations) denomUsed.push_back(make_pair(d, 0)); // look for denominations and update uses to 1 BOOST_FOREACH (CTxOut out, vout) { bool found = false; BOOST_FOREACH (PAIRTYPE(int64_t, int) & s, denomUsed) { if (out.nValue == s.first) { s.second = 1; found = true; } } if (!found) return 0; } int denom = 0; int c = 0; // if the denomination is used, shift the bit on. // then move to the next BOOST_FOREACH (PAIRTYPE(int64_t, int) & s, denomUsed) { int bit = (fSingleRandomDenom ? rand() % 2 : 1) * s.second; denom |= bit << c++; if (fSingleRandomDenom && bit) break; // use just one random denomination } // Function returns as follows: // // bit 0 - 100AUDAX+1 ( bit on if present ) // bit 1 - 10AUDAX+1 // bit 2 - 1AUDAX+1 // bit 3 - .1AUDAX+1 return denom; } int CObfuscationPool::GetDenominationsByAmounts(std::vector<CAmount>& vecAmount) { CScript e = CScript(); std::vector<CTxOut> vout1; // Make outputs by looping through denominations, from small to large BOOST_REVERSE_FOREACH (CAmount v, vecAmount) { CTxOut o(v, e); vout1.push_back(o); } return GetDenominations(vout1, true); } int CObfuscationPool::GetDenominationsByAmount(CAmount nAmount, int nDenomTarget) { CScript e = CScript(); CAmount nValueLeft = nAmount; std::vector<CTxOut> vout1; // Make outputs by looping through denominations, from small to large BOOST_REVERSE_FOREACH (CAmount v, obfuScationDenominations) { if (nDenomTarget != 0) { bool fAccepted = false; if ((nDenomTarget & (1 << 0)) && v == ((100 * COIN) + 100000)) { fAccepted = true; } else if ((nDenomTarget & (1 << 1)) && v == ((10 * COIN) + 10000)) { fAccepted = true; } else if ((nDenomTarget & (1 << 2)) && v == ((1 * COIN) + 1000)) { fAccepted = true; } else if ((nDenomTarget & (1 << 3)) && v == ((.1 * COIN) + 100)) { fAccepted = true; } if (!fAccepted) continue; } int nOutputs = 0; // add each output up to 10 times until it can't be added again while (nValueLeft - v >= 0 && nOutputs <= 10) { CTxOut o(v, e); vout1.push_back(o); nValueLeft -= v; nOutputs++; } LogPrintf("GetDenominationsByAmount --- %d nOutputs %d\n", v, nOutputs); } return GetDenominations(vout1); } std::string CObfuscationPool::GetMessageByID(int messageID) { switch (messageID) { case ERR_ALREADY_HAVE: return _("Already have that input."); case ERR_DENOM: return _("No matching denominations found for mixing."); case ERR_ENTRIES_FULL: return _("Entries are full."); case ERR_EXISTING_TX: return _("Not compatible with existing transactions."); case ERR_FEES: return _("Transaction fees are too high."); case ERR_INVALID_COLLATERAL: return _("Collateral not valid."); case ERR_INVALID_INPUT: return _("Input is not valid."); case ERR_INVALID_SCRIPT: return _("Invalid script detected."); case ERR_INVALID_TX: return _("Transaction not valid."); case ERR_MAXIMUM: return _("Value more than Obfuscation pool maximum allows."); case ERR_MN_LIST: return _("Not in the Masternode list."); case ERR_MODE: return _("Incompatible mode."); case ERR_NON_STANDARD_PUBKEY: return _("Non-standard public key detected."); case ERR_NOT_A_MN: return _("This is not a Masternode."); case ERR_QUEUE_FULL: return _("Masternode queue is full."); case ERR_RECENT: return _("Last Obfuscation was too recent."); case ERR_SESSION: return _("Session not complete!"); case ERR_MISSING_TX: return _("Missing input transaction information."); case ERR_VERSION: return _("Incompatible version."); case MSG_SUCCESS: return _("Transaction created successfully."); case MSG_ENTRIES_ADDED: return _("Your entries added successfully."); case MSG_NOERR: default: return ""; } } bool CObfuScationSigner::IsVinAssociatedWithPubkey(CTxIn& vin, CPubKey& pubkey) { CScript payee2; payee2 = GetScriptForDestination(pubkey.GetID()); CTransaction txVin; uint256 hash; if (GetTransaction(vin.prevout.hash, txVin, hash, true)) { BOOST_FOREACH (CTxOut out, txVin.vout) { if (out.nValue == 150000 * COIN) { if (out.scriptPubKey == payee2) return true; } } } return false; } bool CObfuScationSigner::SetKey(std::string strSecret, std::string& errorMessage, CKey& key, CPubKey& pubkey) { CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) { errorMessage = _("Invalid private key."); return false; } key = vchSecret.GetKey(); pubkey = key.GetPubKey(); return true; } bool CObfuScationSigner::GetKeysFromSecret(std::string strSecret, CKey& keyRet, CPubKey& pubkeyRet) { CBitcoinSecret vchSecret; if (!vchSecret.SetString(strSecret)) return false; keyRet = vchSecret.GetKey(); pubkeyRet = keyRet.GetPubKey(); return true; } bool CObfuScationSigner::SignMessage(std::string strMessage, std::string& errorMessage, vector<unsigned char>& vchSig, CKey key) { CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; if (!key.SignCompact(ss.GetHash(), vchSig)) { errorMessage = _("Signing failed."); return false; } return true; } bool CObfuScationSigner::VerifyMessage(CPubKey pubkey, vector<unsigned char>& vchSig, std::string strMessage, std::string& errorMessage) { CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; CPubKey pubkey2; if (!pubkey2.RecoverCompact(ss.GetHash(), vchSig)) { errorMessage = _("Error recovering public key."); return false; } if (fDebug && pubkey2.GetID() != pubkey.GetID()) LogPrintf("CObfuScationSigner::VerifyMessage -- keys don't match: %s %s\n", pubkey2.GetID().ToString(), pubkey.GetID().ToString()); return (pubkey2.GetID() == pubkey.GetID()); } bool CObfuscationQueue::Sign() { if (!fMasterNode) return false; std::string strMessage = vin.ToString() + std::to_string(nDenom) + std::to_string(time) + std::to_string(ready); CKey key2; CPubKey pubkey2; std::string errorMessage = ""; if (!obfuScationSigner.SetKey(strMasterNodePrivKey, errorMessage, key2, pubkey2)) { LogPrintf("CObfuscationQueue():Relay - ERROR: Invalid Masternodeprivkey: '%s'\n", errorMessage); return false; } if (!obfuScationSigner.SignMessage(strMessage, errorMessage, vchSig, key2)) { LogPrintf("CObfuscationQueue():Relay - Sign message failed"); return false; } if (!obfuScationSigner.VerifyMessage(pubkey2, vchSig, strMessage, errorMessage)) { LogPrintf("CObfuscationQueue():Relay - Verify message failed"); return false; } return true; } bool CObfuscationQueue::Relay() { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) { // always relay to everyone pnode->PushMessage(NetMsgType::DSQ, (*this)); } return true; } bool CObfuscationQueue::CheckSignature() { CMasternode* pmn = mnodeman.Find(vin); if (pmn != NULL) { std::string strMessage = vin.ToString() + std::to_string(nDenom) + std::to_string(time) + std::to_string(ready); std::string errorMessage = ""; if (!obfuScationSigner.VerifyMessage(pmn->pubKeyMasternode, vchSig, strMessage, errorMessage)) { return error("CObfuscationQueue::CheckSignature() - Got bad Masternode address signature %s \n", vin.ToString().c_str()); } return true; } return false; } void CObfuscationPool::RelayFinalTransaction(const int sessionID, const CTransaction& txNew) { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) { pnode->PushMessage(NetMsgType::DSF, sessionID, txNew); } } void CObfuscationPool::RelayIn(const std::vector<CTxDSIn>& vin, const int64_t& nAmount, const CTransaction& txCollateral, const std::vector<CTxDSOut>& vout) { if (!pSubmittedToMasternode) return; std::vector<CTxIn> vin2; std::vector<CTxOut> vout2; BOOST_FOREACH (CTxDSIn in, vin) vin2.push_back(in); BOOST_FOREACH (CTxDSOut out, vout) vout2.push_back(out); CNode* pnode = FindNode(pSubmittedToMasternode->addr); if (pnode != NULL) { LogPrintf("RelayIn - found master, relaying message - %s \n", pnode->addr.ToString()); pnode->PushMessage(NetMsgType::DSI, vin2, nAmount, txCollateral, vout2); } } void CObfuscationPool::RelayStatus(const int sessionID, const int newState, const int newEntriesCount, const int newAccepted, const int errorID) { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) pnode->PushMessage(NetMsgType::DSSU, sessionID, newState, newEntriesCount, newAccepted, errorID); } void CObfuscationPool::RelayCompletedTransaction(const int sessionID, const bool error, const int errorID) { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) pnode->PushMessage(NetMsgType::DSC, sessionID, error, errorID); } //TODO: Rename/move to core void ThreadCheckObfuScationPool() { if (fLiteMode) return; //disable all Obfuscation/Masternode related functionality // Make this thread recognisable as the wallet flushing thread RenameThread("audax-obfuscation"); unsigned int c = 0; while (true) { MilliSleep(1000); //LogPrintf("ThreadCheckObfuScationPool::check timeout\n"); // try to sync from all available nodes, one step at a time masternodeSync.Process(); if (masternodeSync.IsBlockchainSynced()) { c++; // check if we should activate or ping every few minutes, // start right after sync is considered to be done if (c % MASTERNODE_PING_SECONDS == 1) activeMasternode.ManageStatus(); if (c % 60 == 0) { mnodeman.CheckAndRemove(); mnodeman.ProcessMasternodeConnections(); masternodePayments.CleanPaymentList(); CleanTransactionLocksList(); } //if(c % MASTERNODES_DUMP_SECONDS == 0) DumpMasternodes(); obfuScationPool.CheckTimeout(); obfuScationPool.CheckForCompleteQueue(); if (obfuScationPool.GetState() == POOL_STATUS_IDLE && c % 15 == 0) { obfuScationPool.DoAutomaticDenominating(); } } } }
[ "theaudaxproject@gmail.com" ]
theaudaxproject@gmail.com
6e5eea4955a18d5dbdd393050e7cd0de87638791
f125d550d0457a35220ed35a375c8820efd373e6
/Userland/Libraries/LibJS/Runtime/Symbol.cpp
c25ebf2fceb3837defddbddeef8591471c676118
[ "BSD-2-Clause" ]
permissive
seven1m/serenity
3c4a744fe1cc65e54c9aa62c9f97fb5df04b43bf
447b8e808219d7f326fa6a4fd922adf7a3f86759
refs/heads/master
2021-06-24T19:44:42.274014
2021-02-07T17:25:30
2021-02-07T17:36:31
207,917,650
1
0
BSD-2-Clause
2019-09-11T22:28:44
2019-09-11T22:28:44
null
UTF-8
C++
false
false
1,948
cpp
/* * Copyright (c) 2020, Matthew Olsson <matthewcolsson@gmail.com> * 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <LibJS/Heap/Heap.h> #include <LibJS/Runtime/Symbol.h> #include <LibJS/Runtime/VM.h> namespace JS { Symbol::Symbol(String description, bool is_global) : m_description(move(description)) , m_is_global(is_global) { } Symbol::~Symbol() { } Symbol* js_symbol(Heap& heap, String description, bool is_global) { return heap.allocate_without_global_object<Symbol>(move(description), is_global); } Symbol* js_symbol(VM& vm, String description, bool is_global) { return js_symbol(vm.heap(), move(description), is_global); } }
[ "kling@serenityos.org" ]
kling@serenityos.org
0778adb81b3603d3831e76db4d9d526aa2dcc34c
3011002fecd35f3c878875394ec010967b16929f
/Userland/Libraries/LibJS/Runtime/Temporal/Calendar.h
4009bb0e4e7c4d3b6ebcda69096f2c73e47d13c8
[ "BSD-2-Clause" ]
permissive
yhf20071/serenity
e0bb471733764a4814c2cc61eb0f1fcbe5fb1045
3d4abd7154d8050487a6bad96e6ef4ca0167a32f
refs/heads/master
2023-06-28T10:11:30.887978
2021-07-26T10:44:05
2021-07-26T12:56:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,092
h
/* * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org> * Copyright (c) 2021, Linus Groh <linusg@serenityos.org> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <LibJS/Runtime/Object.h> #include <LibJS/Runtime/Temporal/AbstractOperations.h> #include <LibJS/Runtime/Value.h> namespace JS::Temporal { class Calendar final : public Object { JS_OBJECT(Calendar, Object); public: Calendar(String identifier, Object& prototype); virtual ~Calendar() override = default; String const& identifier() const { return m_identifier; } private: // 12.5 Properties of Temporal.Calendar Instances, https://tc39.es/proposal-temporal/#sec-properties-of-temporal-calendar-instances // [[Identifier]] String m_identifier; }; Calendar* create_temporal_calendar(GlobalObject&, String const& identifier, FunctionObject* new_target = nullptr); bool is_builtin_calendar(String const& identifier); Calendar* get_builtin_calendar(GlobalObject&, String const& identifier); Calendar* get_iso8601_calendar(GlobalObject&); Vector<String> calendar_fields(GlobalObject&, Object& calendar, Vector<StringView> const& field_names); double calendar_year(GlobalObject&, Object& calendar, Object& date_like); double calendar_month(GlobalObject&, Object& calendar, Object& date_like); String calendar_month_code(GlobalObject&, Object& calendar, Object& date_like); double calendar_day(GlobalObject&, Object& calendar, Object& date_like); Value calendar_day_of_week(GlobalObject&, Object& calendar, Object& date_like); Value calendar_day_of_year(GlobalObject&, Object& calendar, Object& date_like); Value calendar_week_of_year(GlobalObject&, Object& calendar, Object& date_like); Value calendar_days_in_week(GlobalObject&, Object& calendar, Object& date_like); Value calendar_days_in_month(GlobalObject&, Object& calendar, Object& date_like); Value calendar_days_in_year(GlobalObject&, Object& calendar, Object& date_like); Value calendar_months_in_year(GlobalObject&, Object& calendar, Object& date_like); Value calendar_in_leap_year(GlobalObject&, Object& calendar, Object& date_like); Object* to_temporal_calendar(GlobalObject&, Value); Object* to_temporal_calendar_with_iso_default(GlobalObject&, Value); Object* get_temporal_calendar_with_iso_default(GlobalObject&, Object&); PlainDate* date_from_fields(GlobalObject&, Object& calendar, Object& fields, Object& options); bool calendar_equals(GlobalObject&, Object& one, Object& two); bool is_iso_leap_year(i32 year); u16 iso_days_in_year(i32 year); i32 iso_days_in_month(i32 year, i32 month); u8 to_iso_day_of_week(i32 year, u8 month, u8 day); u16 to_iso_day_of_year(i32 year, u8 month, u8 day); u8 to_iso_week_of_year(i32 year, u8 month, u8 day); String build_iso_month_code(i32 month); double resolve_iso_month(GlobalObject&, Object& fields); Optional<TemporalDate> iso_date_from_fields(GlobalObject&, Object& fields, Object& options); i32 iso_year(Object& temporal_object); u8 iso_month(Object& temporal_object); String iso_month_code(Object& temporal_object); u8 iso_day(Object& temporal_object); }
[ "mail@linusgroh.de" ]
mail@linusgroh.de
c52cc9a00c502bcbccaa77c805f096c29ea7f3d9
1f032ac06a2fc792859a57099e04d2b9bc43f387
/c8/d4/31/80/6460da460bdf71506f525e808054d4ef131f12289bf0c5fc83237c4838a4c560ace4c536273801aae2c0ffa157a5fbb9e6502bc5a7b7d361fa57702f/sw.cpp
2684b1246d00df78c3e7af4effdfc256eb824d23
[]
no_license
SoftwareNetwork/specifications
9d6d97c136d2b03af45669bad2bcb00fda9d2e26
ba960f416e4728a43aa3e41af16a7bdd82006ec3
refs/heads/master
2023-08-16T13:17:25.996674
2023-08-15T10:45:47
2023-08-15T10:45:47
145,738,888
0
0
null
null
null
null
UTF-8
C++
false
false
227
cpp
void build(Solution &s) { auto &t = s.addStaticLibrary("BLAKE3_team.BLAKE3", "1.0.0"); t += Git("https://github.com/BLAKE3-team/BLAKE3"); t.setRootDirectory("c"); t += "blake3.*"_r; t -= "blake3_neon.c"; }
[ "cppanbot@gmail.com" ]
cppanbot@gmail.com
768c7e395acead526330a74bb15ef2ead0582f97
92c2c9b30dd81e602b1ade90d21567822964f269
/New IAS/DLP-C++/dlpspec_scan.cpp
0e25f947d2a548793c7d98e1fbae11c7e04e1e24
[]
no_license
wyfnevermore/New-IAS
0713fdba3d54359adcf3a75b3ea394060086b160
ce8937eda91842ee688d314258f19a658597ae57
refs/heads/master
2021-01-21T10:55:07.500158
2017-03-01T02:31:05
2017-03-01T02:31:05
83,502,430
0
0
null
null
null
null
UTF-8
C++
false
false
37,566
cpp
/***************************************************************************** ** ** Copyright (c) 2015 Texas Instruments Incorporated. ** ****************************************************************************** ** ** DLP Spectrum Library ** *****************************************************************************/ #include "stdafx.h" #include <stddef.h> #include <stdio.h> #include <string.h> //#include <stdbool.h> #include <stdlib.h> #include <math.h> #include "dlpspec_scan.h" #include "dlpspec_scan_col.h" #include "dlpspec_scan_had.h" #include "dlpspec_types.h" #include "dlpspec_helper.h" #include "dlpspec_util.h" #include "dlpspec_calib.h" /** * @addtogroup group_scan * * @{ */ static patDefHad patDefH; static int32_t dlpspec_scan_slew_genPatterns(const slewScanConfig *pCfg, const calibCoeffs *pCoeffs, const FrameBufferDescriptor *pFB) { int32_t numPatterns=0; patDefCol patDefC; int i; scanConfig cfg; DLPSPEC_ERR_CODE ret_val = (DLPSPEC_PASS); uint32_t start_pattern = 0; cfg.scanConfigIndex = pCfg->head.scanConfigIndex; strcpy(cfg.ScanConfig_serial_number, pCfg->head.ScanConfig_serial_number); strcpy(cfg.config_name, pCfg->head.config_name); cfg.num_repeats = pCfg->head.num_repeats; for(i=0; i < pCfg->head.num_sections; i++) { cfg.scan_type = pCfg->section[i].section_scan_type; cfg.wavelength_start_nm = pCfg->section[i].wavelength_start_nm; cfg.wavelength_end_nm = pCfg->section[i].wavelength_end_nm; cfg.width_px = pCfg->section[i].width_px; cfg.num_patterns = pCfg->section[i].num_patterns; switch (cfg.scan_type) { case COLUMN_TYPE: ret_val = dlpspec_scan_col_genPatDef(&cfg, pCoeffs, &patDefC); if (ret_val == DLPSPEC_PASS) numPatterns = dlpspec_scan_col_genPatterns(&patDefC, pFB, start_pattern); break; case HADAMARD_TYPE: ret_val = dlpspec_scan_had_genPatDef(&cfg, pCoeffs, &patDefH); if (ret_val == DLPSPEC_PASS) numPatterns = dlpspec_scan_had_genPatterns(&patDefH, pFB, start_pattern); break; default: return ERR_DLPSPEC_INVALID_INPUT; } start_pattern += numPatterns; } if (ret_val < 0) { return ret_val; } else { return start_pattern; } } int32_t dlpspec_scan_genPatterns(const uScanConfig* pCfg, const calibCoeffs *pCoeffs, const FrameBufferDescriptor *pFB) /** * @brief Function to generate patterns for a scan. * * This is a wrapper function for the pattern generation functions of the * supported scan modules (Column and Hadamard). In this way, any supported * scan configuration can have patterns generated by calling this function * * @param[in] pCfg Pointer to scan config * @param[in] pCoeffs Pointer to calibration coefficients of the target * optical engine * @param[in] pFB Pointer to frame buffer descriptor where the * patterns will be stored * * @return >0 Number of binary patterns generated from scan config * @return ≤0 Error code as #DLPSPEC_ERR_CODE */ { int32_t numPatterns=0; patDefCol patDefC; DLPSPEC_ERR_CODE ret_val = (DLPSPEC_PASS); switch (pCfg->scanCfg.scan_type) { case COLUMN_TYPE: ret_val = dlpspec_scan_col_genPatDef(&pCfg->scanCfg, pCoeffs, &patDefC); if (ret_val == DLPSPEC_PASS) numPatterns = dlpspec_scan_col_genPatterns(&patDefC, pFB, 0); break; case HADAMARD_TYPE: ret_val = dlpspec_scan_had_genPatDef(&pCfg->scanCfg, pCoeffs, &patDefH); if (ret_val == DLPSPEC_PASS) numPatterns = dlpspec_scan_had_genPatterns(&patDefH, pFB, 0); break; case SLEW_TYPE: numPatterns = dlpspec_scan_slew_genPatterns(&pCfg->slewScanCfg, pCoeffs, pFB); break; default: return ERR_DLPSPEC_INVALID_INPUT; } if (ret_val < 0) { return ret_val; } else { return numPatterns; } } DLPSPEC_ERR_CODE dlpspec_scan_bendPatterns(const FrameBufferDescriptor *pFB , const calibCoeffs* calCoeff, const int32_t numPatterns) /** * Function to bend existing patterns to correct for optical distortion * * @param[in,out] pFB Pointer to frame buffer descriptor where the patterns will be stored * @param[in] calCoeff Pointer to calibration coefficients of the target optical engine * @param[out] numPatterns Number of binary patterns stored in frame buffer * * @return Error code * */ { uint32_t line; int buffer; uint8_t *pLine; uint8_t *pOrigLine; int8_t* shiftVector = NULL; int numBuffers; uint8_t *pBuffer; int lineWidthInBytes; int frameBufferSz; int offset; DLPSPEC_ERR_CODE ret_val = (DLPSPEC_PASS); if ((pFB == NULL) || (calCoeff == NULL)) return (ERR_DLPSPEC_NULL_POINTER); if ((numPatterns < 0)) return (ERR_DLPSPEC_INVALID_INPUT); numBuffers = (numPatterns + (pFB->bpp-1))/pFB->bpp; pBuffer = (uint8_t *)pFB->frameBuffer; lineWidthInBytes = pFB->width * (pFB->bpp/8); frameBufferSz = (lineWidthInBytes * pFB->height); offset = lineWidthInBytes/2; shiftVector = (int8_t*)(malloc(sizeof(uint8_t)*pFB->height)); //Copy line to a larger buffer with zeroes filled on both ends pOrigLine = (uint8_t*)(malloc(lineWidthInBytes * 2)); if( (NULL == shiftVector) || (pOrigLine == NULL)) { ret_val = ERR_DLPSPEC_INSUFFICIENT_MEM; goto cleanup_and_exit; } memset(pOrigLine, 0, lineWidthInBytes*2); /* Calculate the shift vector */ ret_val = dlpspec_calib_genShiftVector(calCoeff->ShiftVectorCoeffs, pFB->height, shiftVector); if (ret_val < 0) { goto cleanup_and_exit; } for(buffer = 0; buffer < numBuffers; buffer++) { memcpy(pOrigLine+offset, pBuffer, lineWidthInBytes); for(line=0 ; line< pFB->height; line++ ) { pLine = pBuffer + (line * lineWidthInBytes); memcpy(pLine, pOrigLine+offset-(shiftVector[line] * (pFB->bpp/8)), lineWidthInBytes); }/*end of line loop*/ pBuffer += frameBufferSz; } /*end of buffer loop*/ cleanup_and_exit: if(shiftVector != NULL) free(shiftVector); if(pOrigLine != NULL) free(pOrigLine); return ret_val; } DLPSPEC_ERR_CODE dlpspec_get_scan_config_dump_size(const uScanConfig *pCfg, size_t *pBufSize) /** * Function that retuns buffer size required to store given scan config structure * after serialization. This should be called to determine the size of array to * be passed to dlpspec_scan_write_configuration(). * * @param[in] pCfg Pointer to scan config * @param[out] pBufSize buffer size required in bytes retuned in this * * @return Error code * */ { DLPSPEC_ERR_CODE ret_val = (DLPSPEC_PASS); size_t size; if (pCfg == NULL) return (ERR_DLPSPEC_NULL_POINTER); if(pCfg->scanCfg.scan_type != SLEW_TYPE) { ret_val = dlpspec_get_serialize_dump_size(pCfg, pBufSize, CFG_TYPE); } else { ret_val = dlpspec_get_serialize_dump_size(pCfg, &size, SLEW_CFG_HEAD_TYPE); if(ret_val != DLPSPEC_PASS) return ret_val; *pBufSize = size; ret_val = dlpspec_get_serialize_dump_size(&pCfg->slewScanCfg.section[0], &size, SLEW_CFG_SECT_TYPE); *pBufSize += size; } return ret_val; } DLPSPEC_ERR_CODE dlpspec_scan_write_configuration(const uScanConfig *pCfg, void *pBuf, const size_t bufSize) /** * Function to write scan configuration to serialized format * * @param[in] pCfg Pointer to scan config * @param[in,out] pBuf Pointer to buffer in which to store the serialized config * @param[in] bufSize buffer size, in bytes * * @return Error code * */ { DLPSPEC_ERR_CODE ret_val = (DLPSPEC_PASS); void *pHeadBuf; void *pSectBuf; size_t size; size_t size1; if ((pCfg == NULL) || (pBuf == NULL)) return (ERR_DLPSPEC_NULL_POINTER); if(pCfg->scanCfg.scan_type != SLEW_TYPE) { ret_val = dlpspec_get_serialize_dump_size(pCfg, &size, CFG_TYPE); if(ret_val != DLPSPEC_PASS) return ret_val; if(bufSize < size) //if allocated size less than required size { return ERR_DLPSPEC_INSUFFICIENT_MEM; } ret_val = dlpspec_serialize(pCfg, pBuf, bufSize, CFG_TYPE); } else { ret_val = dlpspec_get_serialize_dump_size(pCfg, &size, SLEW_CFG_HEAD_TYPE); if(ret_val != DLPSPEC_PASS) return ret_val; ret_val = dlpspec_get_serialize_dump_size(&pCfg->slewScanCfg.section[0], &size1, SLEW_CFG_SECT_TYPE); if(ret_val != DLPSPEC_PASS) return ret_val; if(bufSize < size+size1) //if allocated size less than required size { return ERR_DLPSPEC_INSUFFICIENT_MEM; } pHeadBuf = pBuf; ret_val = dlpspec_serialize(pCfg, pHeadBuf, size, SLEW_CFG_HEAD_TYPE); if(ret_val != DLPSPEC_PASS) return ret_val; pSectBuf = (void *)((char*)pHeadBuf + size); ret_val = dlpspec_serialize(&pCfg->slewScanCfg.section[0], pSectBuf, size1, SLEW_CFG_SECT_TYPE); } return ret_val; } DLPSPEC_ERR_CODE dlpspec_scan_read_configuration(void *pBuf, const size_t bufSize) /** * Function to read scan configuration from a serialized format by deserializing in place * * @param[in,out] pBuf Pointer to the serialized scan config buffer * @param[in] bufSize buffer size, in bytes * * @return Error code * */ { DLPSPEC_ERR_CODE ret_val = (DLPSPEC_PASS); void *pHeadBuf; void *pSectBuf; uScanConfig *pCfg = (uScanConfig *)pBuf; size_t size; size_t size1; if (pBuf == NULL) return (ERR_DLPSPEC_NULL_POINTER); if(dlpspec_is_slewcfgtype(pBuf, bufSize) == false) { ret_val = dlpspec_get_serialize_dump_size(pCfg, &size, CFG_TYPE); if(ret_val != DLPSPEC_PASS) return ret_val; if(bufSize < size) //if allocated size less than required size { return ERR_DLPSPEC_INSUFFICIENT_MEM; } ret_val = dlpspec_deserialize(pBuf, bufSize, CFG_TYPE); } else { ret_val = dlpspec_get_serialize_dump_size(pCfg, &size, SLEW_CFG_HEAD_TYPE); if(ret_val != DLPSPEC_PASS) return ret_val; ret_val = dlpspec_get_serialize_dump_size(&pCfg->slewScanCfg.section[0], &size1, SLEW_CFG_SECT_TYPE); if(ret_val != DLPSPEC_PASS) return ret_val; if(bufSize < size+size1) //if allocated size less than required size { return ERR_DLPSPEC_INSUFFICIENT_MEM; } pHeadBuf = pBuf; ret_val = dlpspec_deserialize(pHeadBuf, size, SLEW_CFG_HEAD_TYPE); if(ret_val != DLPSPEC_PASS) return ret_val; //modify by x00128706 2016/12/2 pSectBuf = (void *)((char *)pHeadBuf + size); //pSectBuf = (void *)((int)pHeadBuf + size); ret_val = dlpspec_deserialize(pSectBuf, size1, SLEW_CFG_SECT_TYPE); memcpy(&pCfg->slewScanCfg.section[0], pSectBuf, sizeof(slewScanSection)*SLEW_SCAN_MAX_SECTIONS); } return ret_val; } static DLPSPEC_ERR_CODE dlpspec_get_scan_data_dump_sizes( const slewScanData *pData, size_t *pSizeDataHead, size_t *pSizeCfgHead, size_t *pSizeSect, size_t *pSizeADCData) { DLPSPEC_ERR_CODE ret_val = (DLPSPEC_PASS); if (pData == NULL) return (ERR_DLPSPEC_NULL_POINTER); ret_val = dlpspec_get_serialize_dump_size(pData, pSizeDataHead, SLEW_DATA_HEAD_TYPE); if(ret_val != DLPSPEC_PASS) return ret_val; ret_val = dlpspec_get_serialize_dump_size(&pData->slewCfg, pSizeCfgHead, SLEW_CFG_HEAD_TYPE); if(ret_val != DLPSPEC_PASS) return ret_val; ret_val = dlpspec_get_serialize_dump_size(&pData->slewCfg.section[0], pSizeSect, SLEW_CFG_SECT_TYPE); if(ret_val != DLPSPEC_PASS) return ret_val; ret_val = dlpspec_get_serialize_dump_size(&pData->adc_data[0], pSizeADCData, SLEW_DATA_ADC_TYPE); return ret_val; } DLPSPEC_ERR_CODE dlpspec_get_scan_data_dump_size(const uScanData *pData, size_t *pBufSize) /** * Function that retuns buffer size required to store given scan data structure * after serialization. This should be called to determine the size of array to * be passed to dlpspec_scan_write_data(). * * @param[in] pData Pointer to scan data * @param[out] pBufSize buffer size required in bytes retuned in this * * @return Error code * */ { DLPSPEC_ERR_CODE ret_val = (DLPSPEC_PASS); size_t size_data_head; size_t size_cfg_head; size_t size_sect; size_t size_adc_data; if (pData == NULL) return (ERR_DLPSPEC_NULL_POINTER); if(pData->data.scan_type != SLEW_TYPE) { ret_val = dlpspec_get_serialize_dump_size(pData, pBufSize, SCAN_DATA_TYPE); } else { ret_val = dlpspec_get_scan_data_dump_sizes(&pData->slew_data, &size_data_head, &size_cfg_head, &size_sect, &size_adc_data); *pBufSize = size_data_head+size_cfg_head+size_sect+size_adc_data; } return ret_val; } DLPSPEC_ERR_CODE dlpspec_scan_write_data(const uScanData *pData, void *pBuf, const size_t bufSize) /** * Function to write scan data to serialized format * * @param[in] pData Pointer to scan data * @param[in,out] pBuf Pointer to buffer in which to store the * serialized scan data * @param[in] bufSize buffer size, in bytes * * @return Error code * */ { DLPSPEC_ERR_CODE ret_val = (DLPSPEC_PASS); size_t size; size_t size_data_head; size_t size_cfg_head; size_t size_sect; size_t size_adc_data; void *pHeadBuf; void *pSectBuf; void *pADCdataBuf; int type; if ((pData == NULL) || (pBuf == NULL)) return (ERR_DLPSPEC_NULL_POINTER); type = dlpspec_scan_data_get_type(pData); if(type != SLEW_TYPE) { ret_val = dlpspec_get_serialize_dump_size(pData, &size, SCAN_DATA_TYPE); if(ret_val != DLPSPEC_PASS) return ret_val; if(bufSize < size) //if allocated size less than required size { return ERR_DLPSPEC_INSUFFICIENT_MEM; } ret_val = dlpspec_serialize(pData, pBuf, bufSize, SCAN_DATA_TYPE); } else { ret_val = dlpspec_get_scan_data_dump_sizes(&pData->slew_data, &size_data_head, &size_cfg_head, &size_sect, &size_adc_data); if(ret_val != DLPSPEC_PASS) return ret_val; if(bufSize < size_data_head+size_cfg_head+size_sect+size_adc_data) //if allocated size less than required size { return ERR_DLPSPEC_INSUFFICIENT_MEM; } ret_val = dlpspec_serialize(pData, pBuf, size_data_head, SLEW_DATA_HEAD_TYPE); if(ret_val != DLPSPEC_PASS) return ret_val; pHeadBuf = (void *)((char*)pBuf + size_data_head); ret_val = dlpspec_serialize(&pData->slew_data.slewCfg, pHeadBuf, size_cfg_head, SLEW_CFG_HEAD_TYPE); if(ret_val != DLPSPEC_PASS) return ret_val; pSectBuf = (void *)((char*)pHeadBuf + size_cfg_head); ret_val = dlpspec_serialize(&pData->slew_data.slewCfg.section[0], pSectBuf, size_sect, SLEW_CFG_SECT_TYPE); if(ret_val != DLPSPEC_PASS) return ret_val; pADCdataBuf = (void *)((char*)pSectBuf + size_sect); ret_val = dlpspec_serialize(&pData->slew_data.adc_data[0], pADCdataBuf, size_adc_data, SLEW_DATA_ADC_TYPE); } return ret_val; } DLPSPEC_ERR_CODE dlpspec_scan_read_data(void *pBuf, const size_t bufSize) /** * Function to deserialize a serialized scan data blob. The deserialized data * is placed at the same buffer (pBuf). * * @param[in] pBuf Pointer to serialized scan data blob; where output * deserialized data is also returned. * @param[in] bufSize buffer size, in bytes * * @return Error code * */ { DLPSPEC_ERR_CODE ret_val = (DLPSPEC_PASS); void *pHeadBuf; void *pSectBuf; void *pADCdataBuf; size_t size_data_head; size_t size_cfg_head; size_t size_sect; size_t size_adc_data; uScanData *pData = (uScanData *)pBuf; if (pBuf == NULL) return (ERR_DLPSPEC_NULL_POINTER); if(dlpspec_is_slewdatatype(pBuf, bufSize) == false) { ret_val = dlpspec_deserialize(pBuf, bufSize, SCAN_DATA_TYPE); } else { ret_val = dlpspec_get_scan_data_dump_sizes(&pData->slew_data, &size_data_head, &size_cfg_head, &size_sect, &size_adc_data); if(ret_val != DLPSPEC_PASS) return ret_val; if(bufSize < size_data_head+size_cfg_head+size_sect+size_adc_data) //if allocated size less than required size { return ERR_DLPSPEC_INSUFFICIENT_MEM; } ret_val = dlpspec_deserialize(pBuf, size_data_head, SLEW_DATA_HEAD_TYPE); pHeadBuf = (void *)((char*)pBuf + size_data_head); ret_val = dlpspec_deserialize(pHeadBuf, size_cfg_head, SLEW_CFG_HEAD_TYPE); if(ret_val != DLPSPEC_PASS) return ret_val; memcpy(&pData->slew_data.slewCfg.head, pHeadBuf, sizeof(struct slewScanConfigHead)); pSectBuf = (void *)((char*)pHeadBuf + size_cfg_head); ret_val = dlpspec_deserialize(pSectBuf, size_sect, SLEW_CFG_SECT_TYPE); memcpy(&pData->slew_data.slewCfg.section[0], pSectBuf, sizeof(slewScanSection)*SLEW_SCAN_MAX_SECTIONS); pADCdataBuf = (void *)((char*)pSectBuf + size_sect); ret_val = dlpspec_deserialize(pADCdataBuf, size_adc_data, SLEW_DATA_ADC_TYPE); memcpy(pData->slew_data.adc_data, pADCdataBuf, sizeof(uint32_t)*ADC_DATA_LEN); } return ret_val; } static DLPSPEC_ERR_CODE dlpspec_scan_slew_interpret(uScanData *pData, scanResults *pRefResults) { scanResults tempScanResults; uScanData thisScanData; DLPSPEC_ERR_CODE ret_val = (DLPSPEC_PASS); int i; int num_data; dlpspec_subtract_dc_level(&pData->slew_data); for(i=0; i < pData->slew_data.slewCfg.head.num_sections; i++) { dlpspec_get_scanData_from_slewScanData(&pData->slew_data, &thisScanData.data, i); if(pData->slew_data.slewCfg.section[i].section_scan_type == COLUMN_TYPE) ret_val = dlpspec_scan_col_interpret(&thisScanData, &tempScanResults); else if(pData->slew_data.slewCfg.section[i].section_scan_type == HADAMARD_TYPE) ret_val = dlpspec_scan_had_interpret(&thisScanData, &tempScanResults); else return ERR_DLPSPEC_ILLEGAL_SCAN_TYPE; if(ret_val != DLPSPEC_PASS) break; if(i==0) { memcpy(pRefResults, &tempScanResults, sizeof(scanResults)); dlpspec_copy_scanData_hdr_to_scanResults(pData, pRefResults); num_data = tempScanResults.cfg.section[0].num_patterns; } else { memcpy(&pRefResults->intensity[num_data], &tempScanResults.intensity[0], tempScanResults.cfg.section[0].num_patterns*sizeof(int)); memcpy(&pRefResults->wavelength[num_data], &tempScanResults.wavelength[0], tempScanResults.cfg.section[0].num_patterns*sizeof(double)); num_data += tempScanResults.cfg.section[0].num_patterns; pRefResults->length += tempScanResults.length; } } return ret_val; } DLPSPEC_ERR_CODE dlpspec_scan_interpret(const void *pBuf, const size_t bufSize, scanResults *pResults) /** * Function to interpret a serialized scan data blob into a results struct * * @param[in] pBuf Pointer to serialized scan data blob * @param[in] bufSize buffer size, in bytes * @param[out] pResults Pointer to scanResults struct * * @return Error code * */ { uScanData *pData; DLPSPEC_ERR_CODE ret_val = (DLPSPEC_PASS); SCAN_TYPES type; if ((pBuf == NULL) || (pResults == NULL)) return (ERR_DLPSPEC_NULL_POINTER); void *pCopyBuff = (void *)malloc(bufSize); if(pCopyBuff == NULL) return (ERR_DLPSPEC_INSUFFICIENT_MEM); memcpy(pCopyBuff, pBuf, bufSize); ret_val = dlpspec_scan_read_data(pCopyBuff, bufSize); if(ret_val < 0) { goto cleanup_and_exit; } pData = (uScanData *)pCopyBuff; if(pData->data.header_version != CUR_SCANDATA_VERSION) { ret_val = ERR_DLPSPEC_FAIL; goto cleanup_and_exit; } memset(pResults,0,sizeof(scanResults)); type = dlpspec_scan_data_get_type(pData); if(type == HADAMARD_TYPE) { ret_val = dlpspec_scan_had_interpret((uScanData*)pCopyBuff, pResults); } else if(type == COLUMN_TYPE) { ret_val = dlpspec_scan_col_interpret((uScanData*)pCopyBuff, pResults); } else if(type == SLEW_TYPE) { ret_val = dlpspec_scan_slew_interpret((uScanData*)pCopyBuff, pResults); } else { ret_val = ERR_DLPSPEC_INVALID_INPUT; } cleanup_and_exit: if(pCopyBuff != NULL) free(pCopyBuff); return ret_val; } static DLPSPEC_ERR_CODE dlpspec_scan_scale_for_pga_gain(const scanResults *pScanResults, scanResults *pRefResults) { DLPSPEC_ERR_CODE ret_val = (DLPSPEC_PASS); int j; if (pScanResults->pga != pRefResults->pga) { if (pRefResults->pga > 0) { for (j=0; j < ADC_DATA_LEN; j++) { if (pRefResults->wavelength[j] != 0) pRefResults->intensity[j] = pRefResults->intensity[j] * pScanResults->pga / pRefResults->pga; else break; } } else ret_val = ERR_DLPSPEC_INVALID_INPUT; } return ret_val; } static DLPSPEC_ERR_CODE dlpspec_scan_recomputeRefIntensities(const scanResults *pScanResults, scanResults *pRefResults, const refCalMatrix *pMatrix) /** * Function to interpret a results struct of intensities into a predicted * spectrum which would have been measured with a target configuration that * has a different pixel width and/or PGA setting. Due to the diffraction * efficiency of the DMD varying with wavelength and the width of on pixels, * the efficiency of reflection can vary with these inputs. This is used * internally by the dlpspec_scan_interpReference() function. * * @param[in] pScanResults Scan results from sample scan data * (output of dlpspec_scan_interpret function) * @param[in,out] pRefResults Pointer to scanResults struct with the * original scan data. This is assumed to have * only one scan section (ref scan cannot be * a slew scan). * @param[in] pMatrix Pointer to the reference calibration matrix. This * matrix will be opto-mechanical design specific. * * @return Error code * */ { double factor[ADC_DATA_LEN]; double wavelengths[ADC_DATA_LEN]; uint32_t i = 0, j = 0; int temp_val = 0; int s_idx; uint32_t section_data_len; uint32_t adc_data_idx = 0; int px_width_lower_bound =0, px_width_upper_bound=0; int ref_val = 0; DLPSPEC_ERR_CODE ret_val = (DLPSPEC_PASS); if ((pRefResults == NULL) || (pMatrix == NULL) || (pScanResults == NULL)) return (ERR_DLPSPEC_NULL_POINTER); memset(wavelengths,0,sizeof(double)*ADC_DATA_LEN); memset(factor,0,sizeof(double)*ADC_DATA_LEN); for(s_idx = 0; s_idx < pScanResults->cfg.head.num_sections; s_idx++) { for (j=0; j < REF_CAL_INTERP_WAVELENGTH; j++) { factor[j] = 1; wavelengths[j] = pMatrix->wavelength[j]; } section_data_len = pScanResults->cfg.section[s_idx].num_patterns; /* If width is not the same between reference cal data config and input, * then we need to compute the values */ if (((pRefResults->cfg.head.num_sections == 1) && (pScanResults->cfg.head.num_sections == 1) && (pScanResults->cfg.section[0].width_px == pRefResults->cfg.section[0].width_px)) == false) { /* Compute the indices to pixel widths less and greater than pixel * width used for reference calibration. This is used later on to * normalize factors with respect to reference calibration intensities */ for (i=0;i < REF_CAL_INTERP_WIDTH;i++) { if (pMatrix->width[i] < pRefResults->cfg.section[0].width_px) continue; else if (pMatrix->width[i] == pRefResults->cfg.section[0].width_px) { px_width_lower_bound = i; px_width_upper_bound = i; } else { px_width_lower_bound = i-1; px_width_upper_bound = i; } break; } for (j=0; j < REF_CAL_INTERP_WAVELENGTH; j++) { if (i == 0) { ret_val = dlpspec_compute_from_references(pMatrix->width[i], pMatrix->width[i+1], pMatrix->ref_lookup[i][j], pMatrix->ref_lookup[i+1][j], pScanResults->cfg.section[s_idx].width_px, &temp_val); } else if (i == (REF_CAL_INTERP_WIDTH - 1)) { ret_val = dlpspec_compute_from_references(pMatrix->width[i-1], pMatrix->width[i], pMatrix->ref_lookup[i-1][j], pMatrix->ref_lookup[i][j], pScanResults->cfg.section[s_idx].width_px, &temp_val); } else { ret_val = dlpspec_compute_from_references(pMatrix->width[i], pMatrix->width[i-1], pMatrix->ref_lookup[i][j], pMatrix->ref_lookup[i-1][j], pScanResults->cfg.section[s_idx].width_px, &temp_val); } if (ret_val < 0) { return ret_val; } // Compute the intensity at pixel width used for reference // calibration and use it to normalize the computed factor if (px_width_lower_bound == px_width_upper_bound) ref_val = pMatrix->ref_lookup[px_width_lower_bound][j]; else { ret_val = dlpspec_compute_from_references( pMatrix->width[px_width_lower_bound], pMatrix->width[px_width_upper_bound], pMatrix->ref_lookup[px_width_lower_bound][j], pMatrix->ref_lookup[px_width_upper_bound][j], pRefResults->cfg.section[0].width_px, &ref_val); } if (ret_val < 0) { return ret_val; } factor[j] = factor[j] * temp_val / ref_val; } /* Next adjust the factors based on wavelengths in reference scan data * and ones used in reference matrix measurements */ ret_val = dlpspec_interpolate_double_wavelengths(&pRefResults->wavelength[adc_data_idx], wavelengths, factor, section_data_len); if (ret_val < 0) { return ret_val; } for (i = 0; i < section_data_len; adc_data_idx++, i++) { if (pRefResults->wavelength[adc_data_idx] != 0) { pRefResults->intensity[adc_data_idx] = pRefResults->intensity[adc_data_idx] * factor[i]; } else break; } } } ret_val = dlpspec_scan_scale_for_pga_gain(pScanResults, pRefResults); return (ret_val); } DLPSPEC_ERR_CODE dlpspec_scan_interpReference(const void *pRefCal, size_t calSize, const void *pMatrix, size_t matrixSize, const scanResults *pScanResults, scanResults *pRefResults) /** * Function to interpret reference scan data into what the reference scan would have been * if it were scanned with the configuration which @p pScanResults was scanned with. * This can be used to compute a reference for an arbitrary scan taken when a physical * reflective reference is not available to take a new reference measurement. * * @param[in] pRefCal Pointer to serialized reference calibration data * @param[in] calSize Size of reference calibration data blob * @param[in] pMatrix Pointer to serialized reference calibration matrix * @param[in] matrixSize Size of reference calibration matrix data blob * @param[in] pScanResults Scan results from sample scan data (output of dlpspec_scan_interpret function) * @param[out] pRefResults Reference scan data result * * @return Error code * */ { DLPSPEC_ERR_CODE ret_val = (DLPSPEC_PASS); scanData *pDesRefScanData = NULL; //To hold deserialized reference scan data refCalMatrix *pDesRefCalMatrix = NULL; //To hold deserialized reference cal matrix data int i = 0; if ((pRefCal == NULL) || (pMatrix == NULL) || (pScanResults == NULL) || (pRefResults == NULL)) return (ERR_DLPSPEC_NULL_POINTER); /* New error checking since SCAN_DATA_BLOB_SIZE and REF_CAL_MATRIX_BLOB_SIZE will vary based on compilation target with sizeof() call */ if ((calSize == 0) || (matrixSize == 0)) return (ERR_DLPSPEC_INVALID_INPUT); /* Previous error checking if ((calSize == 0) || (calSize > SCAN_DATA_BLOB_SIZE) || (matrixSize == 0) || (matrixSize > REF_CAL_MATRIX_BLOB_SIZE)) return (ERR_DLPSPEC_INVALID_INPUT); */ // Make a local copy of the input data and deserialize them pDesRefScanData = (scanData *)malloc(calSize); if (pDesRefScanData == NULL) return (ERR_DLPSPEC_INSUFFICIENT_MEM); memcpy(pDesRefScanData,pRefCal, calSize); pDesRefCalMatrix = (refCalMatrix *)malloc(matrixSize); if (pDesRefCalMatrix == NULL) { ret_val = ERR_DLPSPEC_INSUFFICIENT_MEM; goto cleanup_and_exit; } memcpy(pDesRefCalMatrix, pMatrix, matrixSize); ret_val = dlpspec_deserialize((void *)pDesRefCalMatrix, matrixSize, REF_CAL_MATRIX_TYPE); if (ret_val < 0) { goto cleanup_and_exit; } // Interpret reference scan data - creates scan results from reference scan data memset(pRefResults,0,sizeof(scanResults)); ret_val = dlpspec_scan_interpret(pDesRefScanData, calSize, pRefResults); if (ret_val < 0) { goto cleanup_and_exit; } /* No need to interpolate if the two scan configs are same */ if(dlpspec_scan_cfg_compare(&pScanResults->cfg, &pRefResults->cfg) == DLPSPEC_PASS) { ret_val = dlpspec_scan_scale_for_pga_gain(pScanResults, pRefResults); goto cleanup_and_exit; } ret_val = dlpspec_valid_configs_to_interp(&pScanResults->cfg, &pRefResults->cfg); if (ret_val < 0) { goto cleanup_and_exit; } /* * Check for data integrity before interpolating wavelengths */ for (i =0; i< pScanResults->length; i++) { if (pScanResults->wavelength[i] == 0) { ret_val = (ERR_DLPSPEC_INVALID_INPUT); goto cleanup_and_exit; } } for (i =0; i< pRefResults->length; i++) { if ((pRefResults->wavelength[i] == 0) || (pRefResults->intensity[i] == 0)) { ret_val = (ERR_DLPSPEC_INVALID_INPUT); goto cleanup_and_exit; } } /* Using wavelengths from pScanResults, wavelengths from pRefResults, and magnitudes of pRefResult * modify refIntensity using piecewise linear interpolation at refNM wavelengths */ ret_val = dlpspec_interpolate_int_wavelengths(pScanResults->wavelength, pScanResults->length, pRefResults->wavelength, pRefResults->intensity, pRefResults->length); if (ret_val < 0) { goto cleanup_and_exit; } // Populate data length - may be required by functions down stream pRefResults->length = pScanResults->length; /* Transfer function from pRefResults at the scan configuration taken * during reference calibration to the scan configuration used in * pScanResults. Inputs will be: refIntensity, scanConfig, * refWavelength, and the baked in model equation / coefficients. * Primary drivers will be pattern width * but there may be some differences between linescan and Hadamard also. */ ret_val = dlpspec_scan_recomputeRefIntensities( pScanResults, pRefResults, pDesRefCalMatrix); if (ret_val < 0) { goto cleanup_and_exit; } /* TBD: Add transfer function from pRefResults at the environmental * readings in pRefResults to what it would be in pScanResults with those * environmental readings. Inputs will be: refIntensity, refEnvironment, * and scanEnvironment and the baked in model equation / coefficients. * Primary drivers will be humidity, detector photodiode, and detector * temperature * Timeline: v2.0 */ cleanup_and_exit: if (pDesRefScanData != NULL) free(pDesRefScanData); if (pDesRefCalMatrix != NULL) free(pDesRefCalMatrix); return (ret_val); } SCAN_TYPES dlpspec_scan_slew_get_cfg_type(const slewScanConfig *pCfg) /** * If the cfg has only one section, returns the type of that section. Otherwise * returns type as SLEW_TYPE. * * @param[in] pCfg Pointer to slew scan configuration * * @return returns the type of scan as defined in SCAN_TYPES enum * */ { if(pCfg->head.num_sections != 1) return SLEW_TYPE; else { if(pCfg->section[0].section_scan_type == COLUMN_TYPE) return COLUMN_TYPE; else return HADAMARD_TYPE; } } int16_t dlpspec_scan_slew_get_num_patterns(const slewScanConfig *pCfg) /** * Returns the total number of patterns in this slew scan. The number returned excludes the count of black * patterns inserted during scan to compensate for stray light. * * @param[in] pCfg Pointer to slew scan configuration * * @return Total number of patterns in this slew scan (does not include the count of black * patterns inserted during scan to compensate for stray light) * */ { int16_t pattern_count = 0; int i; if(pCfg == NULL) return ERR_DLPSPEC_NULL_POINTER; for(i=0; i<pCfg->head.num_sections; i++) pattern_count += pCfg->section[i].num_patterns; return pattern_count; } int16_t dlpspec_scan_slew_get_end_nm(const slewScanConfig *pCfg) /** * Returns the largest wavelength that this slew scan definition includes. * * @param[in] pCfg Pointer to slew scan configuration * * @return the largest wavelength that this slew scan definition includes. * */ { int16_t end_nm = 0; int i; if(pCfg == NULL) return ERR_DLPSPEC_NULL_POINTER; for(i=0; i<pCfg->head.num_sections; i++) { if(pCfg->section[i].wavelength_end_nm > end_nm) end_nm = pCfg->section[i].wavelength_end_nm; } return end_nm; } uint32_t dlpspec_scan_get_exp_time_us(EXP_TIME time_enum) /** * Returns the actual exposure time for a given section in microseconds given the * specified enumerated exposure time value. Since the user is not allowed to pass * any desired number as the exposure time, we have defined an enum EXP_TIME which * is to be passed in the exp_time field of each section in a slew scan definition. * Then this function is to be used to converted that enum value to the actual exposure * time in microseconds. * * @param[in] time_enum Enumerated value that is specified as exposure time. * * @return Actual exposure time in microseconds corresponding to the given enum value. * */ { switch(time_enum) { case T_635_US: return 635; case T_1270_US: return 1270; case T_2450_US: return 2450; case T_5080_US: return 5080; case T_15240_US: return 15240; case T_30480_US: return 30480; case T_60960_US: return 60960; default: return 0; } } DLPSPEC_ERR_CODE dlpspec_scan_section_get_adc_data_range(const slewScanData *pData, int section_index,int *p_section_start_index, uint16_t *p_num_patterns, uint16_t *p_num_black_patterns) /** * Given a slew scan data, this function helps separate data corresponding to different * sections of the scan. For the given section index, it returns the start index of adc * data corresponding to that section, number of non-black patterns in that section and * number of black patterns. * * @param[in] pData Pointer to slew scan data * @param[in] section_index section specifier * @param[out] p_section_start_index start index of ADC data corresponding to given section * @param[out] p_num_patterns number of patterns (excluding additonally inserted black patterns) * in the given section. * @param[out] p_num_black_patterns Number of black patterns inserted during scan corresponding * to the given section. * * @return Error code * */ { uint16_t num_patterns; uint16_t num_black_patterns; scanConfig cfg; int i; int j; int32_t section_start_index = 0; for(i=0; i<=section_index; i++) { if(pData->slewCfg.section[i].section_scan_type == COLUMN_TYPE) { num_patterns = pData->slewCfg.section[i].num_patterns; } else if (pData->slewCfg.section[i].section_scan_type == HADAMARD_TYPE) { cfg.wavelength_start_nm = pData->slewCfg.section[i].wavelength_start_nm; cfg.wavelength_end_nm = pData->slewCfg.section[i].wavelength_end_nm; cfg.width_px = pData->slewCfg.section[i].width_px; cfg.num_patterns = pData->slewCfg.section[i].num_patterns; cfg.num_repeats = pData->slewCfg.head.num_repeats; cfg.scan_type = pData->slewCfg.section[i].section_scan_type; dlpspec_scan_had_genPatDef(&cfg, &pData->calibration_coeffs, &patDefH); num_patterns = patDefH.numPatterns; } else { return ERR_DLPSPEC_INVALID_INPUT; } num_black_patterns = 0; for(j=section_start_index; j < (section_start_index + num_patterns + num_black_patterns); j++) if((j+1)%pData->black_pattern_period == 0) num_black_patterns++; if(i==section_index) { *p_section_start_index = section_start_index; *p_num_patterns = num_patterns; *p_num_black_patterns = num_black_patterns; } else { section_start_index += (num_patterns + num_black_patterns); } } return DLPSPEC_PASS; } /** @} // group group_scan * */
[ "843645610@qq.com" ]
843645610@qq.com
428bc94c268a9c58a2fbe8b10ab1deb25e421bbe
b2101f4e8123b7a692932b741a2b9be2b2209ddb
/July-21/JUly-21.2/main.cpp
e2a040ae1e5f4566aca04c451ecbabf824fdc442
[]
no_license
Sweety4/cpp
465e560ce7bcec04d461044bd1d2b2dab84cf548
dba08f024ad2f356f65f0e952250369cc1f7f5f9
refs/heads/master
2022-11-29T05:30:12.680733
2020-08-01T14:03:53
2020-08-01T14:03:53
283,262,529
2
0
null
null
null
null
UTF-8
C++
false
false
79
cpp
#include"Test.h" void main() { Test t1(10); t1.Display(); cout << "\n\n"; }
[ "sweetyjangale5@gmail.com" ]
sweetyjangale5@gmail.com
a91c5dd077fb41793808d96b05ccb51266b61290
9ac887713ffc194682d6f088b690b76b8525b260
/books/pc_data_structure/19/puzzle8.cpp
86164f9a88220198dab5ce4e9415f9459bdb8e83
[]
no_license
ganmacs/playground
27b3e0625796f6ee5324a70b06d3d3e5c77e1511
a007f9fabc337561784b2a6040b5be77361460f8
refs/heads/master
2022-05-25T05:52:49.583453
2022-05-09T03:39:12
2022-05-09T04:06:15
36,348,909
6
0
null
2019-06-18T07:23:16
2015-05-27T06:50:59
C++
UTF-8
C++
false
false
1,812
cpp
#include <algorithm> #include <iostream> #include <sstream> #include <string> #include <vector> #include <cstdio> #include <cmath> #include <queue> #include <map> #include <set> using namespace std; static const int N = 9; static const int N2 = 3; struct m_t { int m[N2][N2]; int x0, y0; int dist; bool operator < (const m_t &oth) const { for (int i = 0; i < N2; i++) { for (int j = 0; j < N2; j++) { if (oth.m[i][j] == m[i][j]) continue; return m[i][j] > oth.m[i][j]; } } return false; } }; map<m_t, bool> M; queue<m_t> Q; int n; const int dy[4] = {-1, 0, 0, 1}; const int dx[4] = {0, -1, 1, 0}; int ans[N2][N2] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 0}}; void pp(m_t m) { for (int i = 0; i < N2; i++) { for (int j = 0; j < N2; j++) { cout << m.m[i][j] << " "; } cout << endl; } } bool is_goal(m_t m) { for (int i = 0; i < N2; i++) { for (int j = 0; j < N2; j++) { if (ans[i][j] != m.m[i][j]) return false; } } return true; } int bfs(m_t mm) { m_t m, tmp; int xx, yy; Q.push(mm); M[mm] = true; while (!Q.empty()) { m = Q.front(); Q.pop(); if (is_goal(m)) return m.dist; for (int i = 0; i < 4; i++) { yy = dy[i] + m.y0; xx = dx[i] + m.x0; if (!(0 <= xx && xx < N2 && 0 <= yy && yy < N2)) continue; tmp = m; swap(tmp.m[yy][xx], tmp.m[m.y0][m.x0]); if(!M[tmp]) { tmp.y0 = yy; tmp.x0 = xx; M[tmp] = true; tmp.dist += 1; Q.push(tmp); } } } return -1; } int main(){ m_t m; int v; m.dist = 0; for (int i = 0; i < N2; i++) { for (int j = 0; j < N2; j++) { cin >> v; if (v == 0) { m.y0 = i; m.x0 = j; } m.m[i][j] = v; } } cout << bfs(m) << endl;; }
[ "ganmacs@gmail.com" ]
ganmacs@gmail.com
9a1ededaacc4193b8ce12c29d589d6122b064214
e0258286b3345c7afc09cc0b31b28b981f1f3ac7
/Serveur_interaction_sans_contact-master/Serveur_isc/Serveur_isc/CommandeHelp.cpp
6945017f980a72ced6f0cb8e5e9da9262f739428
[]
no_license
IHMISC2020/ISCServer
6e3423655ebb97815aaac149915af83d9f862a7f
f3861e81569b8932240e2dbea3a22d7fe2856432
refs/heads/main
2023-04-09T16:42:20.783647
2021-04-13T17:26:59
2021-04-13T17:26:59
357,605,967
0
0
null
null
null
null
UTF-8
C++
false
false
830
cpp
#include "CommandeHelp.h" #include <sstream> CommandeHelp::CommandeHelp(CommandesServeurLst* next, ServerTCP& serveur) : CommandesServeurLst(next), m_serveur(serveur) {} CommandeHelp::~CommandeHelp() {} int CommandeHelp::resoud_expert(const std::string& commande, const std::vector<std::string>& args) { if (commande == "help" || commande == "h" || commande == "aide") { std::ostringstream oss; oss << "voici la liste des commandes disponibles : " << std::endl; oss << "commande -- explication" << std::endl; oss << "<help> ou <h> -- liste des commandes disponibles" << std::endl; oss << "<quit> ou <q> -- etein le serveur et vous deconnecte" << std::endl; oss << "<motive> ou <m> -- envoi la liste des points capter par motive" << std::endl; m_serveur.envoi_message(oss.str()); return 0; } return -1; }
[ "noreply@github.com" ]
IHMISC2020.noreply@github.com
e1156a73c6110b398fd6b052274f77452b70dd31
3ef99240a541f699d71d676db514a4f3001b0c4b
/UVa Online Judge/v3/343.cc
df0a253fe4166134d3819cd136b1df6cd8817a24
[ "MIT" ]
permissive
mjenrungrot/competitive_programming
36bfdc0e573ea2f8656b66403c15e46044b9818a
e0e8174eb133ba20931c2c7f5c67732e4cb2b703
refs/heads/master
2022-03-26T04:44:50.396871
2022-02-10T11:44:13
2022-02-10T11:44:13
46,323,679
1
0
null
null
null
null
UTF-8
C++
false
false
4,371
cc
/*============================================================================= # Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/ # FileName: 343.cc # Description: UVa Online Judge - 343 =============================================================================*/ #include <bits/stdc++.h> #pragma GCC optimizer("Ofast") #pragma GCC target("avx2") using namespace std; typedef pair<int, int> ii; typedef pair<long long, long long> ll; typedef pair<double, double> dd; typedef tuple<int, int, int> iii; typedef tuple<long long, long long, long long> lll; typedef tuple<double, double, double> ddd; typedef vector<string> vs; typedef vector<int> vi; typedef vector<vector<int>> vvi; typedef vector<long long> vl; typedef vector<vector<long long>> vvl; typedef vector<double> vd; typedef vector<vector<double>> vvd; typedef vector<ii> vii; typedef vector<ll> vll; typedef vector<dd> vdd; // Debug Snippets void __print(int x) { cerr << x; } void __print(long x) { cerr << x; } void __print(long long x) { cerr << x; } void __print(unsigned x) { cerr << x; } void __print(unsigned long x) { cerr << x; } void __print(unsigned long long x) { cerr << x; } void __print(float x) { cerr << x; } void __print(double x) { cerr << x; } void __print(long double x) { cerr << x; } void __print(char x) { cerr << '\'' << x << '\''; } void __print(const char* x) { cerr << '\"' << x << '\"'; } void __print(const string& x) { cerr << '\"' << x << '\"'; } void __print(bool x) { cerr << (x ? "true" : "false"); } template <typename T, typename V> void __print(const pair<T, V>& x) { cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}'; } template <typename T> void __print(const T& x) { int f = 0; cerr << '{'; for (auto& i : x) cerr << (f++ ? "," : ""), __print(i); cerr << "}"; } void _print() { cerr << "]\n"; } template <typename T, typename... V> void _print(T t, V... v) { __print(t); if (sizeof...(v)) cerr << ", "; _print(v...); } #define debug(x...) \ cerr << "[" << #x << "] = ["; \ _print(x) template <class Ch, class Tr, class Container> basic_ostream<Ch, Tr>& operator<<(basic_ostream<Ch, Tr>& os, Container const& x) { os << "{ "; for (auto& y : x) os << y << " "; return os << "}"; } template <class X, class Y> ostream& operator<<(ostream& os, pair<X, Y> const& p) { return os << "[ " << p.first << ", " << p.second << "]"; } // End Debug Snippets vs split(string line) { vs output; istringstream iss(line); string tmp; while (iss >> tmp) { output.push_back(tmp); } return output; } vs split(string line, regex re) { vs output; sregex_token_iterator it(line.begin(), line.end(), re, -1), it_end; while (it != it_end) { output.push_back(it->str()); it++; } return output; } const int INF_INT = 1e9 + 7; const long long INF_LL = 1e18; const int MAXBASE = 40; string A, B; int valid1[MAXBASE], valid2[MAXBASE]; int f(char ch) { if (ch >= '0' and ch <= '9') return ch - '0'; return ch - 'A' + 10; } int eval(string x, int base) { int ans = 0; for (int i = 0; i < x.length(); i++) { ans *= base; int val = f(x[i]); if (val >= base) return -INF_INT; ans += val; } return ans; } void solve() { memset(valid1, -1, sizeof(valid1)); memset(valid2, -1, sizeof(valid2)); for (int base1 = 2; base1 <= 36; base1++) for (int base2 = 2; base2 <= 36; base2++) { int val1, val2; if (valid1[base1] != -1) val1 = valid1[base1]; else val1 = valid1[base1] = eval(A, base1); if (valid2[base2] != -1) val2 = valid2[base2]; else val2 = valid2[base2] = eval(B, base2); if (val1 == -INF_INT or val2 == -INF_INT) continue; if (val1 == val2) { cout << A << " (base " << base1 << ") = " << B << " (base " << base2 << ")" << endl; return; } } cout << A << " is not equal to " << B << " in any base 2..36" << endl; } int main() { ios::sync_with_stdio(false); cin.tie(0); while (cin >> A >> B) solve(); return 0; }
[ "" ]
d432a68af8098d507badad62ef6150291f94dc01
e22ab275a7122dfad34f60effe8654d6fd57f781
/Enemies/Paver.h
11f8977f8ec7a83d294f20349d41942bce823aa0
[]
no_license
RadwaSK/BattleGameSimulation
4a6a81d6ef0025d85d88ba4eacddd0245282cd0f
2c50522de58721955e09bd902a4369bfb21a151d
refs/heads/master
2021-06-02T23:05:10.724716
2019-05-07T19:27:37
2019-05-07T19:27:37
135,958,609
1
7
null
2020-10-01T07:54:27
2018-06-04T02:06:16
C
UTF-8
C++
false
false
309
h
#pragma once #include"Enemy.h" class Paver :public Enemy { public: Paver(int id,double arrTime,double heal,double firepow,double reloadper, char r_region,int sp); //virtual functions virtual void ResetFireHeatTime(); virtual void Move(); virtual void Attack(); virtual void Heal(); };
[ "noreply@github.com" ]
RadwaSK.noreply@github.com
c735ef797badad60851be30f473639a6a569b0e1
10c357134005fadbfbd251d59ce0bd02e5b8e5f7
/stack/card.cpp
d18a02e3c263795b02ad39b06787232bf581a3eb
[]
no_license
atalhassan/lets-learn-cpp
a8333ec0a42bc9b56d8167865c8cbd3de8b55122
6738a0e09fa8e7da47e22a8caef70ca35a3bb8bc
refs/heads/master
2021-07-13T14:41:43.483610
2017-10-13T18:55:47
2017-10-13T18:55:47
103,607,676
0
0
null
null
null
null
UTF-8
C++
false
false
1,385
cpp
/*@author Abdullah Alhassan *@version 1 *@file card.cpp */ #include <string> #include <cstdio> #include "card.h" // default is ace of spades Card::Card() : suit(1), rank(1) { } //change suit value void Card::set_suit(int the_suit) { if (the_suit >= 1 && the_suit <= 4) suit = the_suit; } //change rank value void Card::set_rank(int the_rank) { if (the_rank >= 1 && the_rank <= 13) rank = the_rank; } bool Card::is_spade() { return suit == 1; } bool Card::is_heart() { return suit == 2; } bool Card::is_diamond() { return suit == 3; } bool Card::is_club() { return suit == 4; } bool Card::is_ace() { return rank == 1; } bool Card::is_jack() { return rank == 11; } bool Card::is_queen() { return rank == 12; } bool Card::is_king() { return rank == 13; } int Card::get_rank() { return rank; } std::string Card::to_string() { std::string name = ""; // confirm the correct rank value if (is_ace()) name += "A"; else if (is_jack()) name += "J"; else if (is_queen()) name += "Q"; else if (is_king()) name += "K"; else { //convert int to string char buffer[3]; sprintf(buffer, "%d", get_rank()); name += buffer; } // combine the suit if (is_spade()) name += "S"; else if(is_heart()) name += "H"; else if(is_diamond()) name += "D"; else name += "C"; return name; }
[ "aalhassan2@zagmail.gonzaga.edu" ]
aalhassan2@zagmail.gonzaga.edu
37e674817baf89ee8c9939b42ecc027ed40bd0ca
9d58243fb3f239447c8e889862988b6e527e8828
/common/json/ujson.cpp
852f0f059219fbb532291c008bfdb9be2f62c6b2
[]
no_license
roctomato/UvNetLib
855cb8f852af4902a87093c495933e8703c189be
6d091a01b0b8757e49b5672a66bd6121dcd7a857
refs/heads/master
2023-01-09T12:04:53.191908
2020-09-15T07:39:32
2020-09-15T07:39:32
259,222,956
0
1
null
2020-10-13T21:32:36
2020-04-27T06:16:10
C++
UTF-8
C++
false
false
60,267
cpp
/* Generated by re2c 0.13.5 */ /* * Copyright (c) 2014 Anders Wang Kristensen * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "ujson.hpp" #include "double-conversion.h" #include <algorithm> #include <sstream> #ifdef __GNUC__ #ifdef __SSE2__ #define UJSON_USE_SSE2 #endif #endif #ifdef _MSC_VER #if (defined(_M_AMD64) || defined(_M_X64)) #define UJSON_USE_SSE2 #elif _M_IX86_FP==2 #define UJSON_USE_SSE2 #endif #endif #ifdef UJSON_USE_SSE2 #include <emmintrin.h> #endif // vs2013 ctp 1 supports noexcept but rest don't #if defined _MSC_VER && _MSC_FULL_VER != 180021114 #define noexcept #endif const ujson::value ujson::null = ujson::value(); // -------------------------------------------------------------------------- // utf-8 // // Code Points | 1st | 2nd | 3rd | 4th // // U+0000 - U+007F 00..7F // U+0080 - U+07FF C2..DF 80..BF // U+0800 - U+0FFF E0 A0..BF 80..BF // U+1000 - U+CFFF E1..EC 80..BF 80..BF // U+D000 - U+D7FF ED 80..9F 80..BF // U+D800 - U+DFFF illformed // U+E000 - U+FFFF EE..EF 80..BF 80..BF // U+10000 - U+3FFFF F0 90..BF 80..BF 80..BF // U+40000 - U+FFFFF F1..F3 80..BF 80..BF 80..BF // U+100000 - U+10FFFF F4 80..8F 80..BF 80..BF typedef std::pair<std::uint8_t, std::uint8_t> range_t; struct utf8_ranges_t { std::uint8_t upper_bound; std::uint8_t num_ranges; range_t ranges[3]; }; static const utf8_ranges_t utf8_ranges[] = { { 0x7F, 0 }, { 0xBF, 1 }, // 80-BF invalid continuation { 0xC1, 1 }, // 0xC0-0xC1 invalid as first byte { 0xDF, 1, { { 0x80, 0xBF + 1 } } }, { 0xE0, 2, { { 0xA0, 0xBF + 1 }, { 0x80, 0xBF + 1 } } }, { 0xEC, 2, { { 0x80, 0xBF + 1 }, { 0x80, 0xBF + 1 } } }, { 0xED, 2, { { 0x80, 0x9F + 1 }, { 0x80, 0xBF + 1 } } }, { 0xEF, 2, { { 0x80, 0xBF + 1 }, { 0x80, 0xBF + 1 } } }, { 0xF0, 3, { { 0x90, 0xBF + 1 }, { 0x80, 0xBF + 1 }, { 0x80, 0xBF + 1 } } }, { 0xF3, 3, { { 0x80, 0xBF + 1 }, { 0x80, 0xBF + 1 }, { 0x80, 0xBF + 1 } } }, { 0xF4, 3, { { 0x80, 0x8F + 1 }, { 0x80, 0xBF + 1 }, { 0x80, 0xBF + 1 } } }, { 0xFF, 1 } // 0xF5-0xFF invalid as first byte }; static const std::size_t num_utf8_ranges = sizeof(utf8_ranges) / sizeof(utf8_ranges[0]); bool ujson::value::is_valid_utf8(const char *ptr, const char *end) noexcept { while (ptr < end) { #ifdef UJSON_USE_SSE2 // test if the next 16 chars are ascii and skip forward as much as // possible while (end - ptr >= 16) { __m128i chunk = _mm_loadu_si128(reinterpret_cast<const __m128i *>(ptr)); // signed comparison: multibyte utf-8 sequences have high bit set // are thus negative __m128i compare = _mm_cmplt_epi8(chunk, _mm_setzero_si128()); int mask = _mm_movemask_epi8(compare); if (mask == 0) { ptr += 16; continue; } #ifdef __GNUC__ int index = __builtin_ffs(mask) - 1; #else unsigned long index = 0; _BitScanForward(&index, mask); #endif assert(index >= 0 && index <= 15); ptr += index; break; } #endif auto c = static_cast<std::uint8_t>(*ptr++); auto it = utf8_ranges; for (; it != utf8_ranges + num_utf8_ranges; ++it) { if (c <= it->upper_bound) break; } assert(it < utf8_ranges + num_utf8_ranges); const auto limit = it->ranges + it->num_ranges; for (auto rng = it->ranges; rng < limit; ++rng) { auto d = static_cast<std::uint8_t>(*ptr++); if (d < rng->first || d >= rng->second) return false; } } return true; } // convert utf8 to utf32; returns utf32 + number of bytes consumed static std::pair<std::uint32_t, std::uint32_t> utf8_to_utf32(const char *ptr) { auto utf8 = reinterpret_cast<const std::uint8_t *>(ptr); std::uint8_t first = *utf8; std::uint32_t trailing_bytes; if (first <= 0x7F) trailing_bytes = 0; else if (first <= 0xDF) trailing_bytes = 1; else if (first <= 0xEF) trailing_bytes = 2; else trailing_bytes = 3; std::uint32_t utf32 = 0; switch (trailing_bytes) { case 3: utf32 += *utf8++; utf32 <<= 6; case 2: utf32 += *utf8++; utf32 <<= 6; case 1: utf32 += *utf8++; utf32 <<= 6; case 0: utf32 += *utf8++; } static const std::uint32_t magic[] = { 0x0, 0x3080, 0xE2080, 0x3C82080 }; utf32 -= magic[trailing_bytes]; assert(utf32 <= 0x10FFFF); return { utf32, trailing_bytes + 1 }; } // convert utf32 code point to 1-4 bytes of utf8 static char *utf32_to_utf8(char *str, std::uint32_t cp) { assert(cp <= 0x10FFFF); std::size_t num_bytes; if (cp <= 0x7F) num_bytes = 1; else if (cp <= 0x7FF) num_bytes = 2; else if (cp <= 0xFFFF) num_bytes = 3; else num_bytes = 4; static const std::uint32_t offset[] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0 }; switch (num_bytes) { case 4: str[3] = static_cast<char>((cp | 0x80) & 0xBF); cp >>= 6; case 3: str[2] = static_cast<char>((cp | 0x80) & 0xBF); cp >>= 6; case 2: str[1] = static_cast<char>((cp | 0x80) & 0xBF); cp >>= 6; case 1: str[0] = static_cast<char>(cp | offset[num_bytes]); } return str + num_bytes; } // convert four byte hex string to int static std::uint32_t hex_to_int(const std::uint8_t *hex) { static const std::uint8_t lookup[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 11, 12, 13, 14, 15 }; assert(lookup['0' - '0'] == 0); assert(lookup['1' - '0'] == 1); assert(lookup['2' - '0'] == 2); assert(lookup['3' - '0'] == 3); assert(lookup['4' - '0'] == 4); assert(lookup['5' - '0'] == 5); assert(lookup['6' - '0'] == 6); assert(lookup['7' - '0'] == 7); assert(lookup['8' - '0'] == 8); assert(lookup['9' - '0'] == 9); assert(lookup['A' - '0'] == 10); assert(lookup['B' - '0'] == 11); assert(lookup['C' - '0'] == 12); assert(lookup['D' - '0'] == 13); assert(lookup['E' - '0'] == 14); assert(lookup['F' - '0'] == 15); assert(lookup['a' - '0'] == 10); assert(lookup['b' - '0'] == 11); assert(lookup['c' - '0'] == 12); assert(lookup['d' - '0'] == 13); assert(lookup['e' - '0'] == 14); assert(lookup['f' - '0'] == 15); std::uint32_t result = 0; for (int i = 0; i < 4; ++i) { result <<= 4; std::uint8_t c = hex[i]; std::uint32_t h = lookup[c - '0']; result += h; } return result; } // convert int (<=0xFFFF) to six byte escaped hex string static void int_to_hex(std::uint32_t cp, char *str) { assert(cp <= 0xFFFF); static const char *hex = "0123456789ABCDEF"; str[0] = '\\'; str[1] = 'u'; str[2] = hex[(cp & 0xF000) >> 12]; str[3] = hex[(cp & 0x0F00) >> 8]; str[4] = hex[(cp & 0x00F0) >> 4]; str[5] = hex[(cp & 0x000F) >> 0]; } // --------------------------------------------------------------------------- // to_string static void to_string(std::string &result, ujson::string_view input, const ujson::to_string_options &opts) { // upper bound on how much result can grow (happens if string consists of // certain control characters, since they are encoded as six characters, // \uXXXX) const auto max_size_increase = 6 * input.length() + 2; const auto old_size = result.size(); result.resize(old_size + max_size_increase); char *out = &result[old_size]; *out++ = '"'; for (auto in = input.c_str(); in != input.c_str() + input.length(); ++in) { std::uint8_t c = *in; if (c >= 0x20) { if (c == '"') { *out++ = '\\'; *out++ = '"'; } else if (c == '\\') { *out++ = '\\'; *out++ = '\\'; } else if (c <= 127) { // ascii *out++ = c; } else if (opts.encoding == ujson::character_encoding::utf8) { // utf-8 multi-byte case *out++ = c; } else { // encode utf-8 multi-byte as utf-16 auto pair = utf8_to_utf32(in); if (pair.first < 0x10000) { int_to_hex(pair.first, out); out += 6; } else { std::uint32_t cp = pair.first - 0x10000; std::uint32_t leading = (cp >> 10) + 0xD800; assert(leading >= 0xD800 && leading < 0xDC00); std::uint32_t trailing = (cp & 0x3FF) + 0xDC00; assert(trailing >= 0xDC00 && trailing < 0xE000); int_to_hex(leading, out); out += 6; int_to_hex(trailing, out); out += 6; } in += pair.second - 1; } } else { if (c == '\b') { *out++ = '\\'; *out++ = 'b'; } else if (c == '\f') { *out++ = '\\'; *out++ = 'f'; } else if (c == '\n') { *out++ = '\\'; *out++ = 'n'; } else if (c == '\r') { *out++ = '\\'; *out++ = 'r'; } else if (c == '\t') { *out++ = '\\'; *out++ = 't'; } else { int_to_hex(c, out); out += 6; } } } *out++ = '"'; // trim result to actual size const auto new_size = out - &result[0]; assert(new_size - old_size <= max_size_increase); result.resize(new_size); } static void to_string(std::string &str, double v) { using namespace double_conversion; const int buffer_size = 128; char buffer[buffer_size]; StringBuilder builder(buffer, buffer_size); auto flags = DoubleToStringConverter::NO_FLAGS; DoubleToStringConverter d2sc(flags, nullptr, nullptr, 'e', -10, 20, 0, 0); #ifdef NDEBUG d2sc.ToShortest(v, &builder); #else bool result = d2sc.ToShortest(v, &builder); assert(result); #endif str += builder.Finalize(); } static void to_string_impl(std::string &str, ujson::value const &v, const ujson::to_string_options &opts, std::size_t current_indent) { switch (v.type()) { case ujson::value_type::null: str += "null"; break; case ujson::value_type::boolean: str += bool_cast(v) ? "true" : "false"; break; case ujson::value_type::number: to_string(str, double_cast(v)); break; case ujson::value_type::string: to_string(str, string_cast(v), opts); break; case ujson::value_type::array: { str += '['; if (opts.indent_amount > 0) str += '\n'; auto const &array = array_cast(v); for (auto const &value : array) { str.append(current_indent + opts.indent_amount, ' '); to_string_impl(str, value, opts, current_indent + opts.indent_amount); if (&value != &array.back()) str += ','; if (opts.indent_amount > 0) str += '\n'; } str.append(current_indent, ' '); str += ']'; break; } case ujson::value_type::object: { str += '{'; if (opts.indent_amount > 0) str += '\n'; auto const &object = object_cast(v); bool first = true; for (auto const &kvp : object) { if (!first) { str += ','; if (opts.indent_amount > 0) str += '\n'; } str.append(current_indent + opts.indent_amount, ' '); to_string(str, { kvp.first.c_str(), kvp.first.length() }, opts); if (opts.indent_amount > 0) str += " : "; else str += ':'; to_string_impl(str, kvp.second, opts, current_indent + opts.indent_amount); first = false; } if (opts.indent_amount > 0 && !object.empty()) str += '\n'; str.append(current_indent, ' '); str += '}'; break; } default: assert(false); break; } } std::string ujson::to_string(value const &v, const ujson::to_string_options &opts) { std::string result; to_string_impl(result, v, opts, 0); return result; } std::ostream &ujson::operator<<(std::ostream &stream, value const &v) { stream << to_string(v); return stream; } //---------------------------------------------------------------------------- // exception ujson::exception::exception(error_code error, int line) : m_error_code(error), m_line(line) {} const char *ujson::exception::what() const noexcept{ if (m_what.empty()) { std::stringstream ss; switch (m_error_code) { case error_code::bad_cast: ss << "Bad cast."; break; case error_code::bad_number: if (m_line == -1) ss << "Bad number."; else ss << "Bad number on line " << m_line << "."; break; case error_code::bad_string: ss << "Bad UTF-8."; break; case error_code::invalid_syntax: ss << "Invalid syntax on line " << m_line << "."; break; case error_code::integer_overflow: ss << "Number out of range for integer cast."; break; default: assert(false); break; } m_what = ss.str(); } return m_what.c_str(); } ujson::error_code ujson::exception::get_error_code() const { return m_error_code; } int ujson::exception::get_line() const { return m_line; } //---------------------------------------------------------------------------- // parser namespace { enum token { ujson_colon, ujson_comma, ujson_null, ujson_true, ujson_false, ujson_number, ujson_string, ujson_array_begin, ujson_array_end, ujson_object_begin, ujson_object_end, ujson_eof }; // helper class used for providing a sentinel token to the parser // when it reads beyond the supplied buffer class safe_ptr { public: safe_ptr(const std::uint8_t *ptr, const std::uint8_t *limit); inline const std::uint8_t *ptr() const; inline const std::uint8_t *limit() const; inline std::uint8_t operator*() const; inline operator const std::uint8_t *() const; inline safe_ptr &operator++(); inline safe_ptr &operator+=(std::size_t); inline safe_ptr &operator=(const std::uint8_t *); private: const std::uint8_t *m_ptr; const std::uint8_t *m_limit; }; class parser { public: parser(const std::uint8_t *ptr, std::size_t len); token peek_token(); token read_token(); void expect(token token); double read_double() const; std::string read_string() const; int line() const; private: token scan(); const std::uint8_t *const m_start; const std::uint8_t *const m_limit; bool m_peeked; token m_current_token; safe_ptr m_cursor; const std::uint8_t *m_token; }; } //---------------------------------------------------------------------------- safe_ptr::safe_ptr(const std::uint8_t *ptr, const std::uint8_t *limit) : m_ptr(ptr), m_limit(limit) { assert(m_ptr <= m_limit); } const std::uint8_t *safe_ptr::ptr() const { return m_ptr; } const std::uint8_t *safe_ptr::limit() const { return m_limit; } std::uint8_t safe_ptr::operator*() const { return m_ptr < m_limit ? *m_ptr : 0; } safe_ptr::operator const std::uint8_t *() const { return m_ptr; } safe_ptr &safe_ptr::operator++() { ++m_ptr; return *this; } safe_ptr &safe_ptr::operator+=(std::size_t offset) { m_ptr += offset; return *this; } safe_ptr &safe_ptr::operator=(const std::uint8_t *ptr) { m_ptr = ptr; return *this; } //---------------------------------------------------------------------------- parser::parser(const std::uint8_t *ptr, std::size_t len) : m_start(ptr), m_limit(ptr + len), m_cursor(ptr, ptr + len) { m_peeked = false; } int parser::line() const { return static_cast<int>(std::count(m_start, m_cursor.ptr(), '\n') + 1); } token parser::peek_token() { if (!m_peeked) { m_current_token = scan(); m_peeked = true; } return m_current_token; } token parser::read_token() { if (!m_peeked) m_current_token = scan(); m_peeked = false; return m_current_token; } void parser::expect(token token) { if (token != read_token()) throw ujson::exception(ujson::error_code::invalid_syntax, line()); } double parser::read_double() const { const auto len = static_cast<int>(m_cursor.ptr() - m_token); using namespace double_conversion; auto flags = StringToDoubleConverter::NO_FLAGS; StringToDoubleConverter s2dc(flags, 0.0, 0.0, nullptr, nullptr); int processed_chars; auto token = reinterpret_cast<const char *>(m_token); double result = s2dc.StringToDouble(token, len, &processed_chars); // handle invalid number if (processed_chars != len) throw ujson::exception(ujson::error_code::bad_number, line()); // handle overflow if (!std::isfinite(result)) throw ujson::exception(ujson::error_code::bad_number, line()); return result; } std::string parser::read_string() const { // m_token points to first double qoute and m_cursor points to last auto in = m_token + 1; const auto limit = m_cursor.ptr() - 1; if (in == limit) return ""; // limit-in is an upper bound on the size of the resulting string std::string result(limit - in, '\0'); char *out = &result.front(); while (in < limit) { #ifdef UJSON_USE_SSE2 while (limit - in >= 16) { __m128i backslash = _mm_set1_epi8(0x5C); __m128i chunk = _mm_loadu_si128(reinterpret_cast<const __m128i *>(in)); __m128i compare = _mm_cmpeq_epi8(chunk, backslash); int mask = _mm_movemask_epi8(compare); if (!mask) { in += 16; _mm_storeu_si128(reinterpret_cast<__m128i *>(out), chunk); out += 16; continue; } #ifdef __GNUC__ int index = __builtin_ffs(mask) - 1; #else unsigned long index = 0; _BitScanForward(&index, mask); #endif assert(index >= 0 && index <= 15); for (decltype(index) i = 0; i < index; ++i) *out++ = *in++; break; } if (in == limit) break; #endif char c = *in++; if (c != '\\') { *out++ = c; } else { c = *in++; if (c == '\\') *out++ = '\\'; else if (c == '"') *out++ = '"'; else if (c == '/') *out++ = '/'; else if (c == 'b') *out++ = '\b'; else if (c == 'f') *out++ = '\f'; else if (c == 'n') *out++ = '\n'; else if (c == 'r') *out++ = '\r'; else if (c == 't') *out++ = '\t'; else if (c == 'u') { std::uint32_t cp = hex_to_int(in); in += 4; // surrogate pair? if (cp >= 0xD800 && cp <= 0xDBFF) { in += 2; std::uint32_t trailing = hex_to_int(in); in += 4; assert(trailing >= 0xDC00 && trailing <= 0xDFFF); cp = ((cp - 0xD800) << 10) + (trailing - 0xDC00) + 0x10000; } // translate to 1-4 utf-8 chars out = utf32_to_utf8(out, cp); } else { // can't happen unless regexes are wrong assert(false); } } } result.resize(out - result.data()); return result; } //---------------------------------------------------------------------------- token parser::scan() { safe_ptr marker(m_cursor, m_limit); std: #ifdef UJSON_USE_SSE2 while (m_limit - m_cursor.ptr() >= 16) { __m128i chunk = _mm_loadu_si128( reinterpret_cast<const __m128i *>(m_cursor.ptr())); __m128i tabs = _mm_set1_epi8(0x09); __m128i newlines = _mm_set1_epi8(0x0A); __m128i carriage_return = _mm_set1_epi8(0x0D); __m128i spaces = _mm_set1_epi8(0x20); __m128i is_tabs = _mm_cmpeq_epi8(chunk, tabs); __m128i is_newlines = _mm_cmpeq_epi8(chunk, newlines); __m128i is_carriage_return = _mm_cmpeq_epi8(chunk, carriage_return); __m128i is_space = _mm_cmpeq_epi8(chunk, spaces); __m128i is_white_space = _mm_or_si128(_mm_or_si128(is_tabs, is_newlines), _mm_or_si128(is_carriage_return, is_space)); int mask = _mm_movemask_epi8(is_white_space); if (mask == 0xFFFF) { m_cursor += 16; continue; } #ifdef __GNUC__ m_cursor += __builtin_ffs(~mask) - 1; #else unsigned long index = 0; if (_BitScanForward(&index, ~mask)) m_cursor += index; #endif break; } #endif m_token = m_cursor.ptr(); { std::uint8_t yych; unsigned int yyaccept = 0; yych = *m_cursor; switch (yych) { case 0x00: goto ujson25; case '\t': case '\n': case '\r': case ' ': goto ujson23; case '"': goto ujson22; case ',': goto ujson4; case '-': goto ujson18; case '0': goto ujson19; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto ujson21; case ':': goto ujson2; case '[': goto ujson10; case ']': goto ujson12; case 'f': goto ujson9; case 'n': goto ujson6; case 't': goto ujson8; case '{': goto ujson14; case '}': goto ujson16; default: goto ujson27; } ujson2: ++m_cursor; { return ujson_colon; } ujson4: ++m_cursor; { return ujson_comma; } ujson6: yyaccept = 0; yych = *(marker = ++m_cursor); switch (yych) { case 'u': goto ujson91; default: goto ujson7; } ujson7: { throw ujson::exception(ujson::error_code::invalid_syntax, line()); } ujson8: yyaccept = 0; yych = *(marker = ++m_cursor); switch (yych) { case 'r': goto ujson87; default: goto ujson7; } ujson9: yyaccept = 0; yych = *(marker = ++m_cursor); switch (yych) { case 'a': goto ujson82; default: goto ujson7; } ujson10: ++m_cursor; { return ujson_array_begin; } ujson12: ++m_cursor; { return ujson_array_end; } ujson14: ++m_cursor; { return ujson_object_begin; } ujson16: ++m_cursor; { return ujson_object_end; } ujson18: yych = *++m_cursor; switch (yych) { case '0': goto ujson81; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto ujson72; default: goto ujson7; } ujson19: yyaccept = 1; yych = *(marker = ++m_cursor); switch (yych) { case '.': goto ujson74; case 'E': case 'e': goto ujson75; default: goto ujson20; } ujson20: { return ujson_number; } ujson21: yyaccept = 1; yych = *(marker = ++m_cursor); goto ujson73; ujson22: yyaccept = 0; yych = *(marker = ++m_cursor); switch (yych) { case ' ': case '!': case '"': case '#': case '$': case '%': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case '-': case '.': case '/': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case ':': case ';': case '<': case '=': case '>': case '?': case '@': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '[': case '\\': case ']': case '^': case '_': case '`': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case '{': case '|': case '}': case '~': case 0x7F: case 0xC2: case 0xC3: case 0xC4: case 0xC5: case 0xC6: case 0xC7: case 0xC8: case 0xC9: case 0xCA: case 0xCB: case 0xCC: case 0xCD: case 0xCE: case 0xCF: case 0xD0: case 0xD1: case 0xD2: case 0xD3: case 0xD4: case 0xD5: case 0xD6: case 0xD7: case 0xD8: case 0xD9: case 0xDA: case 0xDB: case 0xDC: case 0xDD: case 0xDE: case 0xDF: case 0xE0: case 0xE1: case 0xE2: case 0xE3: case 0xE4: case 0xE5: case 0xE6: case 0xE7: case 0xE8: case 0xE9: case 0xEA: case 0xEB: case 0xEC: case 0xED: case 0xEE: case 0xEF: case 0xF0: case 0xF1: case 0xF2: case 0xF3: case 0xF4: goto ujson31; default: goto ujson7; } ujson23: ++m_cursor; yych = *m_cursor; goto ujson29; ujson24: { goto std; } ujson25: ++m_cursor; { return ujson_eof; } ujson27: yych = *++m_cursor; goto ujson7; ujson28: ++m_cursor; yych = *m_cursor; ujson29: switch (yych) { case '\t': case '\n': case '\r': case ' ': goto ujson28; default: goto ujson24; } ujson30: ++m_cursor; yych = *m_cursor; ujson31: switch (yych) { case ' ': case '!': case '#': case '$': case '%': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case '-': case '.': case '/': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case ':': case ';': case '<': case '=': case '>': case '?': case '@': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '[': case ']': case '^': case '_': case '`': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case '{': case '|': case '}': case '~': case 0x7F: goto ujson30; case '"': goto ujson42; case '\\': goto ujson33; case 0xC2: case 0xC3: case 0xC4: case 0xC5: case 0xC6: case 0xC7: case 0xC8: case 0xC9: case 0xCA: case 0xCB: case 0xCC: case 0xCD: case 0xCE: case 0xCF: case 0xD0: case 0xD1: case 0xD2: case 0xD3: case 0xD4: case 0xD5: case 0xD6: case 0xD7: case 0xD8: case 0xD9: case 0xDA: case 0xDB: case 0xDC: case 0xDD: case 0xDE: case 0xDF: goto ujson34; case 0xE0: goto ujson35; case 0xE1: case 0xE2: case 0xE3: case 0xE4: case 0xE5: case 0xE6: case 0xE7: case 0xE8: case 0xE9: case 0xEA: case 0xEB: case 0xEC: goto ujson36; case 0xED: goto ujson37; case 0xEE: case 0xEF: goto ujson38; case 0xF0: goto ujson39; case 0xF1: case 0xF2: case 0xF3: goto ujson40; case 0xF4: goto ujson41; default: goto ujson32; } ujson32: m_cursor = marker; switch (yyaccept) { case 0: goto ujson7; case 1: goto ujson20; } ujson33: ++m_cursor; yych = *m_cursor; switch (yych) { case '"': case '/': case '\\': case 'b': case 'f': case 'n': case 'r': case 't': goto ujson30; case 'u': goto ujson54; default: goto ujson32; } ujson34: ++m_cursor; yych = *m_cursor; switch (yych) { case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: case 0x98: case 0x99: case 0x9A: case 0x9B: case 0x9C: case 0x9D: case 0x9E: case 0x9F: case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: case 0xB8: case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: goto ujson30; default: goto ujson32; } ujson35: ++m_cursor; yych = *m_cursor; switch (yych) { case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: case 0xB8: case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: goto ujson53; default: goto ujson32; } ujson36: ++m_cursor; yych = *m_cursor; switch (yych) { case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: case 0x98: case 0x99: case 0x9A: case 0x9B: case 0x9C: case 0x9D: case 0x9E: case 0x9F: case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: case 0xB8: case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: goto ujson52; default: goto ujson32; } ujson37: ++m_cursor; yych = *m_cursor; switch (yych) { case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: case 0x98: case 0x99: case 0x9A: case 0x9B: case 0x9C: case 0x9D: case 0x9E: case 0x9F: goto ujson51; default: goto ujson32; } ujson38: ++m_cursor; yych = *m_cursor; switch (yych) { case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: case 0x98: case 0x99: case 0x9A: case 0x9B: case 0x9C: case 0x9D: case 0x9E: case 0x9F: case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: case 0xB8: case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: goto ujson50; default: goto ujson32; } ujson39: ++m_cursor; yych = *m_cursor; switch (yych) { case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: case 0x98: case 0x99: case 0x9A: case 0x9B: case 0x9C: case 0x9D: case 0x9E: case 0x9F: case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: case 0xB8: case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: goto ujson48; default: goto ujson32; } ujson40: ++m_cursor; yych = *m_cursor; switch (yych) { case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: case 0x98: case 0x99: case 0x9A: case 0x9B: case 0x9C: case 0x9D: case 0x9E: case 0x9F: case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: case 0xB8: case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: goto ujson46; default: goto ujson32; } ujson41: ++m_cursor; yych = *m_cursor; switch (yych) { case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: goto ujson44; default: goto ujson32; } ujson42: ++m_cursor; { return ujson_string; } ujson44: ++m_cursor; yych = *m_cursor; switch (yych) { case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: case 0x98: case 0x99: case 0x9A: case 0x9B: case 0x9C: case 0x9D: case 0x9E: case 0x9F: case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: case 0xB8: case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: goto ujson45; default: goto ujson32; } ujson45: ++m_cursor; yych = *m_cursor; switch (yych) { case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: case 0x98: case 0x99: case 0x9A: case 0x9B: case 0x9C: case 0x9D: case 0x9E: case 0x9F: case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: case 0xB8: case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: goto ujson30; default: goto ujson32; } ujson46: ++m_cursor; yych = *m_cursor; switch (yych) { case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: case 0x98: case 0x99: case 0x9A: case 0x9B: case 0x9C: case 0x9D: case 0x9E: case 0x9F: case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: case 0xB8: case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: goto ujson47; default: goto ujson32; } ujson47: ++m_cursor; yych = *m_cursor; switch (yych) { case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: case 0x98: case 0x99: case 0x9A: case 0x9B: case 0x9C: case 0x9D: case 0x9E: case 0x9F: case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: case 0xB8: case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: goto ujson30; default: goto ujson32; } ujson48: ++m_cursor; yych = *m_cursor; switch (yych) { case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: case 0x98: case 0x99: case 0x9A: case 0x9B: case 0x9C: case 0x9D: case 0x9E: case 0x9F: case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: case 0xB8: case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: goto ujson49; default: goto ujson32; } ujson49: ++m_cursor; yych = *m_cursor; switch (yych) { case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: case 0x98: case 0x99: case 0x9A: case 0x9B: case 0x9C: case 0x9D: case 0x9E: case 0x9F: case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: case 0xB8: case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: goto ujson30; default: goto ujson32; } ujson50: ++m_cursor; yych = *m_cursor; switch (yych) { case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: case 0x98: case 0x99: case 0x9A: case 0x9B: case 0x9C: case 0x9D: case 0x9E: case 0x9F: case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: case 0xB8: case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: goto ujson30; default: goto ujson32; } ujson51: ++m_cursor; yych = *m_cursor; switch (yych) { case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: case 0x98: case 0x99: case 0x9A: case 0x9B: case 0x9C: case 0x9D: case 0x9E: case 0x9F: case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: case 0xB8: case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: goto ujson30; default: goto ujson32; } ujson52: ++m_cursor; yych = *m_cursor; switch (yych) { case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: case 0x98: case 0x99: case 0x9A: case 0x9B: case 0x9C: case 0x9D: case 0x9E: case 0x9F: case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: case 0xB8: case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: goto ujson30; default: goto ujson32; } ujson53: ++m_cursor; yych = *m_cursor; switch (yych) { case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: case 0x98: case 0x99: case 0x9A: case 0x9B: case 0x9C: case 0x9D: case 0x9E: case 0x9F: case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: case 0xB8: case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: goto ujson30; default: goto ujson32; } ujson54: ++m_cursor; yych = *m_cursor; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'a': case 'b': case 'c': goto ujson55; case 'D': case 'd': goto ujson56; case 'E': case 'F': case 'e': case 'f': goto ujson57; default: goto ujson32; } ujson55: ++m_cursor; yych = *m_cursor; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': goto ujson70; default: goto ujson32; } ujson56: ++m_cursor; yych = *m_cursor; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': goto ujson61; case '8': case '9': case 'A': case 'B': case 'a': case 'b': goto ujson60; default: goto ujson32; } ujson57: ++m_cursor; yych = *m_cursor; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': goto ujson58; default: goto ujson32; } ujson58: ++m_cursor; yych = *m_cursor; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': goto ujson59; default: goto ujson32; } ujson59: ++m_cursor; yych = *m_cursor; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': goto ujson30; default: goto ujson32; } ujson60: ++m_cursor; yych = *m_cursor; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': goto ujson63; default: goto ujson32; } ujson61: ++m_cursor; yych = *m_cursor; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': goto ujson62; default: goto ujson32; } ujson62: ++m_cursor; yych = *m_cursor; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': goto ujson30; default: goto ujson32; } ujson63: ++m_cursor; yych = *m_cursor; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': goto ujson64; default: goto ujson32; } ujson64: ++m_cursor; yych = *m_cursor; switch (yych) { case '\\': goto ujson65; default: goto ujson32; } ujson65: ++m_cursor; yych = *m_cursor; switch (yych) { case 'u': goto ujson66; default: goto ujson32; } ujson66: ++m_cursor; yych = *m_cursor; switch (yych) { case 'D': case 'd': goto ujson67; default: goto ujson32; } ujson67: ++m_cursor; yych = *m_cursor; switch (yych) { case 'C': case 'D': case 'E': case 'F': case 'c': case 'd': case 'e': case 'f': goto ujson68; default: goto ujson32; } ujson68: ++m_cursor; yych = *m_cursor; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': goto ujson69; default: goto ujson32; } ujson69: ++m_cursor; yych = *m_cursor; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': goto ujson30; default: goto ujson32; } ujson70: ++m_cursor; yych = *m_cursor; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': goto ujson71; default: goto ujson32; } ujson71: ++m_cursor; yych = *m_cursor; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': goto ujson30; default: goto ujson32; } ujson72: yyaccept = 1; marker = ++m_cursor; yych = *m_cursor; ujson73: switch (yych) { case '.': goto ujson74; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto ujson72; case 'E': case 'e': goto ujson75; default: goto ujson20; } ujson74: yych = *++m_cursor; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto ujson79; default: goto ujson32; } ujson75: yych = *++m_cursor; switch (yych) { case '+': case '-': goto ujson76; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto ujson77; default: goto ujson32; } ujson76: yych = *++m_cursor; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto ujson77; default: goto ujson32; } ujson77: ++m_cursor; yych = *m_cursor; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto ujson77; default: goto ujson20; } ujson79: yyaccept = 1; marker = ++m_cursor; yych = *m_cursor; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto ujson79; case 'E': case 'e': goto ujson75; default: goto ujson20; } ujson81: yyaccept = 1; yych = *(marker = ++m_cursor); switch (yych) { case '.': goto ujson74; case 'E': case 'e': goto ujson75; default: goto ujson20; } ujson82: yych = *++m_cursor; switch (yych) { case 'l': goto ujson83; default: goto ujson32; } ujson83: yych = *++m_cursor; switch (yych) { case 's': goto ujson84; default: goto ujson32; } ujson84: yych = *++m_cursor; switch (yych) { case 'e': goto ujson85; default: goto ujson32; } ujson85: ++m_cursor; { return ujson_false; } ujson87: yych = *++m_cursor; switch (yych) { case 'u': goto ujson88; default: goto ujson32; } ujson88: yych = *++m_cursor; switch (yych) { case 'e': goto ujson89; default: goto ujson32; } ujson89: ++m_cursor; { return ujson_true; } ujson91: yych = *++m_cursor; switch (yych) { case 'l': goto ujson92; default: goto ujson32; } ujson92: yych = *++m_cursor; switch (yych) { case 'l': goto ujson93; default: goto ujson32; } ujson93: ++m_cursor; { return ujson_null; } } } //---------------------------------------------------------------------------- static ujson::value parse_value(parser &parser) { switch (parser.peek_token()) { case ujson_null: parser.read_token(); return ujson::null; case ujson_true: parser.read_token(); return true; case ujson_false: parser.read_token(); return false; case ujson_number: parser.read_token(); return parser.read_double(); case ujson_string: { parser.read_token(); auto string = parser.read_string(); return ujson::value(std::move(string), ujson::validate_utf8::no); } case ujson_array_begin: { parser.read_token(); ujson::array array; bool first = true; while (parser.peek_token() != ujson_array_end) { if (!first) parser.expect(ujson_comma); auto value = parse_value(parser); array.push_back(std::move(value)); first = false; } parser.read_token(); return ujson::value(std::move(array)); } case ujson_object_begin: { parser.read_token(); ujson::object object; bool first = true; while (parser.peek_token() != ujson_object_end) { if (!first) parser.expect(ujson_comma); parser.expect(ujson_string); auto key = parser.read_string(); parser.expect(ujson_colon); auto value = parse_value(parser); object.emplace_back(std::move(key), std::move(value)); first = false; } parser.read_token(); return ujson::value(std::move(object), ujson::validate_utf8::no); } default: throw ujson::exception(ujson::error_code::invalid_syntax, parser.line()); } } ujson::value ujson::parse(const std::string &str) { return parse(str.c_str(), str.size()); } ujson::value ujson::parse(const char *buffer, std::size_t len) { auto buf = reinterpret_cast<const std::uint8_t *>(buffer); parser parser(buf, len ? len : std::strlen(buffer)); auto result = parse_value(parser); // fail if trailing junk is found if (parser.read_token() != ujson_eof) throw ujson::exception(ujson::error_code::invalid_syntax, parser.line()); return result; }
[ "txqc4@163.com" ]
txqc4@163.com
ccd7fbb1382a5f2e0246692905e7b8939bbd4b48
b3ce65d02c886ecf659a50585bc902068dc561ae
/semaphore.hpp
916e39267992282a864b78153c4b9ea91a2f8a69
[ "MIT" ]
permissive
graham-riches/cpp17-semaphore
b8b500a77c427ad64a64e8bce03f550c83e4710d
12b062fad72e93a3cbcc89f465a167beb566844e
refs/heads/main
2023-08-10T23:23:35.753015
2021-09-22T13:07:26
2021-09-22T13:07:26
409,207,999
0
0
null
null
null
null
UTF-8
C++
false
false
4,996
hpp
/** * \file semaphore.hpp * \author Graham Riches (graham.riches@live.com) * \brief C++17 Implementation of a semaphore until the toolchain is updated to C++20 * that conforms to the API of the C++20 semaphore so that it can easily be updated * in the future. * \version 0.1 * \date 2021-09-15 * * @copyright Copyright (c) 2021 * */ #pragma once /********************************** Includes *******************************************/ #include <chrono> #include <condition_variable> #include <cstddef> #include <mutex> #include <atomic> #include <algorithm> /********************************** Types *******************************************/ namespace std { template <std::ptrdiff_t LeastMaxValue> class counting_semaphore { public: //!< Constructors and assignment operators /** * \brief Constructs a counting semaphore with the internal counter initialized to desired * \param desired The initial counter value */ constexpr explicit counting_semaphore(std::ptrdiff_t desired = 0) : m_count(desired) { } /** * \brief Destroy the counting semaphore object * \note UB if any thread is pending on this semaphore */ ~counting_semaphore() = default; //!< Sempahore is not copyable or movable counting_semaphore(const counting_semaphore& other) = delete; counting_semaphore& operator=(const counting_semaphore& other) = delete; counting_semaphore(counting_semaphore&& other) = delete; counting_semaphore&& operator=(counting_semaphore&& other) = delete; //!< Member functions /** * \brief Atomically increments the internal counter by the value update * \note Any thread waiting (via acquire) on the counter value may be released by this * \param update The value to update the counter by */ void release(std::ptrdiff_t update = 1) { std::unique_lock<std::mutex> lock(m_lock); m_count = std::clamp(m_count + update, std::ptrdiff_t{0}, LeastMaxValue); m_cv.notify_all(); lock.unlock(); } /** * \brief Atomically decrements the internal counter value by 1 if it is greater than 0, otherwise blocks * until the counter is greater than 0 */ void acquire() { std::unique_lock<std::mutex> lock(m_lock); m_cv.wait(lock, [&] { return (m_count > 0); } ); m_count = std::clamp(m_count - 1, std::ptrdiff_t{0}, LeastMaxValue); m_cv.notify_all(); lock.unlock(); } /** * \brief Tries to atomically decrement the counter by 1 if it's greater than 0, otherwise returns error * * \retval true If counter was decremented * \retval false Otherwise */ bool try_acquire() noexcept { std::unique_lock<std::mutex> lock(m_lock); if (lock.try_lock()) { m_count = std::clamp(m_count - 1, std::ptrdiff_t{0}, LeastMaxValue); lock.unlock(); return true; } return false; } /** * \brief Tries to atomically decrement the internal counter by 1, otherwise blocks for a period of time * * \param rel_time The time period to wait for * \retval true If counter decremented by 1 within the time period * \retval false Otherwise */ template <class Rep, class Period> bool try_acquire_for(const std::chrono::duration<Rep, Period>& rel_time) { std::unique_lock<std::mutex> lock(m_lock); if (m_cv.wait_for(lock, rel_time, [&]{ return (m_count > 0); })) { m_count = std::clamp(m_count - 1, std::ptrdiff_t{0}, LeastMaxValue); return true; } else { return false; } } /** * \brief Tries to atomically decrement the internal counter by 1, otherwise blocks until a set point in time * * \param abs_time The time point to wait until * \retval true if counter decremented before time period passes * \retval false otherwise */ template<class Clock, class Duration> bool try_acquire_until(const std::chrono::time_point<Clock, Duration>& abs_time) { std::unique_lock<std::mutex> lock(m_lock); if (m_cv.wait_until(lock, abs_time, [&]{ return (m_count > 0); })) { m_count = std::clamp(m_count - 1, std::ptrdiff_t{0}, LeastMaxValue); return true; } else { return false; } } //!< Constants /** * \brief Returns the internal counter's maximum possible value, which is greater than * or equal to LeastMaxValue. For specialization binary_semaphore, LeastMaxValue is equal to 1. * * \retval std::ptrdiff_t value */ constexpr std::ptrdiff_t max() noexcept { return LeastMaxValue; } private: std::ptrdiff_t m_count; std::condition_variable m_cv; std::mutex m_lock; }; using binary_semaphore = counting_semaphore<1>; }; // namespace std
[ "graham.riches@live.com" ]
graham.riches@live.com
4af920ec37f9519e6e4c23aa4063217af80e81ea
14d19c29e4c296381870250503ff9a889ac897f5
/tools/obj2mesh/ObjParser.cc
9ee0f168a31bd8d713a247539d7412298172b67a
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
caomw/Fujiyama-Renderer
c23fbf25f405fdd46529d2c053da45a5dca89c4c
01fba59d8c4919a5869b23ef9c778cc026325a8f
refs/heads/master
2020-12-26T01:38:21.051778
2016-08-30T16:56:38
2016-08-30T16:56:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,694
cc
// Copyright (c) 2011-2016 Hiroshi Tsubokawa // See LICENSE and README #include "ObjParser.h" #include <sstream> #include <fstream> #include <iostream> namespace obj { class Vertex { public: Vertex() : data_count(0), x(0.), y(0.), z(0.), w(0.) {} Vertex(int count, double xx, double yy, double zz, double ww) : data_count(count), x(xx), y(yy), z(zz), w(ww) {} ~Vertex() {} public: int data_count; double x, y, z, w; }; class Triplet { public: Triplet() : v(0), vt(0), vn(0), has_v(false), has_vt(false), has_vn(false) {} ~Triplet() {} public: long v, vt, vn; bool has_v, has_vt, has_vn; }; class TripletList { static const size_t INITIAL_INDEX_ALLOC = 8; public: TripletList() : vertex_ (INITIAL_INDEX_ALLOC), texture_(INITIAL_INDEX_ALLOC), normal_ (INITIAL_INDEX_ALLOC) {} ~TripletList() {} void Push(const Triplet &triplet) { if (triplet.has_v) vertex_.push_back(triplet.v); if (triplet.has_vt) texture_.push_back(triplet.vt); if (triplet.has_vn) normal_.push_back(triplet.vn); } void Clear() { vertex_.clear(); texture_.clear(); normal_.clear(); } long Count() const { return vertex_.size(); } const long *GetVertex() const { return vertex_.empty() ? NULL : &vertex_[0]; } const long *GetTexture() const { return texture_.empty() ? NULL : &texture_[0]; } const long *GetNormal() const { return normal_.empty() ? NULL : &normal_[0]; } private: std::vector<long> vertex_; std::vector<long> texture_; std::vector<long> normal_; }; static bool get_triplet(std::istream &is, Triplet &triplet) { Triplet tri; is >> tri.v; if (!is) { return false; } tri.has_v = true; if (is.get() != '/') { triplet = tri; return true; } if (is.peek() == '/') { is.get(); // skip '/' is >> tri.vn; tri.has_vn = true; triplet = tri; return true; } is >> tri.vt; tri.has_vt = true; if (is.get() != '/') { triplet = tri; return true; } is >> tri.vn; tri.has_vn = true; triplet = tri; return true; } static Vertex get_vector(std::istream &is) { double v[4] = {0, 0, 0, 0}; int data_count = 0; for (int i = 0; i < 4; i++) { is >> v[i]; if (!is) { is.clear(); break; } data_count++; } return Vertex( data_count, v[0], v[1], v[2], v[3]); } static std::string trimed(const std::string &line) { const char white_spaces[] = " \t\f\v\n\r"; size_t f = line.find_first_not_of(white_spaces); size_t l = line.find_last_not_of(white_spaces); if (f == std::string::npos) f = 0; return line.substr(f, l - f + 1); } static long reindicing_single(long total, long index) { if (index > 0) { return index - 1; } else if (index < 0) { return index + total; } else { return 0; } } static void reindicing(long v_count, long vt_count, long vn_count, Triplet *triplet) { triplet->v = reindicing_single(v_count, triplet->v); triplet->vt = reindicing_single(vt_count, triplet->vt); triplet->vn = reindicing_single(vn_count, triplet->vn); } ObjParser::ObjParser() : v_count_(0), vt_count_(0), vn_count_(0), f_count_(0) { } ObjParser::~ObjParser() { } int ObjParser::Parse(std::istream &stream) { TripletList triplets; std::string line; while (getline(stream, line)) { std::istringstream iss(trimed(line)); std::string tag; iss >> tag; if (tag == "v") { const Vertex vertex = get_vector(iss); read_v(vertex.data_count, vertex.x, vertex.y, vertex.z, vertex.w); v_count_++; } else if (tag == "vt") { const Vertex vertex = get_vector(iss); read_vt(vertex.data_count, vertex.x, vertex.y, vertex.z, vertex.w); vt_count_++; } else if (tag == "vn") { const Vertex vertex = get_vector(iss); read_vn(vertex.data_count, vertex.x, vertex.y, vertex.z, vertex.w); vn_count_++; } else if (tag == "f") { triplets.Clear(); for (;;) { Triplet triplet; if(!get_triplet(iss, triplet)) { break; } reindicing(v_count_, vt_count_, vn_count_, &triplet); triplets.Push(triplet); } read_f( triplets.Count(), triplets.GetVertex(), triplets.GetTexture(), triplets.GetNormal()); f_count_++; } else if (tag == "g") { std::vector<std::string> groups; while (iss) { std::string name; iss >> name; if (!iss.fail()) { groups.push_back(name); } } read_g(groups); } } return 0; } } // namespace xxx
[ "hiroshi@fujiyama-renderer.com" ]
hiroshi@fujiyama-renderer.com
f6d663b963e88c83312aaf5b406a017fef7faab5
a21b33f87dab1ba160dc4933aa61550062fca08b
/install/include/scheduling_msgs/ProductionMaterialList.h
9f62a0dfaa2b3f7cfc0dc79c7b47a891ca10f21f
[]
no_license
servant007/release
4c009c479eaeb0dcf70e2b17ca7631a63745cd0c
c460a36b61668cc380b0e4f99a225dcf55a3c595
refs/heads/master
2020-03-28T03:31:33.535089
2018-09-05T08:28:52
2018-09-05T08:28:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,361
h
// Generated by gencpp from file scheduling_msgs/ProductionMaterialList.msg // DO NOT EDIT! #ifndef SCHEDULING_MSGS_MESSAGE_PRODUCTIONMATERIALLIST_H #define SCHEDULING_MSGS_MESSAGE_PRODUCTIONMATERIALLIST_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <scheduling_msgs/ProductionMaterial.h> namespace scheduling_msgs { template <class ContainerAllocator> struct ProductionMaterialList_ { typedef ProductionMaterialList_<ContainerAllocator> Type; ProductionMaterialList_() : materials() { } ProductionMaterialList_(const ContainerAllocator& _alloc) : materials(_alloc) { (void)_alloc; } typedef std::vector< ::scheduling_msgs::ProductionMaterial_<ContainerAllocator> , typename ContainerAllocator::template rebind< ::scheduling_msgs::ProductionMaterial_<ContainerAllocator> >::other > _materials_type; _materials_type materials; typedef boost::shared_ptr< ::scheduling_msgs::ProductionMaterialList_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::scheduling_msgs::ProductionMaterialList_<ContainerAllocator> const> ConstPtr; }; // struct ProductionMaterialList_ typedef ::scheduling_msgs::ProductionMaterialList_<std::allocator<void> > ProductionMaterialList; typedef boost::shared_ptr< ::scheduling_msgs::ProductionMaterialList > ProductionMaterialListPtr; typedef boost::shared_ptr< ::scheduling_msgs::ProductionMaterialList const> ProductionMaterialListConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::scheduling_msgs::ProductionMaterialList_<ContainerAllocator> & v) { ros::message_operations::Printer< ::scheduling_msgs::ProductionMaterialList_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace scheduling_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False} // {'scheduling_msgs': ['/home/ouiyeah/catkin_ws/src/scheduling_msgs/msg'], 'geometry_msgs': ['/opt/ros/indigo/share/geometry_msgs/cmake/../msg'], 'actionlib_msgs': ['/opt/ros/indigo/share/actionlib_msgs/cmake/../msg'], 'nav_msgs': ['/opt/ros/indigo/share/nav_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/indigo/share/std_msgs/cmake/../msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::scheduling_msgs::ProductionMaterialList_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::scheduling_msgs::ProductionMaterialList_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::scheduling_msgs::ProductionMaterialList_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::scheduling_msgs::ProductionMaterialList_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::scheduling_msgs::ProductionMaterialList_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::scheduling_msgs::ProductionMaterialList_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::scheduling_msgs::ProductionMaterialList_<ContainerAllocator> > { static const char* value() { return "1dada5f7ba7a8f32db51b8a7e9e26cb3"; } static const char* value(const ::scheduling_msgs::ProductionMaterialList_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x1dada5f7ba7a8f32ULL; static const uint64_t static_value2 = 0xdb51b8a7e9e26cb3ULL; }; template<class ContainerAllocator> struct DataType< ::scheduling_msgs::ProductionMaterialList_<ContainerAllocator> > { static const char* value() { return "scheduling_msgs/ProductionMaterialList"; } static const char* value(const ::scheduling_msgs::ProductionMaterialList_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::scheduling_msgs::ProductionMaterialList_<ContainerAllocator> > { static const char* value() { return "# msg for innolux\n\ ProductionMaterial[] materials\n\ ================================================================================\n\ MSG: scheduling_msgs/ProductionMaterial\n\ # msg for innolux\n\ string line\n\ string station\n\ string machine\n\ string model\n\ string material_type\n\ string material_no\n\ "; } static const char* value(const ::scheduling_msgs::ProductionMaterialList_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::scheduling_msgs::ProductionMaterialList_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.materials); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct ProductionMaterialList_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::scheduling_msgs::ProductionMaterialList_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::scheduling_msgs::ProductionMaterialList_<ContainerAllocator>& v) { s << indent << "materials[]" << std::endl; for (size_t i = 0; i < v.materials.size(); ++i) { s << indent << " materials[" << i << "]: "; s << std::endl; s << indent; Printer< ::scheduling_msgs::ProductionMaterial_<ContainerAllocator> >::stream(s, indent + " ", v.materials[i]); } } }; } // namespace message_operations } // namespace ros #endif // SCHEDULING_MSGS_MESSAGE_PRODUCTIONMATERIALLIST_H
[ "ouiyeah@qq.com" ]
ouiyeah@qq.com
307ac49de74d486357090f4c5e62a78a95dc8187
aef2146ee1508d3ad31bd4feba66cd5da6182e16
/source/out_put.h
8da2411231b3b557c48b1972036de323d67a871f
[]
no_license
zongxin/AAE512_spectral_solver_MPI
6757c5abb39403cebf4f32436744c8a5c2b123e2
0cfe7e357a7d63e18928b2a56b1696d5478ce525
refs/heads/main
2023-03-18T06:57:14.552280
2021-03-07T20:38:53
2021-03-07T20:38:53
345,447,375
0
0
null
null
null
null
UTF-8
C++
false
false
2,839
h
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <fstream> #include <sstream> using namespace std; void out_put_solution(int n ){ int one_d = 0; int two_d = 1; fstream fout; string num; stringstream ss; ss << n; ss >> num;//或者 res = ss.str(); string filename="./temp/solution_"; string tail=".dat"; string name=filename+num+tail; fout.open(name.c_str(),ios::out); if (one_d==1){ for (int nb=0;nb<Nblock;nb++){ for (int i=0;i<ng;i++){ //printf("%f \n", ); fout << xg[i]+nb<<" "<<cv2d[nb].ug_new_class[i]<<"\n"; } } } //1d if (two_d==1){ for (int nb=0;nb<Nblock;nb++){ for (int i=0;i<ng;i++){ for (int j=0;j<ng;j++){ fout <<cv2d[nb].ug_new_class[i*ng+j]<<" "; } fout<<"\n"; } } } //1d fout.close(); }//end solution void out_put_mesh(void ){ fstream fout_x; fstream fout_y; string namex="./temp/mesh_x.dat"; string namey="./temp/mesh_y.dat"; fout_x.open(namex.c_str(),ios::out); for (int nb=0;nb<Nblock;nb++){ for (int i=0;i<ng;i++){ for (int j=0;j<ng;j++){ fout_x <<cv2d[nb].xxg[i*ng+j]<<" "; } fout_x<<"\n"; } } fout_x.close(); fout_y.open(namey.c_str(),ios::out); for (int nb=0;nb<Nblock;nb++){ for (int i=0;i<ng;i++){ for (int j=0;j<ng;j++){ fout_y <<cv2d[nb].yyg[i*ng+j]<<" "; } fout_y<<"\n"; } } fout_y.close(); }//end mesh void output_ini(void){ int two_d = 1; fstream fout; string name="./temp/Initial.dat"; fout.open(name.c_str(),ios::out); if (two_d==1){ for (int nb=0;nb<Nblock;nb++){ for (int i=0;i<ng;i++){ for (int j=0;j<ng;j++){ fout <<cv2d[nb].ug_new_class[i*ng+j]<<" "; } fout<<"\n"; } } } //1d fout.close(); }//end solution void test_der(double* Fx,double* Fy){ fstream fout; string name1="dx.dat"; string name2="dy.dat" ; fout.open(name1.c_str(),ios::out); for (int nb=0;nb<Nblock;nb++){ for (int i=0;i<ng;i++){ for (int j=0;j<ng;j++){ fout <<Fx[i*ng+j]<<" "; } fout<<"\n"; } } fout.close(); fout.open(name2.c_str(),ios::out); for (int nb=0;nb<Nblock;nb++){ for (int i=0;i<ng;i++){ for (int j=0;j<ng;j++){ fout <<Fy[i*ng+j]<<" "; } fout<<"\n"; } } fout.close(); }//end solution void test_l_mesh(double* Fx,double* Fy){ fstream fout; string name1="dx.dat"; string name2="dy.dat" ; fout.open(name1.c_str(),ios::out); for (int nb=0;nb<Nblock;nb++){ for (int i=0;i<ng;i++){ for (int j=0;j<nl;j++){ fout <<Fx[i*nl+j]<<" "; } fout<<"\n"; } } fout.close(); fout.open(name2.c_str(),ios::out); for (int nb=0;nb<Nblock;nb++){ for (int i=0;i<nl;i++){ for (int j=0;j<ng;j++){ fout <<Fy[i*ng+j]<<" "; } fout<<"\n"; } } fout.close(); }//end solution
[ "zongxin@zongxin.local" ]
zongxin@zongxin.local
a727669efb3f8570566680046b18d9a8dca354ac
ad567857f44a8c663ae0820fc544eca613ef24aa
/contracts/include/contracts/devices/access_device/iaccess_coordinator.hpp
6e6b7ace2ed53f749fbf23d45f105c0cfecb3673
[]
no_license
jackersson/UnitService
81f3e15e943901016f3a1de600075f172ee60156
4ffa07e773680f119bd3d6e0fce365abbee860bf
refs/heads/master
2021-01-11T20:20:18.674820
2016-10-29T15:50:03
2016-10-29T15:50:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
617
hpp
#ifndef IAccessCoordinator_Included #define IAccessCoordinator_Included #include <datatypes/visit_record.pb.h> namespace contracts { namespace devices { namespace access_device { class IAccessDeviceUpdatable { public: virtual ~IAccessDeviceUpdatable() {} virtual void update(const DataTypes::AccessDevice& device) = 0; }; class IAccessCoordinator: public IAccessDeviceUpdatable , public common::ILifecycle { public: virtual ~IAccessCoordinator() {} virtual void set_state(DataTypes::AccessState state) const = 0; }; } } } #endif
[ "jackersson@gmail.com" ]
jackersson@gmail.com
5832f5b5d48af278d48da0547141dd0baf118b58
ec6e5c5de4615e50e02f73c540f112fdca166431
/Classes/Game/FileOperation.cpp
e63e6ebf950f4714a46b2be57daed1f149d6b709
[]
no_license
revantn/SOH
f4734adc38624bc46a6db97226a29a1d73909677
51d35e3cbbeaf43c938009ce8d8ca96446a955a3
refs/heads/master
2021-01-10T05:06:59.292528
2016-01-28T18:12:09
2016-01-28T18:12:09
50,594,250
0
0
null
null
null
null
UTF-8
C++
false
false
1,644
cpp
// to enable CCLOG() #define COCOS2D_DEBUG 1 #include "cocos2d.h" #include "FileOperation.h" #include <stdio.h> using namespace std; void FileOperation::saveFile(char* buffer) { CCLOG("In FIle SAvE"); string path = getFilePath(); FILE *fp = fopen(path.c_str(), "w"); if (! fp) { CCLOG("can not create file %s", path.c_str()); return; } fputs(buffer, fp); fclose(fp); CCLOG("In FIle ENDddddddddd SAvE"); } void FileOperation::readFile(char* buffer) { CCLOG("In FIle Readdddddddddddddddd"); string path = getFilePath(); FILE *fp = fopen(path.c_str(), "r"); char buf[50] = {0}; if (! fp) { CCLOG("can not open file %s", path.c_str()); return; } fgets(buffer, 50, fp); CCLOG("read content %s", buf); fclose(fp); CCLOG("In FIle Readdddddddd end"); } string FileOperation::getFilePath() { string path(""); #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) // In android, every programe has a director under /data/data. // The path is /data/data/ + start activity package name. // You can save application specific data here. path.append("/data/data/com.rgames.SOH/me.sav"); #endif #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) // You can save file in anywhere if you have the permision. path.append("E:/PI/SOH_client/SOH/proj.win32/Debug.win32/me.sav"); #endif #if (CC_TARGET_PLATFORM == CC_PLATFORM_WOPHONE) path = cocos2d::CCApplication::sharedApplication().getAppDataPath(); #ifdef _TRANZDA_VM_ // If runs on WoPhone simulator, you should insert "D:/Work7" at the // begin. We will fix the bug in no far future. path = "D:/Work7" + path; path.append("tmpfile"); #endif #endif return path; }
[ "rknbgm@gmail.com" ]
rknbgm@gmail.com
a300ac0ab0e3ec3e357bdbdbf2f16c1703c4b269
3b9b4049a8e7d38b49e07bb752780b2f1d792851
/src/chrome/browser/ui/android/usb_chooser_dialog_android.cc
6026fed341672954c0bd680959514597cc65f021
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
webosce/chromium53
f8e745e91363586aee9620c609aacf15b3261540
9171447efcf0bb393d41d1dc877c7c13c46d8e38
refs/heads/webosce
2020-03-26T23:08:14.416858
2018-08-23T08:35:17
2018-09-20T14:25:18
145,513,343
0
2
Apache-2.0
2019-08-21T22:44:55
2018-08-21T05:52:31
null
UTF-8
C++
false
false
9,376
cc
// 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 "chrome/browser/ui/android/usb_chooser_dialog_android.h" #include <stddef.h> #include <algorithm> #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/bind.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ssl/chrome_security_state_model_client.h" #include "chrome/browser/usb/usb_chooser_context.h" #include "chrome/browser/usb/usb_chooser_context_factory.h" #include "chrome/browser/usb/web_usb_histograms.h" #include "chrome/common/url_constants.h" #include "components/url_formatter/elide_url.h" #include "content/public/browser/android/content_view_core.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "device/core/device_client.h" #include "device/usb/mojo/type_converters.h" #include "device/usb/usb_device.h" #include "device/usb/usb_device_filter.h" #include "device/usb/webusb_descriptors.h" #include "jni/UsbChooserDialog_jni.h" #include "ui/android/window_android.h" #include "url/gurl.h" using device::UsbDevice; namespace { void OnDevicePermissionRequestComplete( scoped_refptr<UsbDevice> device, const device::usb::ChooserService::GetPermissionCallback& callback, bool granted) { device::usb::DeviceInfoPtr device_info; if (granted) device_info = device::usb::DeviceInfo::From(*device); callback.Run(std::move(device_info)); } } // namespace UsbChooserDialogAndroid::UsbChooserDialogAndroid( mojo::Array<device::usb::DeviceFilterPtr> device_filters, content::RenderFrameHost* render_frame_host, const device::usb::ChooserService::GetPermissionCallback& callback) : render_frame_host_(render_frame_host), callback_(callback), usb_service_observer_(this), weak_factory_(this) { device::UsbService* usb_service = device::DeviceClient::Get()->GetUsbService(); if (!usb_service) return; if (!usb_service_observer_.IsObserving(usb_service)) usb_service_observer_.Add(usb_service); if (!device_filters.is_null()) filters_ = device_filters.To<std::vector<device::UsbDeviceFilter>>(); // Create (and show) the UsbChooser dialog. content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host_); base::android::ScopedJavaLocalRef<jobject> window_android = content::ContentViewCore::FromWebContents(web_contents) ->GetWindowAndroid() ->GetJavaObject(); JNIEnv* env = base::android::AttachCurrentThread(); base::android::ScopedJavaLocalRef<jstring> origin_string = base::android::ConvertUTF16ToJavaString( env, url_formatter::FormatUrlForSecurityDisplay(GURL( render_frame_host->GetLastCommittedOrigin().Serialize()))); ChromeSecurityStateModelClient* security_model_client = ChromeSecurityStateModelClient::FromWebContents(web_contents); DCHECK(security_model_client); java_dialog_.Reset(Java_UsbChooserDialog_create( env, window_android.obj(), origin_string.obj(), security_model_client->GetSecurityInfo().security_level, reinterpret_cast<intptr_t>(this))); if (!java_dialog_.is_null()) { usb_service->GetDevices( base::Bind(&UsbChooserDialogAndroid::GotUsbDeviceList, weak_factory_.GetWeakPtr())); } } UsbChooserDialogAndroid::~UsbChooserDialogAndroid() { if (!callback_.is_null()) callback_.Run(nullptr); if (!java_dialog_.is_null()) { Java_UsbChooserDialog_closeDialog(base::android::AttachCurrentThread(), java_dialog_.obj()); } } void UsbChooserDialogAndroid::OnDeviceAdded(scoped_refptr<UsbDevice> device) { if (DisplayDevice(device)) { AddDeviceToChooserDialog(device); devices_.push_back(device); } } void UsbChooserDialogAndroid::OnDeviceRemoved(scoped_refptr<UsbDevice> device) { auto it = std::find(devices_.begin(), devices_.end(), device); if (it != devices_.end()) { RemoveDeviceFromChooserDialog(device); devices_.erase(it); } } void UsbChooserDialogAndroid::Select(const std::string& guid) { for (size_t i = 0; i < devices_.size(); ++i) { scoped_refptr<UsbDevice>& device = devices_[i]; if (device->guid() == guid) { content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host_); GURL embedding_origin = web_contents->GetMainFrame()->GetLastCommittedURL().GetOrigin(); Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); UsbChooserContext* chooser_context = UsbChooserContextFactory::GetForProfile(profile); chooser_context->GrantDevicePermission( render_frame_host_->GetLastCommittedURL().GetOrigin(), embedding_origin, device->guid()); device->RequestPermission( base::Bind(&OnDevicePermissionRequestComplete, device, callback_)); callback_.Reset(); // Reset |callback_| so that it is only run once. Java_UsbChooserDialog_closeDialog(base::android::AttachCurrentThread(), java_dialog_.obj()); RecordWebUsbChooserClosure( device->serial_number().empty() ? WEBUSB_CHOOSER_CLOSED_EPHEMERAL_PERMISSION_GRANTED : WEBUSB_CHOOSER_CLOSED_PERMISSION_GRANTED); return; } } } void UsbChooserDialogAndroid::Cancel() { DCHECK(!callback_.is_null()); callback_.Run(nullptr); callback_.Reset(); // Reset |callback_| so that it is only run once. Java_UsbChooserDialog_closeDialog(base::android::AttachCurrentThread(), java_dialog_.obj()); RecordWebUsbChooserClosure(devices_.size() == 0 ? WEBUSB_CHOOSER_CLOSED_CANCELLED_NO_DEVICES : WEBUSB_CHOOSER_CLOSED_CANCELLED); } void UsbChooserDialogAndroid::OnItemSelected( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jstring>& device_id) { Select(base::android::ConvertJavaStringToUTF8(env, device_id)); } void UsbChooserDialogAndroid::OnDialogCancelled( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj) { Cancel(); } void UsbChooserDialogAndroid::LoadUsbHelpPage( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj) { OpenUrl(chrome::kChooserUsbOverviewURL); Cancel(); } // Get a list of devices that can be shown in the chooser bubble UI for // user to grant permsssion. void UsbChooserDialogAndroid::GotUsbDeviceList( const std::vector<scoped_refptr<UsbDevice>>& devices) { for (const auto& device : devices) { if (DisplayDevice(device)) { AddDeviceToChooserDialog(device); devices_.push_back(device); } } JNIEnv* env = base::android::AttachCurrentThread(); Java_UsbChooserDialog_setIdleState(env, java_dialog_.obj()); } void UsbChooserDialogAndroid::AddDeviceToChooserDialog( scoped_refptr<UsbDevice> device) const { JNIEnv* env = base::android::AttachCurrentThread(); base::android::ScopedJavaLocalRef<jstring> device_guid = base::android::ConvertUTF8ToJavaString(env, device->guid()); base::android::ScopedJavaLocalRef<jstring> device_name = base::android::ConvertUTF16ToJavaString(env, device->product_string()); Java_UsbChooserDialog_addDevice(env, java_dialog_.obj(), device_guid.obj(), device_name.obj()); } void UsbChooserDialogAndroid::RemoveDeviceFromChooserDialog( scoped_refptr<UsbDevice> device) const { JNIEnv* env = base::android::AttachCurrentThread(); base::android::ScopedJavaLocalRef<jstring> device_guid = base::android::ConvertUTF8ToJavaString(env, device->guid()); base::android::ScopedJavaLocalRef<jstring> device_name = base::android::ConvertUTF16ToJavaString(env, device->product_string()); Java_UsbChooserDialog_removeDevice(env, java_dialog_.obj(), device_guid.obj(), device_name.obj()); } void UsbChooserDialogAndroid::OpenUrl(const std::string& url) { content::WebContents::FromRenderFrameHost(render_frame_host_) ->OpenURL(content::OpenURLParams(GURL(url), content::Referrer(), NEW_FOREGROUND_TAB, ui::PAGE_TRANSITION_AUTO_TOPLEVEL, false)); // is_renderer_initiated } bool UsbChooserDialogAndroid::DisplayDevice( scoped_refptr<UsbDevice> device) const { if (!device::UsbDeviceFilter::MatchesAny(device, filters_)) return false; // On Android it is not possible to read the WebUSB descriptors until Chrome // has been granted permission to open it. Instead we must list all devices // and perform the allowed origins check after the device has been selected. if (!device->permission_granted()) return true; return device::FindInWebUsbAllowedOrigins( device->webusb_allowed_origins(), render_frame_host_->GetLastCommittedURL().GetOrigin()); } // static bool UsbChooserDialogAndroid::Register(JNIEnv* env) { return RegisterNativesImpl(env); }
[ "changhyeok.bae@lge.com" ]
changhyeok.bae@lge.com
1bea31c1e66a9900f8b021704728addf9349e04c
8d14bcf9b38f657b356ba832b91634d62fe61920
/src/masternode-payments.cpp
a46f9d7e5d76c5da024ed613e772e498c919308d
[ "MIT" ]
permissive
cryptoghass/wallet-1
2e1300f1c4fb09206b01337204ec5f785d53d331
7700987b288e14c5a3326328a79e3f5992c21932
refs/heads/master
2020-07-23T16:42:27.692951
2018-06-30T21:18:00
2018-06-30T21:18:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
42,248
cpp
// Copyright (c) 2014-2017 The Dash Core developers // Copyright (c) 2018 The GLYNO Coin Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "activemasternode.h" #include "governance-classes.h" #include "masternode-payments.h" #include "masternode-sync.h" #include "masternodeman.h" #include "messagesigner.h" #include "netfulfilledman.h" #include "spork.h" #include "util.h" #include <boost/lexical_cast.hpp> /** Object for who's going to get paid on which blocks */ CMasternodePayments mnpayments; CCriticalSection cs_vecPayees; CCriticalSection cs_mapMasternodeBlocks; CCriticalSection cs_mapMasternodePaymentVotes; /** * IsBlockValueValid * * Determine if coinbase outgoing created money is the correct value * * Why is this needed? * - In GLYNO some blocks are superblocks, which output much higher amounts of coins * - Otherblocks are 10% lower in outgoing value, so in total, no extra coins are created * - When non-superblocks are detected, the normal schedule should be maintained */ bool IsBlockValueValid(const CBlock& block, int nBlockHeight, CAmount blockReward, std::string &strErrorRet) { strErrorRet = ""; bool isBlockRewardValueMet = (block.vtx[0].GetValueOut() <= blockReward); if(fDebug) LogPrintf("block.vtx[0].GetValueOut() %lld <= blockReward %lld\n", block.vtx[0].GetValueOut(), blockReward); // we are still using budgets, but we have no data about them anymore, // all we know is predefined budget cycle and window const Consensus::Params& consensusParams = Params().GetConsensus(); if(nBlockHeight < consensusParams.nSuperblockStartBlock) { int nOffset = nBlockHeight % consensusParams.nBudgetPaymentsCycleBlocks; if(nBlockHeight >= consensusParams.nBudgetPaymentsStartBlock && nOffset < consensusParams.nBudgetPaymentsWindowBlocks) { // NOTE: make sure SPORK_13_OLD_SUPERBLOCK_FLAG is disabled when 12.1 starts to go live if(masternodeSync.IsSynced() && !sporkManager.IsSporkActive(SPORK_13_OLD_SUPERBLOCK_FLAG)) { // no budget blocks should be accepted here, if SPORK_13_OLD_SUPERBLOCK_FLAG is disabled LogPrint("gobject", "IsBlockValueValid -- Client synced but budget spork is disabled, checking block value against block reward\n"); if(!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, budgets are disabled", nBlockHeight, block.vtx[0].GetValueOut(), blockReward); } return isBlockRewardValueMet; } LogPrint("gobject", "IsBlockValueValid -- WARNING: Skipping budget block value checks, accepting block\n"); // TODO: reprocess blocks to make sure they are legit? return true; } // LogPrint("gobject", "IsBlockValueValid -- Block is not in budget cycle window, checking block value against block reward\n"); if(!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, block is not in budget cycle window", nBlockHeight, block.vtx[0].GetValueOut(), blockReward); } return isBlockRewardValueMet; } // superblocks started CAmount nSuperblockMaxValue = blockReward + CSuperblock::GetPaymentsLimit(nBlockHeight); bool isSuperblockMaxValueMet = (block.vtx[0].GetValueOut() <= nSuperblockMaxValue); LogPrint("gobject", "block.vtx[0].GetValueOut() %lld <= nSuperblockMaxValue %lld\n", block.vtx[0].GetValueOut(), nSuperblockMaxValue); if(!masternodeSync.IsSynced()) { // not enough data but at least it must NOT exceed superblock max value if(CSuperblock::IsValidBlockHeight(nBlockHeight)) { if(fDebug) LogPrintf("IsBlockPayeeValid -- WARNING: Client not synced, checking superblock max bounds only\n"); if(!isSuperblockMaxValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded superblock max value", nBlockHeight, block.vtx[0].GetValueOut(), nSuperblockMaxValue); } return isSuperblockMaxValueMet; } if(!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, only regular blocks are allowed at this height", nBlockHeight, block.vtx[0].GetValueOut(), blockReward); } // it MUST be a regular block otherwise return isBlockRewardValueMet; } // we are synced, let's try to check as much data as we can if(sporkManager.IsSporkActive(SPORK_9_SUPERBLOCKS_ENABLED)) { if(CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { if(CSuperblockManager::IsValid(block.vtx[0], nBlockHeight, blockReward)) { LogPrint("gobject", "IsBlockValueValid -- Valid superblock at height %d: %s", nBlockHeight, block.vtx[0].ToString()); // all checks are done in CSuperblock::IsValid, nothing to do here return true; } // triggered but invalid? that's weird LogPrintf("IsBlockValueValid -- ERROR: Invalid superblock detected at height %d: %s", nBlockHeight, block.vtx[0].ToString()); // should NOT allow invalid superblocks, when superblocks are enabled strErrorRet = strprintf("invalid superblock detected at height %d", nBlockHeight); return false; } LogPrint("gobject", "IsBlockValueValid -- No triggered superblock detected at height %d\n", nBlockHeight); if(!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, no triggered superblock detected", nBlockHeight, block.vtx[0].GetValueOut(), blockReward); } } else { // should NOT allow superblocks at all, when superblocks are disabled LogPrint("gobject", "IsBlockValueValid -- Superblocks are disabled, no superblocks allowed\n"); if(!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, superblocks are disabled", nBlockHeight, block.vtx[0].GetValueOut(), blockReward); } } // it MUST be a regular block return isBlockRewardValueMet; } bool IsBlockPayeeValid(const CTransaction& txNew, int nBlockHeight, CAmount blockReward) { if(!masternodeSync.IsSynced()) { //there is no budget data to use to check anything, let's just accept the longest chain if(fDebug) LogPrintf("IsBlockPayeeValid -- WARNING: Client not synced, skipping block payee checks\n"); return true; } // we are still using budgets, but we have no data about them anymore, // we can only check masternode payments const Consensus::Params& consensusParams = Params().GetConsensus(); if(nBlockHeight < consensusParams.nSuperblockStartBlock) { if(mnpayments.IsTransactionValid(txNew, nBlockHeight)) { LogPrint("mnpayments", "IsBlockPayeeValid -- Valid masternode payment at height %d: %s", nBlockHeight, txNew.ToString()); return true; } int nOffset = nBlockHeight % consensusParams.nBudgetPaymentsCycleBlocks; if(nBlockHeight >= consensusParams.nBudgetPaymentsStartBlock && nOffset < consensusParams.nBudgetPaymentsWindowBlocks) { if(!sporkManager.IsSporkActive(SPORK_13_OLD_SUPERBLOCK_FLAG)) { // no budget blocks should be accepted here, if SPORK_13_OLD_SUPERBLOCK_FLAG is disabled LogPrint("gobject", "IsBlockPayeeValid -- ERROR: Client synced but budget spork is disabled and masternode payment is invalid\n"); return false; } // NOTE: this should never happen in real, SPORK_13_OLD_SUPERBLOCK_FLAG MUST be disabled when 12.1 starts to go live LogPrint("gobject", "IsBlockPayeeValid -- WARNING: Probably valid budget block, have no data, accepting\n"); // TODO: reprocess blocks to make sure they are legit? return true; } if(sporkManager.IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT)) { LogPrintf("IsBlockPayeeValid -- ERROR: Invalid masternode payment detected at height %d: %s", nBlockHeight, txNew.ToString()); return false; } LogPrintf("IsBlockPayeeValid -- WARNING: Masternode payment enforcement is disabled, accepting any payee\n"); return true; } // superblocks started // SEE IF THIS IS A VALID SUPERBLOCK if(sporkManager.IsSporkActive(SPORK_9_SUPERBLOCKS_ENABLED)) { if(CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { if(CSuperblockManager::IsValid(txNew, nBlockHeight, blockReward)) { LogPrint("gobject", "IsBlockPayeeValid -- Valid superblock at height %d: %s", nBlockHeight, txNew.ToString()); return true; } LogPrintf("IsBlockPayeeValid -- ERROR: Invalid superblock detected at height %d: %s", nBlockHeight, txNew.ToString()); // should NOT allow such superblocks, when superblocks are enabled return false; } // continue validation, should pay MN LogPrint("gobject", "IsBlockPayeeValid -- No triggered superblock detected at height %d\n", nBlockHeight); } else { // should NOT allow superblocks at all, when superblocks are disabled LogPrint("gobject", "IsBlockPayeeValid -- Superblocks are disabled, no superblocks allowed\n"); } // IF THIS ISN'T A SUPERBLOCK OR SUPERBLOCK IS INVALID, IT SHOULD PAY A MASTERNODE DIRECTLY if(mnpayments.IsTransactionValid(txNew, nBlockHeight)) { LogPrint("mnpayments", "IsBlockPayeeValid -- Valid masternode payment at height %d: %s", nBlockHeight, txNew.ToString()); return true; } if(sporkManager.IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT)) { LogPrintf("IsBlockPayeeValid -- ERROR: Invalid masternode payment detected at height %d: %s", nBlockHeight, txNew.ToString()); return false; } LogPrintf("IsBlockPayeeValid -- WARNING: Masternode payment enforcement is disabled, accepting any payee\n"); return true; } void FillBlockPayments(CMutableTransaction& txNew, int nBlockHeight, CAmount blockReward, CTxOut& txoutMasternodeRet, std::vector<CTxOut>& voutSuperblockRet) { // only create superblocks if spork is enabled AND if superblock is actually triggered // (height should be validated inside) if(sporkManager.IsSporkActive(SPORK_9_SUPERBLOCKS_ENABLED) && CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { LogPrint("gobject", "FillBlockPayments -- triggered superblock creation at height %d\n", nBlockHeight); CSuperblockManager::CreateSuperblock(txNew, nBlockHeight, voutSuperblockRet); return; } // FILL BLOCK PAYEE WITH MASTERNODE PAYMENT OTHERWISE mnpayments.FillBlockPayee(txNew, nBlockHeight, blockReward, txoutMasternodeRet); LogPrint("mnpayments", "FillBlockPayments -- nBlockHeight %d blockReward %lld txoutMasternodeRet %s txNew %s", nBlockHeight, blockReward, txoutMasternodeRet.ToString(), txNew.ToString()); } std::string GetRequiredPaymentsString(int nBlockHeight) { // IF WE HAVE A ACTIVATED TRIGGER FOR THIS HEIGHT - IT IS A SUPERBLOCK, GET THE REQUIRED PAYEES if(CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { return CSuperblockManager::GetRequiredPaymentsString(nBlockHeight); } // OTHERWISE, PAY MASTERNODE return mnpayments.GetRequiredPaymentsString(nBlockHeight); } void CMasternodePayments::Clear() { LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes); mapMasternodeBlocks.clear(); mapMasternodePaymentVotes.clear(); } bool CMasternodePayments::CanVote(COutPoint outMasternode, int nBlockHeight) { LOCK(cs_mapMasternodePaymentVotes); if (mapMasternodesLastVote.count(outMasternode) && mapMasternodesLastVote[outMasternode] == nBlockHeight) { return false; } //record this masternode voted mapMasternodesLastVote[outMasternode] = nBlockHeight; return true; } /** * FillBlockPayee * * Fill Masternode ONLY payment block */ void CMasternodePayments::FillBlockPayee(CMutableTransaction& txNew, int nBlockHeight, CAmount blockReward, CTxOut& txoutMasternodeRet) { // make sure it's not filled yet txoutMasternodeRet = CTxOut(); CScript payee; if(!mnpayments.GetBlockPayee(nBlockHeight, payee)) { // no masternode detected... int nCount = 0; masternode_info_t mnInfo; if(!mnodeman.GetNextMasternodeInQueueForPayment(nBlockHeight, true, nCount, mnInfo)) { // ...and we can't calculate it on our own LogPrintf("CMasternodePayments::FillBlockPayee -- Failed to detect masternode to pay\n"); return; } // fill payee with locally calculated winner and hope for the best payee = GetScriptForDestination(mnInfo.pubKeyCollateralAddress.GetID()); } // GET MASTERNODE PAYMENT VARIABLES SETUP CAmount masternodePayment = GetMasternodePayment(nBlockHeight, blockReward); // split reward between miner ... txNew.vout[0].nValue -= masternodePayment; // ... and masternode txoutMasternodeRet = CTxOut(masternodePayment, payee); txNew.vout.push_back(txoutMasternodeRet); CTxDestination address1; ExtractDestination(payee, address1); CBitcoinAddress address2(address1); LogPrintf("CMasternodePayments::FillBlockPayee -- Masternode payment %lld to %s\n", masternodePayment, address2.ToString()); } int CMasternodePayments::GetMinMasternodePaymentsProto() { return sporkManager.IsSporkActive(SPORK_10_MASTERNODE_PAY_UPDATED_NODES) ? MIN_MASTERNODE_PAYMENT_PROTO_VERSION_2 : MIN_MASTERNODE_PAYMENT_PROTO_VERSION_1; } void CMasternodePayments::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv, CConnman& connman) { if(fLiteMode) return; // disable all GLYNO specific functionality if (strCommand == NetMsgType::MASTERNODEPAYMENTSYNC) { //Masternode Payments Request Sync // Ignore such requests until we are fully synced. // We could start processing this after masternode list is synced // but this is a heavy one so it's better to finish sync first. if (!masternodeSync.IsSynced()) return; int nCountNeeded; vRecv >> nCountNeeded; if(netfulfilledman.HasFulfilledRequest(pfrom->addr, NetMsgType::MASTERNODEPAYMENTSYNC)) { // Asking for the payments list multiple times in a short period of time is no good LogPrintf("MASTERNODEPAYMENTSYNC -- peer already asked me for the list, peer=%d\n", pfrom->id); Misbehaving(pfrom->GetId(), 20); return; } netfulfilledman.AddFulfilledRequest(pfrom->addr, NetMsgType::MASTERNODEPAYMENTSYNC); Sync(pfrom, connman); LogPrintf("MASTERNODEPAYMENTSYNC -- Sent Masternode payment votes to peer %d\n", pfrom->id); } else if (strCommand == NetMsgType::MASTERNODEPAYMENTVOTE) { // Masternode Payments Vote for the Winner CMasternodePaymentVote vote; vRecv >> vote; if(pfrom->nVersion < GetMinMasternodePaymentsProto()) return; uint256 nHash = vote.GetHash(); pfrom->setAskFor.erase(nHash); // TODO: clear setAskFor for MSG_MASTERNODE_PAYMENT_BLOCK too // Ignore any payments messages until masternode list is synced if(!masternodeSync.IsMasternodeListSynced()) return; { LOCK(cs_mapMasternodePaymentVotes); if(mapMasternodePaymentVotes.count(nHash)) { LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- hash=%s, nHeight=%d seen\n", nHash.ToString(), nCachedBlockHeight); return; } // Avoid processing same vote multiple times mapMasternodePaymentVotes[nHash] = vote; // but first mark vote as non-verified, // AddPaymentVote() below should take care of it if vote is actually ok mapMasternodePaymentVotes[nHash].MarkAsNotVerified(); } int nFirstBlock = nCachedBlockHeight - GetStorageLimit(); if(vote.nBlockHeight < nFirstBlock || vote.nBlockHeight > nCachedBlockHeight+20) { LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- vote out of range: nFirstBlock=%d, nBlockHeight=%d, nHeight=%d\n", nFirstBlock, vote.nBlockHeight, nCachedBlockHeight); return; } std::string strError = ""; if(!vote.IsValid(pfrom, nCachedBlockHeight, strError, connman)) { LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- invalid message, error: %s\n", strError); return; } if(!CanVote(vote.vinMasternode.prevout, vote.nBlockHeight)) { LogPrintf("MASTERNODEPAYMENTVOTE -- masternode already voted, masternode=%s\n", vote.vinMasternode.prevout.ToStringShort()); return; } masternode_info_t mnInfo; if(!mnodeman.GetMasternodeInfo(vote.vinMasternode.prevout, mnInfo)) { // mn was not found, so we can't check vote, some info is probably missing LogPrintf("MASTERNODEPAYMENTVOTE -- masternode is missing %s\n", vote.vinMasternode.prevout.ToStringShort()); mnodeman.AskForMN(pfrom, vote.vinMasternode.prevout, connman); return; } int nDos = 0; if(!vote.CheckSignature(mnInfo.pubKeyMasternode, nCachedBlockHeight, nDos)) { if(nDos) { LogPrintf("MASTERNODEPAYMENTVOTE -- ERROR: invalid signature\n"); Misbehaving(pfrom->GetId(), nDos); } else { // only warn about anything non-critical (i.e. nDos == 0) in debug mode LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- WARNING: invalid signature\n"); } // Either our info or vote info could be outdated. // In case our info is outdated, ask for an update, mnodeman.AskForMN(pfrom, vote.vinMasternode.prevout, connman); // but there is nothing we can do if vote info itself is outdated // (i.e. it was signed by a mn which changed its key), // so just quit here. return; } CTxDestination address1; ExtractDestination(vote.payee, address1); CBitcoinAddress address2(address1); LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- vote: address=%s, nBlockHeight=%d, nHeight=%d, prevout=%s, hash=%s new\n", address2.ToString(), vote.nBlockHeight, nCachedBlockHeight, vote.vinMasternode.prevout.ToStringShort(), nHash.ToString()); if(AddPaymentVote(vote)){ vote.Relay(connman); masternodeSync.BumpAssetLastTime("MASTERNODEPAYMENTVOTE"); } } } bool CMasternodePaymentVote::Sign() { std::string strError; std::string strMessage = vinMasternode.prevout.ToStringShort() + boost::lexical_cast<std::string>(nBlockHeight) + ScriptToAsmStr(payee); if(!CMessageSigner::SignMessage(strMessage, vchSig, activeMasternode.keyMasternode)) { LogPrintf("CMasternodePaymentVote::Sign -- SignMessage() failed\n"); return false; } if(!CMessageSigner::VerifyMessage(activeMasternode.pubKeyMasternode, vchSig, strMessage, strError)) { LogPrintf("CMasternodePaymentVote::Sign -- VerifyMessage() failed, error: %s\n", strError); return false; } return true; } bool CMasternodePayments::GetBlockPayee(int nBlockHeight, CScript& payee) { if(mapMasternodeBlocks.count(nBlockHeight)){ return mapMasternodeBlocks[nBlockHeight].GetBestPayee(payee); } return false; } // Is this masternode scheduled to get paid soon? // -- Only look ahead up to 8 blocks to allow for propagation of the latest 2 blocks of votes bool CMasternodePayments::IsScheduled(CMasternode& mn, int nNotBlockHeight) { LOCK(cs_mapMasternodeBlocks); if(!masternodeSync.IsMasternodeListSynced()) return false; CScript mnpayee; mnpayee = GetScriptForDestination(mn.pubKeyCollateralAddress.GetID()); CScript payee; for(int64_t h = nCachedBlockHeight; h <= nCachedBlockHeight + 8; h++){ if(h == nNotBlockHeight) continue; if(mapMasternodeBlocks.count(h) && mapMasternodeBlocks[h].GetBestPayee(payee) && mnpayee == payee) { return true; } } return false; } bool CMasternodePayments::AddPaymentVote(const CMasternodePaymentVote& vote) { uint256 blockHash = uint256(); if(!GetBlockHash(blockHash, vote.nBlockHeight - 101)) return false; if(HasVerifiedPaymentVote(vote.GetHash())) return false; LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes); mapMasternodePaymentVotes[vote.GetHash()] = vote; if(!mapMasternodeBlocks.count(vote.nBlockHeight)) { CMasternodeBlockPayees blockPayees(vote.nBlockHeight); mapMasternodeBlocks[vote.nBlockHeight] = blockPayees; } mapMasternodeBlocks[vote.nBlockHeight].AddPayee(vote); return true; } bool CMasternodePayments::HasVerifiedPaymentVote(uint256 hashIn) { LOCK(cs_mapMasternodePaymentVotes); std::map<uint256, CMasternodePaymentVote>::iterator it = mapMasternodePaymentVotes.find(hashIn); return it != mapMasternodePaymentVotes.end() && it->second.IsVerified(); } void CMasternodeBlockPayees::AddPayee(const CMasternodePaymentVote& vote) { LOCK(cs_vecPayees); BOOST_FOREACH(CMasternodePayee& payee, vecPayees) { if (payee.GetPayee() == vote.payee) { payee.AddVoteHash(vote.GetHash()); return; } } CMasternodePayee payeeNew(vote.payee, vote.GetHash()); vecPayees.push_back(payeeNew); } bool CMasternodeBlockPayees::GetBestPayee(CScript& payeeRet) { LOCK(cs_vecPayees); if(!vecPayees.size()) { LogPrint("mnpayments", "CMasternodeBlockPayees::GetBestPayee -- ERROR: couldn't find any payee\n"); return false; } int nVotes = -1; BOOST_FOREACH(CMasternodePayee& payee, vecPayees) { if (payee.GetVoteCount() > nVotes) { payeeRet = payee.GetPayee(); nVotes = payee.GetVoteCount(); } } return (nVotes > -1); } bool CMasternodeBlockPayees::HasPayeeWithVotes(const CScript& payeeIn, int nVotesReq) { LOCK(cs_vecPayees); BOOST_FOREACH(CMasternodePayee& payee, vecPayees) { if (payee.GetVoteCount() >= nVotesReq && payee.GetPayee() == payeeIn) { return true; } } LogPrint("mnpayments", "CMasternodeBlockPayees::HasPayeeWithVotes -- ERROR: couldn't find any payee with %d+ votes\n", nVotesReq); return false; } bool CMasternodeBlockPayees::IsTransactionValid(const CTransaction& txNew) { LOCK(cs_vecPayees); int nMaxSignatures = 0; std::string strPayeesPossible = ""; CAmount nMasternodePayment = GetMasternodePayment(nBlockHeight, txNew.GetValueOut()); //require at least MNPAYMENTS_SIGNATURES_REQUIRED signatures BOOST_FOREACH(CMasternodePayee& payee, vecPayees) { if (payee.GetVoteCount() >= nMaxSignatures) { nMaxSignatures = payee.GetVoteCount(); } } // if we don't have at least MNPAYMENTS_SIGNATURES_REQUIRED signatures on a payee, approve whichever is the longest chain if(nMaxSignatures < MNPAYMENTS_SIGNATURES_REQUIRED) return true; BOOST_FOREACH(CMasternodePayee& payee, vecPayees) { if (payee.GetVoteCount() >= MNPAYMENTS_SIGNATURES_REQUIRED) { BOOST_FOREACH(CTxOut txout, txNew.vout) { if (payee.GetPayee() == txout.scriptPubKey && nMasternodePayment == txout.nValue) { LogPrint("mnpayments", "CMasternodeBlockPayees::IsTransactionValid -- Found required payment\n"); return true; } } CTxDestination address1; ExtractDestination(payee.GetPayee(), address1); CBitcoinAddress address2(address1); if(strPayeesPossible == "") { strPayeesPossible = address2.ToString(); } else { strPayeesPossible += "," + address2.ToString(); } } } LogPrintf("CMasternodeBlockPayees::IsTransactionValid -- ERROR: Missing required payment, possible payees: '%s', amount: %f GLYNO\n", strPayeesPossible, (float)nMasternodePayment/COIN); return false; } std::string CMasternodeBlockPayees::GetRequiredPaymentsString() { LOCK(cs_vecPayees); std::string strRequiredPayments = "Unknown"; BOOST_FOREACH(CMasternodePayee& payee, vecPayees) { CTxDestination address1; ExtractDestination(payee.GetPayee(), address1); CBitcoinAddress address2(address1); if (strRequiredPayments != "Unknown") { strRequiredPayments += ", " + address2.ToString() + ":" + boost::lexical_cast<std::string>(payee.GetVoteCount()); } else { strRequiredPayments = address2.ToString() + ":" + boost::lexical_cast<std::string>(payee.GetVoteCount()); } } return strRequiredPayments; } std::string CMasternodePayments::GetRequiredPaymentsString(int nBlockHeight) { LOCK(cs_mapMasternodeBlocks); if(mapMasternodeBlocks.count(nBlockHeight)){ return mapMasternodeBlocks[nBlockHeight].GetRequiredPaymentsString(); } return "Unknown"; } bool CMasternodePayments::IsTransactionValid(const CTransaction& txNew, int nBlockHeight) { LOCK(cs_mapMasternodeBlocks); if(mapMasternodeBlocks.count(nBlockHeight)){ return mapMasternodeBlocks[nBlockHeight].IsTransactionValid(txNew); } return true; } void CMasternodePayments::CheckAndRemove() { if(!masternodeSync.IsBlockchainSynced()) return; LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes); int nLimit = GetStorageLimit(); std::map<uint256, CMasternodePaymentVote>::iterator it = mapMasternodePaymentVotes.begin(); while(it != mapMasternodePaymentVotes.end()) { CMasternodePaymentVote vote = (*it).second; if(nCachedBlockHeight - vote.nBlockHeight > nLimit) { LogPrint("mnpayments", "CMasternodePayments::CheckAndRemove -- Removing old Masternode payment: nBlockHeight=%d\n", vote.nBlockHeight); mapMasternodePaymentVotes.erase(it++); mapMasternodeBlocks.erase(vote.nBlockHeight); } else { ++it; } } LogPrintf("CMasternodePayments::CheckAndRemove -- %s\n", ToString()); } bool CMasternodePaymentVote::IsValid(CNode* pnode, int nValidationHeight, std::string& strError, CConnman& connman) { masternode_info_t mnInfo; if(!mnodeman.GetMasternodeInfo(vinMasternode.prevout, mnInfo)) { strError = strprintf("Unknown Masternode: prevout=%s", vinMasternode.prevout.ToStringShort()); // Only ask if we are already synced and still have no idea about that Masternode if(masternodeSync.IsMasternodeListSynced()) { mnodeman.AskForMN(pnode, vinMasternode.prevout, connman); } return false; } int nMinRequiredProtocol; if(nBlockHeight >= nValidationHeight) { // new votes must comply SPORK_10_MASTERNODE_PAY_UPDATED_NODES rules nMinRequiredProtocol = mnpayments.GetMinMasternodePaymentsProto(); } else { // allow non-updated masternodes for old blocks nMinRequiredProtocol = MIN_MASTERNODE_PAYMENT_PROTO_VERSION_1; } if(mnInfo.nProtocolVersion < nMinRequiredProtocol) { strError = strprintf("Masternode protocol is too old: nProtocolVersion=%d, nMinRequiredProtocol=%d", mnInfo.nProtocolVersion, nMinRequiredProtocol); return false; } // Only masternodes should try to check masternode rank for old votes - they need to pick the right winner for future blocks. // Regular clients (miners included) need to verify masternode rank for future block votes only. if(!fMasterNode && nBlockHeight < nValidationHeight) return true; int nRank; if(!mnodeman.GetMasternodeRank(vinMasternode.prevout, nRank, nBlockHeight - 101, nMinRequiredProtocol)) { LogPrint("mnpayments", "CMasternodePaymentVote::IsValid -- Can't calculate rank for masternode %s\n", vinMasternode.prevout.ToStringShort()); return false; } if(nRank > MNPAYMENTS_SIGNATURES_TOTAL) { // It's common to have masternodes mistakenly think they are in the top 10 // We don't want to print all of these messages in normal mode, debug mode should print though strError = strprintf("Masternode is not in the top %d (%d)", MNPAYMENTS_SIGNATURES_TOTAL, nRank); // Only ban for new mnw which is out of bounds, for old mnw MN list itself might be way too much off if(nRank > MNPAYMENTS_SIGNATURES_TOTAL*2 && nBlockHeight > nValidationHeight) { strError = strprintf("Masternode is not in the top %d (%d)", MNPAYMENTS_SIGNATURES_TOTAL*2, nRank); LogPrintf("CMasternodePaymentVote::IsValid -- Error: %s\n", strError); Misbehaving(pnode->GetId(), 20); } // Still invalid however return false; } return true; } bool CMasternodePayments::ProcessBlock(int nBlockHeight, CConnman& connman) { // DETERMINE IF WE SHOULD BE VOTING FOR THE NEXT PAYEE if(fLiteMode || !fMasterNode) return false; // We have little chances to pick the right winner if winners list is out of sync // but we have no choice, so we'll try. However it doesn't make sense to even try to do so // if we have not enough data about masternodes. if(!masternodeSync.IsMasternodeListSynced()) return false; int nRank; if (!mnodeman.GetMasternodeRank(activeMasternode.outpoint, nRank, nBlockHeight - 101, GetMinMasternodePaymentsProto())) { LogPrint("mnpayments", "CMasternodePayments::ProcessBlock -- Unknown Masternode\n"); return false; } if (nRank > MNPAYMENTS_SIGNATURES_TOTAL) { LogPrint("mnpayments", "CMasternodePayments::ProcessBlock -- Masternode not in the top %d (%d)\n", MNPAYMENTS_SIGNATURES_TOTAL, nRank); return false; } // LOCATE THE NEXT MASTERNODE WHICH SHOULD BE PAID LogPrintf("CMasternodePayments::ProcessBlock -- Start: nBlockHeight=%d, masternode=%s\n", nBlockHeight, activeMasternode.outpoint.ToStringShort()); // pay to the oldest MN that still had no payment but its input is old enough and it was active long enough int nCount = 0; masternode_info_t mnInfo; if (!mnodeman.GetNextMasternodeInQueueForPayment(nBlockHeight, true, nCount, mnInfo)) { LogPrintf("CMasternodePayments::ProcessBlock -- ERROR: Failed to find masternode to pay\n"); return false; } LogPrintf("CMasternodePayments::ProcessBlock -- Masternode found by GetNextMasternodeInQueueForPayment(): %s\n", mnInfo.vin.prevout.ToStringShort()); CScript payee = GetScriptForDestination(mnInfo.pubKeyCollateralAddress.GetID()); CMasternodePaymentVote voteNew(activeMasternode.outpoint, nBlockHeight, payee); CTxDestination address1; ExtractDestination(payee, address1); CBitcoinAddress address2(address1); LogPrintf("CMasternodePayments::ProcessBlock -- vote: payee=%s, nBlockHeight=%d\n", address2.ToString(), nBlockHeight); // SIGN MESSAGE TO NETWORK WITH OUR MASTERNODE KEYS LogPrintf("CMasternodePayments::ProcessBlock -- Signing vote\n"); if (voteNew.Sign()) { LogPrintf("CMasternodePayments::ProcessBlock -- AddPaymentVote()\n"); if (AddPaymentVote(voteNew)) { voteNew.Relay(connman); return true; } } return false; } void CMasternodePayments::CheckPreviousBlockVotes(int nPrevBlockHeight) { if (!masternodeSync.IsWinnersListSynced()) return; std::string debugStr; debugStr += strprintf("CMasternodePayments::CheckPreviousBlockVotes -- nPrevBlockHeight=%d, expected voting MNs:\n", nPrevBlockHeight); CMasternodeMan::rank_pair_vec_t mns; if (!mnodeman.GetMasternodeRanks(mns, nPrevBlockHeight - 101, GetMinMasternodePaymentsProto())) { debugStr += "CMasternodePayments::CheckPreviousBlockVotes -- GetMasternodeRanks failed\n"; LogPrint("mnpayments", "%s", debugStr); return; } LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes); for (int i = 0; i < MNPAYMENTS_SIGNATURES_TOTAL && i < (int)mns.size(); i++) { auto mn = mns[i]; CScript payee; bool found = false; if (mapMasternodeBlocks.count(nPrevBlockHeight)) { for (auto &p : mapMasternodeBlocks[nPrevBlockHeight].vecPayees) { for (auto &voteHash : p.GetVoteHashes()) { if (!mapMasternodePaymentVotes.count(voteHash)) { debugStr += strprintf("CMasternodePayments::CheckPreviousBlockVotes -- could not find vote %s\n", voteHash.ToString()); continue; } auto vote = mapMasternodePaymentVotes[voteHash]; if (vote.vinMasternode.prevout == mn.second.vin.prevout) { payee = vote.payee; found = true; break; } } } } if (!found) { debugStr += strprintf("CMasternodePayments::CheckPreviousBlockVotes -- %s - no vote received\n", mn.second.vin.prevout.ToStringShort()); mapMasternodesDidNotVote[mn.second.vin.prevout]++; continue; } CTxDestination address1; ExtractDestination(payee, address1); CBitcoinAddress address2(address1); debugStr += strprintf("CMasternodePayments::CheckPreviousBlockVotes -- %s - voted for %s\n", mn.second.vin.prevout.ToStringShort(), address2.ToString()); } debugStr += "CMasternodePayments::CheckPreviousBlockVotes -- Masternodes which missed a vote in the past:\n"; for (auto it : mapMasternodesDidNotVote) { debugStr += strprintf("CMasternodePayments::CheckPreviousBlockVotes -- %s: %d\n", it.first.ToStringShort(), it.second); } LogPrint("mnpayments", "%s", debugStr); } void CMasternodePaymentVote::Relay(CConnman& connman) { // Do not relay until fully synced if(!masternodeSync.IsSynced()) { LogPrint("mnpayments", "CMasternodePayments::Relay -- won't relay until fully synced\n"); return; } CInv inv(MSG_MASTERNODE_PAYMENT_VOTE, GetHash()); connman.RelayInv(inv); } bool CMasternodePaymentVote::CheckSignature(const CPubKey& pubKeyMasternode, int nValidationHeight, int &nDos) { // do not ban by default nDos = 0; std::string strMessage = vinMasternode.prevout.ToStringShort() + boost::lexical_cast<std::string>(nBlockHeight) + ScriptToAsmStr(payee); std::string strError = ""; if (!CMessageSigner::VerifyMessage(pubKeyMasternode, vchSig, strMessage, strError)) { // Only ban for future block vote when we are already synced. // Otherwise it could be the case when MN which signed this vote is using another key now // and we have no idea about the old one. if(masternodeSync.IsMasternodeListSynced() && nBlockHeight > nValidationHeight) { nDos = 20; } return error("CMasternodePaymentVote::CheckSignature -- Got bad Masternode payment signature, masternode=%s, error: %s", vinMasternode.prevout.ToStringShort().c_str(), strError); } return true; } std::string CMasternodePaymentVote::ToString() const { std::ostringstream info; info << vinMasternode.prevout.ToStringShort() << ", " << nBlockHeight << ", " << ScriptToAsmStr(payee) << ", " << (int)vchSig.size(); return info.str(); } // Send only votes for future blocks, node should request every other missing payment block individually void CMasternodePayments::Sync(CNode* pnode, CConnman& connman) { LOCK(cs_mapMasternodeBlocks); if(!masternodeSync.IsWinnersListSynced()) return; int nInvCount = 0; for(int h = nCachedBlockHeight; h < nCachedBlockHeight + 20; h++) { if(mapMasternodeBlocks.count(h)) { BOOST_FOREACH(CMasternodePayee& payee, mapMasternodeBlocks[h].vecPayees) { std::vector<uint256> vecVoteHashes = payee.GetVoteHashes(); BOOST_FOREACH(uint256& hash, vecVoteHashes) { if(!HasVerifiedPaymentVote(hash)) continue; pnode->PushInventory(CInv(MSG_MASTERNODE_PAYMENT_VOTE, hash)); nInvCount++; } } } } LogPrintf("CMasternodePayments::Sync -- Sent %d votes to peer %d\n", nInvCount, pnode->id); connman.PushMessage(pnode, NetMsgType::SYNCSTATUSCOUNT, MASTERNODE_SYNC_MNW, nInvCount); } // Request low data/unknown payment blocks in batches directly from some node instead of/after preliminary Sync. void CMasternodePayments::RequestLowDataPaymentBlocks(CNode* pnode, CConnman& connman) { if(!masternodeSync.IsMasternodeListSynced()) return; LOCK2(cs_main, cs_mapMasternodeBlocks); std::vector<CInv> vToFetch; int nLimit = GetStorageLimit(); const CBlockIndex *pindex = chainActive.Tip(); while(nCachedBlockHeight - pindex->nHeight < nLimit) { if(!mapMasternodeBlocks.count(pindex->nHeight)) { // We have no idea about this block height, let's ask vToFetch.push_back(CInv(MSG_MASTERNODE_PAYMENT_BLOCK, pindex->GetBlockHash())); // We should not violate GETDATA rules if(vToFetch.size() == MAX_INV_SZ) { LogPrintf("CMasternodePayments::SyncLowDataPaymentBlocks -- asking peer %d for %d blocks\n", pnode->id, MAX_INV_SZ); connman.PushMessage(pnode, NetMsgType::GETDATA, vToFetch); // Start filling new batch vToFetch.clear(); } } if(!pindex->pprev) break; pindex = pindex->pprev; } std::map<int, CMasternodeBlockPayees>::iterator it = mapMasternodeBlocks.begin(); while(it != mapMasternodeBlocks.end()) { int nTotalVotes = 0; bool fFound = false; BOOST_FOREACH(CMasternodePayee& payee, it->second.vecPayees) { if(payee.GetVoteCount() >= MNPAYMENTS_SIGNATURES_REQUIRED) { fFound = true; break; } nTotalVotes += payee.GetVoteCount(); } // A clear winner (MNPAYMENTS_SIGNATURES_REQUIRED+ votes) was found // or no clear winner was found but there are at least avg number of votes if(fFound || nTotalVotes >= (MNPAYMENTS_SIGNATURES_TOTAL + MNPAYMENTS_SIGNATURES_REQUIRED)/2) { // so just move to the next block ++it; continue; } // DEBUG DBG ( // Let's see why this failed BOOST_FOREACH(CMasternodePayee& payee, it->second.vecPayees) { CTxDestination address1; ExtractDestination(payee.GetPayee(), address1); CBitcoinAddress address2(address1); printf("payee %s votes %d\n", address2.ToString().c_str(), payee.GetVoteCount()); } printf("block %d votes total %d\n", it->first, nTotalVotes); ) // END DEBUG // Low data block found, let's try to sync it uint256 hash; if(GetBlockHash(hash, it->first)) { vToFetch.push_back(CInv(MSG_MASTERNODE_PAYMENT_BLOCK, hash)); } // We should not violate GETDATA rules if(vToFetch.size() == MAX_INV_SZ) { LogPrintf("CMasternodePayments::SyncLowDataPaymentBlocks -- asking peer %d for %d payment blocks\n", pnode->id, MAX_INV_SZ); connman.PushMessage(pnode, NetMsgType::GETDATA, vToFetch); // Start filling new batch vToFetch.clear(); } ++it; } // Ask for the rest of it if(!vToFetch.empty()) { LogPrintf("CMasternodePayments::SyncLowDataPaymentBlocks -- asking peer %d for %d payment blocks\n", pnode->id, vToFetch.size()); connman.PushMessage(pnode, NetMsgType::GETDATA, vToFetch); } } std::string CMasternodePayments::ToString() const { std::ostringstream info; info << "Votes: " << (int)mapMasternodePaymentVotes.size() << ", Blocks: " << (int)mapMasternodeBlocks.size(); return info.str(); } bool CMasternodePayments::IsEnoughData() { float nAverageVotes = (MNPAYMENTS_SIGNATURES_TOTAL + MNPAYMENTS_SIGNATURES_REQUIRED) / 2; int nStorageLimit = GetStorageLimit(); return GetBlockCount() > nStorageLimit && GetVoteCount() > nStorageLimit * nAverageVotes; } int CMasternodePayments::GetStorageLimit() { return std::max(int(mnodeman.size() * nStorageCoeff), nMinBlocksToStore); } void CMasternodePayments::UpdatedBlockTip(const CBlockIndex *pindex, CConnman& connman) { if(!pindex) return; nCachedBlockHeight = pindex->nHeight; LogPrint("mnpayments", "CMasternodePayments::UpdatedBlockTip -- nCachedBlockHeight=%d\n", nCachedBlockHeight); int nFutureBlock = nCachedBlockHeight + 10; CheckPreviousBlockVotes(nFutureBlock - 1); ProcessBlock(nFutureBlock, connman); }
[ "OhCreativeYT@gmail.com" ]
OhCreativeYT@gmail.com
c945bf9099ac55cd75de4155337bde9b658588ec
d0be9a869d4631c58d09ad538b0908554d204e1c
/utf8/lib/client/cegui/CEGUI/src/falagard/extend/IExpProperty.cpp
9443f27b9ed30e7e767f814fb1f0ce301192f786
[]
no_license
World3D/pap
19ec5610393e429995f9e9b9eb8628fa597be80b
de797075062ba53037c1f68cd80ee6ab3ed55cbe
refs/heads/master
2021-05-27T08:53:38.964500
2014-07-24T08:10:40
2014-07-24T08:10:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
928
cpp
#include "IExpProperty.h" // Start of CEGUI namespace section namespace CEGUI { namespace IExpPropertyProperties { String ChildItem::get(const PropertyReceiver* receiver) const { return ""; } void ChildItem::set(PropertyReceiver* receiver, const String& value) { char szKey[128]; char szName[128]; sscanf( value.c_str(), "key:%127s name:%127s", szKey, szName); static_cast<IExpProperty*>(receiver)->setChildType( szKey, (utf8*)szName ); } }; IExpPropertyProperties::ChildItem IExpProperty::d_ChildItemProperty; IExpProperty::IExpProperty(const String& type, const String& name) : Window(type, name) { CEGUI_START_ADD_STATICPROPERTY( IExpProperty ) CEGUI_ADD_STATICPROPERTY( &d_ChildItemProperty ); CEGUI_END_ADD_STATICPROPERTY } void IExpProperty::setChildType( const String& szKey, const String& strName ) { m_mapChildType[szKey] = strName; } };
[ "viticm@126.com" ]
viticm@126.com
d25d20afc19877d2eac330c616a17e1d39e34385
5afd26de6bcb0012450381b4064d8253817c2bb6
/benchmark/scenario1/impl_boost_pt.cpp
fd04c8341f4a45ae2fbc16ff7c3b3b8eb3c2c062
[ "MIT" ]
permissive
mserdarsanli/QuantumJson
1e90f4c383939cb2cbd71f8bd9b60a814a44bb49
7aa8c7e17d2ff6677264edd20f54d7ee20821213
refs/heads/master
2021-01-11T17:04:23.637017
2018-10-20T14:47:23
2018-10-20T14:47:23
69,503,276
6
0
null
null
null
null
UTF-8
C++
false
false
2,407
cpp
// The MIT License (MIT) // // Copyright (c) 2016 Mustafa Serdar Sanli // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "benchmark/Benchmark.hpp" #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> namespace pt = boost::property_tree; void Benchmark(int repeat, const std::string &input) { BENCHMARK_BEGIN; for (int i = 0; i < repeat; ++i) { BENCHMARK_LOOP_BEGIN; // TODO boost property_tree does not read from string directly. // So this may not be a fair comparison. std::stringstream ss; ss.str(input); pt::ptree root; pt::read_json(ss, root); #ifdef BENCHMARK_CHECK_CORRECTNESS std::string url1, url25; int score1, score25; // boost_pt has a horrible api, not allowing random access to // list elements. int n = 0; for (const auto &ch : root.get_child("data.children")) { ++n; if (n == 1) { url1 = ch.second.get<std::string>("data.url"); score1 = ch.second.get<int>("data.score"); } if (n == 25) { url25 = ch.second.get<std::string>("data.url"); score25 = ch.second.get<int>("data.score"); } } // Check first and last values CHECK(url1 == "http://i.imgur.com/RkeezA0.jpg"); CHECK(score1 == 6607); CHECK(url25 == "https://www.youtube.com/watch?v=PMNFaAUs2mo"); CHECK(score25 == 4679); #endif BENCHMARK_LOOP_END; } BENCHMARK_END; }
[ "mserdarsanli@gmail.com" ]
mserdarsanli@gmail.com
a50a330aef7ffb31abac3ae3db6726fca49a1698
b6659e14894d4e8d26c2857cb3b5c16ef1a8c207
/sudoku_solver.cpp
0c44b950ce6e0e9da72b3793d32c41ca08c3d536
[]
no_license
JustineVuillemot/SudokuSolver
d6b4b447e72ef9e2c9732a16cc79798f4c044155
697fc295a8c759afa18d44d941ecc4111bc9eeb1
refs/heads/master
2020-04-02T06:23:20.347093
2018-10-22T15:50:40
2018-10-22T15:50:40
154,145,751
0
0
null
null
null
null
UTF-8
C++
false
false
96
cpp
#include "sudoku_solver.hpp" SudokuSolver::SudokuSolver(Sudoku &sudoku) : ss_sudoku(sudoku) { }
[ "vuillemotjustine@gmail.com" ]
vuillemotjustine@gmail.com
ee951f6d4fcaaadb2b6757b6f0d44855efc4c84e
84283cea46b67170bb50f22dcafef2ca6ddaedff
/Nowcoder Multi-University/4/H1.cpp
2dbf11d8c49290a573caf2da920ccfcb583eeb82
[]
no_license
ssyze/Codes
b36fedf103c18118fd7375ce7a40e864dbef7928
1376c40318fb67a7912f12765844f5eefb055c13
refs/heads/master
2023-01-09T18:36:05.417233
2020-11-03T15:45:45
2020-11-03T15:45:45
282,236,294
0
0
null
null
null
null
UTF-8
C++
false
false
1,705
cpp
/* * @Date : 2020-07-20 22:21:12 * @Author : ssyze * @Description : */ #include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 5; int t, n, prime[maxn], vis[maxn], bg[maxn], tot, ansn; vector<int> num[50000]; map<int, int> mp; vector<pair<int, int>> ans; void init() { for (int i = 2; i < maxn; i++) bg[i] = i; for (int i = 2; i < maxn; i++) { if (!vis[i]) { prime[++tot] = i; for (int j = i; j < maxn; j += i) { vis[j] = 1; while (bg[j] % i == 0) bg[j] /= i; if (bg[j] == 1) bg[j] *= i; } } } for (int i = 1; i <= tot; i++) mp[prime[i]] = i; } int main() { init(); scanf("%d", &t); while (t--) { ansn = 0; ans.clear(); scanf("%d", &n); for (int i = 2; i <= n; i++) num[mp[bg[i]]].push_back(i); for (int i = tot; i >= 2; i--) { if (num[i].size() <= 1) continue; if (num[i].size() % 2 == 1) { num[1].push_back(num[i][1]); ans.push_back({num[i][0], num[i][2]}); for (int j = 3; j < num[i].size() - 1; j += 2) { ans.push_back({num[i][j], num[i][j + 1]}); } continue; } for (int j = 0; j < num[i].size() - 1; j += 2) ans.push_back({num[i][j], num[i][j + 1]}); } for (int i = 0; i < num[1].size() - 1; i += 2) ans.push_back({num[1][i], num[1][i + 1]}); printf("%d\n", ans.size()); for (auto& x : ans) printf("%d %d\n", x.first, x.second); for (int i = 1; i < 50000; i++) num[i].clear(); } }
[ "46869158+shu-ssyze@users.noreply.github.com" ]
46869158+shu-ssyze@users.noreply.github.com
92a3bb1af6fb0a73c25fe408c21469f0d677015a
2ecb48b3a749513f64099ce086cc2184661a437f
/HomeAutomationNode_pcRemote_V1/HomeAutomationNode_pcRemote_V1.ino
f333408eca319911b13554b574061487b741432c
[]
no_license
dabare/arduino
db956ff32c4004dd1cb2ec7b5c7cb7819e380a02
b33587f06a355eabe95318642140778bc3e6f02a
refs/heads/master
2021-07-25T16:51:06.104378
2017-11-07T11:44:30
2017-11-07T11:44:30
109,827,947
0
0
null
null
null
null
UTF-8
C++
false
false
2,410
ino
/* 77777777777 777777777 ----- IOPIUOP */ #include <avr/wdt.h> #include "RF24.h" #include "Keyboard.h" #define id 2 RF24 radio(9, 10); const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL }; // Radio pipe addresses for the 2 nodes to communicate. byte signalRead[2] = {0, 0}; //id,val void setup() { radio.begin(); radio.setAutoAck(false); radio.openWritingPipe(pipes[1]); radio.openReadingPipe(1, pipes[0]); radio.startListening(); Keyboard.begin(); Serial.begin(115200); watchdogSetup(); } void loop() { wdt_reset(); if ( radio.available() ) { while (radio.available()) { radio.read( &signalRead, 2 ); } if (signalRead[0] == id) { switch (signalRead[1]) { case 1: Keyboard.press(KEY_UP_ARROW); Keyboard.release(KEY_UP_ARROW); break; case 2: Keyboard.press(KEY_DOWN_ARROW); Keyboard.release(KEY_DOWN_ARROW); break; case 3: Keyboard.write(" "); break; case 4: Keyboard.press(KEY_LEFT_ARROW); Keyboard.release(KEY_LEFT_ARROW); break; case 5: Keyboard.press(KEY_RIGHT_ARROW); Keyboard.release(KEY_RIGHT_ARROW); break; case 6: Keyboard.write("a"); break; case 7: Keyboard.write("b"); break; } } } } void watchdogSetup(void) { cli(); // disable all interrupts wdt_reset(); // reset the WDT timer /* WDTCSR configuration: WDIE = 1: Interrupt Enable WDE = 1 :Reset Enable WDP3 = 0 :For 2000ms Time-out WDP2 = 1 :For 2000ms Time-out WDP1 = 1 :For 2000ms Time-out WDP0 = 1 :For 2000ms Time-out WDP3 = 0 :For 1000ms Time-out WDP2 = 1 :For 1000ms Time-out WDP1 = 1 :For 1000ms Time-out WDP0 = 0 :For 1000ms Time-out WDP3 = 0 :For 1000ms Time-out WDP2 = 1 :For 1000ms Time-out WDP1 = 0 :For 1000ms Time-out WDP0 = 1 :For 1000ms Time-out */ // Enter Watchdog Configuration mode: WDTCSR |= (1 << WDCE) | (1 << WDE); // Set Watchdog settings: WDTCSR = (1 << WDIE) | (1 << WDE) | (0 << WDP3) | (1 << WDP2) | (0 << WDP1) | (1 << WDP0); sei(); } ISR(WDT_vect) // Watchdog timer interrupt. { // Include your code here - be careful not to use functions they may cause the interrupt to hang and // prevent a reset. }
[ "dabaremadhava@gmail.com" ]
dabaremadhava@gmail.com
5b38c6bd2ad6598b143ca400e154fdd3f2c4db61
3a2e172106b0d1248fef3d3163c471eb8b48e49a
/RegularContest/100-109/100/C.cpp
1b9ad6b2bacb27683d2d20507b288057ed0b4c97
[]
no_license
rsotani/AtCoder
4b7eadb99981af1b2e9154d1382f011ac3100880
22d30769136bcb8496007a04126376984d533357
refs/heads/master
2020-03-27T09:09:12.612611
2019-01-01T13:05:29
2019-01-01T13:05:29
146,317,531
0
0
null
null
null
null
UTF-8
C++
false
false
290
cpp
#include <bits/stdc++.h> using namespace std; int main(){ int N; cin >> N; vector<int> A(N); for (int i=0; i<N; i++) {cin >> A[i]; A[i] -= i;} sort(A.begin(), A.end()); long long ans = 0; int b = A[N/2]; for (int i=0; i<N; i++) ans += abs(A[i]-b); cout << ans << endl; }
[ "sosososotaniryota@gmail.com" ]
sosososotaniryota@gmail.com
02a61742de2521649c1aa8bd94e1025a3e6ac903
f94b69060df692f53457862d7ad3bccf5819c1c1
/tests/zfunction.tests.cpp
ade32d6f268c14127d7be956b22e64e14490558e
[ "MIT" ]
permissive
pedroteosousa/caderno
f8e39f0f7ff59acaf8f12b6d309c4f37fd31369b
9d13449df8734dc979d1f66cd4c424b8a7d8cc48
refs/heads/master
2022-01-12T21:02:19.119324
2019-06-11T15:47:55
2019-06-11T15:47:55
114,820,935
0
0
MIT
2018-02-04T23:07:41
2017-12-19T23:21:47
C++
UTF-8
C++
false
false
509
cpp
#include <bits/stdc++.h> #include "gtest/gtest.h" using namespace std; const int N = 1e5; #include "../code/zfunction.cpp" void brutao(string s) { Z(s); for (int i = 1; i < (int)s.size(); i++) { int match = 0; while (i + match < (int)s.size() && s[i + match] == s[match]) match++; EXPECT_EQ(z[i], match); } } TEST(Simple, Random) { int num_tests = 10, alf = 26, n = 10000; while (num_tests--) { string s; while ((int)s.size() < n) { s.push_back('a' + (rand()%alf)); } brutao(s); } }
[ "pedroteosousa@gmail.com" ]
pedroteosousa@gmail.com
0c51979a3fc546bfe9cda1aa029a3995c3eaec8e
5b5f25e95e40b2096df571a75e142e82c147b986
/base/tools.h
1df71745de5e3c648ed73798f84af3e774d884b8
[]
no_license
feidegenggao/lib
5b552292332abb0d046454f8e1aa7b863407188c
3903ff4e9817a5e8ffd747e7f30fa8f5a3e255a0
refs/heads/master
2021-01-01T18:42:08.409470
2013-08-08T09:13:17
2013-08-08T09:13:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
761
h
/* * ============================================================================ * * Filename: tool.h * * Description: * * Version: 1.0 * Created: 07/18/13 14:42:15 * Revision: none * Compiler: gcc * * Author: lxf (), * Company: NDSL * * ============================================================================ */ #ifndef BASE_TOOL_HEADER #define BASE_TOOL_HEADER #include <sstream> namespace base { template<typename DstT, typename SrcT> DstT Convert(const SrcT &a) { std::stringstream temp_stream; temp_stream << a; DstT result; temp_stream >> result; return result; } } #endif
[ "liuxiaofei333@gmail.com" ]
liuxiaofei333@gmail.com
2723565ab6184a540b0396906b4855de8a84254d
2a856abdd214cf37bf5ebfaeac5e9464b4ff1713
/week5/light_pattern/light_pattern.cpp
9512eca1d676cdbb5b677d47a4eed67707d6fe88
[]
no_license
jandono/algolab-ETH
f1622f37af637980634a94b829143643b38a9858
3a599e6b574b00f03f6862c7d83577d75665841e
refs/heads/master
2020-08-30T22:25:05.176748
2019-10-30T11:14:13
2019-10-30T11:14:13
218,505,745
0
0
null
null
null
null
UTF-8
C++
false
false
1,710
cpp
/* 2 x One dimensional DPs. DP[i] is tracking with how many moves can I obtain the pattern x everywhere DP_FLIPPED[i] is tracking with how many moves can I obtain the pattern x_flipped everywhere Two functions for working with bits: dist(x, y) = number of different bits between X and Y flip(x) = flips the bits of an integer considering it of size K. K is global. */ #include <iostream> #include <vector> using namespace std; int n, k, x, x_flipped, m, bit; vector<int> patches, patches_flipped; int dist(int x, int y){ if(x == 0 && y==0) return 0; return ((x & 1) != (y & 1)) + dist(x>>1, y>>1); } int flip(int x){ int mask = (1 << k) - 1; return x ^ mask; } void read_testcase(){ patches.clear(); cin >> n >> k >> x; x_flipped = flip(x); m = n / k; for(int i=0;i<m;i++){ int bit_segment = 0; for(int j=0;j<k;j++){ cin >> bit; bit_segment += (bit << (k - j - 1)); } patches.push_back(bit_segment); } } void solve(){ int dp[m], dp_flipped[m]; dp[0] = min(dist(patches[0], x), dist(patches[0], x_flipped) + 1); dp_flipped[0] = min(dist(patches[0], x_flipped), dist(patches[0], x) + 1); for(int i=1;i<m;i++){ dp[i] = min(dp[i-1] + dist(patches[i], x), dp_flipped[i-1] + dist(patches[i], x_flipped) + 1); dp_flipped[i] = min(dp_flipped[i-1] + dist(patches[i], x_flipped), dp[i-1] + dist(patches[i], x) + 1); } cout << dp[m-1] << endl; } void testcase(){ read_testcase(); solve(); } int main(){ ios_base::sync_with_stdio(true); int T; cin >> T; while(T--) testcase(); return 0; }
[ "ac1d@ac1ds-MacBook-Pro.local" ]
ac1d@ac1ds-MacBook-Pro.local
4967eae82f9e6658ce36f799c608508169257013
a9156ec0aed4c1d34335ea2cceba8ad1b279dc10
/src/vscp/common/vscp_client_rs232.h
1189a153cfbd1dc5b1d356b89091d599a43ed23a
[ "MIT" ]
permissive
aji-s/vscp
a3c2a9231380cdf6d496c39b82f4fecf521c1e0b
b08570de18fbf1e41485e20a4e48ed67cf3394a6
refs/heads/master
2023-07-16T18:27:58.250337
2021-09-02T13:44:45
2021-09-02T13:44:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,814
h
// vscp_client_rs232.h // // RS-232 client communication classes. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version // 2 of the License, or (at your option) any later version. // // This file is part of the VSCP (https://www.vscp.org) // // Copyright: © 2007-2021 // Ake Hedman, the VSCP project, <info@vscp.org> // // This file is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this file see the file COPYING. If not, write to // the Free Software Foundation, 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. // #if !defined(VSCPCLIENTRS232_H__INCLUDED_) #define VSCPCLIENTRS232_H__INCLUDED_ #include "vscp.h" #include "vscp_client_base.h" class vscpClientRs232 : public CVscpClient { public: vscpClientRs232(); ~vscpClientRs232(); /*! Connect to remote host @param bPoll If true polling is used. @return Return VSCP_ERROR_SUCCESS of OK and error code else. */ virtual int connect(void); /*! Check if connected. @return true if connected, false otherwise. */ virtual bool isConnected(void); /*! Disconnect from remote host @return Return VSCP_ERROR_SUCCESS of OK and error code else. */ virtual int disconnect(void); /*! Send VSCP event to remote host. @return Return VSCP_ERROR_SUCCESS of OK and error code else. */ virtual int send(vscpEvent &ev); /*! Send VSCP event to remote host. @return Return VSCP_ERROR_SUCCESS of OK and error code else. */ virtual int send(vscpEventEx &ex); /*! Receive VSCP event from remote host @return Return VSCP_ERROR_SUCCESS of OK and error code else. */ virtual int receive(vscpEvent &ev); /*! Receive VSCP event ex from remote host @return Return VSCP_ERROR_SUCCESS of OK and error code else. */ virtual int receive(vscpEventEx &ex); /*! Set interface filter @param filter VSCP Filter to set. @return Return VSCP_ERROR_SUCCESS of OK and error code else. */ virtual int setfilter(vscpEventFilter &filter); /*! Get number of events waiting to be received on remote interface @param pcount Pointer to an unsigned integer that get the count of events. @return Return VSCP_ERROR_SUCCESS of OK and error code else. */ virtual int getcount(uint16_t *pcount); /*! Clear the input queue @return Return VSCP_ERROR_SUCCESS of OK and error code else. */ virtual int clear(void); /*! Get version from interface @param pmajor Pointer to uint8_t that get major version of interface. @param pminor Pointer to uint8_t that get minor version of interface. @param prelease Pointer to uint8_t that get release version of interface. @param pbuild Pointer to uint8_t that get build version of interface. @return Return VSCP_ERROR_SUCCESS of OK and error code else. */ virtual int getversion(uint8_t *pmajor, uint8_t *pminor, uint8_t *prelease, uint8_t *pbuild); /*! Get interfaces @param iflist Get a list of available interfaces @return Return VSCP_ERROR_SUCCESS of OK and error code else. */ virtual int getinterfaces(std::deque<std::string> &iflist); /*! Get capabilities (wcyd) from remote interface @return Return VSCP_ERROR_SUCCESS of OK and error code else. */ virtual int getwcyd(uint64_t &wcyd); /*! Return a JSON representation of connection @return JSON representation as string */ virtual std::string getConfigAsJson(void); /*! Set member variables from JSON representation of connection @param config JSON representation as string @return True on success, false on failure. */ virtual bool initFromJson(const std::string& config); /*! Getter/setters for connection timeout Time is in milliseconds */ virtual void setConnectionTimeout(uint32_t timeout); virtual uint32_t getConnectionTimeout(void); /*! Getter/setters for response timeout Time is in milliseconds */ virtual void setResponseTimeout(uint32_t timeout); virtual uint32_t getResponseTimeout(void); private: }; #endif
[ "akhe@grodansparadis.com" ]
akhe@grodansparadis.com
7c6711fc22a5eff8d4d202806e45ae609f487dd9
933f2ea0a1605ef3fa053dc7a2c7d85490d01597
/aten/src/ATen/native/vulkan/api/Pipeline.cpp
303eea7cb4012c5ea7be7130cda10d6a2f22e2bb
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "Apache-2.0", "BSD-2-Clause" ]
permissive
gcatron/pytorch
cf623092ec55c4aa4909b04090d81f8a4effb8da
2efc618f1971e91fe0f0ca454e7c78b503089b18
refs/heads/master
2023-03-31T18:55:14.957252
2020-09-16T03:25:59
2020-09-16T03:28:39
295,918,845
1
0
NOASSERTION
2020-09-16T04:02:50
2020-09-16T04:02:49
null
UTF-8
C++
false
false
2,914
cpp
#include <ATen/native/vulkan/api/Pipeline.h> namespace at { namespace native { namespace vulkan { namespace api { Pipeline::Layout::Factory::Factory(const VkDevice device) : device_(device) { } typename Pipeline::Layout::Factory::Handle Pipeline::Layout::Factory::operator()( const Descriptor& descriptor) const { const VkPipelineLayoutCreateInfo pipeline_layout_create_info{ VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, nullptr, 0u, 1u, &descriptor.descriptor_set_layout, 0u, nullptr, }; VkPipelineLayout pipeline_layout{}; VK_CHECK(vkCreatePipelineLayout( device_, &pipeline_layout_create_info, nullptr, &pipeline_layout)); return Handle{ pipeline_layout, Deleter(device_), }; } namespace { VkPipelineCache create_pipeline_cache(const VkDevice device) { const VkPipelineCacheCreateInfo pipeline_cache_create_info{ VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0u, 0u, nullptr, }; VkPipelineCache pipeline_cache{}; VK_CHECK(vkCreatePipelineCache( device, &pipeline_cache_create_info, nullptr, &pipeline_cache)); return pipeline_cache; } } // namespace Pipeline::Factory::Factory(const VkDevice device) : device_(device), pipeline_cache_(create_pipeline_cache(device), VK_DELETER(PipelineCache)(device)) { } typename Pipeline::Factory::Handle Pipeline::Factory::operator()( const Descriptor& descriptor) const { constexpr uint32_t x_offset = 0u; constexpr uint32_t x_size = sizeof(Shader::WorkGroup::x); constexpr uint32_t y_offset = x_offset + x_size; constexpr uint32_t y_size = sizeof(Shader::WorkGroup::y); constexpr uint32_t z_offset = y_offset + y_size; constexpr uint32_t z_size = sizeof(Shader::WorkGroup::z); constexpr VkSpecializationMapEntry specialization_map_entires[3]{ // X { 1u, x_offset, x_size, }, // Y { 2u, y_offset, y_size, }, // Z { 3u, z_offset, z_size, }, }; const VkSpecializationInfo specialization_info{ 3u, specialization_map_entires, sizeof(Shader::WorkGroup), &descriptor.work_group, }; const VkComputePipelineCreateInfo compute_pipeline_create_info{ VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, nullptr, 0u, VkPipelineShaderStageCreateInfo{ VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, nullptr, 0u, VK_SHADER_STAGE_COMPUTE_BIT, descriptor.shader_module, "main", &specialization_info, }, descriptor.pipeline_layout, VK_NULL_HANDLE, 0u, }; VkPipeline pipeline{}; VK_CHECK(vkCreateComputePipelines( device_, pipeline_cache_.get(), 1u, &compute_pipeline_create_info, nullptr, &pipeline)); return Handle{ pipeline, Deleter(device_), }; } } // namespace api } // namespace vulkan } // namespace native } // namespace at
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
ea19af380ab7d1e26dcf1db7240a1debc4135205
e4f85676da4b6a7d8eaa56e7ae8910e24b28b509
/extensions/renderer/gin_port.cc
2ee51832009ac5f125f904b9552efb67582aa9f1
[ "BSD-3-Clause" ]
permissive
RyoKodama/chromium
ba2b97b20d570b56d5db13fbbfb2003a6490af1f
c421c04308c0c642d3d1568b87e9b4cd38d3ca5d
refs/heads/ozone-wayland-dev
2023-01-16T10:47:58.071549
2017-09-27T07:41:58
2017-09-27T07:41:58
105,863,448
0
0
null
2017-10-05T07:55:32
2017-10-05T07:55:32
null
UTF-8
C++
false
false
8,242
cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/renderer/gin_port.h" #include <cstring> #include <vector> #include "extensions/common/api/messaging/message.h" #include "extensions/renderer/bindings/api_event_handler.h" #include "extensions/renderer/bindings/event_emitter.h" #include "gin/arguments.h" #include "gin/converter.h" #include "gin/object_template_builder.h" #include "third_party/WebKit/public/web/WebUserGestureIndicator.h" namespace extensions { namespace { constexpr char kSenderKey[] = "sender"; constexpr char kOnMessageEvent[] = "onMessage"; constexpr char kOnDisconnectEvent[] = "onDisconnect"; } // namespace GinPort::GinPort(const PortId& port_id, const std::string& name, APIEventHandler* event_handler, Delegate* delegate) : port_id_(port_id), name_(name), event_handler_(event_handler), delegate_(delegate) {} GinPort::~GinPort() {} gin::WrapperInfo GinPort::kWrapperInfo = {gin::kEmbedderNativeGin}; gin::ObjectTemplateBuilder GinPort::GetObjectTemplateBuilder( v8::Isolate* isolate) { return Wrappable<GinPort>::GetObjectTemplateBuilder(isolate) .SetMethod("disconnect", &GinPort::DisconnectHandler) .SetMethod("postMessage", &GinPort::PostMessageHandler) .SetProperty("name", &GinPort::GetName) .SetProperty("onDisconnect", &GinPort::GetOnDisconnectEvent) .SetProperty("onMessage", &GinPort::GetOnMessageEvent) .SetProperty("sender", &GinPort::GetSender); } void GinPort::DispatchOnMessage(v8::Local<v8::Context> context, const Message& message) { v8::Isolate* isolate = context->GetIsolate(); v8::HandleScope handle_scope(isolate); v8::Context::Scope context_scope(context); v8::Local<v8::String> v8_message_string = gin::StringToV8(isolate, message.data); v8::Local<v8::Value> parsed_message; { v8::TryCatch try_catch(isolate); if (!v8::JSON::Parse(context, v8_message_string).ToLocal(&parsed_message)) { NOTREACHED(); return; } } v8::Local<v8::Object> self = GetWrapper(isolate).ToLocalChecked(); std::vector<v8::Local<v8::Value>> args = {parsed_message, self}; DispatchEvent(context, &args, kOnMessageEvent); } void GinPort::Disconnect(v8::Local<v8::Context> context) { DCHECK(!is_closed_); v8::Isolate* isolate = context->GetIsolate(); v8::HandleScope handle_scope(isolate); v8::Context::Scope context_scope(context); v8::Local<v8::Object> self = GetWrapper(isolate).ToLocalChecked(); std::vector<v8::Local<v8::Value>> args = {self}; DispatchEvent(context, &args, kOnDisconnectEvent); Invalidate(context); } void GinPort::SetSender(v8::Local<v8::Context> context, v8::Local<v8::Value> sender) { v8::Isolate* isolate = context->GetIsolate(); v8::HandleScope handle_scope(isolate); v8::Local<v8::Object> wrapper = GetWrapper(isolate).ToLocalChecked(); v8::Local<v8::Private> key = v8::Private::ForApi(isolate, gin::StringToSymbol(isolate, kSenderKey)); v8::Maybe<bool> set_result = wrapper->SetPrivate(context, key, sender); DCHECK(set_result.IsJust() && set_result.FromJust()); } void GinPort::DisconnectHandler(gin::Arguments* arguments) { if (is_closed_) return; v8::Local<v8::Context> context = arguments->GetHolderCreationContext(); Invalidate(context); } void GinPort::PostMessageHandler(gin::Arguments* arguments, v8::Local<v8::Value> v8_message) { v8::Isolate* isolate = arguments->isolate(); if (is_closed_) { ThrowError(isolate, "Attempting to use a disconnected port object"); return; } // TODO(devlin): For some reason, we don't use the signature for // Port.postMessage when evaluating the parameters. We probably should, but // we don't know how many extensions that may break. It would be good to // investigate, and, ideally, use the signature. if (v8_message->IsUndefined()) { // JSON.stringify won't serialized undefined (it returns undefined), but it // will serialized null. We've always converted undefined to null in JS // bindings, so preserve this behavior for now. v8_message = v8::Null(isolate); } bool success = false; v8::Local<v8::String> stringified; { v8::TryCatch try_catch(isolate); success = v8::JSON::Stringify(arguments->GetHolderCreationContext(), v8_message) .ToLocal(&stringified); } std::string message; if (success) { message = gin::V8ToString(stringified); // JSON.stringify can either fail (with unserializable objects) or can // return undefined. If it returns undefined, the v8 API then coerces it to // the string value "undefined". Throw an error if we were passed // unserializable objects. success = message != "undefined"; } if (!success) { ThrowError(isolate, "Illegal argument to Port.postMessage"); return; } delegate_->PostMessageToPort( port_id_, std::make_unique<Message>( message, blink::WebUserGestureIndicator::IsProcessingUserGesture())); } std::string GinPort::GetName() { return name_; } v8::Local<v8::Value> GinPort::GetOnDisconnectEvent(gin::Arguments* arguments) { return GetEvent(arguments->GetHolderCreationContext(), kOnDisconnectEvent); } v8::Local<v8::Value> GinPort::GetOnMessageEvent(gin::Arguments* arguments) { return GetEvent(arguments->GetHolderCreationContext(), kOnMessageEvent); } v8::Local<v8::Value> GinPort::GetSender(gin::Arguments* arguments) { v8::Isolate* isolate = arguments->isolate(); v8::Local<v8::Object> wrapper = GetWrapper(isolate).ToLocalChecked(); v8::Local<v8::Private> key = v8::Private::ForApi(isolate, gin::StringToSymbol(isolate, kSenderKey)); v8::Local<v8::Value> sender; if (!wrapper->GetPrivate(arguments->GetHolderCreationContext(), key) .ToLocal(&sender)) { NOTREACHED(); return v8::Undefined(isolate); } return sender; } v8::Local<v8::Object> GinPort::GetEvent(v8::Local<v8::Context> context, base::StringPiece event_name) { DCHECK(event_name == kOnMessageEvent || event_name == kOnDisconnectEvent); v8::Isolate* isolate = context->GetIsolate(); v8::Local<v8::Object> wrapper = GetWrapper(isolate).ToLocalChecked(); v8::Local<v8::Private> key = v8::Private::ForApi(isolate, gin::StringToSymbol(isolate, event_name)); v8::Local<v8::Value> event_val; if (!wrapper->GetPrivate(context, key).ToLocal(&event_val)) { NOTREACHED(); return v8::Local<v8::Object>(); } DCHECK(!event_val.IsEmpty()); v8::Local<v8::Object> event_object; if (event_val->IsUndefined()) { event_object = event_handler_->CreateAnonymousEventInstance(context); v8::Maybe<bool> set_result = wrapper->SetPrivate(context, key, event_object); if (!set_result.IsJust() || !set_result.FromJust()) { NOTREACHED(); return v8::Local<v8::Object>(); } } else { event_object = event_val.As<v8::Object>(); } return event_object; } void GinPort::DispatchEvent(v8::Local<v8::Context> context, std::vector<v8::Local<v8::Value>>* args, base::StringPiece event_name) { v8::Isolate* isolate = context->GetIsolate(); v8::Local<v8::Value> on_message = GetEvent(context, event_name); EventEmitter* emitter = nullptr; gin::Converter<EventEmitter*>::FromV8(isolate, on_message, &emitter); CHECK(emitter); emitter->Fire(context, args, nullptr); } void GinPort::Invalidate(v8::Local<v8::Context> context) { is_closed_ = true; event_handler_->InvalidateCustomEvent(context, GetEvent(context, kOnMessageEvent)); event_handler_->InvalidateCustomEvent(context, GetEvent(context, kOnDisconnectEvent)); delegate_->ClosePort(port_id_); } void GinPort::ThrowError(v8::Isolate* isolate, base::StringPiece error) { isolate->ThrowException( v8::Exception::Error(gin::StringToV8(isolate, error))); } } // namespace extensions
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
c685104ca606bb6b79dce8d6d84ff886bc6ecb85
2f16483955d999d90bd6f31ed01593442b2d7139
/practice/post_thesis/model_adaptivity_iso_vs_aniso/diff_mesh/psi_and_superadj_libmesh_1_0_0/convdiff_sadj_aux.h
46abb29ec924501369b6410ffab17f77fb121b80
[]
no_license
kameeko/harriet_libmesh
e3a7e28984ed53fd159f3ee793d5f855578f80df
78178fc6d38801977f96007069e6c4f2cec64cea
refs/heads/master
2021-04-09T16:25:46.798532
2017-10-27T17:36:40
2017-10-27T17:36:40
23,032,708
0
0
null
null
null
null
UTF-8
C++
false
false
2,973
h
#include "libmesh/fem_system.h" #include "libmesh/getpot.h" #include "libmesh/elem.h" #include "libmesh/point_locator_tree.h" using namespace libMesh; class ConvDiff_AuxSadjSys : public FEMSystem { public: // Constructor ConvDiff_AuxSadjSys(EquationSystems& es, const std::string& name_in, const unsigned int number_in) : FEMSystem(es, name_in, number_in){ GetPot infile("contamTrans.in"); std::string find_data_here = infile("data_file","Measurements0.dat"); qoi_option = infile("QoI_option",1); const unsigned int dim = this->get_mesh().mesh_dimension(); //read in data if(FILE *fp=fopen(find_data_here.c_str(),"r")){ Real x, y, z, value; int flag = 1; while(flag != -1){ flag = fscanf(fp,"%lf %lf %lf %lf",&x,&y,&z,&value); if(flag != -1){ if(dim == 3) datapts.push_back(Point(x,y,z)); else if(dim == 2) datapts.push_back(Point(x,y,0.)); datavals.push_back(value); } } fclose(fp); }else{ std::cout << "\n\nAAAAAHHHHH NO DATA FOUND?!?!\n\n" << std::endl; } /* //read in auxiliary variables at data points if(FILE *fp=fopen("auxc_points.dat","r")){ int flag = 1; Real meep; while(flag != -1){ flag = fscanf(fp,"%lf",&meep); if(flag != -1) primal_auxc_vals.push_back(meep); } fclose(fp); } */ //find elements in which data points reside PointLocatorTree point_locator(this->get_mesh()); for(unsigned int dnum=0; dnum<datavals.size(); dnum++){ Point data_point = datapts[dnum]; Elem *this_elem = const_cast<Elem *>(point_locator(data_point)); dataelems.push_back(this_elem->id()); } } // System initialization virtual void init_data (); // Context initialization virtual void init_context(DiffContext &context); // Element residual and jacobian calculations // Time dependent parts virtual bool element_time_derivative (bool request_jacobian, DiffContext& context); //boundary residual and jacobian calculations virtual bool side_time_derivative (bool request_jacobian, DiffContext& context); // Indices for each variable; unsigned int aux_c_var, aux_zc_var, aux_fc_var; Real beta; //regularization parameter Real vx; //west-east velocity (along x-axis, for now); m/s Real react_rate; //reaction rate; 1/s Real porosity; //porosity Real bsource; // ppb (concentration of influx at west boundary) NumberTensorValue dispTens; //dispersion tensor; m^2/s //data-related stuff std::vector<Point> datapts; std::vector<Real> datavals; std::vector<dof_id_type> dataelems; //options for QoI location and nature int qoi_option; std::vector<Real> primal_auxc_vals; void set_auxc_vals(std::vector<Real> auxc_vals){ primal_auxc_vals = auxc_vals; } };
[ "kameeko@gmail.com" ]
kameeko@gmail.com
458e943893786aefce9e04480490417b08e970f4
631a5a51c6aba3930c808cae2adb53f891c9f4be
/src/OutputFile.cpp
cc49c3855fd437a6330ed3df065e4182c49b3ff8
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
kevinpku/hpcg
55f4ce645050efd2e40a233c77a637ddb1f72508
4a8cfde10e0ecfaa7e2693cdda8fef5e13ef6cf4
refs/heads/master
2020-12-28T14:47:02.573046
2016-04-09T20:51:54
2016-04-09T20:51:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,059
cpp
//@HEADER // *************************************************** // // HPCG: High Performance Conjugate Gradient Benchmark // // Contact: // Michael A. Heroux ( maherou@sandia.gov) // Jack Dongarra (dongarra@eecs.utk.edu) // Piotr Luszczek (luszczek@eecs.utk.edu) // // *************************************************** //@HEADER #include <fstream> #include <list> #include <sstream> #include <string> #include "OutputFile.hpp" using std::string; using std::stringstream; using std::list; using std::ofstream; OutputFile::OutputFile(const string & name_arg, const string & version_arg) : name(name_arg), version(version_arg) {} OutputFile::OutputFile(void) {} void OutputFile::add(const string & key_arg, const string & value_arg) { descendants.push_back(allocKeyVal(key_arg, value_arg)); } void OutputFile::add(const string & key_arg, double value_arg) { stringstream ss; ss << value_arg; descendants.push_back(allocKeyVal(key_arg, ss.str())); } void OutputFile::add(const string & key_arg, int value_arg) { stringstream ss; ss << value_arg; descendants.push_back(allocKeyVal(key_arg, ss.str())); } #ifndef HPCG_NO_LONG_LONG void OutputFile::add(const string & key_arg, long long value_arg) { stringstream ss; ss << value_arg; descendants.push_back(allocKeyVal(key_arg, ss.str())); } #endif void OutputFile::add(const string & key_arg, size_t value_arg) { stringstream ss; ss << value_arg; descendants.push_back(allocKeyVal(key_arg, ss.str())); } void OutputFile::setKeyValue(const string & key_arg, const string & value_arg) { key = key_arg; value = value_arg; } OutputFile * OutputFile::get(const string & key_arg) { for (list<OutputFile*>::iterator it = descendants.begin(); it != descendants.end(); ++it) { if ((*it)->key == key_arg) return *it; } return 0; } string OutputFile::generateRecursive(string prefix) { string result = ""; result += prefix + key + "=" + value + eol; for (list<OutputFile*>::iterator it = descendants.begin(); it != descendants.end(); ++it) { result += (*it)->generateRecursive(prefix + key + keySeparator); } return result; } string OutputFile::generate(void) { string result = name + "\nversion=" + version + eol; for (list<OutputFile*>::iterator it = descendants.begin(); it != descendants.end(); ++it) { result += (*it)->generateRecursive(""); } time_t rawtime; time(&rawtime); tm * ptm = localtime(&rawtime); char sdate[25]; //use tm_mon+1 because tm_mon is 0 .. 11 instead of 1 .. 12 sprintf (sdate,"%04d-%02d-%02d_%02d-%02d-%02d",ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min,ptm->tm_sec); string filename = name + "_" + version + "_"; filename += string(sdate) + ".txt"; ofstream myfile(filename.c_str()); myfile << result; myfile.close(); return result; } OutputFile * OutputFile::allocKeyVal(const std::string & key_arg, const std::string & value_arg) { OutputFile * of = new OutputFile(); of->setKeyValue(key_arg, value_arg); return of; }
[ "luszczek@icl.utk.edu" ]
luszczek@icl.utk.edu
53f2ad186510fc8391510d211e5de522956e326c
f2e6508b0655b2eb0f62b47a845776a735adf862
/HellOpenGL - Student/Time.h
c73928f85b262552c57792bf26a88aebe6ca3609
[]
no_license
Zac-King/HellOpenGL---Student
137ac740d3b3da9617256bcce13ce6e9ea8d224a
d5718ce9c353d565b5529019158401bec32bb2db
refs/heads/master
2021-01-22T14:24:49.078087
2015-02-20T05:59:05
2015-02-20T05:59:05
29,701,393
0
0
null
null
null
null
UTF-8
C++
false
false
539
h
#pragma once #include <GLFW\glfw3.h> #include "Core.h" class Time : public Core { private: float m_deltaTime, m_totalTime; Time():m_deltaTime(0), m_totalTime(0) {} protected: bool init() { glfwSetTime(0); return true; } bool step() { float currentTime = glfwGetTime(); m_deltaTime = currentTime - m_totalTime; m_totalTime = currentTime; return true; } public: float getDeltaTime() const { return m_deltaTime; } float getTotalTime() const { return m_totalTime; } static Time &getInstance() { static Time t; return t; } };
[ "thebrokekiller@yahoo.com" ]
thebrokekiller@yahoo.com
e6f890661d794dc71a583f55d8f196fe1ae2dc1d
d41973fab9da00ad56f557f5caac0da259c225ba
/Assignment_05/Assign_05_01 - Paycheck/Assign_05_01 - Paycheck/stdafx.cpp
71f00ef973cea2a9f47a9172bd8c0fd4076fd236
[]
no_license
taquayle/ITAD123
d4505785db492982032f849ff18e3a4bb01030ff
8d4f5455864a69d0e5b1b01bca7040599748efcb
refs/heads/master
2020-04-06T06:23:29.701233
2017-02-23T09:23:33
2017-02-23T09:23:33
82,909,047
0
0
null
null
null
null
UTF-8
C++
false
false
302
cpp
// stdafx.cpp : source file that includes just the standard includes // Assign_05_01 - Paycheck.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "taquayle@uw.edu" ]
taquayle@uw.edu
4d9d840de557d99b5b827f2b1a103865e241436c
5edff52141bb25c0fdf8cb55c66f2df71d3f00b9
/19. 22.02.2021 - Чтение бинарных файлов/2. Home work/Project1/Project1/task4.cpp
91061b49b233ff746e5adbdca4d9824f738ad311
[]
no_license
MikhailGoriachev/C-C
78e9597e3b5dce6b4086ddf9056545b49af8f462
3ef464aa030788c21c49d1d3983a7b5330250b02
refs/heads/master
2023-08-25T18:48:26.464614
2021-10-20T10:24:20
2021-10-20T10:24:20
419,278,130
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
2,425
cpp
#define _CRT_SECURE_NO_WARNINGS #include <iostream> using namespace std; // анализация файла в буфере void analysis(char buff[], size_t count[], char lett[], long size); // вывод результата void outResult(size_t count[], char lett[]); void task4() { // 4. Пользователь вводит имя файла, программа подсчитывает частотный словарь букв файла и выводит его на экран // a - 23 // b - 3 // c - 456 // d - 44 // имя файла char name[40]; // ввод имени файла cout << "Enter name file: "; cin.ignore(); cin.getline(name, 40); // массив с количеством букв size_t count[52] = { 0 }; // строка со всеми бкувами char lett[53] = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"; // открытие файла в режиме битового чтения FILE* file = fopen(name, "rb"); // если файл открыт успешно if (file != nullptr) { // установка указателя в файле в конец fseek(file, 0, SEEK_END); // длина файла long size = ftell(file); // буфер для содержания файла char* buff = new char[size]; // установка указателя в файле в начало fseek(file, 0, SEEK_SET); // считываение файла в буфер fread(buff, sizeof(char), size, file); // анализация буфера analysis(buff, count, lett, size); // вывод результата outResult(count, lett); } // если файл не удалось открыть else cout << "Error opening file" << endl; } // анализация файла в буфере void analysis(char buff[], size_t count[], char lett[], long size) { for (size_t i = 0; i < size; i++) { for (size_t k = 0; lett[k] != 0; k++) { if (buff[i] == lett[k]) { count[k]++; break; } } } } // вывод результата void outResult(size_t count[], char lett[]) { cout << endl; cout << "Result" << endl; bool n = false; for (size_t i = 0; lett[i] != 0; i++) { if (count[i] > 0) { cout << lett[i] << " = " << count[i] << endl; n = true; } } // если никаких букв не найдено if (!n) cout << "Letters NOT found!" << endl; }
[ "mishagor228@gmail.com" ]
mishagor228@gmail.com
290848010bdc941a424e45bfbf7b33f9e0dd555c
7a5790618c23cde39aaa833cb8fdb986298b0850
/57_DeleteDuplicatedListNode.cpp
39864dd26b4e1fb9850bfc8147cd774240d34db9
[]
no_license
keezen/CodingInterviews
399d17374a08adad9939a6f70298f1e3be0bddba
8e82ba5c47c136751c8984ad9103921ecf0a2f3c
refs/heads/master
2020-04-28T08:18:11.933454
2019-03-12T02:45:16
2019-03-12T02:45:16
175,121,290
1
0
null
null
null
null
UTF-8
C++
false
false
2,582
cpp
# include <iostream> # include <cstdlib> # include <vector> # include <limits> using namespace std; struct ListNode { int val; ListNode* next; ListNode(int x) // struct的构造函数 : val(x), next(NULL) {} }; void display_list(ListNode* head) { if (head == NULL) return; for(ListNode* p = head; p != NULL; p = p->next) cout << p->val << ' '; cout << endl; } ListNode* deleteDuplication_iter(ListNode* pHead) { // delete duplicate nodes in sorted list if (pHead == NULL) return NULL; ListNode *empty = new ListNode(numeric_limits<int>::max()); ListNode *prev, *cur; int dup; empty->next = pHead; // add empty node before head prev = empty; cur = pHead; while (cur != NULL && cur->next != NULL) { // duplicate if (cur->val == cur->next->val) { dup = cur->val; while (cur != NULL && cur->val == dup) { prev->next = cur->next; delete cur; cur = prev->next; } } else { prev = cur; cur = cur->next; } } pHead = empty->next; delete empty; return pHead; } ListNode* deleteDuplication(ListNode* pHead) { // delete duplicate nodes in sorted list if (pHead == NULL) return NULL; if (pHead != NULL && pHead->next == NULL) return pHead; ListNode *cur, *next = NULL; if (pHead->val == pHead->next->val) // duplicate { int val = pHead->val; cur = pHead; while (cur != NULL && cur->val == val) { next = cur->next; delete cur; cur = next; } return deleteDuplication(cur); } else // not duplicate { pHead->next = deleteDuplication(pHead->next); return pHead; } } int main(int argc, char *argv[]) { int arr[] = {1, 2, 3, 3, 4, 4, 5}; vector<int> vec(arr, arr + sizeof(arr) / sizeof(int)); ListNode *node = NULL, *head = NULL, *tail = NULL, *res = NULL, *p = NULL; // list for (int i = 0; i < vec.size(); i++) { node = new ListNode(vec[i]); if (head == NULL) head = tail = node; else { tail->next = node; tail = node; node = NULL; } } display_list(head); // result res = deleteDuplication(head); if (res != NULL) display_list(res); else cout << "Null." << endl; return 0; }
[ "noreply@github.com" ]
keezen.noreply@github.com
c2c897a4ca3d9c252dae9689394b0b64096af7ea
2c6aedfc3e5e641ce734d85cb220aa9f241e48b3
/UVa Solved Problems/Graph/UVa-00414.cpp
7b8bc7d38313755b49527ebfff6be8655f194efc
[]
no_license
itadakimatsu97/CompetitiveProgrammingMaterials
e4226dacce085bdb4e10022bf77b0c950ba622a4
1d7f4cb7697293271c4777eb3494eecd87bb6ad5
refs/heads/main
2023-04-11T03:55:46.762498
2021-04-29T10:54:43
2021-04-29T10:54:43
348,260,316
0
0
null
null
null
null
UTF-8
C++
false
false
2,041
cpp
#include<bits/stdc++.h> using namespace std; /****** Template of MACRO/CONSTANT *****/ #define fi first #define se second #define all(x) (x).begin(), (x).end() //Forward traversal #define rall(x) (x).rbegin, (x).rend() //reverse traversal #define present(c, x) ((c).find(x) != (c).end()) #define sz(x) (x.size()) #define Fi(i, from, end) for(int i = from; i < end; i++) #define Trav(it, x) for(auto it = (x).begin(); it != (X).end(); it++) typedef long int int32; typedef unsigned long int uint32; typedef long long int int64; typedef unsigned long long int uint64; typedef long long ll; typedef pair<int, int> ii; typedef vector<int> vi; typedef vector<ii> vii; typedef map<int, int> mii; /****** Template of some basic operations *****/ template<typename T, typename U> inline void amin(T &x, U y) { if(y < x) x = y; } template<typename T, typename U> inline void amax(T &x, U y) { if(x < y) x = y; } void solve(); int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("error.txt", "w", stderr); freopen("output.txt", "w", stdout); #endif int t=1; // cin>>t; while(t--) { solve(); } cerr<<"Time taken : "<<(float)clock()/CLOCKS_PER_SEC<<" secs"<<endl; return 0; } void solve() { int N, Bs, shortest, spaceR; int COL = 25; int space[COL+1]; string line; while(cin>>N){ if(!N) break; cin.ignore(); //Remove first \n shortest = 25; spaceR = 0; Fi(i, 0, N){ Bs = 0; getline(cin, line); Fi(i, 0, COL){ if(line[i] == ' ') Bs++; } if(Bs < shortest){ shortest = Bs; } space[i] = Bs; } Fi(i, 0, N){ spaceR += space[i]-shortest; } cout<<spaceR<<endl; } }
[ "tuan2.le@lge.com" ]
tuan2.le@lge.com
f8ceb450514ed82c139c523a12a17b4fa4fd757e
aedec0779dca9bf78daeeb7b30b0fe02dee139dc
/Modules/Transformation/include/mirtk/RigidTransformation.h
9e920a18ea2450ca5db6a61789e2e2723952aff5
[ "LicenseRef-scancode-proprietary-license", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
BioMedIA/MIRTK
ca92f52b60f7db98c16940cd427a898a461f856c
973ce2fe3f9508dec68892dbf97cca39067aa3d6
refs/heads/master
2022-08-08T01:05:11.841458
2022-07-28T00:03:25
2022-07-28T10:18:00
48,962,880
171
78
Apache-2.0
2022-07-28T10:18:01
2016-01-03T22:25:55
C++
UTF-8
C++
false
false
9,738
h
/* * Medical Image Registration ToolKit (MIRTK) * * Copyright 2008-2015 Imperial College London * Copyright 2008-2013 Daniel Rueckert, Julia Schnabel * Copyright 2013-2015 Andreas Schuh * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MIRTK_RigidTransformation_H #define MIRTK_RigidTransformation_H #include "mirtk/HomogeneousTransformation.h" namespace mirtk { /** * Class for rigid transformations. * * This class defines and implements rigid body transformations. The rigid * body transformations are parameterized by three rotations around the axes * of the coordinate system followed by three translations along the axes of * the coordinate system. Note that the order of rotations is defined as a * rotation around the z-axis, the y-axis and finally around the x-axis. In * total, the transformation is parameterized by six degrees of freedom. */ class RigidTransformation : public HomogeneousTransformation { mirtkTransformationMacro(RigidTransformation); // --------------------------------------------------------------------------- // Data members protected: /// Sine of rotation angle rx double _sinrx; /// Sine of rotation angle ry double _sinry; /// Sine of rotation angle rz double _sinrz; /// Cosine of rotation angle rx double _cosrx; /// Cosine of rotation angle ry double _cosry; /// Cosine of rotation angle rz double _cosrz; /// Update cached sine and cosine of rotation angles void UpdateRotationSineCosine(); // --------------------------------------------------------------------------- // Construction/Destruction protected: /// Default constructor with given number of parameters RigidTransformation(int); /// Copy constructor with given number of parameters RigidTransformation(const RigidTransformation &, int); public: /// Default constructor RigidTransformation(); /// Copy constructor RigidTransformation(const RigidTransformation &); /// Destructor virtual ~RigidTransformation(); // --------------------------------------------------------------------------- // Approximation /// Approximate displacements: This function takes a set of points and a set /// of displacements and finds !new! parameters such that the resulting /// transformation approximates the displacements as good as possible. virtual void ApproximateDOFs(const double *, const double *, const double *, const double *, const double *, const double *, const double *, int); // --------------------------------------------------------------------------- // Transformation parameters /// Construct a matrix based on parameters passed in the array static Matrix DOFs2Matrix(const double *); /// Return an array with parameters corresponding to a given matrix static void Matrix2DOFs(const Matrix &, double *); /// Updates transformation matrix after change of parameter virtual void UpdateMatrix(); /// Updates transformation parameters after change of matrix virtual void UpdateDOFs(); /// Puts translation along the x-axis (transformation matrix is updated) void PutTranslationX(double); /// Gets translation along the x-axis double GetTranslationX() const; /// Puts translation along the y-axis (transformation matrix is updated) void PutTranslationY(double); /// Gets translation along the y-axis double GetTranslationY() const; /// Puts translation along the z-axis (transformation matrix is updated) void PutTranslationZ(double); /// Gets translation along the z-axis double GetTranslationZ() const; /// Puts rotation angle around the x-axis (transformation matrix is updated) void PutRotationX(double); /// Gets rotation angle around the x-axis double GetRotationX() const; /// Puts rotation angle around the y-axis (transformation matrix is updated) void PutRotationY(double); /// Gets rotation angle around the y-axis double GetRotationY() const; /// Puts rotation angle around the z-axis (transformation matrix is updated) void PutRotationZ(double); /// Gets rotation angle around the z-axis double GetRotationZ() const; public: // --------------------------------------------------------------------------- // Point transformation /// Transforms a single point by the translation part of the rigid transformation virtual void Translate(double& x, double& y, double& z) const; /// Transforms a single point by the rotation part of the rigid transformation virtual void Rotate(double& x, double& y, double& z) const; // --------------------------------------------------------------------------- // Derivatives // Do not overwrite other base class overloads using Transformation::JacobianDOFs; /// Calculates the Jacobian of the transformation w.r.t the parameters virtual void JacobianDOFs(double [3], int, double, double, double, double = 0, double = -1) const; /// Calculates the derivative of the Jacobian of the transformation (w.r.t. world coordinates) w.r.t. a transformation parameter virtual void DeriveJacobianWrtDOF(Matrix &, int, double, double, double, double = 0, double = -1) const; // --------------------------------------------------------------------------- // I/O // Do not hide methods of base class using HomogeneousTransformation::Print; /// Prints the parameters of the transformation virtual void Print(ostream &, Indent = 0) const; public: // --------------------------------------------------------------------------- // Deprecated /// Set transformation parameters (DoFs) /// \deprecated Use Put(params) instead. void SetParameters(double *params); }; //////////////////////////////////////////////////////////////////////////////// // Inline definitions //////////////////////////////////////////////////////////////////////////////// // ============================================================================= // Transformation parameters // ============================================================================= // ----------------------------------------------------------------------------- inline void RigidTransformation::PutRotationX(double rx) { Put(RX, rx); } // ----------------------------------------------------------------------------- inline double RigidTransformation::GetRotationX() const { return Get(RX); } // ----------------------------------------------------------------------------- inline void RigidTransformation::PutRotationY(double ry) { Put(RY, ry); } // ----------------------------------------------------------------------------- inline double RigidTransformation::GetRotationY() const { return Get(RY); } // ----------------------------------------------------------------------------- inline void RigidTransformation::PutRotationZ(double rz) { Put(RZ, rz); } // ----------------------------------------------------------------------------- inline double RigidTransformation::GetRotationZ() const { return Get(RZ); } // ----------------------------------------------------------------------------- inline void RigidTransformation::PutTranslationX(double tx) { Put(TX, tx); } // ----------------------------------------------------------------------------- inline double RigidTransformation::GetTranslationX() const { return Get(TX); } // ----------------------------------------------------------------------------- inline void RigidTransformation::PutTranslationY(double ty) { Put(TY, ty); } // ----------------------------------------------------------------------------- inline double RigidTransformation::GetTranslationY() const { return Get(TY); } // ----------------------------------------------------------------------------- inline void RigidTransformation::PutTranslationZ(double tz) { Put(TZ, tz); } // ----------------------------------------------------------------------------- inline double RigidTransformation::GetTranslationZ() const { return Get(TZ); } // ============================================================================= // Point transformation // ============================================================================= // ----------------------------------------------------------------------------- inline void RigidTransformation::Translate(double& x, double& y, double& z) const { x += _matrix(0, 3); y += _matrix(1, 3); z += _matrix(2, 3); } // ----------------------------------------------------------------------------- inline void RigidTransformation::Rotate(double& x, double& y, double& z) const { double a = _matrix(0, 0) * x + _matrix(0, 1) * y + _matrix(0, 2) * z; double b = _matrix(1, 0) * x + _matrix(1, 1) * y + _matrix(1, 2) * z; double c = _matrix(2, 0) * x + _matrix(2, 1) * y + _matrix(2, 2) * z; x = a; y = b; z = c; } // ============================================================================= // Deprecated // ============================================================================= // ----------------------------------------------------------------------------- inline void RigidTransformation::SetParameters(double *params) { Put(params); } } // namespace mirtk #endif // MIRTK_RigidTransformation_H
[ "andreas.schuh.84@gmail.com" ]
andreas.schuh.84@gmail.com
b13f8572a5a8db52e1a8bed176a83c84f706a582
071c53728c400c5486ada97482a921ae5ef80583
/prerequisites/C++/ConC2/hello2.cpp
dd65bd8bddc60850fd94af7b2754b24e53ce55c9
[]
no_license
0xchamin/HPC-LiDAR
6c2ca24fe99bf0e5fc8e4cc2aea28d8199fe6bd3
615f6c196148857b4df6683dd306cf190e5d0520
refs/heads/master
2020-04-11T22:41:06.153766
2019-03-11T16:50:43
2019-03-11T16:50:43
162,144,276
2
0
null
null
null
null
UTF-8
C++
false
false
306
cpp
#include <iostream> #include <thread> #include <fork2> long b1 = 0; long b2 = 0; long j = 0; fork2([&] { // first branch b1 = 1; }, [&] { // second branch b2 = 2; }); // join point j = b1 + b2; std::cout << "b1 = " << b1 << "; b2 = " << b2 << "; "; std::cout << "j = " << j << ";" << std::endl;
[ "chmk90@gmail.com" ]
chmk90@gmail.com
56c3f334ca26af32d661db8d0c2c67c941bad286
1673fddc4307dc9703a93bdef55df3ecd3f2efbd
/zetavm_snapshots/zetavm_0/vm/runtime.h
98965d859920a1d9d58af5058e897483a68f66b1
[ "BSD-3-Clause" ]
permissive
openjamoses/projects_snapshots_1
69e77c20e72d6d3e65faba21a51a2adb18fa7bb4
a6aea1a68044968681068cd16d119c231e45d7e2
refs/heads/master
2022-12-17T19:51:29.159524
2020-09-26T23:30:46
2020-09-26T23:30:46
298,916,205
0
1
null
null
null
null
UTF-8
C++
false
false
8,896
h
#pragma once #include <cstdint> #include <string> /// Type tag, 8 bits typedef uint8_t Tag; /// Heap pointer type typedef uint8_t* refptr; /// Type tag constants const Tag TAG_UNDEF = 0; const Tag TAG_BOOL = 1; const Tag TAG_INT64 = 2; const Tag TAG_FLOAT32 = 3; const Tag TAG_FLOAT64 = 4; const Tag TAG_STRING = 5; const Tag TAG_OBJECT = 6; const Tag TAG_ARRAY = 7; const Tag TAG_HOSTFN = 8; const Tag TAG_IMGREF = 9; /// Object header size const size_t HEADER_SIZE = sizeof(intptr_t); /// Bit flag indicating the next pointer is set const size_t HEADER_IDX_NEXT = 15; const size_t HEADER_MSK_NEXT = 1 << HEADER_IDX_NEXT; /// Offset of the next pointer const size_t OBJ_OF_NEXT = HEADER_SIZE; /** 64-bit word union */ union Word { Word(refptr p) { ptr = p; } Word(int64_t v) { int64 = v; } Word() {} int64_t int64; int8_t int8; refptr ptr; Tag tag; }; /** Tagged value pair type (64-bit word + tag) */ class Value { private: Word word; Tag tag; public: static const Value ZERO; static const Value ONE; static const Value TWO; static const Value UNDEF; static const Value TRUE; static const Value FALSE; Value() : Value(FALSE.word, FALSE.tag) {} Value(int64_t v) : Value(Word(v), TAG_INT64) {} Value(refptr p, Tag t) : Value(Word(p), t) {} Value(Word w, Tag t); ~Value() {} bool isBool() const { return tag == TAG_BOOL; } bool isInt64() const { return tag == TAG_INT64; } bool isString() const { return tag == TAG_STRING; } bool isObject() const { return tag == TAG_OBJECT; } bool isArray() const { return tag == TAG_ARRAY; } bool isHostFn() const { return tag == TAG_HOSTFN; } Word getWord() const { return word; } Tag getTag() const { return tag; } bool isPointer() const; std::string toString() const; operator bool () const; operator int64_t () const; operator refptr () const; operator std::string () const; bool operator == (const Value& that) const { return this->word.int64 == that.word.int64 && this->tag == that.tag; } bool operator != (const Value& that) const { return !(*this == that); } }; /** Virtual Machine object (singleton) */ class VM { private: // TODO: total memory size allocated // TODO: dynamically grow pools? // TODO: pools for sizes up to 32 (words) // TODO: number of elements allocated in each pool public: VM(); /// Allocate a block of memory on the heap Value alloc(uint32_t size, Tag tag); size_t allocated() const; }; /** Run-time error exception class */ class RunError { protected: RunError() {} std::string msg; char msgBuffer[1024]; public: RunError(std::string errorMsg) { this->msg = errorMsg; } virtual ~RunError() { } virtual std::string toString() const { return msg; } virtual void rethrow(std::string contextMsg) { this->msg = msg + "\n" + contextMsg; throw *this; } }; /** Heap object value wrapper base class */ class Wrapper { protected: /// Internal value holding a heap pointer to the string Value val; Wrapper() {} /// Set the next pointer for an object void setNextPtr(refptr obj, refptr nextPtr); /// Get the next pointer for an object refptr getNextPtr(refptr obj, refptr notFound); /// Get a pointer to the object, or its next pointer if set /// Note: this method is necessary because objects may be /// extended through indirection. refptr getObjPtr(); public: uint32_t length() const; /// Wrappers must be passed by value, new/delete not allowed void* operator new (size_t sz) = delete; void operator delete (void* p) = delete; /// Casting operator to get the wrapped value operator Value () { return val; } /// Casting operator to get the wrapped pointer operator refptr () { return val; } }; /** Wrapper to manipulate string values Note: strings are UTF-8 and null-terminated */ class String : public Wrapper { public: /// Offset and size of the length and data fields static const size_t OF_LEN = HEADER_SIZE; static const size_t SZ_LEN = sizeof(uint32_t); static const size_t OF_DATA = OF_LEN + SZ_LEN; /// Compute the size of an object of this type static constexpr size_t memSize(size_t len) { return OF_DATA + (len + 1) * sizeof(char); } String(std::string str); String(Value value); /// Get the length of the string uint32_t length() const; /// Get the raw internal character data /// Warning: this data can get garbage-collected const char* getDataPtr() const; /// Casting operator to extract a string value operator std::string (); /// Comparison with a string literal bool operator == (const char* that) const; // FIXME: temporary until string internsing is implemented bool operator == (String that) { return (std::string)*this == (std::string)that; } /// Get the ith character code char operator [] (size_t i); /// Concatenate two strings static String concat(String a, String b); }; /** Array value wrapper Note: arrays have a fixed length set at allocation time */ class Array : public Wrapper { private: /// Get the array capacity /// Note: we want to avoid publicly exposing the array capacity size_t getCap(); public: /// Offset and size of the fields static const size_t OF_CAP = HEADER_SIZE; static const size_t SZ_CAP = sizeof(uint32_t); static const size_t OF_LEN = OF_CAP + SZ_CAP; static const size_t SZ_LEN = sizeof(uint32_t); static const size_t OF_DATA = OF_LEN + SZ_LEN; /// Compute the size of an object of this type static constexpr size_t memSize(size_t cap) { return OF_DATA + cap * sizeof(Word) + cap * sizeof(Tag); } /// Allocate a new array of a given length Array(size_t minCap); /// Create an array wrapper from a tagged value Array(Value value); /// Get the length of the array uint32_t length(); /// Set the value of the ith element void setElem(size_t i, Value v); /// Get the value of the ith element Value getElem(size_t i); /// Append a value to the array void push(Value val); /// Concatenate two arrays //static Array concat(Array a, Array b); }; /** Object value wrapper */ class Object : public Wrapper { friend class ObjFieldItr; /// Get the object's capacity size_t getCap(); /// Find the slot index at which a field is stored size_t getSlotIdx( refptr ptr, size_t cap, String fieldName, bool newField ); public: /// Minimum guaranteed object capacity static const size_t MIN_CAP = 16; /// Offset and size of the fields static const size_t OF_CAP = HEADER_SIZE; static const size_t SZ_CAP = sizeof(uint32_t); static const size_t OF_SHAPE = OF_CAP + SZ_CAP; static const size_t SZ_SHAPE = sizeof(refptr); static const size_t OF_FIELDS = OF_SHAPE + SZ_SHAPE; /// Compute the size of an object of this type static constexpr size_t memSize(size_t cap) { // FIXME: for now, we store tagged values, this will change // once we have proper shapes implemented //return OF_FIELDS + cap * sizeof(Word); return OF_FIELDS + cap * sizeof(Value); } /// Allocate a new empty object static Object newObject(size_t cap = 0); Object(Value value); bool hasField(String name); void setField(String name, Value val); Value getField(String name); /// Property lookup with a slot index cache bool getField(const char* name, Value& value, size_t& idxCache); bool hasField(std::string name) { return hasField(String(name)); } void setField(std::string name, Value val) { return setField(String(name), val); } Value getField(std::string name) { return getField(String(name)); } }; /** Object field iterator */ class ObjFieldItr { private: Object obj; size_t slotIdx = 0; public: ObjFieldItr(Object obj); bool valid(); std::string get(); void next(); }; /** Image reference/pointer placeholder This is used for linkage during image loading, so that image files can contain circular references. */ class ImgRef : public Wrapper { public: // This object contains only a header and a string pointer static const size_t OF_SYM = HEADER_SIZE; static const size_t SIZE = OF_SYM + sizeof(refptr); ImgRef(String symbol); ImgRef(Value val); std::string getName() const; }; /// Global virtual machine instance extern VM vm; /// Check if a string is a valid identifier bool isValidIdent(std::string identStr); /// Unit test for the runtime void testRuntime();
[ "mosesopenja@Mosess-MacBook-Air.local" ]
mosesopenja@Mosess-MacBook-Air.local
d5e9b053eaaa5a01a68ab0c44c0fe5b4556428c7
8c5f7ef81a92887fcadfe9ef0c62db5d68d49659
/src/include/guinsoodb/planner/binder.hpp
19a8a63590befa2e0f899b14e02fc6690c0a8358
[ "MIT" ]
permissive
xunliu/guinsoodb
37657f00456a053558e3abc433606bc6113daee5
0e90f0743c3b69f8a8c2c03441f5bb1232ffbcf0
refs/heads/main
2023-04-10T19:53:35.624158
2021-04-21T03:25:44
2021-04-21T03:25:44
378,399,976
0
1
MIT
2021-06-19T11:51:49
2021-06-19T11:51:48
null
UTF-8
C++
false
false
9,953
hpp
//===----------------------------------------------------------------------===// // GuinsooDB // // guinsoodb/planner/binder.hpp // // //===----------------------------------------------------------------------===// #pragma once #include "guinsoodb/common/unordered_map.hpp" #include "guinsoodb/parser/column_definition.hpp" #include "guinsoodb/parser/tokens.hpp" #include "guinsoodb/planner/bind_context.hpp" #include "guinsoodb/planner/bound_tokens.hpp" #include "guinsoodb/planner/expression/bound_columnref_expression.hpp" #include "guinsoodb/planner/logical_operator.hpp" #include "guinsoodb/planner/bound_statement.hpp" namespace guinsoodb { class BoundResultModifier; class ClientContext; class ExpressionBinder; class LimitModifier; class OrderBinder; class TableCatalogEntry; class ViewCatalogEntry; struct CreateInfo; struct BoundCreateTableInfo; struct BoundCreateFunctionInfo; struct CommonTableExpressionInfo; struct CorrelatedColumnInfo { ColumnBinding binding; LogicalType type; string name; idx_t depth; explicit CorrelatedColumnInfo(BoundColumnRefExpression &expr) : binding(expr.binding), type(expr.return_type), name(expr.GetName()), depth(expr.depth) { } bool operator==(const CorrelatedColumnInfo &rhs) const { return binding == rhs.binding; } }; //! Bind the parsed query tree to the actual columns present in the catalog. /*! The binder is responsible for binding tables and columns to actual physical tables and columns in the catalog. In the process, it also resolves types of all expressions. */ class Binder : public std::enable_shared_from_this<Binder> { friend class ExpressionBinder; friend class RecursiveSubqueryPlanner; public: static shared_ptr<Binder> CreateBinder(ClientContext &context, Binder *parent = nullptr, bool inherit_ctes = true); //! The client context ClientContext &context; //! A mapping of names to common table expressions unordered_map<string, CommonTableExpressionInfo *> CTE_bindings; //! The CTEs that have already been bound unordered_set<CommonTableExpressionInfo *> bound_ctes; //! The bind context BindContext bind_context; //! The set of correlated columns bound by this binder (FIXME: this should probably be an unordered_set and not a //! vector) vector<CorrelatedColumnInfo> correlated_columns; //! The set of parameter expressions bound by this binder vector<BoundParameterExpression *> *parameters; //! Whether or not the bound statement is read-only bool read_only; //! Whether or not the statement requires a valid transaction to run bool requires_valid_transaction; //! Whether or not the statement can be streamed to the client bool allow_stream_result; //! The alias for the currently processing subquery, if it exists string alias; //! Macro parameter bindings (if any) MacroBinding *macro_binding = nullptr; public: BoundStatement Bind(SQLStatement &statement); BoundStatement Bind(QueryNode &node); unique_ptr<BoundCreateTableInfo> BindCreateTableInfo(unique_ptr<CreateInfo> info); void BindCreateViewInfo(CreateViewInfo &base); SchemaCatalogEntry *BindSchema(CreateInfo &info); SchemaCatalogEntry *BindCreateFunctionInfo(CreateInfo &info); //! Check usage, and cast named parameters to their types static void BindNamedParameters(unordered_map<string, LogicalType> &types, unordered_map<string, Value> &values, QueryErrorContext &error_context, string &func_name); unique_ptr<BoundTableRef> Bind(TableRef &ref); unique_ptr<LogicalOperator> CreatePlan(BoundTableRef &ref); //! Generates an unused index for a table idx_t GenerateTableIndex(); //! Add a common table expression to the binder void AddCTE(const string &name, CommonTableExpressionInfo *cte); //! Find a common table expression by name; returns nullptr if none exists CommonTableExpressionInfo *FindCTE(const string &name, bool skip = false); bool CTEIsAlreadyBound(CommonTableExpressionInfo *cte); void PushExpressionBinder(ExpressionBinder *binder); void PopExpressionBinder(); void SetActiveBinder(ExpressionBinder *binder); ExpressionBinder *GetActiveBinder(); bool HasActiveBinder(); vector<ExpressionBinder *> &GetActiveBinders(); void MergeCorrelatedColumns(vector<CorrelatedColumnInfo> &other); //! Add a correlated column to this binder (if it does not exist) void AddCorrelatedColumn(const CorrelatedColumnInfo &info); string FormatError(ParsedExpression &expr_context, const string &message); string FormatError(TableRef &ref_context, const string &message); string FormatError(idx_t query_location, const string &message); private: //! The parent binder (if any) shared_ptr<Binder> parent; //! The vector of active binders vector<ExpressionBinder *> active_binders; //! The count of bound_tables idx_t bound_tables; //! Whether or not the binder has any unplanned subqueries that still need to be planned bool has_unplanned_subqueries = false; //! Whether or not subqueries should be planned already bool plan_subquery = true; //! Whether CTEs should reference the parent binder (if it exists) bool inherit_ctes = true; //! The root statement of the query that is currently being parsed SQLStatement *root_statement = nullptr; private: //! Bind the default values of the columns of a table void BindDefaultValues(vector<ColumnDefinition> &columns, vector<unique_ptr<Expression>> &bound_defaults); //! Move correlated expressions from the child binder to this binder void MoveCorrelatedExpressions(Binder &other); BoundStatement Bind(SelectStatement &stmt); BoundStatement Bind(InsertStatement &stmt); BoundStatement Bind(CopyStatement &stmt); BoundStatement Bind(DeleteStatement &stmt); BoundStatement Bind(UpdateStatement &stmt); BoundStatement Bind(CreateStatement &stmt); BoundStatement Bind(DropStatement &stmt); BoundStatement Bind(AlterStatement &stmt); BoundStatement Bind(TransactionStatement &stmt); BoundStatement Bind(PragmaStatement &stmt); BoundStatement Bind(ExplainStatement &stmt); BoundStatement Bind(VacuumStatement &stmt); BoundStatement Bind(RelationStatement &stmt); BoundStatement Bind(ShowStatement &stmt); BoundStatement Bind(CallStatement &stmt); BoundStatement Bind(ExportStatement &stmt); BoundStatement Bind(SetStatement &stmt); BoundStatement Bind(LoadStatement &stmt); unique_ptr<BoundQueryNode> BindNode(SelectNode &node); unique_ptr<BoundQueryNode> BindNode(SetOperationNode &node); unique_ptr<BoundQueryNode> BindNode(RecursiveCTENode &node); unique_ptr<BoundQueryNode> BindNode(QueryNode &node); unique_ptr<LogicalOperator> VisitQueryNode(BoundQueryNode &node, unique_ptr<LogicalOperator> root); unique_ptr<LogicalOperator> CreatePlan(BoundRecursiveCTENode &node); unique_ptr<LogicalOperator> CreatePlan(BoundSelectNode &statement); unique_ptr<LogicalOperator> CreatePlan(BoundSetOperationNode &node); unique_ptr<LogicalOperator> CreatePlan(BoundQueryNode &node); unique_ptr<BoundTableRef> Bind(BaseTableRef &ref); unique_ptr<BoundTableRef> Bind(CrossProductRef &ref); unique_ptr<BoundTableRef> Bind(JoinRef &ref); unique_ptr<BoundTableRef> Bind(SubqueryRef &ref, CommonTableExpressionInfo *cte = nullptr); unique_ptr<BoundTableRef> Bind(TableFunctionRef &ref); unique_ptr<BoundTableRef> Bind(EmptyTableRef &ref); unique_ptr<BoundTableRef> Bind(ExpressionListRef &ref); bool BindFunctionParameters(vector<unique_ptr<ParsedExpression>> &expressions, vector<LogicalType> &arguments, vector<Value> &parameters, unordered_map<string, Value> &named_parameters, unique_ptr<BoundSubqueryRef> &subquery, string &error); unique_ptr<LogicalOperator> CreatePlan(BoundBaseTableRef &ref); unique_ptr<LogicalOperator> CreatePlan(BoundCrossProductRef &ref); unique_ptr<LogicalOperator> CreatePlan(BoundJoinRef &ref); unique_ptr<LogicalOperator> CreatePlan(BoundSubqueryRef &ref); unique_ptr<LogicalOperator> CreatePlan(BoundTableFunction &ref); unique_ptr<LogicalOperator> CreatePlan(BoundEmptyTableRef &ref); unique_ptr<LogicalOperator> CreatePlan(BoundExpressionListRef &ref); unique_ptr<LogicalOperator> CreatePlan(BoundCTERef &ref); unique_ptr<LogicalOperator> BindTable(TableCatalogEntry &table, BaseTableRef &ref); unique_ptr<LogicalOperator> BindView(ViewCatalogEntry &view, BaseTableRef &ref); unique_ptr<LogicalOperator> BindTableOrView(BaseTableRef &ref); BoundStatement BindCopyTo(CopyStatement &stmt); BoundStatement BindCopyFrom(CopyStatement &stmt); void BindModifiers(OrderBinder &order_binder, QueryNode &statement, BoundQueryNode &result); void BindModifierTypes(BoundQueryNode &result, const vector<LogicalType> &sql_types, idx_t projection_index); unique_ptr<BoundResultModifier> BindLimit(LimitModifier &limit_mod); unique_ptr<Expression> BindFilter(unique_ptr<ParsedExpression> condition); unique_ptr<Expression> BindOrderExpression(OrderBinder &order_binder, unique_ptr<ParsedExpression> expr); unique_ptr<LogicalOperator> PlanFilter(unique_ptr<Expression> condition, unique_ptr<LogicalOperator> root); void PlanSubqueries(unique_ptr<Expression> *expr, unique_ptr<LogicalOperator> *root); unique_ptr<Expression> PlanSubquery(BoundSubqueryExpression &expr, unique_ptr<LogicalOperator> &root); unique_ptr<LogicalOperator> CastLogicalOperatorToTypes(vector<LogicalType> &source_types, vector<LogicalType> &target_types, unique_ptr<LogicalOperator> op); string FindBinding(const string &using_column, const string &join_side); bool TryFindBinding(const string &using_column, const string &join_side, string &result); public: // This should really be a private constructor, but make_shared does not allow it... Binder(bool I_know_what_I_am_doing, ClientContext &context, shared_ptr<Binder> parent, bool inherit_ctes); }; } // namespace guinsoodb
[ "bqjimaster@gmail.com" ]
bqjimaster@gmail.com
622fd04ac4aaf19b8b0934b4854c3e03c6a490e7
d30787efe95c6b27d988df64fb487dd01658fb77
/Source/Tema2/Playground.h
4503979f8477721bbb6045f0eea1ca937d2d25d4
[ "MIT" ]
permissive
cheez3d/acs-computer-graphics
923fce2b68f0a53c144aefb184ad0c2d82542105
3960639575bc70214f8976abae3270e5c32b985c
refs/heads/master
2023-03-25T20:58:54.169414
2021-03-22T02:42:10
2021-03-22T02:42:10
350,171,073
0
0
null
null
null
null
UTF-8
C++
false
false
1,961
h
#pragma once #include "Scene3D.h" #include <chrono> #include <list> #include <vector> namespace Skyroads { class Playground final : public Scene3D { public: static inline float const LIGHT_Y = 5; private: glm::vec3 light; Player* player; FuelIndicator* fuelIndicator; std::chrono::time_point<std::chrono::steady_clock> lastFuelIndicatorLevelDecrement; std::vector<std::list<Platform*>> platforms; int platformAddRow; std::chrono::time_point<std::chrono::steady_clock> lastPlatformAddRowIncrement; std::vector<float> platformAddShifts; std::vector<int> platformAddEmptyRows; int platformAddEmptyRowsMax; std::chrono::time_point<std::chrono::steady_clock> lastPlatformAddEmptyRowsMaxIncrement; float speed; float speedup; std::chrono::time_point<std::chrono::steady_clock> lastSpeedIncrement; bool isSpeedupLocked; std::chrono::time_point<std::chrono::steady_clock> lastSpeedupLock; protected: virtual void Init() override; virtual void OnInputUpdate(float dt, int mods) override; public: virtual glm::vec3 GetLight() const override; protected: virtual void SetLight(glm::vec3 light) override; public: Player* GetPlayer() const; FuelIndicator* GetFuelIndicator() const; std::vector<std::list<Platform*>>& GetPlatforms(); void AddInitialPlatforms(); void RemovePlatforms(); void SetPlatformAddRow(int platformAddRow); void SetPlatformAddEmptyRowsMax(int platformAddEmptyRowsMax); void AddPlatform(int column, int row); float GetSpeed() const; void SetSpeed(float speed); float GetSpeedup() const; void SetSpeedup(float speedup); bool IsSpeedupLocked() const; void SetSpeedupLocked(bool speedupLocked); void ResetTimes(); }; }
[ "andrei.st03@gmail.com" ]
andrei.st03@gmail.com
7feeda37ca97e5db42398b88b27254fc446b001a
64d8f4e2b19f8dbdf3021d77af5173b5fa432384
/MULTI/casa/ldr/LDR_Definitivo.ino
6eaafcf61c7bf7ca2048f3b0f6084f5e73ce9cdb
[]
no_license
jaime2m1/A-HOME
76ba4317c08fa790e72c79fa19667c1f4b1540c6
8c158867223b52173840f417ddabd012143901af
refs/heads/master
2021-06-10T00:43:47.173323
2021-04-09T16:00:56
2021-04-09T16:00:56
159,738,377
0
0
null
null
null
null
UTF-8
C++
false
false
948
ino
void setup() { pinMode(12,OUTPUT); pinMode(11,OUTPUT); pinMode(10,OUTPUT); pinMode(9,OUTPUT); pinMode(8,OUTPUT); pinMode(7,OUTPUT); pinMode(6,OUTPUT); pinMode(5,OUTPUT); } void loop() { int led0; led0 = analogRead (0); int led1; led1 = analogRead (1); int led2; led2 = analogRead (2); int led3; led3 = analogRead (3); if (led1 < 150) { digitalWrite (8,HIGH); digitalWrite (9,HIGH); digitalWrite (10,HIGH); delay (50); } else { digitalWrite (8,LOW); digitalWrite (9,LOW); digitalWrite (10,LOW); delay (50); } if (led0 < 50) { digitalWrite (12,HIGH); digitalWrite (11,HIGH); delay (10); } else { digitalWrite (12,LOW); digitalWrite (11,LOW); delay (10); } if (led2 < 50) { digitalWrite (7,HIGH); digitalWrite (6,HIGH); delay (10); } else { digitalWrite (7,LOW); digitalWrite (6,LOW); delay (10); } if (led3 < 150) { digitalWrite (5,HIGH); delay (10); } else { digitalWrite (5,LOW); delay (10); } }
[ "noreply@github.com" ]
jaime2m1.noreply@github.com
528f1e7d22074064ba5dfe9967c57ca7b38dc169
870ec854874c0bce93865c23101a9a4682be462a
/kernel/memory/physical_page.h
dedb0f5788896f4dc8ade7dc2509d5aa299274da
[]
no_license
wxuefei/mos-multiboot2
d4a8b656287936593291fe1a20d1d3b3008095de
b0685674b25f156b8efb0fe9408944ee29f9bf31
refs/heads/master
2023-03-20T17:49:37.526289
2020-09-21T16:21:32
2020-09-21T16:21:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,270
h
#pragma once #include <std/stdint.h> #include <std/list.h> #define PAGE_OFFSET 0xFFFFFFFF00000000 #define Virt_To_Phy(addr) ((uint8_t *)(addr)-PAGE_OFFSET) #define Phy_To_Virt(addr) ((uint8_t *)((uint8_t *)(addr) + PAGE_OFFSET)) #define PAGE_1G_SHIFT 30 #define PAGE_2M_SHIFT 21 #define PAGE_4K_SHIFT 12 #define PAGE_2M_SIZE (1UL << PAGE_2M_SHIFT) #define PAGE_4K_SIZE (1UL << PAGE_4K_SHIFT) #define PAGE_2M_MASK_LOW (~(PAGE_2M_SIZE - 1)) #define PAGE_4K_MASK_LOW (~(PAGE_4K_SIZE - 1)) #define PAGE_2M_MASK_HIGH (~PAGE_2M_MASK_LOW) #define PAGE_4K_MASK_HIGH (~PAGE_4K_MASK_LOW) #define PAGE_2M_ALIGN(addr) (((unsigned long)(addr) + PAGE_2M_SIZE - 1) & PAGE_2M_MASK_LOW) #define PAGE_4K_ALIGN(addr) (((unsigned long)(addr) + PAGE_4K_SIZE - 1) & PAGE_4K_MASK_LOW) #define PAGE_4K_ROUND_UP(addr) (addr == (addr & PAGE_4K_MASK_LOW) ? addr : ((addr & PAGE_4K_MASK_LOW) + PAGE_4K_SIZE)) #define PAGE_2M_ROUND_UP(addr) (addr == (addr & PAGE_2M_MASK_LOW) ? addr : ((addr & PAGE_2M_MASK_LOW) + PAGE_2M_SIZE)) #define PAGE_4K_ROUND_DOWN(addr) (addr & PAGE_4K_MASK_LOW) #define PAGE_2M_ROUND_DOWN(addr) (addr & PAGE_2M_MASK_LOW) class Zone; struct Page { Zone *zone; uint8_t*physical_address; List list; uint16_t reference_count; uint16_t attributes; };
[ "liuminghao233@gmail.com" ]
liuminghao233@gmail.com
d09b9e47ac4431425aa29cf80cf9567390321e6a
64e62b04d86c1d772299cc4274cc6f4da61425f4
/chargerII/CommonCode/BootLoader/AVROSP/Source/AVRProgrammer.cpp
d6eeba1e3053870e7d507291ca38d59d7dcf9694
[]
no_license
jason-vanaardt/scoubi
a279a33e751e71d0a86f24ccfa9b8f54a9602135
6a94bef9ed8641972000294cf4b0c5473a695b94
refs/heads/master
2022-11-22T21:15:53.011979
2020-07-27T21:55:23
2020-07-27T21:55:23
282,802,663
0
0
null
null
null
null
UTF-8
C++
false
false
1,729
cpp
/***************************************************************************** * * Atmel Corporation * * File : AVRProgrammer.cpp * Compiler : Dev-C++ 4.9.8.0 - http://bloodshed.net/dev/ * Revision : $Revision: 1.8 $ * Date : $Date: Friday, July 09, 2004 06:35:28 UTC $ * Updated by : $Author: raapeland $ * * Support mail : avr@atmel.com * * Target platform : Win32 * * AppNote : AVR911 - AVR Open-source Programmer * * Description : An abstract class containing a framework for a generic * programmer for AVR parts. Reading and writing Flash, EEPROM * lock bits and all fuse bits and reading OSCCAL and reading * signature bytes are supported. * * ****************************************************************************/ #include "AVRProgrammer.hpp" /* Constructor */ AVRProgrammer::AVRProgrammer( CommChannel * _comm ) : pagesize( -1 ) { if( _comm == NULL ) throw new ErrorMsg( "NULL pointer provided for communication channel!" ); comm = _comm; } /* Destructor */ AVRProgrammer::~AVRProgrammer() { /* No code here */ } string AVRProgrammer::readProgrammerID( CommChannel * _comm ) { string id( "1234567" ); // Reserve 7 characters. if( _comm == NULL ) throw new ErrorMsg( "NULL pointer provided for communication channel!" ); /* Synchonize with programmer */ for( int i = 0; i < 10; i++ ) _comm->sendByte( 27 ); // Send ESC /* Send 'S' command to programmer */ _comm->sendByte( 'S' ); _comm->flushTX(); /* Read 7 characters */ for( long i = 0; i < id.size(); i++ ) { id[i] = _comm->getByte(); } return id; } /* end of file */
[ "jason.vanaardt@gmail.com" ]
jason.vanaardt@gmail.com
466255b6f77f29b2ada156d753757b5d79f7cdc2
ce6307e1a1d49b0d73a7247d9b330ef7deb91577
/src/AliAnaSelector.cxx
8a5ad842b93860f2e94f02eb553fc85fcd6a949c
[]
no_license
qgp/aliana
e32c96b8f678050bbd9d286476de3a0e3eae4c05
6c4b12db8eaed2f5c3f80fcddbb836e2e7a06d1f
refs/heads/master
2021-01-13T08:10:29.953518
2016-11-20T14:01:25
2016-11-20T14:01:25
71,718,728
0
0
null
null
null
null
UTF-8
C++
false
false
1,549
cxx
#include <cstdio> #include <cstdarg> #include "TFile.h" #include "TH1F.h" #include "TH2F.h" #include "TH3F.h" #include "THn.h" #include "AliVTrack.h" #include "TCanvas.h" #include "AliAnaSelector.h" AliAnaSelector::AliAnaSelector(TTree*) : TSelector() { } AliAnaSelector::~AliAnaSelector() { } AliAnaSelector *AliAnaSelector::CreateSelector(const std::string &name) { return (AliAnaSelector*) TClass::GetClass(name.c_str())->New(); } void AliAnaSelector::Init(TTree *tree) { fReader.SetTree(tree); } Bool_t AliAnaSelector::Notify() { return TSelector::Notify(); } void AliAnaSelector::SlaveBegin(TTree *tree) { UserInit(); // register histograms for (const auto kv : fHistoMap) GetOutputList()->Add(kv.second); } Bool_t AliAnaSelector::Process(Long64_t entry) { fReader.SetLocalEntry(entry); return UserProcess(); } void AliAnaSelector::SlaveTerminate() { } void AliAnaSelector::Terminate() { // draw histograms if (fHistoMap.size() == 0) { TIter next(GetOutputList()); while (TObject* obj = next()) if (TH1 *h = dynamic_cast<TH1*> (obj)) { const std::string name = h->GetName(); fHistoMap[name] = h; } } std::unique_ptr<TFile> outFile(TFile::Open("histos.root", "recreate")); for (const auto kv : fHistoMap) outFile->WriteTObject(kv.second); } TH1 *AliAnaSelector::AddHistogram(TH1 *h) { const std::string name = h->GetName(); fHistoMap[name] = h; return h; } TH1 *AliAnaSelector::GetHistogram(const std::string &name) { return fHistoMap[name]; }
[ "jochen.klein@cern.ch" ]
jochen.klein@cern.ch