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
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 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
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
d3c6b82c19a0d58d92695943fa37ddb934d8ac6c
7ce91a98ae434dbb48099699b0b6bcaa705ba693
/TestModule/HK1/Users/19110419/BAI4.CPP
2c2f977759c96b8592f693eb9d9bdf658e05a087
[]
no_license
ngthvan1612/OJCore
ea2e33c1310c71f9375f7c5cd0a7944b53a1d6bd
3ec0752a56c6335967e5bb4c0617f876caabecd8
refs/heads/master
2023-04-25T19:41:17.050412
2021-05-12T05:29:40
2021-05-12T05:29:40
357,612,534
0
0
null
null
null
null
UTF-8
C++
false
false
802
cpp
#include <stdio.h> #include <iostream> #include <math.h> using namespace std; int tongMin (int A[][99], int m, int n); int nto (int n); void nhap (int A[][99], int &m, int &n); int main () { int A[99][99], m, n; nhap (A, m, n); cout << tongMin (A, m, n); return 0; } int tongMin (int A[][99], int m, int n) { int res=0; for (int cot=0; cot<n; cot++) if (nto (A[0][cot])) res += A[0][cot]; for (int i=1; i<m; i++) { int t=0; for (int j=0; j<n; j++) { if (nto (A[i][j])) t+=A[i][j]; } if (t<res) res = t; } return res; } int nto (int n) { if (n<2) return 0; for (int i=2; i<=sqrt(n); i++) if (n%i==0) return 0; return 1; } void nhap (int A[][99], int &m, int &n) { cin >> m>> n; for (int i=0; i<m; i++) for (int j=0; j<n; j++) cin >> A[i][j]; }
[ "Nguyen Van@DESKTOP-8HI58DE" ]
Nguyen Van@DESKTOP-8HI58DE
980c2f8945997e7841959da5821faeca0e4e10f7
db7eacb4c0644266709e845cecfeb98139fca978
/user/UserLogic/src/UserLogicI.h
f425e304f299eba10c785e91e3812eb6eec6ed24
[]
no_license
bradenwu/oce
ce893b762cf91e71f26a72378153cab57bfa18c6
73d2efa57f896a10953428b278babc109cdc2aa4
refs/heads/master
2021-01-22T16:53:20.542536
2012-07-13T17:38:05
2012-07-14T02:08:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,686
h
#ifndef __UserLogicI_h__ #define __UserLogicI_h__ #include "CompleteUserInfoAdapter.h" #include <Ice/Ice.h> #include <IceUtil/AbstractMutex.h> #include <IceUtil/Mutex.h> #include "UserLogic.h" #include "TaskManager.h" #include "Singleton.h" #include "FriendOfFriendIndexerAdapter.h" #include <CallGuarantee/src/CallGuarantee.h> namespace mop { namespace hi { namespace svc { namespace model { const int TASK_LEVEL_USERSTATECACHE = 1; const int TASK_LEVEL_PRESENCEMSG = 2; const int TASK_LEVEL_IM = 3; const int TASK_LEVEL_BUDDYCACHEBYNAME = 4; const int TASK_LEVEL_BUDDYBYIDLOADER = 5; const int TASK_LEVEL_BUDDYBYNAMELOADER = 6; const int TASK_LEVEL_USERCACHERELOADER = 7; const int TASK_LEVEL_STATUSCACHE = 8; const int TASK_LEVEL_USERCACHE = 11; const int TASK_LEVEL_CHARITY = 12; const int TASK_LEVEL_PHOTOSTATEFILTER = 13; const int TASK_LEVEL_SCORECACHEVIP = 14; const int TASK_LEVEL_USERSTATEFILTER = 15; const int TASK_LEVEL_FRIENDOFFREIENDINDEXER = 16; const int TASK_LEVEL_INVITEREWARD = 17; const int TASK_LEVEL_HIGHSCHOOLFILTER = 18; const int TASK_LEVEL_FRIENDFINDERNEWCOMER = 19; const int TASK_LEVEL_USERCOUNT = 20; const int TASK_LEVEL_COMPLETEUSERINFO = 21; const int TASK_LEVEL_DISTBUDDYBYIDCACHERELOADER = 22; const int TASK_LEVEL_FOOTPRINTNOTIFY = 23; const string USER_LOGIC_MANAGER = "M"; const string MODIFY_RECORD_DB = "modify_record"; class UserLogicManagerI: virtual public UserLogicManager, virtual public MyUtil::Singleton < UserLogicManagerI> { public: virtual bool isValid(const Ice::Current& = Ice::Current()); virtual void setValid(bool state, const Ice::Current& = Ice::Current()); //旧接口 virtual void updateUser(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); virtual void updateUserDesc(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); virtual void updateUserNetwork(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); //user_doing virtual void insertUserDoing(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); virtual void updateUserDoing(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); //user_stage virtual void insertUserStage(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); virtual void updateUserStage(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); //user_born virtual void insertUserBorn(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); virtual void updateUserBorn(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); //user_state virtual void insertUserState(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); virtual void updateUserState(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); //user_names virtual void insertUserNames(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); virtual void updateUserNames(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); //user_passport virtual void insertUserPassport(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); virtual void updateUserPassport(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); //user_config virtual void insertUserConfig(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); virtual void updateUserConfig(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); //user_url virtual void insertUserUrl(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); virtual void updateUserUrl(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); //user_time virtual void insertUserTime(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); virtual void updateUserTime(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); //user_contact virtual void insertUserContact(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); virtual void updateUserContact(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); //user_fav virtual void insertUserFav(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); virtual void updateUserFav(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); //user_right virtual void insertUserRight(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); virtual void updateUserRight(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); virtual void updateUserRegion(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); virtual void updateUserWorkplace(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); virtual void updateUserElementarySchool(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); virtual void updateUserJuniorHighSchool(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); virtual void updateUserHighSchool(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); virtual void updateUserCollege(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); virtual void updateUserUniversity(::Ice::Int, const ::MyUtil::Str2StrMap&, const Ice::Current& = Ice::Current()); UserLogicManagerI() {} virtual ~UserLogicManagerI(){} private: bool valid_; IceUtil::RWRecMutex validmutex_; }; class PresenceMsgNotifyTask : public MyUtil::Task { public: PresenceMsgNotifyTask(int userId, const MyUtil::Str2StrMap& props, const Ice::Current& current):Task(TASK_LEVEL_PRESENCEMSG), _userId(userId), _props(props),_current(current) { } virtual ~PresenceMsgNotifyTask(){} virtual void handle(); private: int _userId; MyUtil::Str2StrMap _props; Ice::Current _current; }; class IMNotifyTask : public MyUtil::Task { public: IMNotifyTask(int userId,const MyUtil::Str2StrMap& props, const Ice::Current& current):Task(TASK_LEVEL_IM), _userId(userId){ _props = props; _current = current; }; virtual void handle(); private: int _userId; MyUtil::Str2StrMap _props; Ice::Current _current; }; class StatusCacheNotifyTask : public MyUtil::Task { public: StatusCacheNotifyTask(int userId,const MyUtil::Str2StrMap& props, const Ice::Current& current):Task(TASK_LEVEL_STATUSCACHE), _userId(userId){ _props = props; _current = current; }; virtual void handle(); private: int _userId; MyUtil::Str2StrMap _props; Ice::Current _current; }; class BuddyByIdLoaderNotifyTask : public MyUtil::Task { public: BuddyByIdLoaderNotifyTask (int userId,const MyUtil::Str2StrMap& props, const Ice::Current& current):Task(TASK_LEVEL_BUDDYBYIDLOADER), _userId(userId){ _props = props; _current = current; }; virtual void handle(); private: int _userId; MyUtil::Str2StrMap _props; Ice::Current _current; }; class BuddyByNameLoaderNotifyTask : public MyUtil::Task { public: BuddyByNameLoaderNotifyTask (int userId,const MyUtil::Str2StrMap& props, const Ice::Current& current):Task(TASK_LEVEL_BUDDYBYNAMELOADER), _userId(userId){ _props = props; _current = current; }; virtual void handle(); private: int _userId; MyUtil::Str2StrMap _props; Ice::Current _current; }; class FriendOfFriendIndexerNotifyTask : public MyUtil::Task { public: FriendOfFriendIndexerNotifyTask (int userId,const MyUtil::Str2StrMap& props, const Ice::Current& current):Task(TASK_LEVEL_FRIENDOFFREIENDINDEXER), _userId(userId){ _props = props; _current = current; }; virtual void handle(); private: int _userId; Ice::Current _current; MyUtil::Str2StrMap _props; }; class PhotoStateFilterUpdateNotifyTask : public MyUtil::Task { public: PhotoStateFilterUpdateNotifyTask (int userId,const MyUtil::Str2StrMap& props): Task(TASK_LEVEL_PHOTOSTATEFILTER), _userId(userId), _props(props){ }; virtual void handle(); private: int _userId; MyUtil::Str2StrMap _props; }; class ScoreCacheVipNotifyTask : public MyUtil::Task { public: ScoreCacheVipNotifyTask (int userId,const MyUtil::Str2StrMap& props): Task(TASK_LEVEL_SCORECACHEVIP), _userId(userId), _props(props){ }; virtual void handle(); private: int _userId; MyUtil::Str2StrMap _props; }; class UserStateFilterUpdateNotifyTask : public MyUtil::Task { public: UserStateFilterUpdateNotifyTask (int userId,const MyUtil::Str2StrMap& props): Task(TASK_LEVEL_USERSTATEFILTER), _userId(userId), _props(props){ }; virtual void handle(); private: int _userId; MyUtil::Str2StrMap _props; }; class UserCountNotifyTask : public MyUtil::Task { public: UserCountNotifyTask (int userId): Task(TASK_LEVEL_USERCOUNT), _userId(userId){ }; virtual void handle(); private: int _userId; }; class InviteRewardUpdateNotifyTask : public MyUtil::Task { public: InviteRewardUpdateNotifyTask (int userId,const MyUtil::Str2StrMap& props): Task(TASK_LEVEL_INVITEREWARD), _userId(userId), _props(props){ }; virtual void handle(); private: int _userId; MyUtil::Str2StrMap _props; }; class HighSchoolUpdateNotifyTask : public MyUtil::Task { public: HighSchoolUpdateNotifyTask (int userId,const MyUtil::Str2StrMap& props): Task(TASK_LEVEL_HIGHSCHOOLFILTER), _userId(userId), _props(props){ }; virtual void handle(); private: int _userId; MyUtil::Str2StrMap _props; }; class CharityNotifyTask : public MyUtil::Task { public: CharityNotifyTask(int userid,const MyUtil::Str2StrMap& data) : MyUtil::Task(TASK_LEVEL_CHARITY), userid_(userid), data_(data) {} virtual void handle(); private: int userid_; MyUtil::Str2StrMap data_; }; class UserCacheInsertNotifyTask : public MyUtil::Task { public: UserCacheInsertNotifyTask(int userid) : MyUtil::Task(TASK_LEVEL_USERCACHE), userid_(userid) {} virtual void handle(); private: int userid_; }; class UserCacheUpdateNotifyTask : public MyUtil::Task { public: UserCacheUpdateNotifyTask(int userid, Ice::Byte table, const MyUtil::Str2StrMap& data) : MyUtil::Task(TASK_LEVEL_USERCACHE), userid_(userid), table_(table), data_(data) {} virtual void handle(); private: int userid_; Ice::Byte table_; MyUtil::Str2StrMap data_; }; class UserCacheInsertCallGuarantee : public callguarantee::CallGuarantee, public MyUtil::Singleton<UserCacheInsertCallGuarantee> { public: UserCacheInsertCallGuarantee() {} virtual bool Do(const std::vector<std::pair<int, Ice::ObjectPtr> >& params); virtual bool Redo(const std::vector<int>& ids); }; class UserCacheUpdateCallGuarantee : public callguarantee::CallGuarantee, public MyUtil::Singleton<UserCacheUpdateCallGuarantee> { public: UserCacheUpdateCallGuarantee() {} virtual bool Do(const std::vector<std::pair<int, Ice::ObjectPtr> >& params); virtual bool Redo(const std::vector<int>& ids); }; class UserCacheReloadCallGuarantee : public callguarantee::CallGuarantee, public MyUtil::Singleton<UserCacheReloadCallGuarantee> { public: UserCacheReloadCallGuarantee() {} virtual bool Do(const std::vector<std::pair<int, Ice::ObjectPtr> >& params); virtual bool Redo(const std::vector<int>& ids); }; class FriendFinderNewComerUpdateNotifyTask : public MyUtil::Task { public: FriendFinderNewComerUpdateNotifyTask(int userid) : MyUtil::Task(TASK_LEVEL_FRIENDFINDERNEWCOMER), userid_(userid) {} virtual void handle(); private: int userid_; }; class CompleteUserInfoTask : public MyUtil::Task { public: CompleteUserInfoTask(int userId) : MyUtil::Task(TASK_LEVEL_COMPLETEUSERINFO), userId_(userId) {} virtual void handle(); private: int userId_; }; class FootprintNotifyTask : public MyUtil::Task { public: FootprintNotifyTask(int userId) : MyUtil::Task(TASK_LEVEL_FOOTPRINTNOTIFY), userId_(userId) {} virtual void handle(); private: int userId_; }; class DistBuddyByIdCacheReloaderNotifyTask : public MyUtil::Task { public: DistBuddyByIdCacheReloaderNotifyTask(int userid, const MyUtil::Str2StrMap& m) : MyUtil::Task(TASK_LEVEL_DISTBUDDYBYIDCACHERELOADER), userid_(userid), m_(m) {} virtual void handle(); private: int userid_; MyUtil::Str2StrMap m_; }; } ; } ; } ; } ; #endif
[ "shanshan@localhost.(none)" ]
shanshan@localhost.(none)
6cb284c2c513f937eefa3da6f2a770cf69f23e9f
a81c07a5663d967c432a61d0b4a09de5187be87b
/chrome/browser/android/download/download_controller_base.cc
047ea34bd4276345e255d6559fc24036d23c4103
[ "BSD-3-Clause" ]
permissive
junxuezheng/chromium
c401dec07f19878501801c9e9205a703e8643031
381ce9d478b684e0df5d149f59350e3bc634dad3
refs/heads/master
2023-02-28T17:07:31.342118
2019-09-03T01:42:42
2019-09-03T01:42:42
205,967,014
2
0
BSD-3-Clause
2019-09-03T01:48:23
2019-09-03T01:48:23
null
UTF-8
C++
false
false
1,907
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/android/download/download_controller_base.h" #include "chrome/browser/chrome_content_browser_client.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "net/url_request/url_request.h" const char kOMADrmMessageMimeType[] = "application/vnd.oma.drm.message"; const char kOMADrmContentMimeType[] = "application/vnd.oma.drm.content"; const char kOMADrmRightsMimeType1[] = "application/vnd.oma.drm.rights+xml"; const char kOMADrmRightsMimeType2[] = "application/vnd.oma.drm.rights+wbxml"; content::WebContents* GetWebContents(int render_process_id, int render_view_id) { content::RenderViewHost* render_view_host = content::RenderViewHost::FromID(render_process_id, render_view_id); if (!render_view_host) return nullptr; return content::WebContents::FromRenderViewHost(render_view_host); } // static DownloadControllerBase* DownloadControllerBase::download_controller_ = nullptr; DownloadInfo::DownloadInfo(const GURL& url, const GURL& original_url, const std::string& content_disposition, const std::string& original_mime_type, const std::string& user_agent, const std::string& cookie, const std::string& referer) : url(url), original_url(original_url), content_disposition(content_disposition), original_mime_type(original_mime_type), user_agent(user_agent), cookie(cookie), referer(referer) {} DownloadInfo::DownloadInfo(const DownloadInfo& other) = default; DownloadInfo::~DownloadInfo() {}
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
7c3a746b50db7fda9ece7e4a3d9dbe7883dbc1a5
e140c1c7087d6a4e130ebde2ce7962c40ee7fd0c
/codeforces/1382/D.cpp
51992c0422a625dd01ba547f41284ad441c1519f
[]
no_license
diptayan2k/CP-Submissions
543ccf94b4d43b6f040f975ccce834e883a5efc7
dc32f1dd474cf250f71795f991132f3d52cc1771
refs/heads/master
2023-02-05T15:26:51.480986
2018-07-03T14:25:00
2020-12-21T10:20:15
323,290,119
0
0
null
null
null
null
UTF-8
C++
false
false
1,866
cpp
#include <iostream> #include<bits/stdc++.h> #define ll long long int #define lld long double #define F first #define S second #define f(i,a,b) for(int i=a;i<=b;i++) #define g(i,a,b) for(int i=a;i>=b;i--) #define mp make_pair #define pb push_back #define mh make_heap #define ph push_heap #define pq priority_queue #define bits(x) __builtin_popcountll(x) #define op(x) cout<<"Case #"<<x<<": " #define op1(x) cout<<"Scenario #"<<x<<": " #define endl "\n" using namespace std; const ll mod = 1000000007; const ll INF = 1e18; const int N = 20; ll a[4001]; ll n; vector<ll> v; bool dp[4001][2001]; bool vis[4001][2001]; bool foo(ll idx, ll sum) { if (sum > n) return false; if (sum == n) return true; if (idx == v.size()) { if (sum == n) return true; else return false; } if (vis[idx][sum]) return dp[idx][sum]; bool res = false; res |= foo(idx + 1, sum + v[idx]); res |= foo(idx + 1, sum); vis[idx][sum] = true; return dp[idx][sum] = res; } void solve(int t) { cin >> n; for (int i = 0; i < 2 * n; i++) { cin >> a[i]; } ll b[2 * n] = {0}; ll ma = 0; for (int i = 0; i < 2 * n; i++) { if (a[i] > ma) { b[i] = 1; ma = a[i]; } } ll len = 0; for (int i = 2 * n - 1; i >= 0; i--) { if (b[i] == 1) { len++; v.pb(len); len = 0; } else { len++; } } /* for (auto i : v) { cout << i << " "; } cout << endl;*/ for (int i = 0; i <= 2 * n; i++) { for (int j = 0; j <= n; j++) { vis[i][j] = false; dp[i][j] = false; } } if (foo(0, 0)) { cout << "YES" << endl; } else { cout << "NO" << endl; } v.clear(); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int t = 1; cin >> t; for (int i = 1; i <= t; i++) { solve(i); } }
[ "diptayan2k@gmail.com" ]
diptayan2k@gmail.com
5604646dce81ed32d1eb841a608680fa827bd758
0dda6c092f0d43cc101fe03c3b9f1b19b9d1c9a9
/MRECAMAN.cpp
f3a1112b0bb2c03c98ce6851722d3a6579c62b1e
[]
no_license
sshekhar1094/spoj_solutions
edbecc011e7375b58a65dcab2fce5ccb1b4d57f8
a94b2b965de3b91f8b8905f64ec79cf9694c3cca
refs/heads/master
2021-01-21T14:28:56.128282
2017-06-24T10:43:22
2017-06-24T10:43:22
95,291,397
0
0
null
null
null
null
UTF-8
C++
false
false
901
cpp
#include<stdio.h> #include<stdlib.h> #include<iostream> #include<string.h> #define MAX 7000001 using namespace std; int arr[5000001],occ[MAX]; int main(void){ int n,i,temp,sz; memset(arr,0,sizeof(int)*MAX); memset(occ,0,sizeof(int)*MAX); occ[0]=1; for(i=1;i<=50;i++){ temp=arr[i-1]-i; if(temp<0||(temp>=0&&occ[temp])) temp+=2*i; arr[i]=temp; occ[temp]=1; sz = 50; } while(1){ scanf("%d",&n); if(n<0)break; if(n <= sz){ printf("%d\n", arr[n]); } else{ for(i=sz+1;i<=n;i++){ temp=arr[i-1]-i; if(temp<0||(temp>=0&&occ[temp])) temp+=2*i; arr[i]=temp; occ[temp]=1; sz = i; } printf("%d\n",arr[n]); } } return 0; }
[ "sshekhar1094@gmail.com" ]
sshekhar1094@gmail.com
16963e9e41f279e0b50e897fd0cd46996c37febe
6a68da02d8829b0c403a43d1b35419ffb558e936
/Assignment Practice/src/practice.cpp
f86eb1485638c84beadf0a65135d611ea023db78
[]
no_license
clarka921/CS_106B
df3a95d7e45ae3aeeac240bb5a735397e9ba8398
ca17a805b53aa555a0372a70a6dc8f1def6bc10f
refs/heads/master
2020-03-17T04:40:34.036619
2018-05-14T00:19:33
2018-05-14T00:19:33
133,284,436
0
0
null
null
null
null
UTF-8
C++
false
false
5,392
cpp
#include <iostream> #include <cctype> #include "console.h" #include "simpio.h" #include "strlib.h" #include "tokenscanner.h" #include <fstream> using namespace std; //Class declarations class TokenScanner; //Function prototype ifstream infile; int isalpha( int ch ); string integerToString(int); int abs(int n ); bool is_e(char c); bool is_vowel(char c); bool is_NotProc(int x, string str); bool is_LastE(int g, int k, char q); bool is_FirstLetter(int x); bool letter_BeforeIsVowel(string stra, int x); bool is_LastLetter(int x, int y); int main() { while (true){ cout << endl; cout << "Enter 0 to quit this shizz" << endl; cout << "Enter 1 for division" << endl; cout << "Enter 2 for modulus" << endl; cout << "Enter 3 to convert from an 'int' to a 'ch'"<< endl; cout << "Enter 4 to test your TokenScanner implementation" << endl; cout << endl; int choice = getInteger("Choose, peasant!: "); cout << endl; if (choice == 0) {break;} else if (choice == 1) { cout << "You have chosen division!" << endl; int divid = getInteger("Enter a dividend: "); int divis = getInteger("Enter a divisor: "); cout << divid/divis << endl; cout << endl; } else if (choice == 2) { cout << "You have chosen modulus!" << endl; int divid = getInteger("Enter a dividend: "); int divis = getInteger("Enter a divisor: "); cout << divid%divis << endl; cout << endl; } else if (choice ==3){ cout << "You have chosen to convert!" << endl; int num = getInteger("Enter an int: "); char ch = char(num + '0'); cout << ch << endl; cout << endl; } else if (choice == 4){ cout << "You have chosen to test your TokenScanner implementation. My expectations are... modest." << endl; string loc = "/Users/andrew/Library/Mobile Documents/com~apple~CloudDocs/CS106B/Assignment Practice/res/"; string file = getLine("Enter a file name: "); string path = loc + file; cout << path << endl; infile.open(path.c_str()); TokenScanner scanner(infile); scanner.ignoreWhitespace(); scanner.addWordCharacters("'"); int wordCounter = 0; int sentenceCounter = 0; int syllableCounter = 0; while (scanner.hasMoreTokens()) { string token = scanner.nextToken(); int syl = 0; if (isalpha(token[0]) != 0){ wordCounter++; int b = token.length(); for(int i = 0; i < b; i++){ char w = token[i]; if(is_vowel(w) == true && letter_BeforeIsVowel(token, i) == false && is_LastE(i, b, w) == false){ syl++; syllableCounter++; } } if (syl == 0){ syl++; syllableCounter++; } } if(token[0]== '!' || token[0]== '.' || token[0]== '?' ){ sentenceCounter++; } cout << token << " " << syl << endl; } string intNumWords = integerToString(wordCounter); string intSenWords = integerToString(sentenceCounter); cout << endl; cout << "===============" << endl; cout << endl; cout << "There are " + intNumWords + " words in this file" << endl; cout << "There are " + intSenWords + " sentences in this file" << endl; cout << "There are " << syllableCounter << " syllables in this file" << endl; infile.close(); cout << endl; } } cout << "Exiting......." << endl; return 0; } ////////////////////// //FUNCTION DEFINITIONS ////////////////////// bool is_vowel(char c) { switch(tolower(c)) { case 'a': case 'e': case 'i': case 'o': case 'u': case 'y': return true; default: return false; } } ////////////////////// bool is_NotProc(int x, string strg){ if(is_FirstLetter(x) == false && letter_BeforeIsVowel(strg, x) == false){ return true; } else{ return false; } } ////////////////////// bool is_FirstLetter(int x){ if(x == 0){ return true; } else { return false; } } ////////////////////// bool letter_BeforeIsVowel(string stra, int x){ int prevI = x-1; char cha = stra[prevI]; if(is_vowel(cha) == true){ return true; } else{ return false; } } ////////////////////// bool is_LastE(int x, int u, char c){ if(is_e(c) == true && is_LastLetter(x, u) == true){ return true; }else { return false; } // if last letter in word e, return true // else return false } ////////////////////// bool is_e(char c) { if(tolower(c) == 'e'){ return true; } else { return false; } } ////////////////////// bool is_LastLetter(int x, int y){ if((x+1) == y){ return true; }else{ return false; } }
[ "andrew@valence.io" ]
andrew@valence.io
8aae237759d2d1abd6bc0fba7d8e32855034db96
bbcda48854d6890ad029d5973e011d4784d248d2
/trunk/win/BumpTop Settings/include/wxWidgets/wx/anidecod.h
6e3847614af0691b0b45bf27c728fcbc924828d9
[ "LGPL-2.0-or-later", "WxWindows-exception-3.1", "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
dyzmapl/BumpTop
9c396f876e6a9ace1099b3b32e45612a388943ff
1329ea41411c7368516b942d19add694af3d602f
refs/heads/master
2020-12-20T22:42:55.100473
2020-01-25T21:00:08
2020-01-25T21:00:08
236,229,087
0
0
Apache-2.0
2020-01-25T20:58:59
2020-01-25T20:58:58
null
UTF-8
C++
false
false
2,577
h
///////////////////////////////////////////////////////////////////////////// // Name: wx/anidecod.h // Purpose: wxANIDecoder, ANI reader for wxImage and wxAnimation // Author: Francesco Montorsi // CVS-ID: $Id: anidecod.h 45563 2007-04-21 18:17:50Z VZ $ // Copyright: (c) 2006 Francesco Montorsi // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #ifndef _WX_ANIDECOD_H #define _WX_ANIDECOD_H #include "wx/defs.h" #if wxUSE_STREAMS && wxUSE_ICO_CUR #include "wx/stream.h" #include "wx/image.h" #include "wx/animdecod.h" #include "wx/dynarray.h" class /*WXDLLEXPORT*/ wxANIFrameInfo; WX_DECLARE_EXPORTED_OBJARRAY(wxANIFrameInfo, wxANIFrameInfoArray); WX_DECLARE_EXPORTED_OBJARRAY(wxImage, wxImageArray); // -------------------------------------------------------------------------- // wxANIDecoder class // -------------------------------------------------------------------------- class WXDLLEXPORT wxANIDecoder : public wxAnimationDecoder { public: // constructor, destructor, etc. wxANIDecoder(); ~wxANIDecoder(); virtual wxSize GetFrameSize(unsigned int frame) const; virtual wxPoint GetFramePosition(unsigned int frame) const; virtual wxAnimationDisposal GetDisposalMethod(unsigned int frame) const; virtual long GetDelay(unsigned int frame) const; virtual wxColour GetTransparentColour(unsigned int frame) const; // implementation of wxAnimationDecoder's pure virtuals virtual bool CanRead( wxInputStream& stream ) const; virtual bool Load( wxInputStream& stream ); bool ConvertToImage(unsigned int frame, wxImage *image) const; wxAnimationDecoder *Clone() const { return new wxANIDecoder; } wxAnimationType GetType() const { return wxANIMATION_TYPE_ANI; } private: // frames stored as wxImage(s): ANI files are meant to be used mostly for animated // cursors and thus they do not use any optimization to encode differences between // two frames: they are just a list of images to display sequentially. wxImageArray m_images; // the info about each image stored in m_images. // NB: m_info.GetCount() may differ from m_images.GetCount()! wxANIFrameInfoArray m_info; // this is the wxCURHandler used to load the ICON chunk of the ANI files static wxCURHandler sm_handler; DECLARE_NO_COPY_CLASS(wxANIDecoder) }; #endif // wxUSE_STREAM && wxUSE_ICO_CUR #endif // _WX_ANIDECOD_H
[ "anandx@google.com" ]
anandx@google.com
117cef6364d682c83bcc96fb08cbe5290b148e6b
3391892861a1e1e71af6e414bcdb9fc0df66c62e
/src/libs/test/fixture.cpp
4304ba26442b0882a1cfa5e2bd7d6c3ad7a62acc
[ "Apache-2.0" ]
permissive
jdmclark/gorc
a21208b1d03a85fc5a99fdd51fdad27446cc4767
a03d6a38ab7684860c418dd3d2e77cbe6a6d9fc8
refs/heads/develop
2021-01-21T05:01:26.609783
2020-12-21T00:26:22
2020-12-21T02:34:31
10,290,074
103
10
Apache-2.0
2020-12-21T02:34:33
2013-05-25T21:27:37
C++
UTF-8
C++
false
false
550
cpp
#include "fixture.hpp" #include "log/log.hpp" test::fixture::fixture() { gorc::emplace_log_backend<test_log_backend>( gorc::flag_set<gorc::log_level> { gorc::log_level::error, gorc::log_level::warning, gorc::log_level::info }, log_message_queue); return; } test::fixture::~fixture() { gorc::erase_log_backends(); return; } void test::fixture::setup() { return; } void test::fixture::teardown() { return; }
[ "jon@nullptr.ca" ]
jon@nullptr.ca
38e891c0f2677c6bdb92983e9b52ff318ca5d9d9
4d3400c2ead58e8fc2b25f685c1dbb7a9ce139ff
/libredex/TypeSystem.cpp
4769abde8bc96b4e5974637a679ac22ec3ee29c1
[ "MIT" ]
permissive
shining1984/redex
d05ce218c12be191a9b07073164bf1bbc4a24167
bca8ac9e96068ff84ab2a4c53595f7e53b31ec91
refs/heads/master
2022-11-27T22:51:39.059695
2020-08-05T20:22:03
2020-08-05T20:23:36
285,579,899
1
0
MIT
2020-08-06T13:33:12
2020-08-06T13:33:11
null
UTF-8
C++
false
false
8,200
cpp
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "TypeSystem.h" #include "DexUtil.h" #include "Resolver.h" #include "Timer.h" namespace { void make_instanceof_table(InstanceOfTable& instance_of_table, const ClassHierarchy& hierarchy, const DexType* type, size_t depth = 1) { auto& parent_chain = instance_of_table[type]; const auto cls = type_class(type); if (cls != nullptr) { const auto super = cls->get_super_class(); if (super != nullptr) { const auto& super_chain = instance_of_table.find(super); always_assert(super_chain != instance_of_table.end()); for (const auto& base : super_chain->second) { parent_chain.emplace_back(base); } } } parent_chain.emplace_back(type); always_assert(parent_chain.size() == depth); const auto& children = hierarchy.find(type); if (children == hierarchy.end()) return; for (const auto& child : children->second) { make_instanceof_table(instance_of_table, hierarchy, child, depth + 1); } } void load_interface_children(ClassHierarchy& children, const DexClass* intf) { for (const auto& super_intf : intf->get_interfaces()->get_type_list()) { children[super_intf].insert(intf->get_type()); const auto super_intf_cls = type_class(super_intf); if (super_intf_cls != nullptr) { load_interface_children(children, super_intf_cls); } } } void load_interface_children(ClassHierarchy& children) { g_redex->walk_type_class([&](const DexType* type, const DexClass* cls) { if (!cls->is_external() || !is_interface(cls)) return; load_interface_children(children, cls); }); } void load_interface_children(const Scope& scope, ClassHierarchy& children) { for (const auto& cls : scope) { if (!is_interface(cls)) continue; load_interface_children(children, cls); } load_interface_children(children); } } // namespace const TypeSet TypeSystem::empty_set = TypeSet(); const TypeVector TypeSystem::empty_vec = TypeVector(); TypeSystem::TypeSystem(const Scope& scope) : m_class_scopes(scope) { load_interface_children(scope, m_intf_children); make_instanceof_interfaces_table(); } void TypeSystem::get_all_super_interfaces(const DexType* intf, TypeSet& supers) const { const auto cls = type_class(intf); if (cls == nullptr) return; for (const auto& super : cls->get_interfaces()->get_type_list()) { supers.insert(super); get_all_super_interfaces(super, supers); } } TypeSet TypeSystem::get_all_super_interfaces(const DexType* intf) const { TypeSet supers; get_all_super_interfaces(intf, supers); return supers; } TypeSet TypeSystem::get_local_interfaces(const TypeSet& classes) { // Collect all implemented interfaces. TypeSet implemented_intfs = get_implemented_interfaces(classes); // Remove interfaces that are implemented by other classes too. for (auto it = implemented_intfs.begin(); it != implemented_intfs.end();) { bool keep = true; const auto& implementors = get_implementors(*it); for (const auto& cls : implementors) { if (!classes.count(cls)) { keep = false; break; } } if (keep) { ++it; } else { it = implemented_intfs.erase(it); } } return implemented_intfs; } const VirtualScope* TypeSystem::find_virtual_scope( const DexMethod* meth) const { const auto match = [](const DexMethod* meth1, const DexMethod* meth2) { return meth1->get_name() == meth2->get_name() && meth1->get_proto() == meth2->get_proto(); }; auto type = meth->get_class(); while (type != nullptr) { TRACE(VIRT, 5, "check... %s", SHOW(type)); for (const auto& scope : m_class_scopes.get(type)) { TRACE(VIRT, 5, "check... %s", SHOW(scope->methods[0].first)); if (match(scope->methods[0].first, meth)) { TRACE(VIRT, 5, "return scope"); return scope; } } const auto cls = type_class(type); if (cls == nullptr) break; type = cls->get_super_class(); } return nullptr; } std::vector<const DexMethod*> TypeSystem::select_from( const VirtualScope* scope, const DexType* type) const { std::vector<const DexMethod*> refined_scope; std::unordered_map<const DexType*, DexMethod*> non_child_methods; bool found_root_method = false; for (const auto& method : scope->methods) { if (is_subtype(type, method.first->get_class())) { found_root_method = found_root_method || type == method.first->get_class(); refined_scope.emplace_back(method.first); } else { non_child_methods[method.first->get_class()] = method.first; } } if (!found_root_method) { const auto& parents = parent_chain(type); for (auto parent = parents.rbegin(); parent != parents.rend(); ++parent) { const auto& meth = non_child_methods.find(*parent); if (meth == non_child_methods.end()) continue; refined_scope.emplace_back(meth->second); break; } } return refined_scope; } void TypeSystem::make_instanceof_interfaces_table() { TypeVector no_parents; const auto& hierarchy = m_class_scopes.get_class_hierarchy(); for (const auto& children_it : hierarchy) { const auto parent = children_it.first; const auto parent_cls = type_class(parent); if (parent_cls != nullptr) continue; no_parents.emplace_back(parent); } no_parents.emplace_back(type::java_lang_Object()); for (const auto& root : no_parents) { make_instanceof_table(m_instanceof_table, hierarchy, root); } for (const auto& root : no_parents) { make_interfaces_table(root); } } void TypeSystem::make_interfaces_table(const DexType* type) { const auto cls = type_class(type); if (cls != nullptr) { const auto super = cls->get_super_class(); if (super != nullptr) { const auto& parent_intfs = m_interfaces.find(super); if (parent_intfs != m_interfaces.end()) { m_interfaces[type].insert(parent_intfs->second.begin(), parent_intfs->second.end()); } } for (const auto& intf : cls->get_interfaces()->get_type_list()) { m_interfaces[type].insert(intf); get_all_super_interfaces(intf, m_interfaces[type]); } } const auto& hierarchy = m_class_scopes.get_class_hierarchy(); const auto& children = hierarchy.find(type); if (children == hierarchy.end()) return; for (const auto& child : children->second) { make_interfaces_table(child); } } void TypeSystem::select_methods(const VirtualScope& scope, const std::unordered_set<DexType*>& types, std::unordered_set<DexMethod*>& methods) const { TRACE(VIRT, 1, "select_methods make filter"); std::unordered_set<DexType*> filter; filter.insert(types.begin(), types.end()); TRACE(VIRT, 1, "select_methods make type_method map"); std::unordered_map<const DexType*, DexMethod*> type_method; for (const auto& vmeth : scope.methods) { const auto meth = vmeth.first; if (!meth->is_def()) continue; type_method[meth->get_class()] = meth; } TRACE(VIRT, 1, "select_methods walk hierarchy"); while (!filter.empty()) { const auto type = *filter.begin(); filter.erase(filter.begin()); TRACE(VIRT, 1, "check... %s", SHOW(type)); if (!is_subtype(scope.type, type)) continue; const auto& meth = type_method.find(type); if (meth != type_method.end()) { methods.insert(meth->second); continue; } const auto super = type_class(type)->get_super_class(); if (super == nullptr) continue; if (types.count(super) > 0) continue; filter.insert(super); } } void TypeSystem::select_methods(const InterfaceScope& scope, const std::unordered_set<DexType*>& types, std::unordered_set<DexMethod*>& methods) const { for (const auto& virt_scope : scope) { select_methods(*virt_scope, types, methods); } }
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
a71c7c4a0c5740afaaae2d649e5da1cb1c9460e1
1068a1afb20ecee725e44f66ac14f611d694718a
/jac1.cxx
c12701c48c89e93ef3f10da850dd2cb231ef6bbf
[]
no_license
rfeynman/jklib
926c06015e81dc4fef91955272985177d8e9c7a0
6b0f467b37db22d24fe32e3c3d8b28ca61016f33
refs/heads/master
2020-03-23T13:14:51.080552
2018-07-19T16:57:10
2018-07-19T16:57:10
141,607,949
0
0
null
null
null
null
UTF-8
C++
false
false
2,498
cxx
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <unistd.h> main(int argc, char ** argv) { double sigma1[4]={ 2.1628231e-05 , 1.6919944e-06 , -5.8866938e-07 , -3.5349456e-06 }; double sigma2[4]={ 1.6919944e-06 , 6.6981154e-07 , 3.4054769e-06 , -1.8863767e-08 }; double sigma3[4]={ -5.8866938e-07 , 3.4054769e-06 , 2.2354493e-05 , 1.7614396e-06 }; double sigma4[4]={ -3.5349456e-06 , -1.8863767e-08 , 1.7614396e-06 , 7.0839148e-07 }; double * a[5]; for(int i=0; i< 5; i++) a[i]=new double[5]; } void jacobi(double **a,int n,double d[],double **v,int & nrot) { int j,iq,ip,i; double tresh,theta,tau,t,sm,s,h,g,c,*b,*z,*vector(); double * b = new double[n+1]; double * z = new double[n+1]; for (ip=1;ip<=n;ip++) { for (iq=1;iq<=n;iq++) v[ip][iq]=0.0; v[ip][ip]=1.0; } for (ip=1;ip<=n;ip++) { b[ip]=d[ip]=a[ip][ip]; z[ip]=0.0; } nrot=0; for (i=1;i<=50;i++) { sm=0.0; for (ip=1;ip<=n-1;ip++) { for (iq=ip+1;iq<=n;iq++) sm += fabs(a[ip][iq]); } if (sm == 0.0) { delete [] z; delete [] b; return; } if (i < 4) tresh=0.2*sm/(n*n); else tresh=0.0; for (ip=1;ip<=n-1;ip++) { for (iq=ip+1;iq<=n;iq++) { g=100.0*fabs(a[ip][iq]); if (i > 4 && fabs(d[ip])+g == fabs(d[ip]) && fabs(d[iq])+g == fabs(d[iq])) a[ip][iq]=0.0; else if (fabs(a[ip][iq]) > tresh) { h=d[iq]-d[ip]; if (fabs(h)+g == fabs(h)) t=(a[ip][iq])/h; else { theta=0.5*h/(a[ip][iq]); t=1.0/(fabs(theta)+sqrt(1.0+theta*theta)); if (theta < 0.0) t = -t; } c=1.0/sqrt(1+t*t); s=t*c; tau=s/(1.0+c); h=t*a[ip][iq]; z[ip] -= h; z[iq] += h; d[ip] -= h; d[iq] += h; a[ip][iq]=0.0; for (j=1;j<=ip-1;j++) { double g=a[i][j]; double h=a[k][l]; a[i][j]=g-s*(h+g*tau); a[k][l]=h+s*(g-h*tau); } for (j=ip+1;j<=iq-1;j++) { double g=a[i][j]; double h=a[k][l]; a[i][j]=g-s*(h+g*tau); a[k][l]=h+s*(g-h*tau); } for (j=iq+1;j<=n;j++) { double g=a[i][j]; double h=a[k][l]; a[i][j]=g-s*(h+g*tau); a[k][l]=h+s*(g-h*tau); } for (j=1;j<=n;j++) { double g=a[i][j]; double h=a[k][l]; a[i][j]=g-s*(h+g*tau); a[k][l]=h+s*(g-h*tau); } ++nrot; } } } for (ip=1;ip<=n;ip++) { b[ip] += z[ip]; d[ip]=b[ip]; z[ip]=0.0; } } fprintf(stderr,"Too many iterations in routine JACOBI"); }
[ "wedwrd@gmail.com" ]
wedwrd@gmail.com
02a3f751f220b9a49433695bb5faf4b5ab5d2bc1
fc5c673d30d9fd00de6c6512f2e5e2f8d95a9152
/2 labs/task4/GeneratePrimeNumbersSetTest/GeneratePrimeNumbersSetTest.cpp
74791cfbe610126442f8ceabe5b8e75c37e38894
[]
no_license
VladimirSovkov/OOP
7ea50858bae00c1b7da161bdf68781430779c55d
e74a34d0821976a6d1a88699909d8378e5e4d5f0
refs/heads/master
2021-01-05T14:15:48.318457
2020-07-14T09:47:52
2020-07-14T09:47:52
241,047,511
0
0
null
null
null
null
UTF-8
C++
false
false
1,671
cpp
#define CATCH_CONFIG_MAIN #include "../../../catch2/catch.hpp" #include "../GeneratePrimeNumbersSet/GeneratePrimeNumbersSet.h" TEST_CASE("checking range in which there are no prime numbers") { std::set<int> outputValue = GeneratePrimeNumbersSet(0); std::set<int> sample{}; CHECK(sample == outputValue); outputValue = GeneratePrimeNumbersSet(1); CHECK(sample == outputValue); } TEST_CASE("checking that the output of primes is correct") { std::set<int> outputValue = GeneratePrimeNumbersSet(10); std::set<int> sample{ 2, 3, 5, 7 }; CHECK(sample == outputValue); outputValue = GeneratePrimeNumbersSet(100); sample = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 }; CHECK(sample == outputValue); outputValue = GeneratePrimeNumbersSet(30); sample = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; CHECK(sample == outputValue); } #if !_DEBUG TEST_CASE("check on a large range the number of numbers") { std::set<int> outputValue = GeneratePrimeNumbersSet(100000000); size_t sizeSet = outputValue.size(); size_t sample = 5761455; CHECK(sample == sizeSet); } #endif TEST_CASE("check for the creation of a vector point to prime numbers in the form of an index") { std::vector<bool> outputSet = CreateVectorPointToPrimeNumber(1); std::vector<bool> sample{ false, false }; CHECK(sample == outputSet); outputSet = CreateVectorPointToPrimeNumber(0); sample = { false }; CHECK(sample == outputSet); outputSet = CreateVectorPointToPrimeNumber(-1); sample = {}; CHECK(sample == outputSet); outputSet = CreateVectorPointToPrimeNumber(2); sample = {false, false, true}; CHECK(sample == outputSet); }
[ "vladimir.sovkov@yandex.ru" ]
vladimir.sovkov@yandex.ru
3b8e44e73f22900f55d4b33df45ac7ceef9a4f79
57ac9f29ef44b5463e07fd69ee63cf992c23b9ff
/build-CheckersClientWiktor-Desktop_Qt_5_9_1_GCC_64bit-Release/moc_roomwindow.cpp
50e2854e9741e006f8d8d93ebbec172fd3919d81
[]
no_license
PennyBun/BSR-chequers-client
deb45cf0ce14bd4e8747f764bccbf0454738027b
3d406f70d4589400199bb6928af87add5297f8e6
refs/heads/master
2021-01-16T18:37:24.031007
2017-08-20T16:17:00
2017-08-20T16:17:00
100,100,144
0
0
null
null
null
null
UTF-8
C++
false
false
5,824
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'roomwindow.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.9.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../CheckersClientWiktor/roomwindow.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'roomwindow.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.9.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_RoomWindow_t { QByteArrayData data[9]; char stringdata0[136]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_RoomWindow_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_RoomWindow_t qt_meta_stringdata_RoomWindow = { { QT_MOC_LITERAL(0, 0, 10), // "RoomWindow" QT_MOC_LITERAL(1, 11, 19), // "refreshButtonSignal" QT_MOC_LITERAL(2, 31, 0), // "" QT_MOC_LITERAL(3, 32, 6), // "invite" QT_MOC_LITERAL(4, 39, 4), // "user" QT_MOC_LITERAL(5, 44, 6), // "logout" QT_MOC_LITERAL(6, 51, 28), // "on_refreshPushButton_clicked" QT_MOC_LITERAL(7, 80, 27), // "on_logoutPushButton_clicked" QT_MOC_LITERAL(8, 108, 27) // "on_invitePushButton_clicked" }, "RoomWindow\0refreshButtonSignal\0\0invite\0" "user\0logout\0on_refreshPushButton_clicked\0" "on_logoutPushButton_clicked\0" "on_invitePushButton_clicked" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_RoomWindow[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 6, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 3, // signalCount // signals: name, argc, parameters, tag, flags 1, 0, 44, 2, 0x06 /* Public */, 3, 1, 45, 2, 0x06 /* Public */, 5, 0, 48, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 6, 0, 49, 2, 0x08 /* Private */, 7, 0, 50, 2, 0x08 /* Private */, 8, 0, 51, 2, 0x08 /* Private */, // signals: parameters QMetaType::Void, QMetaType::Void, QMetaType::QString, 4, QMetaType::Void, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::Void, 0 // eod }; void RoomWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { RoomWindow *_t = static_cast<RoomWindow *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->refreshButtonSignal(); break; case 1: _t->invite((*reinterpret_cast< QString(*)>(_a[1]))); break; case 2: _t->logout(); break; case 3: _t->on_refreshPushButton_clicked(); break; case 4: _t->on_logoutPushButton_clicked(); break; case 5: _t->on_invitePushButton_clicked(); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); void **func = reinterpret_cast<void **>(_a[1]); { typedef void (RoomWindow::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&RoomWindow::refreshButtonSignal)) { *result = 0; return; } } { typedef void (RoomWindow::*_t)(QString ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&RoomWindow::invite)) { *result = 1; return; } } { typedef void (RoomWindow::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&RoomWindow::logout)) { *result = 2; return; } } } } const QMetaObject RoomWindow::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_RoomWindow.data, qt_meta_data_RoomWindow, qt_static_metacall, nullptr, nullptr} }; const QMetaObject *RoomWindow::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *RoomWindow::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_RoomWindow.stringdata0)) return static_cast<void*>(const_cast< RoomWindow*>(this)); return QDialog::qt_metacast(_clname); } int RoomWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 6) qt_static_metacall(this, _c, _id, _a); _id -= 6; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 6) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 6; } return _id; } // SIGNAL 0 void RoomWindow::refreshButtonSignal() { QMetaObject::activate(this, &staticMetaObject, 0, nullptr); } // SIGNAL 1 void RoomWindow::invite(QString _t1) { void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 1, _a); } // SIGNAL 2 void RoomWindow::logout() { QMetaObject::activate(this, &staticMetaObject, 2, nullptr); } QT_WARNING_POP QT_END_MOC_NAMESPACE
[ "borowiktor@gmail.com" ]
borowiktor@gmail.com
905cac36d4acf2a58f233c047ed4ccd66ca91ada
7ccccd69629354409566ba01d93572a4da0ba364
/Desarrollo/BulletTest/BulletTest/Network/NetworkDebugger.h
1ffd8018c5d7e4836ff14d932d15314d0c2232e9
[]
no_license
Juliyo/LastBullet
eac779d78f0e8d62eb71ac4ecaa838e828825736
4f93b5260eaba275aa47c3ed13a93e7d7e60c0e9
refs/heads/master
2021-09-11T12:27:29.583652
2018-01-18T14:14:52
2018-01-18T14:14:52
104,806,970
0
0
null
null
null
null
UTF-8
C++
false
false
640
h
#pragma once #include <DebugMarks.h> #include <map> #include <Enemy.h> #include <Estructuras.h> class NetworkDebugger{ public: NetworkDebugger(); ~NetworkDebugger(); bool addDebugMark(int entID); bool removeDebugMark(int entID); DebugMarks* getDebugMark(int entID); void sendSyncPackage(const RakNet::RakNetGUID& guid, unsigned char message); void receivedSyncPacket(const TSyncMessage& sync); void restartPacketsCount(); int getPacketCount(unsigned char message); private: //Contador de paquetes std::unordered_map<unsigned char, int> m_counter; //Enemy ID, DebugMark std::unordered_map<int, DebugMarks*> m_marks; };
[ "julio17795@hotmail.com" ]
julio17795@hotmail.com
68e98a66787fbe9d0d585e5d8c1714d7754c5c4b
4fa9b9b3d0d733a4946984005980b000584cd75d
/CPP/ObjectOrientedProgramming/ObjectOrientedProgramming/Account.cpp
2e8a612594795ddcba72451121e9ada2f0c60bd4
[]
no_license
AdPy97/Projekty
2e8567226973acdfbc0f629cf96863dce2480007
d02afab4452b15fec72baccd00c856e643b7deb7
refs/heads/master
2020-09-17T07:47:08.492252
2019-11-25T15:16:38
2019-11-25T15:16:38
224,030,552
0
0
null
null
null
null
UTF-8
C++
false
false
241
cpp
#include "Account.h" void Account::set_Name(std::string name) { Name = name; } std::string Account::get_Name() { return Name; } void Account::set_Balance(float bal) { Balance = bal; } float Account::get_Balance() { return Balance; }
[ "remekgc@gmail.com" ]
remekgc@gmail.com
ad46e6b6b1a31160d8e2fb2859419d751b244f2e
18df702758fa034d30f7e3573e9a986a93b5ba88
/external/rockx/demo/command_line_demo/rockx_carplate_demo/rockx_carplate_demo.cpp
de5e8c5407af985f6f182b7c8be1acc411110aa9
[ "BSD-3-Clause" ]
permissive
qiaoweibiao/merged
e8eedb87c73f12436fb26b8058ea295fc3e703c0
3b016b1330c2a148753d00c542aaa39e7f86e726
refs/heads/master
2023-08-25T01:53:59.791416
2021-10-25T19:22:50
2021-10-25T19:22:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,800
cpp
/**************************************************************************** * * Copyright (c) 2017 - 2019 by Rockchip Corp. All rights reserved. * * The material in this file is confidential and contains trade secrets * of Rockchip Corporation. This is proprietary information owned by * Rockchip Corporation. No part of this work may be disclosed, * reproduced, copied, transmitted, or used in any way for any purpose, * without the express written permission of Rockchip Corporation. * *****************************************************************************/ #include <stdio.h> #include <memory.h> #include <sys/time.h> #include <stdlib.h> #include "rockx.h" int main(int argc, char** argv) { rockx_ret_t ret; const char *img_path = argv[1]; struct timeval tv; // read image rockx_image_t input_image; rockx_image_read(img_path, &input_image, 1); rockx_handle_t carplate_det_handle; rockx_handle_t carplate_align_handle; rockx_handle_t carplate_recog_handle; ret = rockx_create(&carplate_det_handle, ROCKX_MODULE_CARPLATE_DETECTION, nullptr, 0); if (ret != ROCKX_RET_SUCCESS) { printf("init rockx module ROCKX_MODULE_CARPLATE_DETECTION error %d\n", ret); return -1; } ret = rockx_create(&carplate_align_handle, ROCKX_MODULE_CARPLATE_ALIGN, nullptr, 0); if (ret != ROCKX_RET_SUCCESS) { printf("init rockx module ROCKX_MODULE_CARPLATE_ALIGN error %d\n", ret); return -1; } ret = rockx_create(&carplate_recog_handle, ROCKX_MODULE_CARPLATE_RECOG, nullptr, 0); if (ret != ROCKX_RET_SUCCESS) { printf("init rockx module ROCKX_MODULE_OBJECT_DETECTION error %d\n", ret); return -1; } rockx_object_array_t carplate_array; memset(&carplate_array, 0, sizeof(rockx_object_array_t)); // detect carplate ret = rockx_carplate_detect(carplate_det_handle, &input_image, &carplate_array, nullptr); if (ret != ROCKX_RET_SUCCESS) { printf("rockx_carplate_detect error %d\n", ret); return -1; } for (int i = 0; i < carplate_array.count; i++) { // create rockx_carplate_align_result_t for store result rockx_carplate_align_result_t result; memset(&result, 0, sizeof(rockx_carplate_align_result_t)); printf("(%d %d %d %d) %f\n", carplate_array.object[i].box.left, carplate_array.object[i].box.top, carplate_array.object[i].box.right, carplate_array.object[i].box.bottom, carplate_array.object[i].score); // carplate_fmapping_ ret = rockx_carplate_align(carplate_align_handle, &input_image, &carplate_array.object[i].box, &result); if (ret != ROCKX_RET_SUCCESS) { printf("rockx_carplate_align error %d\n", ret); return -1; } // save image rockx_image_write("./refined_img.jpg", &(result.aligned_image)); // recognize carplate number rockx_carplate_recog_result_t recog_result; ret = rockx_carplate_recognize(carplate_recog_handle, &(result.aligned_image), &recog_result); // remember release aligned image rockx_image_release(&(result.aligned_image)); if (ret != ROCKX_RET_SUCCESS) { printf("rockx_face_detect error %d\n", ret); return -1; } // process result char platename[32]; memset(platename, 0, 32); for(int n = 0; n < recog_result.length; n++) { strcat(platename, CARPLATE_RECOG_CODE[recog_result.namecode[n]]); } printf("carplate: %s\n", platename); } // release rockx_image_release(&input_image); rockx_destroy(carplate_det_handle); rockx_destroy(carplate_align_handle); rockx_destroy(carplate_recog_handle); }
[ "geierconstantinabc@gmail.com" ]
geierconstantinabc@gmail.com
72006e116ca881217dc243e0ba599defaadd903d
b7e30c4413ffc9c29a9f1543648efa393a390666
/libraries/utilities/include/besio/utilities/parallel_markers.hpp
167059201956d6083cec48d1a39d53e61dc3201b
[ "MIT" ]
permissive
apolloaotc/src
3daf159f89dd13e30ab858ce0fcf291c7ecd153b
a4fe59d8322d2ab4eef37a4c7af8db573d230b3d
refs/heads/master
2022-11-19T05:21:54.749513
2020-06-08T03:34:01
2020-06-08T03:34:01
270,195,262
0
0
MIT
2020-07-21T01:26:09
2020-06-07T04:47:52
C++
UTF-8
C++
false
false
1,515
hpp
/** * @file * @copyright defined in bes/LICENSE.txt */ #pragma once #include <boost/range/combine.hpp> #include <boost/range/adaptor/filtered.hpp> #include <boost/range/adaptor/transformed.hpp> namespace besio { namespace utilities { /** * @brief Return values in DataRange corresponding to matching Markers * * Takes two parallel ranges, a Data range containing data values, and a Marker range containing markers on the * corresponding data values. Returns a new Data range containing only the values corresponding to markers which match * markerValue * * For example: * @code{.cpp} * vector<char> data = {'A', 'B', 'C'}; * vector<bool> markers = {true, false, true}; * auto markedData = FilterDataByMarker(data, markers, true); * // markedData contains {'A', 'C'} * @endcode */ template<typename DataRange, typename MarkerRange, typename Marker> DataRange filter_data_by_marker(DataRange data, MarkerRange markers, const Marker& markerValue) { auto remove_mismatched_markers = boost::adaptors::filtered([&markerValue](const auto& tuple) { return boost::get<0>(tuple) == markerValue; }); auto ToData = boost::adaptors::transformed([](const auto& tuple) { return boost::get<1>(tuple); }); // Zip the ranges together, filter out data with markers that don't match, and return the data without the markers auto range = boost::combine(markers, data) | remove_mismatched_markers | ToData; return {range.begin(), range.end()}; } }} // namespace besio::utilities
[ "caokun8008@gmail.com" ]
caokun8008@gmail.com
bc0d03080406560b6a7548ed5fcf1a9c6344f05c
40ef1585129853ca12585f8d352c7034992089bb
/jni/Fighter/src/Personaje/Condicion.cpp
a0bb3e2d1555eed05f946361f670060687fe9035
[]
no_license
Turupawn/FighterAndroid
5f8a48954b813a8e1dc7fda55aafb085a9590edf
cafa8d22dbf888c89d27917671bc34152fe85622
refs/heads/master
2021-01-17T09:42:12.916359
2012-08-02T01:11:51
2012-08-02T01:11:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,136
cpp
#include "Personaje/Condicion.h" Condicion::Condicion(stringw variable,stringw comparacion,int entero,bool personaje_contrario) { tipo=L"entero"; this->variable=variable; this->comparacion=comparacion; this->entero=entero; this->personaje_contrario=personaje_contrario; } Condicion::Condicion(stringw variable,stringw comparacion,stringw cadena,bool personaje_contrario) { tipo=L"cadena"; this->variable=variable; this->comparacion=comparacion; this->cadena=cadena; this->personaje_contrario=personaje_contrario; } bool Condicion::comparar(int c) { //cout<<comparacion.c_str()[0]<<endl;cout.flush(); if(comparacion=="=") return c==entero; if(comparacion=="!=") return c!=entero; if(comparacion=="<") return c<entero; if(comparacion==">") return c>entero; if(comparacion=="<=") return c<=entero; if(comparacion==">=") return c>=entero; return false; } bool Condicion::comparar(stringw s) { if(comparacion=="=") return s==cadena; if(comparacion=="!=") return s!=cadena; return false; }
[ "antares_43@hotmail.com" ]
antares_43@hotmail.com
7e178a625ac652a11a8b83840fb7a29f514ba1c4
86849c581c7844d3ed83f54e268bb271631f2fb7
/main.cpp
08a5fb79be8d1ac00a44dc45b68db71184c74a7f
[ "MIT" ]
permissive
andrea993/SPR_Denoiser
e68def72e31cc46a1accf263081159c83a2d7dd5
9b8f6bca9bb11922b7b6a257996d0b8f217851fd
refs/heads/master
2023-05-27T07:28:12.463970
2021-06-10T16:29:49
2021-06-10T16:29:49
265,279,871
0
1
MIT
2020-06-02T20:50:38
2020-05-19T15:03:38
C++
UTF-8
C++
false
false
672
cpp
#include <iostream> #include <cstdlib> #include "denoiser.hpp" #include <eigen3/Eigen/Dense> std::istream& operator>>(std::istream& is, Eigen::VectorXd& v) { int size; is >> size; v.resize(size); for(int i = 0; i < size; ++i) { is >> v(i); } return is; } int main() { Denoiser den; while(true) { Eigen::Vector2d in_sample; std::cin >> in_sample(0) >> in_sample(1); if(std::cin.fail()) { break; } auto out_sample = den.GetSmp(in_sample); std::cout << out_sample(0) << ' ' << out_sample(1) << '\n'; }; return EXIT_SUCCESS; }
[ "andrea69x@hotmail.it" ]
andrea69x@hotmail.it
a01f33ca35ed4f5f3a3a89af0b0d13779836af18
f53267d2223a023e1c643a648dd9bed4f1e58c53
/software/C64/RISCV/source/ENODE.cpp
dcfb9169430a8e15459cec73fe770358a3d4adb4
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
robfinch/Cores
9eec2c88ba7c2495ed5c1bdde9ff1fd82436a6cd
0015669674bafdc4eff56e816cf714c975536fc3
refs/heads/master
2023-07-06T21:07:31.639981
2023-06-28T23:05:20
2023-06-28T23:05:20
13,174,959
58
27
null
2017-08-12T12:03:51
2013-09-28T15:03:00
C++
UTF-8
C++
false
false
80,518
cpp
// ============================================================================ // __ // \\__/ o\ (C) 2017-2020 Robert Finch, Waterloo // \ __ / All rights reserved. // \/_// robfinch<remove>@finitron.ca // || // // CC64 - 'C' derived language compiler // - 64 bit CPU // // This source file is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This source 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 program. If not, see <http://www.gnu.org/licenses/>. // // ============================================================================ // #include "stdafx.h" void swap_nodes(ENODE *node) { ENODE *temp; temp = node->p[0]; node->p[0] = node->p[1]; node->p[1] = temp; } bool ENODE::IsEqualOperand(Operand *a, Operand *b) { return (Operand::IsEqual(a, b)); }; char ENODE::fsize() { switch (etype) { case bt_float: return ('d'); case bt_double: return ('d'); case bt_triple: return ('t'); case bt_quad: return ('q'); default: return ('d'); } } bool ENODE::HasAssignop() { if (this == nullptr) return (false); if (nodetype == en_asadd || nodetype == en_asadd || nodetype == en_asdiv || nodetype == en_asdivu || nodetype == en_asmod || nodetype == en_asmodu || nodetype == en_asmul || nodetype == en_asmulu || nodetype == en_asor || nodetype == en_asand || nodetype == en_asxor || nodetype == en_assub || nodetype == en_assign || nodetype == en_fcall || nodetype == en_ifcall ) return (true); if (p[0]->HasAssignop()) return (true); if (p[1]->HasAssignop()) return(true); if (p[2]->HasAssignop()) return (true); return(false); } bool ENODE::HasCall() { if (this == nullptr) return (false); if (nodetype == en_fcall) return (true); if (p[0]->HasCall()) return (true); if (p[1]->HasCall()) return (true); if (p[1]->HasCall()) return (true); return (false); } int64_t ENODE::GetReferenceSize() { switch (nodetype) /* get load size */ { case en_ref: case en_fieldref: return (tp->size); case en_fpregvar: if (tp) return(tp->size); else return (sizeOfFPD); case en_tempref: case en_regvar: return (sizeOfWord); // return node->esize; } return (sizeOfWord); } // return the natural evaluation size of a node. int ENODE::GetNaturalSize() { int siz0, siz1; if (this == NULL) return 0; switch (nodetype) { case en_fieldref: return (tp->size); case en_icon: if (i >= -128 && i < 128) return (1); if (-32768 <= i && i <= 32767) return (2); if (-2147483648LL <= i && i <= 2147483647LL) return (4); return (sizeOfWord); case en_fcon: return (tp->precision / 16); case en_tcon: return (6); case en_labcon: case en_clabcon: case en_cnacon: case en_nacon: case en_autocon: case en_classcon: case en_tempref: case en_cbw: case en_cubw: case en_ccw: case en_cucw: case en_chw: case en_cuhw: case en_cbu: case en_ccu: case en_chu: case en_cubu: case en_cucu: case en_cuhu: case en_ccwp: case en_cucwp: case en_sxb: case en_sxc: case en_sxh: return (sizeOfWord); case en_fcall: case en_regvar: case en_fpregvar: if (tp) return (tp->size); else return (sizeOfWord); case en_autofcon: return (sizeOfWord); case en_ref: return (tp->size); case en_cbc: case en_cbh: return (4); case en_cch: return (4); case en_autovcon: case en_tempfpref: if (tp) return (tp->precision / 8); else return (sizeOfWord); case en_not: case en_compl: case en_uminus: case en_assign: return p[0]->GetNaturalSize(); case en_fadd: case en_fsub: case en_fmul: case en_fdiv: case en_fsadd: case en_fssub: case en_fsmul: case en_fsdiv: case en_vadd: case en_vsub: case en_vmul: case en_vdiv: case en_vadds: case en_vsubs: case en_vmuls: case en_vdivs: case en_add: case en_sub: case en_ptrdif: case en_mul: case en_mulu: case en_div: case en_udiv: case en_mod: case en_umod: case en_and: case en_or: case en_xor: case en_asl: case en_shl: case en_shlu: case en_shr: case en_shru: case en_asr: case en_asrshu: case en_feq: case en_fne: case en_flt: case en_fle: case en_fgt: case en_fge: case en_eq: case en_ne: case en_lt: case en_le: case en_gt: case en_ge: case en_ult: case en_ule: case en_ugt: case en_uge: case en_land: case en_lor: case en_land_safe: case en_lor_safe: case en_asadd: case en_assub: case en_asmul: case en_asmulu: case en_asdiv: case en_asdivu: case en_asmod: case en_asmodu: case en_asand: case en_asor: case en_asxor: case en_aslsh: case en_asrsh: siz0 = p[0]->GetNaturalSize(); siz1 = p[1]->GetNaturalSize(); if (siz1 > siz0) return (siz1); else return (siz0); case en_void: case en_cond: case en_safe_cond: return (p[1]->GetNaturalSize()); case en_bchk: return (p[0]->GetNaturalSize()); case en_chk: return 8; case en_q2i: case en_t2i: return (sizeOfWord); case en_i2d: return (sizeOfWord); case en_i2t: case en_d2t: return (sizeOfFPT); case en_i2q: case en_d2q: case en_t2q: return (sizeOfFPQ); case en_object_list: return (p[0]->GetNaturalSize()); case en_addrof: return (sizeOfPtr); default: printf("DIAG - natural size error %d.\n", nodetype); break; } return (0); } bool ENODE::IsBitfield() { return (nodetype == en_fieldref); } bool ENODE::IsSameType(ENODE *node1, ENODE *node2) { if (node1 == nullptr && node2 == nullptr) return (true); // If we have a null pointer for the expression it may be a // void pointer. if (node1 == nullptr || node2 == nullptr) return (true); if (node1->nodetype == en_icon && node2->nodetype == en_icon) return (true); return (TYP::IsSameType(node1->tp, node2->tp, false)); } // // equalnode will return 1 if the expressions pointed to by // node1 and node2 are equivalent. // bool ENODE::IsEqual(ENODE *node1, ENODE *node2, bool lit) { ENODE *ep1, *ep2; if (node1 == nullptr && node2 == nullptr) return (true); if (!lit) { if (node1 == nullptr || node2 == nullptr) { return (false); } } else { if (node1 == nullptr || node2 == nullptr) return (true); } if (node1->nodetype != node2->nodetype) { return (false); } switch (node1->nodetype) { case en_fcon: return (Float128::IsEqual(&node1->f128, &node2->f128)); // return (node1->f == node2->f); case en_regvar: return (node1->rg == node2->rg); case en_fpregvar: return (node1->rg == node2->rg); case en_tempref: case en_tempfpref: case en_icon: case en_labcon: case en_classcon: // Check type ? case en_autocon: case en_autovcon: case en_autofcon: { return (node1->i == node2->i); } case en_nacon: { return (node1->sp->compare(*node2->sp) == 0); } case en_cnacon: return (node1->sp->compare(*node2->sp) == 0); case en_aggregate: return (IsEqual(node1->p[0], node2->p[0], lit)); case en_list: for (ep1 = node1->p[2], ep2 = node2->p[2]; ep1 && ep2; ep1 = ep1->p[2], ep2 = ep2->p[2]) { if (!IsEqual(ep1->p[0], ep2->p[0], lit)) return (false); if (!IsEqual(ep1->p[1], ep2->p[1], lit)) return (false); } if (ep1 != nullptr && ep2 != nullptr) return (true); return(false); default: if (!IsEqual(node1->p[0], node2->p[0], lit)) return (false); if (!IsEqual(node1->p[1], node2->p[1], lit)) return (false); if (!IsEqual(node1->p[2], node2->p[2], lit)) return (false); return (true); //if (IsLValue(node1) && IsEqual(node1->p[0], node2->p[0])) { // // if( equalnode(node1->p[0], node2->p[0]) ) // return (true); //} } return (false); } // For purposes of optimization we only care about cloning the node being // worked on, not the other nodes that are connected to it. So, clone doesn't // do a full clone in order to improve the compiler's performance. A real // clone would clone the whole tree, but it's not required in the current // compiler. ENODE *ENODE::Clone() { ENODE *temp; if (this == nullptr) return (ENODE *)nullptr; temp = allocEnode(); memcpy(temp, this, sizeof(ENODE)); // copy all the fields // temp->p[0] = p[0]->Clone(); // temp->p[1] = p[1]->Clone(); // temp->p[2] = p[2]->Clone(); return (temp); } // ============================================================================ // ============================================================================ // Parsing // ============================================================================ // ============================================================================ // Assign a type to a whole list. bool ENODE::AssignTypeToList(TYP *tp) { ENODE *ep; bool isConst = true; TYP *btp; int ne, cnt; if (nodetype != en_aggregate) return (false); esize = 0; this->tp = tp; this->tp->isConst = isConst; this->esize = tp->size; if (tp->isArray) { ne = tp->numele; cnt = 0; btp = tp->GetBtp(); for (ep = p[0]->p[2]; ep; ep = ep->p[2]) { cnt++; ep->tp = btp; ep->tp->isConst = isConst; ep->esize = btp->size; //if (!ep->tp->isConst) // isConst = false; if (btp->isArray) { if (ep->nodetype == en_aggregate) { if (!ep->AssignTypeToList(btp)) isConst = false; } } else if (btp->IsAggregateType()) { if (ep->nodetype == en_aggregate) { if (!ep->AssignTypeToList(btp)) isConst = false; } } } //if (cnt < tp->numele) { // esize += (tp->numele - cnt) * btp->size; //} } else if (tp->IsAggregateType()) { SYM *thead; thead = SYM::GetPtr(tp->lst.GetHead()); for (ep = p[0]->p[2]; thead && ep; ) { ep->tp = thead->tp; ep->tp->isConst = isConst; ep->esize = thead->tp->size; if (thead->tp->IsAggregateType()) { if (ep->nodetype == en_aggregate) { if (!ep->AssignTypeToList(thead->tp)) isConst = false; } } ep = ep->p[2]; thead = SYM::GetPtr(thead->next); } } return (isConst); } // ============================================================================ // ============================================================================ // Optimization // ============================================================================ // ============================================================================ // repexpr will replace all allocated references within an expression // with tempref nodes. void ENODE::repexpr() { CSE *csp; ENODE *ep; if (this == nullptr) return; switch (nodetype) { case en_fcon: case en_tempfpref: if ((csp = currentFn->csetbl->Search(this)) != nullptr) { csp->isfp = TRUE; //**** a kludge if (csp->reg > 0) { nodetype = en_fpregvar; rg = csp->reg; } } break; // Autofcon resolve to *pointers* which are stored in integer registers. case en_autofcon: if ((csp = currentFn->csetbl->Search(this)) != nullptr) { csp->isfp = FALSE; //**** a kludge if (csp->reg > 0) { nodetype = en_fpregvar; rg = csp->reg; } } break; /* if( (csp = SearchCSEList(node)) != NULL ) { if( csp->reg > 0 ) { node->nodetype = en_fpregvar; node->i = csp->reg; } } break; */ case en_icon: case en_nacon: case en_labcon: case en_autovcon: case en_autocon: case en_classcon: case en_cnacon: case en_clabcon: case en_tempref: if ((csp = currentFn->csetbl->Search(this)) != NULL) { if (!csp->voidf) { if (csp->reg > 0) { nodetype = en_regvar; rg = csp->reg; } } } break; /* case en_c_ref: case en_uc_ref: case en_w_ref: case en_wp_ref: if (p[0]->IsAutocon()) { if ((csp = currentFn->csetbl->Search(this)) != NULL) { if (!csp->voidf) { if (csp->reg > 0) { new_nodetype = en_regvar; rg = csp->reg; p[0]->repexpr(); } else p[0]->repexpr(); } else p[0]->repexpr(); //while (csp = currentFn->csetbl->SearchNext(this)) { // if (!csp->voidf) { // if (csp->reg > 0) { // new_nodetype = en_regvar; // rg = csp->reg; // } // else // p[0]->repexpr(); // } //} } else p[0]->repexpr(); break; } p[0]->repexpr(); p[1]->repexpr(); break; */ case en_ref: case en_fieldref: if ((csp = currentFn->csetbl->Search(this)) != NULL) { if (csp->reg > 0) { nodetype = en_regvar; rg = csp->reg; } else p[0]->repexpr(); } else p[0]->repexpr(); break; case en_cbc: case en_cubw: case en_cbh: case en_cucw: case en_cbw: case en_cuhw: case en_cbu: case en_ccu: case en_chu: case en_cubu: case en_cucu: case en_cuhu: case en_ccwp: case en_cucwp: case en_cch: case en_ccw: case en_chw: case en_uminus: case en_abs: case en_sxb: case en_sxh: case en_sxc: case en_not: case en_compl: case en_chk: p[0]->repexpr(); p[1]->repexpr(); break; case en_i2d: p[0]->repexpr(); p[1]->repexpr(); break; case en_i2q: case en_d2i: case en_q2i: case en_s2q: case en_d2q: case en_t2q: p[0]->repexpr(); break; case en_asadd: case en_add: p[0]->repexpr(); p[1]->repexpr(); break; case en_sub: case en_mulf: case en_mul: case en_mulu: case en_div: case en_udiv: case en_mod: case en_umod: case en_shl: case en_asl: case en_shlu: case en_shru: case en_asr: case en_shr: case en_and: case en_or: case en_xor: case en_land: case en_lor: case en_land_safe: case en_lor_safe: case en_eq: case en_ne: case en_lt: case en_le: case en_gt: case en_ge: case en_ult: case en_ule: case en_ugt: case en_uge: case en_feq: case en_fne: case en_flt: case en_fle: case en_fgt: case en_fge: case en_fdmul: case en_fddiv: case en_fdadd: case en_fdsub: case en_fadd: case en_fsub: case en_fmul: case en_fdiv: case en_veq: case en_vne: case en_vlt: case en_vle: case en_vgt: case en_vge: case en_vadd: case en_vsub: case en_vmul: case en_vdiv: case en_vadds: case en_vsubs: case en_vmuls: case en_vdivs: case en_safe_cond: case en_assub: case en_asmul: case en_asmulu: case en_asdiv: case en_asdivu: case en_asor: case en_asand: case en_asxor: case en_asmod: case en_aslsh: case en_asrsh: case en_fcall: case en_aggregate: case en_void: p[0]->repexpr(); p[1]->repexpr(); break; case en_assign: p[0]->repexpr(); p[1]->repexpr(); break; case en_cond: p[0]->repexpr(); p[1]->repexpr(); break; case en_list: for (ep = p[2]; ep; ep = ep->p[2]) { ep->p[0]->repexpr(); ep->p[1]->repexpr(); } break; case en_regvar: case en_fpregvar: p[0]->repexpr(); p[1]->repexpr(); break; case en_ptrdif: case en_bchk: p[0]->repexpr(); p[1]->repexpr(); p[2]->repexpr(); break; case en_isnullptr: case en_addrof: p[0]->repexpr(); break; default: dfs.printf("Uncoded node in repexr():%d\r\n", nodetype); } if (pfl) pfl->repexpr(); } CSE *ENODE::OptInsertAutocon(int duse) { int nn; CSE *csp; bool first; if (this == nullptr) return (nullptr); nn = currentFn->csetbl->voidauto2(this); csp = currentFn->csetbl->InsertNode(this, duse, &first); if (nn >= 0) { csp->duses += loop_active + nn; csp->uses = csp->duses - loop_active; } return (csp); } CSE *ENODE::OptInsertRef(int duse) { CSE *csp; bool first; ENODE *ep; csp = nullptr; // Search the chain of refs. for (ep = p[0]; ep->IsRefType(); ep = ep->p[0]) ; ep = p[0]; if (ep->IsAutocon()) { csp = currentFn->csetbl->InsertNode(this, duse, &first); // take care: the non-derereferenced use of the autocon node may // already be in the list. In this case, set voidf to 1 if (currentFn->csetbl->Search(p[0]) != NULL) { csp->voidf = 1; p[0]->scanexpr(1); if (pfl) pfl->scanexpr(1); } else { if (csp->voidf) { p[0]->scanexpr(1); if (pfl) pfl->scanexpr(1); } if (first) { // look for register nodes int j = p[0]->rg; if ((p[0]->nodetype == en_regvar) && (j >= regFirstRegvar && j <= regLastRegvar)) { csp->voidf = false; csp->AccUses(3); csp->AccDuses(1); } if ((p[0]->nodetype == en_regvar) && (j >= regFirstArg && j <= regLastArg)) { csp->voidf = false; } // even if that item must not be put in a register, // it is legal to put its address therein if (csp->voidf) p[0]->scanexpr(1); } } } else { // // csp = currentFn->csetbl->InsertNode(this, duse); p[0]->scanexpr(1); p[1]->scanexpr(1); p[2]->scanexpr(1); if (pfl) pfl->scanexpr(1); } return (csp); } /* * scanexpr will scan the expression pointed to by node for optimizable * subexpressions. when an optimizable expression is found it is entered * into the tree. if a reference to an autocon node is scanned the * corresponding auto dereferenced node will be voided. duse should be * set if the expression will be dereferenced. */ void ENODE::scanexpr(int duse) { CSE *csp; bool first; ENODE *ep; if (this == nullptr) return; switch (nodetype) { case en_fpregvar: case en_regvar: currentFn->csetbl->InsertNode(this, duse, &first); break; case en_cnacon: case en_clabcon: case en_fcon: case en_icon: case en_labcon: case en_nacon: currentFn->csetbl->InsertNode(this, duse, &first); break; case en_autofcon: case en_tempfpref: csp = OptInsertAutocon(duse); csp->isfp = FALSE; break; case en_autovcon: case en_autocon: case en_classcon: case en_tempref: OptInsertAutocon(duse); break; case en_cbc: case en_cubw: case en_cbh: case en_cucw: case en_cbw: case en_cuhw: case en_cbu: case en_ccu: case en_chu: case en_cubu: case en_cucu: case en_cuhu: case en_ccwp: case en_cucwp: case en_cch: case en_ccw: case en_chw: p[0]->scanexpr(duse); break; case en_ref: case en_fieldref: OptInsertRef(duse); break; case en_uminus: case en_abs: case en_sxb: case en_sxc: case en_sxh: case en_zxb: case en_zxc: case en_zxh: case en_compl: case en_not: case en_chk: p[0]->scanexpr(duse); break; case en_i2d: p[0]->scanexpr(duse); break; case en_i2q: case en_d2i: case en_q2i: case en_s2q: case en_d2q: case en_t2q: p[0]->scanexpr(duse); break; case en_asadd: case en_assub: case en_add: case en_sub: p[0]->scanexpr(duse); p[1]->scanexpr(duse); break; case en_mulf: case en_mul: case en_mulu: case en_div: case en_udiv: case en_shl: case en_asl: case en_shlu: case en_shr: case en_shru: case en_asr: case en_mod: case en_umod: case en_and: case en_or: case en_xor: case en_lor: case en_land: case en_lor_safe: case en_land_safe: case en_eq: case en_ne: case en_gt: case en_ge: case en_lt: case en_le: case en_ugt: case en_uge: case en_ult: case en_ule: case en_feq: case en_fne: case en_flt: case en_fle: case en_fgt: case en_fge: case en_fdmul: case en_fddiv: case en_fdadd: case en_fdsub: case en_fadd: case en_fsub: case en_fmul: case en_fdiv: case en_veq: case en_vne: case en_vlt: case en_vle: case en_vgt: case en_vge: case en_vadd: case en_vsub: case en_vmul: case en_vdiv: case en_vadds: case en_vsubs: case en_vmuls: case en_vdivs: case en_asmul: case en_asmulu: case en_asdiv: case en_asdivu: case en_asmod: case en_aslsh: case en_asrsh: case en_asand: case en_asxor: case en_asor: case en_cond: case en_safe_cond: case en_void: case en_aggregate: p[0]->scanexpr(0); p[1]->scanexpr(0); break; case en_list: for (ep = p[2]; ep; ep = ep->p[2]) { ep->p[0]->scanexpr(0); ep->p[1]->scanexpr(0); } break; case en_assign: p[0]->scanexpr(0); p[1]->scanexpr(0); break; case en_fcall: p[0]->scanexpr(1); p[1]->scanexpr(0); break; case en_ptrdif: case en_bchk: p[0]->scanexpr(0); p[1]->scanexpr(0); p[2]->scanexpr(0); break; case en_isnullptr: case en_addrof: p[0]->scanexpr(0); break; default: dfs.printf("Uncoded node in ENODE::scanexpr():%d\r\n", nodetype); } if (pfl) pfl->scanexpr(0); } // Debugging use void ENODE::update() { if (this == nullptr) return; if (IsAutocon() || IsRefType()) { if (new_nodetype != en_unknown) nodetype = new_nodetype; } p[0]->update(); p[1]->update(); p[2]->update(); if (pfl) pfl->update(); } // ============================================================================ // ============================================================================ // Code Generation // ============================================================================ // ============================================================================ Operand *ENODE::MakeDataLabel(int lab) { return (compiler.of.MakeDataLabel(lab)); } Operand *ENODE::MakeCodeLabel(int lab) { return (compiler.of.MakeCodeLabel(lab)); } Operand *ENODE::MakeStringAsNameConst(char *s) { return (compiler.of.MakeStringAsNameConst(s)); } Operand *ENODE::MakeString(char *s) { return (compiler.of.MakeString(s)); } Operand *ENODE::MakeImmediate(int64_t i) { return (compiler.of.MakeImmediate(i)); } Operand *ENODE::MakeIndirect(int i) { return (compiler.of.MakeIndirect(i)); } Operand *ENODE::MakeIndexed(int64_t o, int i) { return (compiler.of.MakeIndexed(o, i)); } Operand *ENODE::MakeDoubleIndexed(int i, int j, int scale) { return (compiler.of.MakeDoubleIndexed(i, j, scale)); } Operand *ENODE::MakeDirect(ENODE *node) { return (compiler.of.MakeDirect(node)); } Operand *ENODE::MakeIndexed(ENODE *node, int rg) { return (compiler.of.MakeIndexed(node, rg)); } void ENODE::GenerateHint(int num) { GenerateMonadic(op_hint, 0, MakeImmediate(num)); } void ENODE::GenLoad(Operand *ap3, Operand *ap1, int ssize, int size) { cg.GenLoad(ap3, ap1, ssize, size); } void ENODE::GenStore(Operand *ap1, Operand *ap3, int size) { cg.GenStore(ap1, ap3, size); } void ENODE::GenMemop(int op, Operand *ap1, Operand *ap2, int ssize) { cg.GenMemop(op, ap1, ap2, ssize); } void ENODE::GenRedor(Operand *ap1, Operand *ap2) { GenerateDiadic(op_not, 0, ap1, ap2); GenerateDiadic(op_not, 0, ap1, ap1); } // ---------------------------------------------------------------------------- // Generate code to evaluate an index node (^+) and return the addressing mode // of the result. This routine takes no flags since it always returns either // am_ind or am_indx. // // No reason to ReleaseTempReg() because the registers used are transported // forward. // ---------------------------------------------------------------------------- Operand *ENODE::GenIndex() { Operand *ap1, *ap2, *ap3; int rg, rg1, rg2; if ((p[0]->nodetype == en_tempref || p[0]->nodetype == en_regvar) && (p[1]->nodetype == en_tempref || p[1]->nodetype == en_regvar)) { /* both nodes are registers */ // Don't need to free ap2 here. It is included in ap1. GenerateHint(8); ap3 = GetTempRegister(); ap1 = p[0]->Generate(am_reg, sizeOfWord); ap2 = p[1]->Generate(am_reg, sizeOfWord); if (scale > 1) { GenerateTriadic(op_sll, 0, ap3, ap2, MakeImmediate(scale)); GenerateTriadic(op_add, 0, ap3, ap1, ap3); } else GenerateTriadic(op_add, 0, ap3, ap2, ap1); ReleaseTempRegister(ap2); ReleaseTempRegister(ap1); //GenerateHint(9); //ap1->mode = am_indx2; ap3->mode = am_indx; ap3->offset = makeinode(en_icon, 0); //ap1->scale = scale; return (ap3); } GenerateHint(8); ap1 = p[0]->Generate(am_reg | am_imm, sizeOfWord); if (ap1->mode == am_imm) { ap2 = p[1]->Generate(am_reg | am_imm, sizeOfWord); if (ap2->mode == am_reg && ap2->preg==0) { // value is zero ap1->mode = am_direct; if (ap1->offset) DataLabels[ap1->offset->i] = true; return (ap1); } ap2->isConst = ap2->mode==am_imm; if (ap2->mode == am_imm && ap2->offset->i != 0) ap2->offset2 = ap2->offset; else ap2->offset2 = nullptr; GenerateHint(9); ap2->mode = am_indx; ap2->offset = ap1->offset; ap2->isUnsigned = ap1->isUnsigned; ReleaseTempRegister(ap1); return (ap2); } ap2 = p[1]->Generate(am_all, sizeOfWord); /* get right op */ GenerateHint(9); if (ap2->mode == am_imm && ap1->mode == am_reg) /* make am_indx */ { ap1->mode = am_indx; //ap2->preg = ap1->preg; //ap2->deep = ap1->deep; ap1->offset = ap2->offset; ap1->offset2 = ap2->offset2; return (ap1); } if (ap2->mode == am_ind && ap1->mode == am_reg) { ap3 = GetTempRegister(); GenerateTriadic(op_add, 0, ap3, makereg(ap2->preg), makereg(ap1->preg)); rg = ap2->preg; ap2->preg = ap3->preg; ap3->preg = rg; ReleaseTempRegister(ap3); //ap2->mode = am_indx2; //ap2->sreg = ap1->preg; //ap2->deep2 = ap1->deep; return (ap2); } if (ap2->mode == am_direct && ap1->mode == am_reg) { ap2->mode = am_indx; ap2->preg = ap1->preg; ap2->deep = ap1->deep; return ap2; } // ap1->mode must be am_reg ap3 = GetTempRegister(); ap2->MakeLegal( am_reg, sizeOfWord); rg1 = ap1->preg; rg2 = ap2->preg; if (scale > 1) { GenerateTriadic(op_sll, 0, ap3, ap2, MakeImmediate(scale)); GenerateTriadic(op_add, 0, ap1, ap1, ap3); ReleaseTempRegister(ap3); } else GenerateTriadic(op_add, 0, ap1, ap2, ap1); ReleaseTempRegister(ap3); ReleaseTempRegister(ap2); /* ap1->mode = am_indx2; // make indexed ap1->sreg = ap2->preg; ap1->deep2 = ap2->deep; ap1->offset = makeinode(en_icon, 0); ap1->scale = scale; */ return (ap1); /* return indexed */ } // // Generate code to evaluate a condition operator node (??:) // Operand *ENODE::GenSafeHook(int flags, int size) { Operand *ap1, *ap2, *ap3, *ap4; int false_label, end_label; OCODE *ip1; int n1; ENODE *node; false_label = nextlabel++; end_label = nextlabel++; //flags = (flags & am_reg) | am_volatile; flags |= am_volatile; /* if (p[0]->constflag && p[1]->constflag) { GeneratePredicateMonadic(hook_predreg,op_op_ldi,MakeImmediate(p[0]->i)); GeneratePredicateMonadic(hook_predreg,op_ldi,MakeImmediate(p[0]->i)); } */ ip1 = currentFn->pl.tail; // cmovenz integer only if (!opt_nocgo) { ap4 = GetTempRegister(); ap1 = p[0]->Generate(am_reg, size); ap2 = p[1]->p[0]->Generate(am_reg | am_fpreg, size); ap3 = p[1]->p[1]->Generate(am_reg | am_fpreg | am_imm, size); //if (ap2->mode == am_fpreg || ap3->mode == am_fpreg) goto j1; n1 = currentFn->pl.Count(ip1); if (n1 < 20 && !currentFn->pl.HasCall(ip1)) { Generate4adic(op_cmovenz, 0, ap4, ap1, ap2, ap3); ReleaseTempReg(ap3); ReleaseTempReg(ap2); ReleaseTempReg(ap1); ap4->MakeLegal(flags,size); return (ap4); } j1: ReleaseTempReg(ap3); ReleaseTempReg(ap2); ReleaseTempReg(ap1); ReleaseTempReg(ap4); currentFn->pl.tail = ip1; currentFn->pl.tail->fwd = nullptr; } ap2 = p[1]->p[1]->Generate(flags, size); n1 = currentFn->pl.Count(ip1); if (opt_nocgo) n1 = 9999; if (n1 > 4 || currentFn->pl.HasCall(ip1)) { ReleaseTempReg(ap2); currentFn->pl.tail = ip1; currentFn->pl.tail->fwd = nullptr; cg.GenerateFalseJump(p[0], false_label, 0); node = p[1]; ap1 = node->p[0]->Generate(flags, size); GenerateDiadic(op_bra, 0, MakeCodeLabel(end_label), 0); GenerateLabel(false_label); ap2 = node->p[1]->Generate(flags, size); if (!IsEqualOperand(ap1, ap2)) { GenerateMonadic(op_hint, 0, MakeImmediate(2)); switch (ap1->mode) { case am_reg: switch (ap2->mode) { case am_reg: GenerateDiadic(op_mov, 0, ap1, ap2); break; case am_imm: cg.GenLoadConst(ap2, ap1); if (ap2->isPtr) ap1->isPtr = true; break; default: GenLoad(ap1, ap2, size, size); break; } break; case am_fpreg: switch (ap2->mode) { case am_fpreg: GenerateDiadic(op_mov, 0, ap1, ap2); break; case am_imm: ap4 = GetTempRegister(); GenerateDiadic(op_ldi, 0, ap4, ap2); GenerateDiadic(op_mov, 0, ap1, ap4); if (ap2->isPtr) ap1->isPtr = true; break; default: GenLoad(ap1, ap2, size, size); break; } break; case am_imm: break; default: GenStore(ap2, ap1, size); break; } } GenerateLabel(end_label); ap1->MakeLegal(flags, size); return (ap1); } // N1 <= 4 cg.GenerateFalseJump(p[0], false_label, 0); node = p[1]; ap1 = node->p[0]->Generate(flags, size); GenerateDiadic(op_bra, 0, MakeCodeLabel(end_label), 0); GenerateLabel(false_label); if (!IsEqualOperand(ap1, ap2)) { GenerateMonadic(op_hint, 0, MakeImmediate(2)); switch (ap1->mode) { case am_reg: switch (ap2->mode) { case am_reg: GenerateDiadic(op_mov, 0, ap1, ap2); break; case am_imm: cg.GenLoadConst(ap2, ap1); if (ap2->isPtr) ap1->isPtr = true; break; default: GenLoad(ap1, ap2, size, size); break; } break; case am_fpreg: switch (ap2->mode) { case am_fpreg: GenerateDiadic(op_mov, 0, ap1, ap2); break; case am_imm: ap4 = GetTempRegister(); GenerateDiadic(op_ldi, 0, ap4, ap2); GenerateDiadic(op_mov, 0, ap1, ap4); if (ap2->isPtr) ap1->isPtr = true; break; default: GenLoad(ap1, ap2, size, size); break; } break; case am_imm: break; default: GenStore(ap2, ap1, size); break; } } GenerateLabel(end_label); ap1->MakeLegal(flags, size); return (ap1); } // // Generate code to evaluate a condition operator node (?:) // Operand *ENODE::GenHook(int flags, int size) { Operand *ap1, *ap2, *ap3; int false_label, end_label; ENODE *node; bool voidResult; false_label = nextlabel++; end_label = nextlabel++; //flags = (flags & am_reg) | am_volatile; flags |= am_volatile; /* if (p[0]->constflag && p[1]->constflag) { GeneratePredicateMonadic(hook_predreg,op_op_ldi,MakeImmediate(p[0]->i)); GeneratePredicateMonadic(hook_predreg,op_ldi,MakeImmediate(p[0]->i)); } */ //ip1 = currentFn->pl.tail; //ap2 = cg.GenerateExpression(p[1]->p[1], flags, size); //n1 = currentFn->pl.Count(ip1); //if (opt_nocgo) // n1 = 9999; //ReleaseTempReg(ap2); //currentFn->pl.tail = ip1; //currentFn->pl.tail->fwd = nullptr; voidResult = p[0]->etype == bt_void; cg.GenerateFalseJump(p[0], false_label, 0); node = p[1]; ap3 = GetTempRegister(); ap1 = node->p[0]->Generate(flags, size); ReleaseTempRegister(ap1); GenerateDiadic(op_bra, 0, MakeCodeLabel(end_label), 0); GenerateLabel(false_label); ap2 = node->p[1]->Generate(flags, size); if (!Operand::IsSameType(ap1, ap2) && !voidResult) error(ERR_MISMATCH); //{ // GenerateMonadic(op_hint, 0, MakeImmediate(2)); // switch (ap1->mode) // { // case am_reg: // switch (ap2->mode) { // case am_reg: // GenerateDiadic(op_mov, 0, ap1, ap2); // break; // case am_imm: // GenerateDiadic(op_ldi, 0, ap1, ap2); // if (ap2->isPtr) // ap1->isPtr = true; // break; // default: // GenLoad(ap1, ap2, size, size); // break; // } // break; // case am_fpreg: // switch (ap2->mode) { // case am_fpreg: // GenerateDiadic(op_mov, 0, ap1, ap2); // break; // case am_imm: // ap4 = GetTempRegister(); // GenerateDiadic(op_ldi, 0, ap4, ap2); // GenerateDiadic(op_mov, 0, ap1, ap4); // if (ap2->isPtr) // ap1->isPtr = true; // break; // default: // GenLoad(ap1, ap2, size, size); // break; // } // break; // case am_imm: // break; // default: // GenStore(ap2, ap1, size); // break; // } //} GenerateLabel(end_label); ap2->MakeLegal(flags, size); return (ap2); } Operand *ENODE::GenShift(int flags, int size, int op) { Operand *ap1, *ap2, *ap3; unsigned int Rs1mode, Rs2mode; Rs1mode = opl[op_ins[op]].amclass2; Rs2mode = opl[op_ins[op]].amclass3; ap3 = GetTempRegister(); ap1 = p[0]->Generate(Rs1mode, size); ap2 = p[1]->Generate(Rs2mode, sizeOfWord); GenerateTriadic(op, 0, ap3, ap1, ap2); // Rotates automatically sign extend if ((op == op_rol || op == op_ror) && ap2->isUnsigned) switch (size) { case 1: GenerateTriadic(op_and, 0, ap3, ap3, MakeImmediate(0xFF)); break; case 2: GenerateTriadic(op_and, 0, ap3, ap3, MakeImmediate(0xFFFF)); break; case 4: GenerateDiadic(op_zxh, 0, ap3, ap3); break; default:; } ReleaseTempRegister(ap2); ReleaseTempRegister(ap1); ap3->MakeLegal(flags, size); return (ap3); } Operand *ENODE::GenAssignShift(int flags, int size, int op) { Operand *ap1, *ap2, *ap3; MachineReg *mr; unsigned int Rs1mode, Rs2mode; Rs1mode = opl[op_ins[op]].amclass2; Rs2mode = opl[op_ins[op]].amclass3; //size = GetNaturalSize(node->p[0]); ap3 = p[0]->Generate(am_all & ~am_imm, size); ap2 = p[1]->Generate(Rs2mode, size); if (ap3->mode == am_reg) { GenerateTriadic(op, size, ap3, ap3, ap2); mr = &regs[ap3->preg]; if (mr->assigned) mr->modified = true; mr->assigned = true; mr->isConst = ap3->isConst && ap2->isConst; ReleaseTempRegister(ap2); ap3->MakeLegal(flags, size); return (ap3); } ap1 = GetTempRegister(); GenLoad(ap1, ap3, size, size); GenerateTriadic(op, size, ap1, ap1, ap2); GenStore(ap1, ap3, size); ReleaseTempRegister(ap1); ReleaseTempRegister(ap2); ap3->MakeLegal(flags, size); return (ap3); } // // generate code to evaluate a mod operator or a divide // operator. // Operand *ENODE::GenDivMod(int flags, int size, int op) { Operand *ap1, *ap2, *ap3; unsigned int Rs1mode, Rs2mode; Rs1mode = opl[op_ins[op]].amclass2; Rs2mode = opl[op_ins[op]].amclass3; //if( node->p[0]->nodetype == en_icon ) //??? // swap_nodes(node); if (op == op_fdiv) { ap3 = GetTempFPRegister(); } else { ap3 = GetTempRegister(); } ap1 = p[0]->Generate(Rs1mode, sizeOfWord); ap2 = p[1]->Generate(Rs2mode, sizeOfWord); if (op == op_fdiv) { // Generate a convert operation ? if (ap1->fpsize() != ap2->fpsize()) { if (ap2->fpsize() == 's') GenerateDiadic(op_fcvtsq, 0, ap2, ap2); } GenerateTriadic(op, ap1->fpsize(), ap3, ap1, ap2); } else GenerateTriadic(op, 0, ap3, ap1, ap2); // GenerateDiadic(op_ext,0,ap3,0); ap3->MakeLegal( flags, 2); ReleaseTempReg(ap2); ReleaseTempReg(ap1); return (ap3); } // // generate code to evaluate a multiply node. // Operand *ENODE::GenMultiply(int flags, int size, int op) { Operand *ap1, *ap2, *ap3; bool square = false; unsigned int Rs1mode, Rs2mode; Rs1mode = opl[op_ins[op]].amclass2; Rs2mode = opl[op_ins[op]].amclass3; //Enter("Genmul"); if (p[0]->nodetype == en_icon) swap_nodes(this); if (IsEqual(p[0], p[1])) square = !opt_nocgo; if (op == op_fmul) { ap3 = GetTempFPRegister(); ap1 = p[0]->Generate(Rs1mode, size); if (!square) ap2 = p[1]->Generate(Rs2mode, size); } else { ap3 = GetTempRegister(); ap1 = p[0]->Generate(Rs1mode, sizeOfWord); if (!square) ap2 = p[1]->Generate(Rs2mode, sizeOfWord); } if (op == op_fmul) { // Generate a convert operation ? if (ap1->fpsize() != ap2->fpsize()) { if (ap2->fpsize() == 's') GenerateDiadic(op_fcvtsq, 0, ap2, ap2); } if (square) GenerateTriadic(op, ap1->fpsize(), ap3, ap1, ap1); else GenerateTriadic(op, ap1->fpsize(), ap3, ap1, ap2); } else { if (square) GenerateTriadic(op, 0, ap3, ap1, ap1); else GenerateTriadic(op, 0, ap3, ap1, ap2); } if (!square) ReleaseTempReg(ap2); ReleaseTempReg(ap1); ap3->MakeLegal(flags, 2); //Leave("Genmul", 0); return (ap3); } // // Generate code to evaluate a unary minus or complement. // Operand *ENODE::GenUnary(int flags, int size, int op) { Operand *ap, *ap2; unsigned int Rs1mode; Rs1mode = opl[op_ins[op]].amclass2; if (IsFloatType()) { ap2 = GetTempFPRegister(); ap = p[0]->Generate(Rs1mode, size); if (op == op_neg) op = op_fneg; GenerateDiadic(op, fsize(), ap2, ap); } else if (IsVectorType()) { ap2 = GetTempVectorRegister(); ap = p[0]->Generate(am_vreg, size); GenerateDiadic(op, 0, ap2, ap); } else { ap2 = GetTempRegister(); ap = p[0]->Generate(Rs1mode, size); GenerateHint(3); GenerateDiadic(op, 0, ap2, ap); } ReleaseTempReg(ap); ap2->MakeLegal(flags, size); return (ap2); } // Generate code for a binary expression Operand *ENODE::GenBinary(int flags, int size, int op) { Operand *ap1 = nullptr, *ap2 = nullptr, *ap3, *ap4; bool dup = false; unsigned int Rs1mode, Rs2mode; Rs1mode = opl[op_ins[op]].amclass2; Rs2mode = opl[op_ins[op]].amclass3; if (IsFloatType()) { ap3 = GetTempFPRegister(); if (IsEqual(p[0], p[1])) dup = !opt_nocgo; ap1 = p[0]->Generate(am_fpreg, size); if (!dup) ap2 = p[1]->Generate(am_fpreg, size); // Generate a convert operation ? if (!dup) { if (ap1->fpsize() != ap2->fpsize()) { if (ap2->fpsize() == 's') GenerateDiadic(op_fcvtsq, 0, ap2, ap2); } } if (dup) GenerateTriadic(op, ap1->fpsize(), ap3, ap1, ap1); else GenerateTriadic(op, ap1->fpsize(), ap3, ap1, ap2); ap3->type = ap1->type; } else if (op == op_vex) { ap3 = GetTempRegister(); ap1 = p[0]->Generate(am_reg, size); ap2 = p[1]->Generate(am_reg, size); GenerateTriadic(op, 0, ap3, ap1, ap2); } else if (IsVectorType()) { ap3 = GetTempVectorRegister(); if (ENODE::IsEqual(p[0], p[1]) && !opt_nocgo) { ap1 = p[0]->Generate(am_vreg, size); ap2 = vmask->Generate(am_vmreg, size); Generate4adic(op, 0, ap3, ap1, ap1, ap2); } else { ap1 = p[0]->Generate(am_vreg, size); ap2 = p[1]->Generate(am_vreg, size); ap4 = vmask->Generate(am_vmreg, size); Generate4adic(op, 0, ap3, ap1, ap2, ap4); ReleaseTempReg(ap4); } // Generate a convert operation ? //if (fpsize(ap1) != fpsize(ap2)) { // if (fpsize(ap2)=='s') // GenerateDiadic(op_fcvtsq, 0, ap2, ap2); //} } else { ap3 = GetTempRegister(); if (ENODE::IsEqual(p[0], p[1]) && !opt_nocgo) { // Duh, subtract operand from itself, result would be zero. if (op == op_sub || op == op_ptrdif) GenerateDiadic(op_mov, 0, ap3, makereg(0)); else { ap1 = p[0]->Generate(am_reg, size); GenerateTriadic(op, 0, ap3, ap1, ap1); } } else { ap1 = p[0]->Generate(Rs1mode, size); // modu/ptrdif does not have an immediate mode ap2 = p[1]->Generate(Rs2mode, size); if (Instruction::Get(op)->amclass4) { // op_ptrdif ap4 = p[4]->Generate(Instruction::Get(op)->amclass4, size); Generate4adic(op, 0, ap3, ap1, ap2, ap4); } else { if (ap2->mode == am_imm) { switch (op) { case op_and: GenerateTriadic(op, 0, ap3, ap1, MakeImmediate(ap2->offset->i)); /* if (ap2->offset->i & 0xFFFF0000LL) GenerateDiadic(op_andq1,0,ap3,MakeImmediate((ap2->offset->i >> 16) & 0xFFFFLL)); if (ap2->offset->i & 0xFFFF00000000LL) GenerateDiadic(op_andq2,0,ap3,MakeImmediate((ap2->offset->i >> 32) & 0xFFFFLL)); if (ap2->offset->i & 0xFFFF000000000000LL) GenerateDiadic(op_andq3,0,ap3,MakeImmediate((ap2->offset->i >> 48) & 0xFFFFLL)); */ break; case op_or: GenerateTriadic(op, 0, ap3, ap1, MakeImmediate(ap2->offset->i)); /* if (ap2->offset->i & 0xFFFF0000LL) GenerateDiadic(op_orq1,0,ap3,MakeImmediate((ap2->offset->i >> 16) & 0xFFFFLL)); if (ap2->offset->i & 0xFFFF00000000LL) GenerateDiadic(op_orq2,0,ap3,MakeImmediate((ap2->offset->i >> 32) & 0xFFFFLL)); if (ap2->offset->i & 0xFFFF000000000000LL) GenerateDiadic(op_orq3,0,ap3,MakeImmediate((ap2->offset->i >> 48) & 0xFFFFLL)); */ break; // If there is a pointer plus a constant we really wanted an address calc. case op_add: case op_sub: if (ap1->isPtr && ap2->isPtr) GenerateTriadic(op, 0, ap3, ap1, ap2); else if (ap2->isPtr) GenerateDiadic(op_lea, 0, ap3, op==op_sub ? compiler.of.MakeNegIndexed(ap2->offset, ap1->preg) : MakeIndexed(ap2->offset, ap1->preg)); else GenerateTriadic(op, 0, ap3, ap1, ap2); break; // Most ops handle a max 16 bit immediate operand. If the operand is over 16 bits // it has to be loaded into a register. default: //if (ap2->offset->i < -32768LL || ap2->offset->i > 32767LL) { //ap4 = GetTempRegister(); //GenerateTriadic(op_or, 0, ap4, makereg(regZero), MakeImmediate(ap2->offset->i)); /* if (ap2->offset->i & 0xFFFF0000LL) GenerateDiadic(op_orq1,0,ap4,MakeImmediate((ap2->offset->i >> 16) & 0xFFFFLL)); if (ap2->offset->i & 0xFFFF00000000LL) GenerateDiadic(op_orq2,0,ap4,MakeImmediate((ap2->offset->i >> 32) & 0xFFFFLL)); if (ap2->offset->i & 0xFFFF000000000000LL) GenerateDiadic(op_orq3,0,ap4,MakeImmediate((ap2->offset->i >> 48) & 0xFFFFLL)); */ //GenerateTriadic(op, 0, ap3, ap1, ap4); //ReleaseTempReg(ap4); //} //else GenerateTriadic(op, 0, ap3, ap1, ap2); } } else GenerateTriadic(op, 0, ap3, ap1, ap2); } } } if (ap2) ReleaseTempReg(ap2); if (ap1) ReleaseTempReg(ap1); ap3->MakeLegal( flags, size); return (ap3); } Operand *ENODE::GenerateAssignAdd(int flags, int size, int op) { Operand *ap1, *ap2, *ap3, *ap4; int ssize; bool negf = false; bool intreg = false; MachineReg *mr; ssize = p[0]->GetNaturalSize(); if (ssize > size) size = ssize; if (p[0]->IsBitfield()) { ap3 = GetTempRegister(); ap4 = GetTempRegister(); ap1 = cg.GenerateBitfieldDereference(p[0], am_reg | am_mem, size, 1); // GenerateDiadic(op_mov, 0, ap3, ap1); //ap1 = cg.GenerateExpression(p[0], am_reg | am_mem, size); ap2 = p[1]->Generate(am_reg | am_imm, size); if (ap1->mode == am_reg) { GenerateTriadic(op, 0, ap1, ap1, ap2); cg.GenerateBitfieldInsert(ap3, ap1, ap1->offset->bit_offset, ap1->offset->bit_width); } else { GenLoad(ap3, ap1, size, size); Generate4adic(op_bfext, 0, ap4, ap3, MakeImmediate(ap1->offset->bit_offset), MakeImmediate(ap1->offset->bit_width-1)); GenerateTriadic(op, 0, ap4, ap4, ap2); cg.GenerateBitfieldInsert(ap3, ap4, ap1->offset->bit_offset, ap1->offset->bit_width); GenStore(ap3, ap1, ssize); } ReleaseTempReg(ap2); ReleaseTempReg(ap1); ReleaseTempReg(ap4); ap3->MakeLegal( flags, size); return (ap3); } if (IsFloatType()) { ap1 = p[0]->Generate(am_fpreg | am_mem, ssize); ap2 = p[1]->Generate(am_fpreg, size); if (op == op_add) op = op_fadd; else if (op == op_sub) op = op_fsub; } else if (etype == bt_vector) { ap1 = p[0]->Generate(am_reg | am_mem, ssize); ap2 = p[1]->Generate(am_reg, size); if (op == op_add) op = op_vadd; else if (op == op_sub) op = op_vsub; } else { ap1 = p[0]->Generate(am_all, ssize); ap2 = p[1]->Generate(Instruction::Get(op)->amclass3, size); intreg = true; } if (ap1->mode == am_reg) { GenerateTriadic(op, 0, ap1, ap1, ap2); if (intreg) { mr = &regs[ap1->preg]; if (mr->assigned) mr->modified = true; mr->assigned = true; mr->isConst = ap1->isConst && ap2->isConst; } } else if (ap1->mode == am_fpreg) { GenerateTriadic(op, ap1->fpsize(), ap1, ap1, ap2); ReleaseTempReg(ap2); ap1->MakeLegal( flags, size); return (ap1); } else { GenMemop(op, ap1, ap2, ssize); } ReleaseTempReg(ap2); //if (ap1->type != stddouble.GetIndex() && !ap1->isUnsigned) // ap1 = ap1->GenSignExtend(ssize, size, flags); ap1->MakeLegal( flags, size); return (ap1); } // // generate a *= node. // Operand *ENODE::GenerateAssignMultiply(int flags, int size, int op) { Operand *ap1, *ap2, *ap3; int ssize; MachineReg *mr; ssize = p[0]->GetNaturalSize(); if (ssize > size) size = ssize; if (p[0]->IsBitfield()) { ap3 = GetTempRegister(); ap1 = cg.GenerateBitfieldDereference(p[0], am_reg | am_mem, size, 1); GenerateDiadic(op_mov, 0, ap3, ap1); ap2 = p[1]->Generate(am_reg | am_imm, size); GenerateTriadic(op, 0, ap1, ap1, ap2); cg.GenerateBitfieldInsert(ap3, ap1, ap1->offset->bit_offset, ap1->offset->bit_width); GenStore(ap3, ap1->next, ssize); ReleaseTempReg(ap2); ReleaseTempReg(ap1->next); ReleaseTempReg(ap1); ap3->MakeLegal(flags, size); return (ap3); } if (etype == bt_double || etype == bt_quad || etype == bt_float || etype == bt_triple) { ap1 = p[0]->Generate(am_fpreg | am_mem, ssize); ap2 = p[1]->Generate(am_fpreg, size); op = op_fmul; } else if (etype == bt_vector) { ap1 = p[0]->Generate(am_reg | am_mem, ssize); ap2 = p[1]->Generate(am_reg, size); op = ap2->type == stdvector.GetIndex() ? op_vmul : op_vmuls; } else { ap1 = p[0]->Generate(am_all & ~am_imm, ssize); ap2 = p[1]->Generate(am_reg | am_imm, size); } if (ap1->mode == am_reg) { GenerateTriadic(op, 0, ap1, ap1, ap2); if (op == op_mulu || op == op_mul) { mr = &regs[ap1->preg]; if (mr->assigned) mr->modified = true; mr->assigned = true; mr->isConst = ap1->isConst && ap2->isConst; } } else if (ap1->mode == am_fpreg) { GenerateTriadic(op, ssize == 4 ? 's' : ssize == 8 ? 'd' : ssize == 12 ? 't' : ssize == 16 ? 'q' : 'd', ap1, ap1, ap2); ReleaseTempReg(ap2); ap1->MakeLegal(flags, size); return (ap1); } else { GenMemop(op, ap1, ap2, ssize); } ReleaseTempReg(ap2); ap1 = ap1->GenSignExtend(ssize, size, flags); ap1->MakeLegal(flags, size); return (ap1); } /* * generate /= and %= nodes. */ Operand *ENODE::GenerateAssignModiv(int flags, int size, int op) { Operand *ap1, *ap2, *ap3; int siz1; int isFP; MachineReg *mr; bool cnst = false; siz1 = p[0]->GetNaturalSize(); if (p[0]->IsBitfield()) { ap3 = GetTempRegister(); ap1 = cg.GenerateBitfieldDereference(p[0], am_reg | am_mem, size, 1); GenerateDiadic(op_mov, 0, ap3, ap1); ap2 = p[1]->Generate(am_reg | am_imm, size); GenerateTriadic(op, 0, ap1, ap1, ap2); cg.GenerateBitfieldInsert(ap3, ap1, ap1->offset->bit_offset, ap1->offset->bit_width); GenStore(ap3, ap1->next, siz1); ReleaseTempReg(ap2); ReleaseTempReg(ap1->next); ReleaseTempReg(ap1); ap3->MakeLegal(flags, size); return (ap3); } isFP = etype == bt_double || etype == bt_float || etype == bt_triple || etype == bt_quad; if (isFP) { if (op == op_div || op == op_divu) op = op_fdiv; ap1 = p[0]->Generate(am_fpreg, siz1); ap2 = p[1]->Generate(am_fpreg, size); GenerateTriadic(op, siz1 == 4 ? 's' : siz1 == 8 ? 'd' : siz1 == 12 ? 't' : siz1 == 16 ? 'q' : 'd', ap1, ap1, ap2); ReleaseTempReg(ap2); ap1->MakeLegal(flags, size); return (ap1); // else if (op==op_mod || op==op_modu) // op = op_fdmod; } else { ap1 = GetTempRegister(); ap2 = p[0]->Generate(am_all & ~am_imm, siz1); } if (ap2->mode == am_reg && ap2->preg != ap1->preg) GenerateDiadic(op_mov, 0, ap1, ap2); else if (ap2->mode == am_fpreg && ap2->preg != ap1->preg) GenerateDiadic(op_mov, 0, ap1, ap2); else GenLoad(ap1, ap2, siz1, siz1); //GenerateSignExtend(ap1,siz1,2,flags); if (isFP) ap3 = p[1]->Generate(am_fpreg, 8); else { // modu doesn't support immediate mode ap3 = p[1]->Generate(op == op_modu ? am_reg : am_reg | am_imm, 8); } if (op == op_fdiv) { GenerateTriadic(op, siz1 == 4 ? 's' : siz1 == 8 ? 'd' : siz1 == 12 ? 't' : siz1 == 16 ? 'q' : 'd', ap1, ap1, ap3); } else { GenerateTriadic(op, 0, ap1, ap1, ap3); cnst = ap1->isConst && ap3->isConst; mr = &regs[ap1->preg]; if (mr->assigned) mr->modified = true; mr->assigned = true; mr->isConst = cnst; } ReleaseTempReg(ap3); //GenerateDiadic(op_ext,0,ap1,0); if (ap2->mode == am_reg) { GenerateDiadic(op_mov, 0, ap2, ap1); mr = &regs[ap2->preg]; if (mr->assigned) mr->modified = true; mr->assigned = true; mr->isConst = cnst; } else if (ap2->mode == am_fpreg) GenerateDiadic(op_mov, 0, ap2, ap1); else GenStore(ap1, ap2, siz1); ReleaseTempReg(ap2); if (!isFP) ap1->MakeLegal(flags, size); return (ap1); } Operand *ENODE::GenerateAssignLogic(int flags, int size, int op) { Operand *ap1, *ap2, *ap3; int ssize; MachineReg *mr; ssize = p[0]->GetNaturalSize(); if (ssize > size) size = ssize; if (p[0]->IsBitfield()) { ap3 = GetTempRegister(); ap1 = cg.GenerateBitfieldDereference(p[0], am_reg | am_mem, size, 1); GenerateDiadic(op_mov, 0, ap3, ap1); ap2 = p[1]->Generate(am_reg | am_imm, size); GenerateTriadic(op, 0, ap1, ap1, ap2); cg.GenerateBitfieldInsert(ap3, ap1, ap1->offset->bit_offset, ap1->offset->bit_width); GenStore(ap3, ap1->next, ssize); ReleaseTempReg(ap2); ReleaseTempReg(ap1->next); ReleaseTempReg(ap1); ap3->MakeLegal( flags, size); return (ap3); } ap1 = p[0]->Generate(am_all & ~am_fpreg, ssize); // Some of the logic operations don't support immediate mode, so we check ap2 = p[1]->Generate(Instruction::Get(op)->amclass3, size); if (ap1->mode == am_reg) { GenerateTriadic(op, 0, ap1, ap1, ap2); mr = &regs[ap1->preg]; if (mr->assigned) mr->modified = true; mr->assigned = true; mr->isConst = ap1->isConst && ap2->isConst; } else { GenMemop(op, ap1, ap2, ssize); } ReleaseTempRegister(ap2); if (!ap1->isUnsigned && !(flags & am_novalue)) { if (size > ssize) { if (ap1->mode != am_reg) { ap1->MakeLegal( am_reg, ssize); } switch (ssize) { case 1: GenerateDiadic(op_sxb, 0, ap1, ap1); break; case 2: GenerateDiadic(op_sxc, 0, ap1, ap1); break; case 4: GenerateDiadic(op_sxh, 0, ap1, ap1); break; } ap1->MakeLegal( flags, size); return (ap1); } ap1 = ap1->GenSignExtend(ssize, size, flags); } ap1->MakeLegal( flags, size); return (ap1); } Operand *ENODE::GenLand(int flags, int op, bool safe) { Operand *ap1, *ap2, *ap3, *ap4, *ap5; int lab0, lab1; if (safe) { lab0 = nextlabel++; ap3 = GetTempRegister(); ap1 = p[0]->Generate(am_reg, p[0]->GetNaturalSize()); ap4 = GetTempRegister(); //if (op == op_and) { // GenerateTriadic(op_beq, 0, ap1, makereg(0), MakeDataLabel(lab0)); // ap2 = cg.GenerateExpression(p[1], am_reg, 8); //} if (!ap1->isBool) GenRedor(ap4, ap1); else { ReleaseTempReg(ap4); ap4 = ap1; } ap2 = p[1]->Generate(am_reg, p[1]->GetNaturalSize()); ap5 = GetTempRegister(); if (!ap2->isBool) GenRedor(ap5, ap2); else { ReleaseTempReg(ap5); ap5 = ap2; } GenerateTriadic(op, 0, ap3, ap4, ap5); ReleaseTempReg(ap5); if (ap5 != ap2) ReleaseTempReg(ap2); if (ap4 != ap1) ReleaseTempReg(ap4); ReleaseTempReg(ap1); ap3->MakeLegal(flags, 8); ap3->isBool = true; return (ap3); } lab0 = nextlabel++; lab1 = nextlabel++; ap1 = GetTempRegister(); GenerateDiadic(op_ldi, 0, ap1, MakeImmediate(1)); cg.GenerateFalseJump(this, lab0, 0); GenerateDiadic(op_ldi, 0, ap1, MakeImmediate(0)); GenerateLabel(lab0); ap1->MakeLegal(flags, 8); ap1->isBool = true; return (ap1); } // autocon and autofcon nodes Operand *ENODE::GenerateAutocon(int flags, int size, int type) { Operand *ap1, *ap2; // We always want an address register (GPR) for lea ap1 = GetTempRegister(); ap2 = allocOperand(); ap2->isPtr = etype == bt_pointer; ap2->mode = am_indx; ap2->preg = regFP; // frame pointer ap2->offset = this; /* use as constant node */ ap2->type = type; ap1->type = stdint.GetIndex(); GenerateDiadic(op_lea, 0, ap1, ap2); ap1->MakeLegal(flags, size); return (ap1); /* return reg */ } // // General expression evaluation. returns the addressing mode // of the result. // Operand *ENODE::Generate(int flags, int size) { ENODE *node = this; Operand *ap1, *ap2, *ap3; int natsize, siz1; int lab0, lab1; static char buf[4][20]; static int ndx; static int numDiags = 0; // Enter("<GenerateExpression>"); if (node == (ENODE *)NULL) { throw new C64PException(ERR_NULLPOINTER, 'G'); numDiags++; printf("DIAG - null node in GenerateExpression.\n"); if (numDiags > 100) exit(0); // Leave("</GenerateExpression>", 2); return (Operand *)NULL; } //size = node->esize; GenerateZeradic(op_pfi); switch (node->nodetype) { case en_aggregate: ap1 = p[0]->Generate(flags, size); ap2 = allocOperand(); ap2->mode = am_ind; ap2->preg = ap1->preg; if (node->tp->IsScalar()) GenLoad(ap1, ap2, size, size); else ap1->isPtr = true; goto retpt; //ap1 = allocOperand(); //ap1->offset = node; //ap1->type = 9999; goto retpt; case en_fcon: ap1 = allocOperand(); ap1->isPtr = node->IsPtr(); ap1->mode = am_direct; ap1->offset = node; if (node) DataLabels[node->i] = true; ap1->type = stddouble.GetIndex(); // Don't allow the constant to be loaded into an integer register. ap1->MakeLegal(flags & ~am_reg, size); // Leave("</GenerateExpression>", 2); goto retpt; /* ap1 = allocOperand(); ap1->mode = am_imm; ap1->offset = node; ap1->isFloat = TRUE; ap1->MakeLegal(flags,size); Leave("GenExperssion",2); return ap1; */ case en_icon: ap1 = allocOperand(); ap1->mode = am_imm; ap1->offset = this; ap1->MakeLegal(flags, size); // Leave("GenExpression", 3); goto retpt; case en_labcon: if (use_gp) { ap1 = GetTempRegister(); ap2 = allocOperand(); ap2->mode = am_indx; switch (segment) { case tlsseg: ap2->preg = regTP; break; case dataseg: ap2->preg = regGP; break; default: ap2->preg = regPP; } ap2->offset = this; // use as constant node GenerateDiadic(op_lea, 0, ap1, ap2); ap1->MakeLegal(flags, size); goto retpt; } ap1 = allocOperand(); ap1->isPtr = IsPtr(); /* this code not really necessary, see segments notes if (node->etype==bt_pointer && node->constflag) { ap1->segment = codeseg; } else { ap1->segment = dataseg; } */ ap1->mode = am_imm; ap1->offset = node; ap1->isUnsigned = node->isUnsigned; ap1->MakeLegal(flags, size); goto retpt; case en_nacon: if (use_gp) { ap1 = GetTempRegister(); ap2 = allocOperand(); ap2->mode = am_indx; ap2->preg = regGP; // global pointer ap2->offset = this; // use as constant node if (node) DataLabels[i] = true; GenerateDiadic(op_lea, 0, ap1, ap2); ap1->MakeLegal(flags, size); goto retpt; } // fallthru case en_cnacon: ap1 = allocOperand(); ap1->isPtr = IsPtr(); ap1->mode = am_imm; ap1->offset = this; if (i == 0) i = -1; ap1->isUnsigned = isUnsigned; ap1->MakeLegal(flags, size); goto retpt; case en_clabcon: ap1 = allocOperand(); ap1->mode = am_imm; ap1->offset = this; ap1->isUnsigned = isUnsigned; ap1->MakeLegal(flags, size); goto retpt; case en_autocon: ap1 = cg.GenAutocon(node, flags, size, stdint.GetIndex()); goto retpt; case en_autofcon: switch (node->tp->type) { case bt_float: ap1 = GenerateAutocon(flags, size, stdflt.GetIndex()); goto retpt; case bt_double: ap1 = GenerateAutocon(flags, size, stddouble.GetIndex()); goto retpt; case bt_triple: return GenerateAutocon(flags, size, stdtriple.GetIndex()); case bt_quad: return GenerateAutocon(flags, size, stdquad.GetIndex()); case bt_pointer: ap1 = cg.GenAutocon(node, flags, size, stdint.GetIndex()); goto retpt; } break; case en_autovcon: return GenerateAutocon(flags, size, stdvector.GetIndex()); case en_autovmcon: return GenerateAutocon(flags, size, stdvectormask->GetIndex()); case en_classcon: ap1 = GetTempRegister(); ap2 = allocOperand(); ap2->mode = am_indx; ap2->preg = regCLP; /* frame pointer */ ap2->offset = node; /* use as constant node */ GenerateDiadic(op_lea, 0, ap1, ap2); ap1->MakeLegal(flags, size); goto retpt; case en_addrof: ap1 = GetTempRegister(); ap2 = node->p[0]->Generate(flags & ~am_fpreg, 8); switch (ap2->mode) { case am_reg: GenerateDiadic(op_mov, 0, ap1, ap2); break; default: GenerateDiadic(op_lea, 0, ap1, ap2); } ReleaseTempReg(ap2); goto retpt; case en_ref: ap1 = cg.GenerateDereference(node, flags, node->tp->size, !node->isUnsigned); ap1->isPtr = TRUE; ap1->isUnsigned = node->isUnsigned; goto retpt; case en_fieldref: ap1 = (flags & am_bf_assign) ? cg.GenerateDereference(node, flags & ~am_bf_assign, node->tp->size, !node->isUnsigned) : cg.GenerateBitfieldDereference(node, flags, node->tp->size, !node->isUnsigned); ap1->isUnsigned = node->isUnsigned; goto retpt; case en_regvar: case en_tempref: ap1 = allocOperand(); ap1->isPtr = node->IsPtr(); ap1->mode = am_reg; ap1->preg = node->rg; ap1->tempflag = 0; /* not a temporary */ ap1->MakeLegal(flags, size); goto retpt; case en_tempfpref: ap1 = allocOperand(); ap1->isPtr = node->IsPtr(); ap1->mode = node->IsPtr() ? am_reg : am_fpreg; ap1->preg = node->rg; ap1->tempflag = 0; /* not a temporary */ if (node->tp) switch (node->tp->type) { case bt_float: ap1->type = stdflt.GetIndex(); break; case bt_double: ap1->type = stddouble.GetIndex(); break; case bt_triple: ap1->type = stdtriple.GetIndex(); break; case bt_quad: ap1->type = stdquad.GetIndex(); break; default: ap1->type = stdint.GetIndex(); break; } else ap1->type = stddouble.GetIndex(); ap1->MakeLegal(flags, size); goto retpt; case en_fpregvar: // case en_fptempref: ap1 = allocOperand(); ap1->isPtr = node->IsPtr(); ap1->mode = node->IsPtr() ? am_reg : am_fpreg; ap1->preg = node->rg; ap1->tempflag = 0; /* not a temporary */ if (node->tp) switch (node->tp->type) { case bt_float: ap1->type = stdflt.GetIndex(); break; case bt_double: ap1->type = stddouble.GetIndex(); break; case bt_triple: ap1->type = stdtriple.GetIndex(); break; case bt_quad: ap1->type = stdquad.GetIndex(); break; default: ap1->type = stdint.GetIndex(); break; } else ap1->type = stddouble.GetIndex(); ap1->MakeLegal(flags, size); goto retpt; case en_abs: return node->GenUnary(flags, size, op_abs); case en_uminus: ap1 = node->GenUnary(flags, size, op_neg); goto retpt; case en_compl: ap1 = node->GenUnary(flags, size, op_com); goto retpt; case en_not: ap1 = (node->GenUnary(flags, 8, op_not)); goto retpt; case en_add: ap1 = node->GenBinary(flags, size, op_add); goto retpt; case en_sub: ap1 = node->GenBinary(flags, size, op_sub); goto retpt; case en_ptrdif: ap1 = node->GenBinary(flags, size, op_ptrdif); goto retpt; case en_i2d: ap1 = GetTempFPRegister(); ap2 = node->p[0]->Generate(am_reg, 8); GenerateDiadic(op_itof, 'd', ap1, ap2); ReleaseTempReg(ap2); goto retpt; case en_i2q: ap1 = GetTempFPRegister(); ap2 = node->p[0]->Generate(am_reg, 8); GenerateTriadic(op_csrrw, 0, makereg(0), MakeImmediate(0x18), ap2); GenerateZeradic(op_nop); GenerateZeradic(op_nop); GenerateDiadic(op_itof, 'q', ap1, makereg(63)); ReleaseTempReg(ap2); goto retpt; case en_i2t: ap1 = GetTempFPRegister(); ap2 = node->p[0]->Generate(am_reg, 8); GenerateTriadic(op_csrrw, 0, makereg(0), MakeImmediate(0x18), ap2); GenerateZeradic(op_nop); GenerateZeradic(op_nop); GenerateDiadic(op_itof, 't', ap1, makereg(63)); ReleaseTempReg(ap2); goto retpt; case en_d2i: ap1 = GetTempRegister(); ap2 = node->p[0]->Generate(am_fpreg, 8); GenerateDiadic(op_ftoi, 'd', ap1, ap2); ReleaseTempReg(ap2); goto retpt; case en_q2i: ap1 = GetTempRegister(); ap2 = node->p[0]->Generate(am_fpreg, 8); GenerateDiadic(op_ftoi, 'q', makereg(63), ap2); GenerateZeradic(op_nop); GenerateZeradic(op_nop); GenerateTriadic(op_csrrw, 0, ap1, MakeImmediate(0x18), makereg(0)); ReleaseTempReg(ap2); goto retpt; case en_t2i: ap1 = GetTempRegister(); ap2 = node->p[0]->Generate(am_fpreg, 8); GenerateDiadic(op_ftoi, 't', makereg(63), ap2); GenerateZeradic(op_nop); GenerateZeradic(op_nop); GenerateTriadic(op_csrrw, 0, ap1, MakeImmediate(0x18), makereg(0)); ReleaseTempReg(ap2); goto retpt; case en_s2q: ap1 = GetTempFPRegister(); ap2 = node->p[0]->Generate(am_fpreg, 8); GenerateDiadic(op_fcvtsq, 0, ap1, ap2); ap1->type = stdquad.GetIndex(); ReleaseTempReg(ap2); goto retpt; case en_d2q: ap1 = GetTempFPRegister(); ap2 = node->p[0]->Generate(am_fpreg, 8); GenerateDiadic(op_fcvtdq, 0, ap1, ap2); ap1->type = stdquad.GetIndex(); ReleaseTempReg(ap2); goto retpt; case en_t2q: ap1 = GetTempFPRegister(); ap2 = node->p[0]->Generate(am_fpreg, 8); GenerateDiadic(op_fcvttq, 0, ap1, ap2); ap1->type = stdquad.GetIndex(); ReleaseTempReg(ap2); goto retpt; case en_vadd: return node->GenBinary(flags, size, op_vadd); case en_vsub: return node->GenBinary(flags, size, op_vsub); case en_vmul: return node->GenBinary(flags, size, op_vmul); case en_vadds: return node->GenBinary(flags, size, op_vadds); case en_vsubs: return node->GenBinary(flags, size, op_vsubs); case en_vmuls: return node->GenBinary(flags, size, op_vmuls); case en_vex: return node->GenBinary(flags, size, op_vex); case en_veins: return node->GenBinary(flags, size, op_veins); case en_fadd: ap1 = node->GenBinary(flags, size, op_fadd); goto retpt; case en_fsub: ap1 = node->GenBinary(flags, size, op_fsub); goto retpt; case en_fmul: ap1 = node->GenBinary(flags, size, op_fmul); goto retpt; case en_fdiv: ap1 = node->GenBinary(flags, size, op_fdiv); goto retpt; case en_fdadd: return node->GenBinary(flags, size, op_fdadd); case en_fdsub: return node->GenBinary(flags, size, op_fdsub); case en_fsadd: return node->GenBinary(flags, size, op_fsadd); case en_fssub: return node->GenBinary(flags, size, op_fssub); case en_fdmul: return node->GenMultiply(flags, size, op_fmul); case en_fsmul: return node->GenMultiply(flags, size, op_fmul); case en_fddiv: return node->GenMultiply(flags, size, op_fddiv); case en_fsdiv: return node->GenMultiply(flags, size, op_fsdiv); case en_ftadd: return node->GenBinary(flags, size, op_ftadd); case en_ftsub: return node->GenBinary(flags, size, op_ftsub); case en_ftmul: return node->GenMultiply(flags, size, op_ftmul); case en_ftdiv: return node->GenMultiply(flags, size, op_ftdiv); case en_land: /* lab0 = nextlabel++; lab1 = nextlabel++; GenerateFalseJump(node, lab0, 0); ap1 = GetTempRegister(); GenerateDiadic(op_ld, 0, ap1, MakeImmediate(1)); GenerateMonadic(op_bra, 0, MakeDataLabel(lab1)); GenerateLabel(lab0); GenerateDiadic(op_ld, 0, ap1, MakeImmediate(0)); GenerateLabel(lab1); return (ap1); */ ap1 = (node->GenLand(flags, op_and, false)); goto retpt; case en_lor: ap1 = (node->GenLand(flags, op_or, false)); goto retpt; case en_land_safe: ap1 = (node->GenLand(flags, op_and, true)); goto retpt; case en_lor_safe: ap1 = (node->GenLand(flags, op_or, true)); goto retpt; case en_isnullptr: ap1 = node->GenUnary(flags, size, op_isnullptr); goto retpt; case en_and: ap1 = node->GenBinary(flags, size, op_and); goto retpt; case en_or: ap1 = node->GenBinary(flags, size, op_or); goto retpt; case en_xor: ap1 = node->GenBinary(flags, size, op_xor); goto retpt; case en_mulf: ap1 = node->GenMultiply(flags, size, op_mulf); goto retpt; case en_mul: ap1 = node->GenMultiply(flags, size, op_mul); goto retpt; case en_mulu: ap1 = node->GenMultiply(flags, size, op_mulu); goto retpt; case en_div: ap1 = node->GenDivMod(flags, size, op_div); goto retpt; case en_udiv: ap1 = node->GenDivMod(flags, size, op_divu); goto retpt; case en_mod: ap1 = node->GenDivMod(flags, size, op_rem); goto retpt; case en_umod: ap1 = node->GenDivMod(flags, size, op_remu); goto retpt; case en_asl: ap1 = node->GenShift(flags, size, op_sll); goto retpt; case en_shl: ap1 = node->GenShift(flags, size, op_sll); goto retpt; case en_shlu: ap1 = node->GenShift(flags, size, op_sll); goto retpt; case en_asr: ap1 = node->GenShift(flags, size, op_sra); goto retpt; case en_shr: ap1 = node->GenShift(flags, size, op_sra); goto retpt; case en_shru: ap1 = node->GenShift(flags, size, op_srl); goto retpt; case en_rol: ap1 = node->GenShift(flags, size, op_rol); goto retpt; case en_ror: ap1 = node->GenShift(flags, size, op_ror); goto retpt; /* case en_asfadd: return GenerateAssignAdd(node,flags,size,op_fadd); case en_asfsub: return GenerateAssignAdd(node,flags,size,op_fsub); case en_asfmul: return GenerateAssignAdd(node,flags,size,op_fmul); case en_asfdiv: return GenerateAssignAdd(node,flags,size,op_fdiv); */ case en_asadd: ap1 = node->GenerateAssignAdd(flags, size, op_add); goto retpt; case en_assub: ap1 = node->GenerateAssignAdd(flags, size, op_sub); goto retpt; case en_asand: ap1 = node->GenerateAssignLogic(flags, size, op_and); goto retpt; case en_asor: ap1 = node->GenerateAssignLogic(flags, size, op_or); goto retpt; case en_asxor: ap1 = node->GenerateAssignLogic(flags, size, op_xor); goto retpt; case en_aslsh: ap1 = (node->GenAssignShift(flags, size, op_stpl)); goto retpt; case en_asrsh: ap1 = (node->GenAssignShift(flags, size, op_asr)); goto retpt; case en_asrshu: ap1 = (node->GenAssignShift(flags, size, op_stpru)); goto retpt; case en_asmul: ap1 = cg.GenerateAssignMultiply(node, flags, size, op_mul); goto retpt; case en_asmulu: ap1 = cg.GenerateAssignMultiply(node, flags, size, op_mulu); goto retpt; case en_asdiv: ap1 = cg.GenerateAssignModiv(node, flags, size, op_div); goto retpt; case en_asdivu: ap1 = cg.GenerateAssignModiv(node, flags, size, op_divu); goto retpt; case en_asmod: ap1 = cg.GenerateAssignModiv(node, flags, size, op_rem); goto retpt; case en_asmodu: ap1 = cg.GenerateAssignModiv(node, flags, size, op_remu); goto retpt; case en_assign: ap1 = cg.GenerateAssign(node, flags, size); goto retpt; case en_chk: return (cg.GenExpr(node)); case en_eq: case en_ne: case en_lt: case en_le: case en_gt: case en_ge: case en_ult: case en_ule: case en_ugt: case en_uge: case en_feq: case en_fne: case en_flt: case en_fle: case en_fgt: case en_fge: case en_veq: case en_vne: case en_vlt: case en_vle: case en_vgt: case en_vge: ap1 = cg.GenExpr(node); ap1->isBool = true; goto retpt; case en_cond: ap1 = node->GenHook(flags, size); goto retpt; case en_safe_cond: ap1 = (node->GenSafeHook(flags, size)); goto retpt; case en_void: natsize = node->p[0]->GetNaturalSize(); ap1 = node->p[0]->Generate(am_all | am_novalue, natsize); ReleaseTempRegister(node->p[1]->Generate(flags, size)); ap1->isPtr = node->IsPtr(); goto retpt; case en_fcall: ap1 = (cg.GenerateFunctionCall(node, flags)); goto retpt; case en_sxb: ap1 = GetTempRegister(); ap2 = node->p[0]->Generate(am_reg, 1); GenerateDiadic(op_sxb, 0, ap1, ap2); ReleaseTempReg(ap2); ap1->MakeLegal(flags, 8); goto retpt; case en_sxc: ap1 = GetTempRegister(); ap2 = node->p[0]->Generate(am_reg, 2); GenerateDiadic(op_sxc, 0, ap1, ap2); ReleaseTempReg(ap2); ap1->MakeLegal(flags, 8); goto retpt; case en_sxh: ap1 = GetTempRegister(); ap2 = node->p[0]->Generate(am_reg, 4); GenerateDiadic(op_sxh, 0, ap1, ap2); ReleaseTempReg(ap2); ap1->MakeLegal(flags, 8); goto retpt; case en_cubw: case en_cubu: case en_cbu: ap1 = node->p[0]->Generate(am_reg, 1); GenerateTriadic(op_and, 0, ap1, ap1, MakeImmediate(0xff)); goto retpt; case en_cucw: case en_cucu: case en_ccu: ap1 = node->p[0]->Generate(am_reg, 2); GenerateTriadic(op_and, 0, ap1, ap1, MakeImmediate(0xFFFF)); //GenerateDiadic(op_zxc,0,ap1,ap1); goto retpt; case en_ccwp: ap1 = node->p[0]->Generate(am_reg, 2); ap1->isPtr = TRUE; GenerateDiadic(op_sxc, 0, ap1, ap1); goto retpt; case en_cucwp: ap1 = node->p[0]->Generate(am_reg, 2); ap1->isPtr = TRUE; // zxc GenerateTriadic(op_and, 0, ap1, ap1, MakeImmediate(0xFFFF)); goto retpt; case en_cuhw: case en_cuhu: case en_chu: ap1 = node->p[0]->Generate(am_reg, 4); GenerateDiadic(op_zxh, 0, ap1, ap1); goto retpt; case en_cbw: ap1 = node->p[0]->Generate(am_reg, 1); //GenerateDiadic(op_sxb,0,ap1,ap1); GenerateDiadic(op_sxb, 0, ap1, ap1); goto retpt; case en_ccw: ap1 = node->p[0]->Generate(am_reg, 2); GenerateDiadic(op_sxc, 0, ap1, ap1); goto retpt; case en_chw: ap1 = node->p[0]->Generate(am_reg, 4); GenerateDiadic(op_sxh, 0, ap1, ap1); goto retpt; case en_list: ap1 = GetTempRegister(); GenerateDiadic(op_lea, 0, ap1, MakeDataLabel(node->i)); ap1->isPtr = true; goto retpt; case en_object_list: ap1 = GetTempRegister(); GenerateDiadic(op_lea, 0, ap1, MakeIndexed(-8, regFP)); ap1->MakeLegal(flags, sizeOfWord); goto retpt; default: printf("DIAG - uncoded node (%d) in GenerateExpression.\n", node->nodetype); return 0; } return(0); retpt: if (node->pfl) { ReleaseTempRegister(node->pfl->Generate(flags, size)); } return (ap1); } // return the natural evaluation size of a node. int GetNaturalSize(ENODE *node) { int siz0, siz1; if( node == NULL ) return 0; switch( node->nodetype ) { case en_fieldref: return (node->tp->size); case en_icon: if (node->i >= -128 && node->i < 128) return (1); if( -32768 <= node->i && node->i <= 32767 ) return (2); if (-2147483648LL <= node->i && node->i <= 2147483647LL) return (4); return (sizeOfWord); case en_fcon: return (node->tp->precision / 8); case en_tcon: return (6); case en_labcon: case en_clabcon: case en_cnacon: case en_nacon: case en_autocon: case en_classcon: case en_tempref: case en_cbw: case en_cubw: case en_ccw: case en_cucw: case en_chw: case en_cuhw: case en_cbu: case en_ccu: case en_chu: case en_cubu: case en_cucu: case en_cuhu: case en_ccwp: case en_cucwp: case en_sxb: case en_sxc: case en_sxh: return (sizeOfWord); case en_fcall: case en_regvar: case en_fpregvar: if (node->tp) return (node->tp->size); else return (sizeOfWord); case en_autofcon: return (sizeOfWord); case en_ref: return (node->tp->size); case en_cbc: case en_cbh: return (sizeOfWord/2); case en_cch: return (sizeOfWord/2); case en_autovcon: case en_tempfpref: if (node->tp) return (node->tp->precision/16); else return (sizeOfWord); case en_not: case en_compl: case en_uminus: case en_assign: return GetNaturalSize(node->p[0]); case en_fadd: case en_fsub: case en_fmul: case en_fdiv: case en_fsadd: case en_fssub: case en_fsmul: case en_fsdiv: case en_vadd: case en_vsub: case en_vmul: case en_vdiv: case en_vadds: case en_vsubs: case en_vmuls: case en_vdivs: case en_add: case en_sub: case en_ptrdif: case en_mul: case en_mulu: case en_div: case en_udiv: case en_mod: case en_umod: case en_and: case en_or: case en_xor: case en_asl: case en_shl: case en_shlu: case en_shr: case en_shru: case en_asr: case en_asrshu: case en_feq: case en_fne: case en_flt: case en_fle: case en_fgt: case en_fge: case en_eq: case en_ne: case en_lt: case en_le: case en_gt: case en_ge: case en_ult: case en_ule: case en_ugt: case en_uge: case en_land: case en_lor: case en_land_safe: case en_lor_safe: case en_asadd: case en_assub: case en_asmul: case en_asmulu: case en_asdiv: case en_asdivu: case en_asmod: case en_asmodu: case en_asand: case en_asor: case en_asxor: case en_aslsh: case en_asrsh: siz0 = GetNaturalSize(node->p[0]); siz1 = GetNaturalSize(node->p[1]); if( siz1 > siz0 ) return (siz1); else return (siz0); case en_void: case en_cond: case en_safe_cond: return (GetNaturalSize(node->p[1])); case en_bchk: return (GetNaturalSize(node->p[0])); case en_chk: return 8; case en_q2i: case en_t2i: return (sizeOfWord); case en_i2d: return (sizeOfWord); case en_i2t: case en_d2t: return (sizeOfFPT); case en_i2q: case en_d2q: case en_t2q: return (sizeOfFPQ); case en_object_list: return (GetNaturalSize(node->p[0])); case en_addrof: return (sizeOfPtr); default: printf("DIAG - natural size error %d.\n", node->nodetype); break; } return (0); } void ENODE::PutConstant(txtoStream& ofs, unsigned int lowhigh, unsigned int rshift, bool opt) { // ASM statment text (up to 3500 chars) may be placed in the following buffer. static char buf[4000]; // Used only by lea for subtract if (isNeg) ofs.write("-"); switch (nodetype) { case en_autofcon: sprintf_s(buf, sizeof(buf), "%lld", i); ofs.write(buf); break; case en_fcon: if (!opt) goto j1; // The following spits out a warning, but is okay. sprintf_s(buf, sizeof(buf), "0x%llx", f); ofs.write(buf); break; case en_autovcon: case en_autocon: case en_icon: if (lowhigh == 2) { sprintf_s(buf, sizeof(buf), "%lld", i & 0xffff); ofs.write(buf); } else if (lowhigh == 3) { sprintf_s(buf, sizeof(buf), "%lld", (i >> 16) & 0xffff); ofs.write(buf); } else { sprintf_s(buf, sizeof(buf), "%lld", i); ofs.write(buf); } if (rshift > 0) { sprintf_s(buf, sizeof(buf), ">>%d", rshift); ofs.write(buf); } break; case en_labcon: j1: sprintf_s(buf, sizeof(buf), "%s_%lld", GetNamespace(), i); DataLabels[i] = true; ofs.write(buf); if (rshift > 0) { sprintf_s(buf, sizeof(buf), ">>%d", rshift); ofs.write(buf); } break; case en_clabcon: sprintf_s(buf, sizeof(buf), "%s_%lld", GetNamespace(), i); DataLabels[i] = true; ofs.write(buf); if (rshift > 0) { sprintf_s(buf, sizeof(buf), ">>%d", rshift); ofs.write(buf); } break; case en_nacon: sprintf_s(buf, sizeof(buf), "%s", (char *)sp->c_str()); ofs.write(buf); if (lowhigh == 3) { sprintf_s(buf, sizeof(buf), ">>16"); ofs.write(buf); } if (rshift > 0) { sprintf_s(buf, sizeof(buf), ">>%d", rshift); ofs.write(buf); } break; case en_scon: sprintf_s(buf, sizeof(buf), "\"%s\",0", (char *)sp->c_str()); ofs.write(buf); break; case en_cnacon: sprintf_s(buf, sizeof(buf), "%s", (char *)msp->c_str()); ofs.write(buf); if (rshift > 0) { sprintf_s(buf, sizeof(buf), ">>%d", rshift); ofs.write(buf); } break; case en_add: p[0]->PutConstant(ofs, 0, 0); ofs.write("+"); p[1]->PutConstant(ofs, 0, 0); break; case en_sub: p[0]->PutConstant(ofs, 0, 0); ofs.write("-"); p[1]->PutConstant(ofs, 0, 0); break; case en_ptrdif: ofs.printf("("); p[0]->PutConstant(ofs, 0, 0); ofs.write("-"); p[1]->PutConstant(ofs, 0, 0); ofs.printf(") >> "); p[4]->PutConstant(ofs, 0, 0); break; case en_uminus: ofs.write("-"); p[0]->PutConstant(ofs, 0, 0); break; default: printf("DIAG - illegal constant node.\n"); break; } } ENODE *ENODE::GetConstantHex(std::ifstream& ifs) { static char buf[4000]; ENODE *ep; ep = allocEnode(); ifs.read(buf, 2); buf[2] = '\0'; ep->nodetype = (e_node)strtol(buf, nullptr, 16); switch (ep->nodetype) { case en_autofcon: ifs.read(buf, 8); buf[8] = '\0'; ep->i = strtol(buf, nullptr, 16); break; case en_fcon: goto j1; case en_autovcon: case en_autocon: case en_icon: ifs.read(buf, 8); buf[8] = '\0'; ep->i = strtol(buf, nullptr, 16); break; case en_labcon: j1: ; } return (ep); } void ENODE::PutConstantHex(txtoStream& ofs, unsigned int lowhigh, unsigned int rshift) { // ASM statment text (up to 3500 chars) may be placed in the following buffer. static char buf[4000]; ofs.printf("N%02X", nodetype); switch (nodetype) { case en_autofcon: sprintf_s(buf, sizeof(buf), "%08LLX", i); ofs.write(buf); break; case en_fcon: sprintf_s(buf, sizeof(buf), "%s_%lld:", GetNamespace(), i); ofs.write(buf); break; case en_autovcon: case en_autocon: case en_icon: sprintf_s(buf, sizeof(buf), "%08llX", i); ofs.write(buf); break; case en_labcon: sprintf_s(buf, sizeof(buf), "%s_%lld:", GetNamespace(), i); ofs.write(buf); break; case en_clabcon: sprintf_s(buf, sizeof(buf), "%s_%lld:", GetNamespace(), i); ofs.write(buf); break; case en_nacon: sprintf_s(buf, sizeof(buf), "%s:", (char *)sp->c_str()); ofs.write(buf); break; case en_cnacon: sprintf_s(buf, sizeof(buf), "%s:", (char *)msp->c_str()); ofs.write(buf); break; case en_add: p[0]->PutConstantHex(ofs, 0, 0); ofs.write("+"); p[1]->PutConstantHex(ofs, 0, 0); break; case en_sub: p[0]->PutConstantHex(ofs, 0, 0); ofs.write("-"); p[1]->PutConstantHex(ofs, 0, 0); break; case en_uminus: ofs.write("-"); p[0]->PutConstantHex(ofs, 0, 0); break; default: printf("DIAG - illegal constant node.\n"); break; } } void ENODE::storeHex(txtoStream& ofs) { if (this == nullptr) { ofs.puts("x"); return; } ofs.puts("X"); ofs.writeAsHex((char *)this, sizeof(ENODE)); if (tp) ofs.printf("%05X:", tp->typeno); else ofs.printf("FFFFF:"); if (sym) ofs.printf("%05X:", sym->number); else ofs.printf("FFFFF:"); vmask->store(ofs); if (sp) { ofs.printf("%03X:", (int)sp->length()); ofs.writeAsHex(sp->c_str(), sp->length()); } else ofs.printf("000:"); if (msp) { ofs.printf("%03X:", (int)msp->length()); ofs.writeAsHex(msp->c_str(), msp->length()); } else ofs.printf("000:"); if (udnm) { ofs.printf("%03X:", (int)udnm->length()); ofs.writeAsHex(udnm->c_str(), udnm->length()); } else ofs.printf("000:"); p[0]->store(ofs); p[1]->store(ofs); p[2]->store(ofs); } void ENODE::loadHex(txtiStream& ifs) { int nn; static char buf[8000]; ifs.readAsHex(this, sizeof(ENODE)); ifs.read(buf, 6); nn = strtoul(buf, nullptr, 16); if (nn < 65535) tp = &compiler.typeTable[nn]; ifs.read(buf, 6); nn = strtoul(buf, nullptr, 16); if (nn < 65535) sym = &compiler.symbolTable[nn]; vmask = allocEnode(); vmask->load(ifs); ifs.read(buf, 4); nn = strtoul(buf, nullptr, 16); ifs.readAsHex(buf, nn * 2); buf[nn * 2] = '\0'; sp = new std::string(buf); ifs.read(buf, 4); nn = strtoul(buf, nullptr, 16); ifs.readAsHex(buf, nn * 2); buf[nn * 2] = '\0'; msp = new std::string(buf); ifs.read(buf, 4); nn = strtoul(buf, nullptr, 16); ifs.readAsHex(buf, nn * 2); buf[nn * 2] = '\0'; udnm = new std::string(buf); ifs.read(buf, 1); // should be 'X' if (buf[0]=='X') p[0]->load(ifs); ifs.read(buf, 1); if (buf[0] == 'X') p[1]->load(ifs); ifs.read(buf, 1); if (buf[0] == 'X') p[2]->load(ifs); } void ENODE::store(txtoStream& ofs) { } void ENODE::load(txtiStream& ifs) { } int ENODE::PutStructConst(txtoStream& ofs) { int64_t n, k; ENODE *ep1; ENODE *ep = this; bool isStruct; if (ep == nullptr) return (0); if (ep->nodetype != en_aggregate) return (0); isStruct = ep->tp->IsStructType(); for (n = 0, ep1 = ep->p[0]->p[2]; ep1; ep1 = ep1->p[2]) { if (ep1->nodetype == en_aggregate) { k = ep1->PutStructConst(ofs); } else { if (isStruct) { switch (ep1->tp->walignment()) { case 1: break; default: ofs.printf("align %ld\t", (int)ep1->tp->walignment()); break; } k = ep1->tp->struct_offset + ep1->esize; } else k = ep1->esize; switch (ep1->esize) { case 1: ofs.printf("db\t"); ep1->PutConstant(ofs, 0, 0); ofs.printf("\n"); break; case 2: ofs.printf("dc\t"); ep1->PutConstant(ofs, 0, 0); ofs.printf("\n"); break; case 4: ofs.printf("dh\t"); ep1->PutConstant(ofs, 0, 0); ofs.printf("\n"); break; case 8: ofs.printf("dw\t"); ep1->PutConstant(ofs, 0, 0, true); ofs.printf("\n"); break; default: ofs.printf("fill.b %ld,0x00\n", ep1->esize - 1); ofs.printf("db\t"); ep1->PutConstant(ofs, 0, 0, true); ofs.printf("\n"); break; } } if (isStruct) n = k; else n = n + k; } if (n < ep->esize) { ofs.printf("fill.b %ld,0x00\n", ep->esize - n); } return (n); } // ============================================================================ // ============================================================================ // Debugging // ============================================================================ // ============================================================================ std::string ENODE::nodetypeStr() { switch (nodetype) { case en_regvar: return "en_regvar"; case en_autocon: return "en_autocon"; case en_cond: return "en_cond"; case en_void: return "en_void"; case en_asadd: return "en_asadd"; case en_icon: return "en_icon"; case en_assign: return "en_assign"; case en_eq: return "en_eq"; default: if (IsRefType()) { return "en_ref"; } break; } return "???"; } void ENODE::Dump() { int nn; static int level = 0; //return; if (this == nullptr) return; for (nn = 0; nn < level * 2; nn++) dfs.printf(" "); dfs.printf("Node:%d\n", number); for (nn = 0; nn < level * 2; nn++) dfs.printf(" "); dfs.printf("nodetype: %d: ", nodetype); dfs.printf("%s\n", (char *)nodetypeStr().c_str()); for (nn = 0; nn < level * 2; nn++) dfs.printf(" "); dfs.printf("rg: %d\n", rg); level++; p[0]->Dump(); p[1]->Dump(); p[2]->Dump(); level--; }
[ "5563401+robfinch@users.noreply.github.com" ]
5563401+robfinch@users.noreply.github.com
411530139537e4c291bbf787859bba969eb40406
e23512edf95ea66640eab85adb8ca0c24ae6e3f7
/tensorflow/core/distributed_runtime/rpc/grpc_server_lib.cc
c4ac92d809627e7134b5d4ae694f9978cd5390b4
[ "Apache-2.0" ]
permissive
snuspl/tensorflow
755ac46c3163adb119de0755ed706b1c960991fb
212d4e9e5f4093ecb90e5b7837d4e02da7506228
refs/heads/r1.6
2021-06-25T18:03:17.625202
2018-12-30T09:35:50
2018-12-30T09:35:50
134,066,972
1
3
Apache-2.0
2020-06-10T06:12:19
2018-05-19T14:02:25
C++
UTF-8
C++
false
false
16,097
cc
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/distributed_runtime/rpc/grpc_server_lib.h" #include <cstring> #include <limits> #include <memory> #include "grpc++/grpc++.h" #include "grpc++/security/credentials.h" #include "grpc++/server_builder.h" #include "grpc/support/alloc.h" #include "tensorflow/core/common_runtime/device_factory.h" #include "tensorflow/core/common_runtime/device_mgr.h" #include "tensorflow/core/common_runtime/process_util.h" #include "tensorflow/core/distributed_runtime/graph_mgr.h" #include "tensorflow/core/distributed_runtime/local_master.h" #include "tensorflow/core/distributed_runtime/master.h" #include "tensorflow/core/distributed_runtime/master_env.h" #include "tensorflow/core/distributed_runtime/master_session.h" #include "tensorflow/core/distributed_runtime/rpc/async_service_interface.h" #include "tensorflow/core/distributed_runtime/rpc/grpc_channel.h" #include "tensorflow/core/distributed_runtime/rpc/grpc_master_service.h" #include "tensorflow/core/distributed_runtime/rpc/grpc_worker_cache.h" #include "tensorflow/core/distributed_runtime/rpc/grpc_worker_service.h" #include "tensorflow/core/distributed_runtime/rpc/rpc_rendezvous_mgr.h" #include "tensorflow/core/distributed_runtime/server_lib.h" #include "tensorflow/core/distributed_runtime/worker_env.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/mem.h" #include "tensorflow/core/public/session_options.h" namespace tensorflow { namespace { // Define an option subclass in order to disable SO_REUSEPORT for the // server socket. class NoReusePortOption : public ::grpc::ServerBuilderOption { public: void UpdateArguments(::grpc::ChannelArguments* args) override { args->SetInt(GRPC_ARG_ALLOW_REUSEPORT, 0); } void UpdatePlugins(std::vector<std::unique_ptr<::grpc::ServerBuilderPlugin>>* plugins) override {} }; // static utility function RendezvousMgrInterface* NewRpcRendezvousMgr(const WorkerEnv* env) { return new RpcRendezvousMgr(env); } } // namespace GrpcServer::GrpcServer(const ServerDef& server_def, Env* env) : server_def_(server_def), env_(env), state_(NEW) {} GrpcServer::~GrpcServer() { TF_CHECK_OK(Stop()); TF_CHECK_OK(Join()); delete master_service_; delete worker_service_; // TODO(mrry): Refactor the *Env classes so that it is less fiddly // to destroy them. // Shut down all outstanding rendezvous. delete worker_env_.rendezvous_mgr; // We must delete graph_mgr before device_mgr, due to shared // ownership of OpKernels in the executors. (The graph_mgr will // free all stateless OpKernels, and pass over borrowed stateful // OpKernels, which are also held in their respective devices' // OpSegments.) if (worker_env_.session_mgr != nullptr) { delete worker_env_.session_mgr; // Deletes graph_mgr's. } else { // Note: session_mgr's legacy_session_ deletes device_mgr now. delete worker_env_.device_mgr; } // Do not delete (as these are not owned by the server): // - master_env_.env // - worker_env_.env // - worker_env_.compute_pool } Status GrpcServer::Init( ServiceInitFunction service_func, const RendezvousMgrCreationFunction& rendezvous_mgr_func, const WorkerCreationFunction& worker_func) { mutex_lock l(mu_); CHECK_EQ(state_, NEW); master_env_.env = env_; worker_env_.env = env_; SessionOptions sess_opts; ConfigProto config = server_def_.default_session_config(); sess_opts.config = config; // Configure shared devices between master and worker. string name_prefix = strings::StrCat("/job:", server_def_.job_name(), "/replica:0", "/task:", server_def_.task_index()); TF_RETURN_IF_ERROR(DeviceFactory::AddDevices(sess_opts, name_prefix, &master_env_.local_devices)); worker_env_.local_devices = master_env_.local_devices; worker_env_.device_mgr = new DeviceMgr(worker_env_.local_devices); worker_env_.rendezvous_mgr = rendezvous_mgr_func == nullptr ? new RpcRendezvousMgr(&worker_env_) : rendezvous_mgr_func(&worker_env_); string unused; string default_worker_name; if (!DeviceNameUtils::SplitDeviceName(master_env_.local_devices[0]->name(), &default_worker_name, &unused)) { return errors::Internal("Could not parse worker name."); } // Look up the port that has been requested for this task in `server_def_`. int requested_port = -1; for (const auto& job : server_def_.cluster().job()) { if (job.name() == server_def_.job_name()) { auto iter = job.tasks().find(server_def_.task_index()); if (iter == job.tasks().end()) { return errors::InvalidArgument("Task ", server_def_.task_index(), " was not defined in job \"", server_def_.job_name(), "\""); } const std::vector<string> hostname_port = str_util::Split(iter->second, ':'); if (hostname_port.size() != 2 || !strings::safe_strto32(hostname_port[1], &requested_port)) { return errors::InvalidArgument( "Could not parse port for local server from \"", iter->second, "\""); } else { break; } } } if (requested_port == -1) { return errors::Internal("Job \"", server_def_.job_name(), "\" was not defined in cluster"); } // N.B. The order of initialization here is intricate, because we // wish to allow `requested_port == 0` (for choosing any port, // mostly for testing). Therefore, the construction of the channel // and worker caches depends on `bound_port_`, which is not set // until we call `builder.BuildAndStart()`. We must create the // service objects before calling `builder.BuildAndStart()`, but // `master_env_` and `worker_env_` are only partially // configured. However, this is not dangerous, because we do not // start serving requests until `this->Start()` is called, which // happens after this method returns. // // TODO(mrry): Provide a general mechanism for dynamically setting // the identities of tasks in the worker pool after the service is // running. ::grpc::ServerBuilder builder; builder.AddListeningPort(strings::StrCat("0.0.0.0:", requested_port), GetServerCredentials(server_def_), &bound_port_); builder.SetMaxMessageSize(std::numeric_limits<int32>::max()); builder.SetOption( std::unique_ptr<::grpc::ServerBuilderOption>(new NoReusePortOption)); master_impl_ = CreateMaster(&master_env_); master_service_ = NewGrpcMasterService( master_impl_.get(), config.operation_timeout_in_ms(), &builder); worker_impl_ = worker_func ? worker_func(&worker_env_) : NewGrpcWorker(&worker_env_); worker_service_ = NewGrpcWorkerService(worker_impl_.get(), &builder).release(); // extra service: if (service_func != nullptr) { service_func(&worker_env_, &builder); } server_ = builder.BuildAndStart(); if (!server_) { return errors::Unknown("Could not start gRPC server"); } WorkerCacheInterface* worker_cache; WorkerCacheFactoryOptions worker_cache_factory_options(server_def_); TF_RETURN_IF_ERROR( WorkerCacheFactory(worker_cache_factory_options, &worker_cache)); CHECK_NE(nullptr, worker_cache); // Set up worker environment. worker_env_.session_mgr = new SessionMgr( &worker_env_, SessionMgr::WorkerNameFromServerDef(server_def_), std::unique_ptr<WorkerCacheInterface>(worker_cache), [this](const ServerDef& server_def, WorkerCacheInterface** worker_cache) { WorkerCacheFactoryOptions options(server_def); return WorkerCacheFactory(options, worker_cache); }); worker_env_.compute_pool = ComputePool(sess_opts); // Finish setting up master environment. master_env_.ops = OpRegistry::Global(); master_env_.worker_cache = worker_cache; master_env_.master_session_factory = [config]( SessionOptions options, const MasterEnv* env, std::unique_ptr<std::vector<std::unique_ptr<Device>>> remote_devs, std::unique_ptr<WorkerCacheInterface> worker_cache, std::unique_ptr<DeviceSet> device_set) { options.config.MergeFrom(config); return new MasterSession(options, env, std::move(remote_devs), std::move(worker_cache), std::move(device_set), CreateNoOpStatsPublisher); }; master_env_.worker_cache_factory = [this](const WorkerCacheFactoryOptions& options, WorkerCacheInterface** worker_cache) { return WorkerCacheFactory(options, worker_cache); }; // Provide direct access to the master from in-process clients. LocalMaster::Register(target(), master_impl_.get(), config.operation_timeout_in_ms()); return Status::OK(); } Status GrpcServer::Init( ServiceInitFunction service_func, const RendezvousMgrCreationFunction& rendezvous_mgr_func) { return Init(service_func, rendezvous_mgr_func, nullptr); } Status GrpcServer::Init() { return Init(nullptr, nullptr, nullptr); } Status GrpcServer::ParseChannelSpec(const WorkerCacheFactoryOptions& options, GrpcChannelSpec* channel_spec) { for (const auto& job : options.cluster_def->job()) { std::map<int, string> host_ports; for (const auto& task : job.tasks()) { string& host_port = host_ports[task.first]; if (!host_port.empty()) { return errors::InvalidArgument("JobDef for job \"", job.name(), "\" specified two addresses for task \"", task.first, "\": ", host_port, " and ", task.second); } if (job.name() == *options.job_name && task.first == options.task_index) { host_port = strings::StrCat("localhost:", bound_port_); } else { host_port = task.second; } } TF_RETURN_IF_ERROR(channel_spec->AddHostPortsJob(job.name(), host_ports)); } return Status::OK(); } Status GrpcServer::WorkerCacheFactory(const WorkerCacheFactoryOptions& options, WorkerCacheInterface** worker_cache) { if (options.job_name == nullptr || options.job_name->empty()) { Status s = errors::InvalidArgument( "The master (current machine) is not included in the provided " "cluster_def. ", options.cluster_def->DebugString()); LOG(WARNING) << s; return s; } GrpcChannelSpec channel_spec; TF_RETURN_IF_ERROR(ParseChannelSpec(options, &channel_spec)); std::unique_ptr<GrpcChannelCache> channel_cache( NewGrpcChannelCache(channel_spec, GetChannelCreationFunction())); string name_prefix = strings::StrCat("/job:", *options.job_name, "/replica:0", "/task:", options.task_index); const string host_port = channel_cache->TranslateTask(name_prefix); int requested_port; if (!strings::safe_strto32(str_util::Split(host_port, ':')[1], &requested_port)) { return errors::Internal("Could not parse port for local server from \"", channel_cache->TranslateTask(name_prefix), "\"."); } if (requested_port != bound_port_) { return errors::InvalidArgument("Requested port ", requested_port, " differs from expected port ", bound_port_); } *worker_cache = NewGrpcWorkerCacheWithLocalWorker( channel_cache.release(), worker_impl_.get(), name_prefix); return Status::OK(); } Status GrpcServer::Start() { mutex_lock l(mu_); switch (state_) { case NEW: { master_thread_.reset( env_->StartThread(ThreadOptions(), "TF_master_service", [this] { master_service_->HandleRPCsLoop(); })); worker_thread_.reset( env_->StartThread(ThreadOptions(), "TF_worker_service", [this] { worker_service_->HandleRPCsLoop(); })); state_ = STARTED; LOG(INFO) << "Started server with target: " << target(); return Status::OK(); } case STARTED: LOG(INFO) << "Server already started (target: " << target() << ")"; return Status::OK(); case STOPPED: return errors::FailedPrecondition("Server has stopped."); default: LOG(FATAL); } } Status GrpcServer::Stop() { mutex_lock l(mu_); switch (state_) { case NEW: state_ = STOPPED; return Status::OK(); case STARTED: return errors::Unimplemented( "Clean shutdown is not currently implemented"); case STOPPED: LOG(INFO) << "Server already stopped (target: " << target() << ")"; return Status::OK(); default: LOG(FATAL); } } Status GrpcServer::Join() { mutex_lock l(mu_); switch (state_) { case NEW: // Prevent the server from being started subsequently. state_ = STOPPED; return Status::OK(); case STARTED: case STOPPED: master_thread_.reset(); worker_thread_.reset(); return Status::OK(); default: LOG(FATAL); } } const string GrpcServer::target() const { return strings::StrCat("grpc://localhost:", bound_port_); } std::shared_ptr<::grpc::ServerCredentials> GrpcServer::GetServerCredentials( const ServerDef& server_def) const { return ::grpc::InsecureServerCredentials(); } ChannelCreationFunction GrpcServer::GetChannelCreationFunction() const { // We can do this because SparseGrpcChannelCache is robust to nullptr being // returned by the channel creation function return ConvertToChannelCreationFunction(NewHostPortGrpcChannel); } std::unique_ptr<Master> GrpcServer::CreateMaster(MasterEnv* master_env) { return std::unique_ptr<Master>(new Master(master_env, 0.0)); } /* static */ Status GrpcServer::Create(const ServerDef& server_def, Env* env, std::unique_ptr<ServerInterface>* out_server) { std::unique_ptr<GrpcServer> ret( new GrpcServer(server_def, env == nullptr ? Env::Default() : env)); ServiceInitFunction service_func = nullptr; TF_RETURN_IF_ERROR(ret->Init(service_func, NewRpcRendezvousMgr)); *out_server = std::move(ret); return Status::OK(); } namespace { class GrpcServerFactory : public ServerFactory { public: bool AcceptsOptions(const ServerDef& server_def) override { return server_def.protocol() == "grpc"; } Status NewServer(const ServerDef& server_def, std::unique_ptr<ServerInterface>* out_server) override { return GrpcServer::Create(server_def, Env::Default(), out_server); } }; // Registers a `ServerFactory` for `GrpcServer` instances. class GrpcServerRegistrar { public: GrpcServerRegistrar() { gpr_allocation_functions alloc_fns; memset(&alloc_fns, 0, sizeof(alloc_fns)); alloc_fns.malloc_fn = port::Malloc; alloc_fns.realloc_fn = port::Realloc; alloc_fns.free_fn = port::Free; gpr_set_allocation_functions(alloc_fns); ServerFactory::Register("GRPC_SERVER", new GrpcServerFactory()); } }; static GrpcServerRegistrar registrar; } // namespace } // namespace tensorflow
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
6d91806d2e4b43b44f14f59b593d5c59188e09b7
eebcd9faf7b821b8006debbab33c0260ab8c128e
/cpp/activationFunctions.hpp
63159f7a43a531fc6b2fef47c687024fbfc6c52c
[ "MIT" ]
permissive
marfeljoergsen/cppnnml
5acc541467e6bcd28ec1c48921c4b66f9b5848e5
5b1bba4b68180c644df6d2c9ae95f3388ce75429
refs/heads/master
2022-11-24T22:29:13.202203
2020-07-30T22:55:00
2020-07-30T22:55:00
283,890,360
0
0
MIT
2020-07-30T22:38:08
2020-07-30T22:38:07
null
UTF-8
C++
false
false
7,894
hpp
/** * Copyright (c) 2020 Intel Corporation * * 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. */ #pragma once #include "lookupTable.hpp" #include "constants.hpp" #include "sigmoid.hpp" #include "tanh.hpp" #include "exp.hpp" #include "typeChooser.hpp" namespace tinymind { template<typename ValueType> struct NullActivationPolicy { static ValueType activationFunction(const ValueType& value) { return 0; } static ValueType activationFunctionDerivative(const ValueType& value) { return 0; } }; template<typename ValueType> struct ReluActivationPolicy { static ValueType activationFunction(const ValueType& value) { if(value <= 0) { return 0; } return value; } static ValueType activationFunctionDerivative(const ValueType& value) { if(value <= 0) { return 0; } return Constants<ValueType>::one(); } }; template<typename ValueType, typename FullWidthFieldTypeShim<ValueType>::FullWidthFieldType MaxValue> struct CappedReluActivationPolicy { typedef typename FullWidthFieldTypeShim<ValueType>::FullWidthFieldType FullWidthFieldType; static const FullWidthFieldType MAX_VALUE = MaxValue; static ValueType activationFunction(const ValueType& value) { if(value <= 0) { return 0; } if(value > MAX_VALUE) { return MAX_VALUE; } else { return value; } } static ValueType activationFunctionDerivative(const ValueType& value) { return ReluActivationPolicy<ValueType>::activationFunctionDerivative(value); } }; template<typename ValueType> struct SigmoidActivationPolicy { typedef LookupTable<ValueType> LookupTableType; typedef typename SigmoidValuesTableSelector<ValueType::NumberOfFixedBits, ValueType::NumberOfFractionalBits, ValueType::IsSigned>::SigmoidTableType SigmoidTableType; static ValueType activationFunction(const ValueType& value) { static const ptrdiff_t MAX_ACTIVATION_INDEX = ((sizeof(sigmoidActivationTable.values) / sizeof(sigmoidActivationTable.values[0])) - 1); const ValueType result = LookupTableType::getValue(value, &sigmoidActivationTable.values[0], MAX_ACTIVATION_INDEX); return result; } static ValueType activationFunctionDerivative(const ValueType& value) { //Approximation for 1st derivative of sigmoid const ValueType oneMinusValue = (Constants<ValueType>::one() - value); return (value * oneMinusValue); } private: static const SigmoidTableType sigmoidActivationTable; }; template<typename ValueType> const typename SigmoidValuesTableSelector<ValueType::NumberOfFixedBits, ValueType::NumberOfFractionalBits, ValueType::IsSigned>::SigmoidTableType SigmoidActivationPolicy<ValueType>::sigmoidActivationTable; template<typename ValueType> struct TanhActivationPolicy { typedef typename ValueType::FullWidthFieldType FullWidthFieldType; typedef LookupTable<ValueType> LookupTableType; typedef typename TanhValuesTableSelector<ValueType::NumberOfFixedBits, ValueType::NumberOfFractionalBits, ValueType::IsSigned>::TanhTableType TanhTableType; static ValueType activationFunction(const ValueType& value) { static const ptrdiff_t MAX_ACTIVATION_INDEX = (((sizeof(FullWidthFieldType) * NUMBER_OF_ACTIVATION_TABLE_VALUES) / sizeof(tanhActivationTable.values[0])) - 1); const ValueType result = LookupTableType::getValue(value, &tanhActivationTable.values[0], MAX_ACTIVATION_INDEX); return result; } static ValueType activationFunctionDerivative(const ValueType& value) { //Approximation for 1st derivative of tanh const ValueType valueSquared = (value * value); return (Constants<ValueType>::one() - valueSquared); } private: static const TanhTableType tanhActivationTable; }; template<typename ValueType> const typename TanhValuesTableSelector<ValueType::NumberOfFixedBits, ValueType::NumberOfFractionalBits, ValueType::IsSigned>::TanhTableType TanhActivationPolicy<ValueType>::tanhActivationTable; template<typename ValueType> struct SoftmaxActivationPolicy { typedef typename ValueType::FullWidthFieldType FullWidthFieldType; typedef LookupTable<ValueType> LookupTableType; typedef typename ExpValuesTableSelector<ValueType::NumberOfFixedBits, ValueType::NumberOfFractionalBits, ValueType::IsSigned>::ExpTableType ExpTableType; static void activationFunction(ValueType const* const values, ValueType* results, const size_t numberOfNerons) { static const ptrdiff_t MAX_ACTIVATION_INDEX = (((sizeof(FullWidthFieldType) * NUMBER_OF_ACTIVATION_TABLE_VALUES) / sizeof(expActivationTable.values[0])) - 1); ValueType result; ValueType sum(0); for(size_t neuron = 0;neuron < numberOfNerons;++neuron) { result = LookupTableType::getValue(values[neuron], &expActivationTable.values[0], MAX_ACTIVATION_INDEX); results[neuron] = result; sum += result; } for(size_t neuron = 0;neuron < numberOfNerons;++neuron) { results[neuron] /= sum; } } static void activationFunctionDerivative(ValueType const* const values, ValueType const* const targetValues, ValueType* results, const size_t numberOfNerons) { for(size_t neuron = 0;neuron < numberOfNerons;++neuron) { if(targetValues[neuron] == Constants<ValueType>::one()) { results[neuron] = (values[neuron] - Constants<ValueType>::one()); } else { results[neuron] = values[neuron]; } } } private: static const ExpTableType expActivationTable; }; template<typename ValueType> const typename ExpValuesTableSelector<ValueType::NumberOfFixedBits, ValueType::NumberOfFractionalBits, ValueType::IsSigned>::ExpTableType SoftmaxActivationPolicy<ValueType>::expActivationTable; }
[ "daniel.mcleran@intel.com" ]
daniel.mcleran@intel.com
3b46c6d0a9b20345f0057c7e56d493caf910b9a7
0754c3886e02d08dc337148b59674e62488d6234
/chapter3/orphan.cpp
7f560543ef32f95815fdeea0de23ab1d8494a5fc
[]
no_license
sarahchai/operatingsystems-classroom-examples
920c8b77ecb23017f5881a228a07aafe4531dbfb
60f32f6218ed773d4922a32fc340e0a379881931
refs/heads/master
2023-06-18T03:00:29.632802
2021-07-11T19:34:16
2021-07-11T19:34:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
738
cpp
// A C program to demonstrate Orphan Process. // Child becomes an orphan if the parent exits // while the child is still running. #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include <iostream> using namespace std; int main() { cout << "Parent pid: " << getpid() << ". " << "Parent of parent: " << getppid() << endl; // Create a child process int pid = fork(); if (pid > 0) { sleep(5); } else if (pid == 0) { // We're in the child process cout << "Child pid: " << getpid() << ". Parent pid: " << getppid() << endl; sleep(6); cout << "Child pid: " << getpid() << ". Parent pid: " << getppid() << endl; } return 0; }
[ "skamens1@fordham.edu" ]
skamens1@fordham.edu
d5871bdd2b7aedd00f93ac67969e42d9df0c2e35
6fff0893ef43f1018d65f2e8e1bf27d9f8accf5b
/pw_thread_threadx/public/pw_thread_threadx/thread_inline.h
33ab70f27b1239d5907b83bf76df26f379878903
[ "Apache-2.0" ]
permissive
isabella232/pigweed
eeb68a4eda6f0a9b5ef0b8145d0204bc9f85bfdc
53c2f3e2569d7e582d3dd3056ceb9b2c3b8197b2
refs/heads/main
2023-06-03T10:32:29.498066
2021-06-17T06:38:15
2021-06-17T20:44:55
378,165,913
0
0
Apache-2.0
2021-06-18T13:54:37
2021-06-18T13:53:40
null
UTF-8
C++
false
false
1,388
h
// Copyright 2021 The Pigweed Authors // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. #pragma once #include <algorithm> #include "pw_assert/assert.h" #include "pw_thread/id.h" #include "pw_thread_threadx/config.h" #include "pw_thread_threadx/options.h" namespace pw::thread { inline Thread::Thread() : native_type_(nullptr) {} inline Thread& Thread::operator=(Thread&& other) { native_type_ = other.native_type_; other.native_type_ = nullptr; return *this; } inline Thread::~Thread() { PW_DASSERT(native_type_ == nullptr); } inline Id Thread::get_id() const { if (native_type_ == nullptr) { return Id(nullptr); } return Id(&native_type_->tcb()); } inline void Thread::swap(Thread& other) { std::swap(native_type_, other.native_type_); } inline Thread::native_handle_type Thread::native_handle() { return native_type_; } } // namespace pw::thread
[ "pigweed-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
pigweed-scoped@luci-project-accounts.iam.gserviceaccount.com
6ed837ffeede7e070a699cf12e6ff081556cc333
55d560fe6678a3edc9232ef14de8fafd7b7ece12
/libs/random/test/test_lagged_fibonacci4423.cpp
ae6a32dcbfb7b0805dd233e48e4e9e8718422f81
[ "BSL-1.0" ]
permissive
stardog-union/boost
ec3abeeef1b45389228df031bf25b470d3d123c5
caa4a540db892caa92e5346e0094c63dea51cbfb
refs/heads/stardog/develop
2021-06-25T02:15:10.697006
2020-11-17T19:50:35
2020-11-17T19:50:35
148,681,713
0
0
BSL-1.0
2020-11-17T19:50:36
2018-09-13T18:38:54
C++
UTF-8
C++
false
false
733
cpp
/* test_lagged_fibonacci4423.cpp * * Copyright Steven Watanabe 2011 * 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) * * $Id$ * */ #include <boost/random/lagged_fibonacci.hpp> #define BOOST_RANDOM_URNG boost::random::lagged_fibonacci4423 #define BOOST_RANDOM_SEED_WORDS 4423*2 #define BOOST_RANDOM_VALIDATION_VALUE 0.23188533286820601 #define BOOST_RANDOM_SEED_SEQ_VALIDATION_VALUE 0.3872440622693567 #define BOOST_RANDOM_ITERATOR_VALIDATION_VALUE 0.012893676760814543 #define BOOST_RANDOM_GENERATE_VALUES { 0x6D4DBAFU, 0x8039C1A9U, 0x3DA53D58U, 0x95155BE5U } #include "test_generator.ipp"
[ "james.pack@stardog.com" ]
james.pack@stardog.com
1d2eecd5d294eb8472bdec23bee4b7de2aefdd37
6c3dfad0b73252a5c8737c6210ebfe5ccbb38e41
/TraktanaQt/Traktana.h
2ac7a52ff39b78fcfc84fa195d636f3510066c7c
[]
no_license
rggama/traktana
16b9afc8c3f7bd8176c150d3219cc80fc8ee4323
246cf99fca676958c8467c05f950adc93d92de23
refs/heads/master
2021-05-29T01:36:48.542150
2012-03-26T14:03:32
2012-03-26T14:03:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
291
h
/* * File: Traktana.h * Author: victor * * Created on 24 de Outubro de 2010, 19:29 */ #ifndef TRAKTANA_H #define TRAKTANA_H #include "TraktanaDebug.h" class Traktana : public TraktanaDebug { public: Traktana(); virtual ~Traktana(); private: }; #endif /* TRAKTANA_H */
[ "victor.ecomp@980a965b-2580-2584-76ce-5b5fa40a2959" ]
victor.ecomp@980a965b-2580-2584-76ce-5b5fa40a2959
5ca8f0bcc87ee353f414549f88109e6ee04e474d
a090f580010d07c7f609ab13c3a84e7500fc63fa
/src/cubemap/CubeMap.cpp
569de2b79162438b74399355a5a05797db9dce74
[ "LicenseRef-scancode-public-domain", "Unlicense", "MIT" ]
permissive
2n2b1/magnum-examples
176524bfb4ae31b9fd4705f4c2c44f3b98f1fdb0
21a60acabcb7c4628dc8ba91d12f6c7ba20fb414
refs/heads/master
2020-07-07T15:34:11.292229
2019-07-29T14:34:30
2019-07-29T14:34:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,497
cpp
/* This file is part of Magnum. Original authors — credit is appreciated but not required: 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 — Vladimír Vondruš <mosra@centrum.cz> This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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 "CubeMap.h" #include <Corrade/Containers/Optional.h> #include <Corrade/Utility/Directory.h> #include <Corrade/Utility/Resource.h> #include <Magnum/ImageView.h> #include <Magnum/Mesh.h> #include <Magnum/GL/Buffer.h> #include <Magnum/GL/Mesh.h> #include <Magnum/GL/CubeMapTexture.h> #include <Magnum/GL/Texture.h> #include <Magnum/GL/TextureFormat.h> #include <Magnum/Math/Functions.h> #include <Magnum/MeshTools/FlipNormals.h> #include <Magnum/MeshTools/Interleave.h> #include <Magnum/MeshTools/CompressIndices.h> #include <Magnum/Primitives/Cube.h> #include <Magnum/SceneGraph/Scene.h> #include <Magnum/SceneGraph/Camera.h> #include <Magnum/Trade/AbstractImporter.h> #include <Magnum/Trade/ImageData.h> #include <Magnum/Trade/MeshData3D.h> #include "CubeMapShader.h" namespace Magnum { namespace Examples { CubeMap::CubeMap(const std::string& prefix, Object3D* parent, SceneGraph::DrawableGroup3D* group): Object3D(parent), SceneGraph::Drawable3D(*this, group) { CubeMapResourceManager& resourceManager = CubeMapResourceManager::instance(); /* Cube mesh */ if(!(_cube = resourceManager.get<GL::Mesh>("cube"))) { Trade::MeshData3D cubeData = Primitives::cubeSolid(); MeshTools::flipFaceWinding(cubeData.indices()); GL::Buffer* buffer = new GL::Buffer; buffer->setData(MeshTools::interleave(cubeData.positions(0)), GL::BufferUsage::StaticDraw); Containers::Array<char> indexData; MeshIndexType indexType; UnsignedInt indexStart, indexEnd; std::tie(indexData, indexType, indexStart, indexEnd) = MeshTools::compressIndices(cubeData.indices()); GL::Buffer* indexBuffer = new GL::Buffer; indexBuffer->setData(indexData, GL::BufferUsage::StaticDraw); GL::Mesh* mesh = new GL::Mesh; mesh->setPrimitive(cubeData.primitive()) .setCount(cubeData.indices().size()) .addVertexBuffer(*buffer, 0, CubeMapShader::Position{}) .setIndexBuffer(*indexBuffer, 0, indexType, indexStart, indexEnd); resourceManager.set("cube-buffer", buffer, ResourceDataState::Final, ResourcePolicy::Resident) .set("cube-index-buffer", indexBuffer, ResourceDataState::Final, ResourcePolicy::Resident) .set(_cube.key(), mesh, ResourceDataState::Final, ResourcePolicy::Resident); } /* Cube map texture */ if(!(_texture = resourceManager.get<GL::CubeMapTexture>("texture"))) { GL::CubeMapTexture* cubeMap = new GL::CubeMapTexture; cubeMap->setWrapping(GL::SamplerWrapping::ClampToEdge) .setMagnificationFilter(GL::SamplerFilter::Linear) .setMinificationFilter(GL::SamplerFilter::Linear, GL::SamplerMipmap::Linear); Resource<Trade::AbstractImporter> importer = resourceManager.get<Trade::AbstractImporter>("jpeg-importer"); /* Configure texture storage using size of first image */ importer->openFile(Utility::Directory::join(prefix, "+x.jpg")); Containers::Optional<Trade::ImageData2D> image = importer->image2D(0); CORRADE_INTERNAL_ASSERT(image); Vector2i size = image->size(); cubeMap->setStorage(Math::log2(size.min())+1, GL::TextureFormat::RGB8, size) .setSubImage(GL::CubeMapCoordinate::PositiveX, 0, {}, *image); importer->openFile(Utility::Directory::join(prefix, "-x.jpg")); CORRADE_INTERNAL_ASSERT_OUTPUT(image = importer->image2D(0)); cubeMap->setSubImage(GL::CubeMapCoordinate::NegativeX, 0, {}, *image); importer->openFile(Utility::Directory::join(prefix, "+y.jpg")); CORRADE_INTERNAL_ASSERT_OUTPUT(image = importer->image2D(0)); cubeMap->setSubImage(GL::CubeMapCoordinate::PositiveY, 0, {}, *image); importer->openFile(Utility::Directory::join(prefix, "-y.jpg")); CORRADE_INTERNAL_ASSERT_OUTPUT(image = importer->image2D(0)); cubeMap->setSubImage(GL::CubeMapCoordinate::NegativeY, 0, {}, *image); importer->openFile(Utility::Directory::join(prefix, "+z.jpg")); CORRADE_INTERNAL_ASSERT_OUTPUT(image = importer->image2D(0)); cubeMap->setSubImage(GL::CubeMapCoordinate::PositiveZ, 0, {}, *image); importer->openFile(Utility::Directory::join(prefix, "-z.jpg")); CORRADE_INTERNAL_ASSERT_OUTPUT(image = importer->image2D(0)); cubeMap->setSubImage(GL::CubeMapCoordinate::NegativeZ, 0, {}, *image); cubeMap->generateMipmap(); resourceManager.set(_texture.key(), cubeMap, ResourceDataState::Final, ResourcePolicy::Manual); } /* Shader */ if(!(_shader = resourceManager.get<GL::AbstractShaderProgram, CubeMapShader>("shader"))) resourceManager.set<GL::AbstractShaderProgram>(_shader.key(), new CubeMapShader, ResourceDataState::Final, ResourcePolicy::Manual); } void CubeMap::draw(const Matrix4& transformationMatrix, SceneGraph::Camera3D& camera) { _shader->setTransformationProjectionMatrix(camera.projectionMatrix()*transformationMatrix) .setTexture(*_texture); _cube->draw(*_shader); } }}
[ "mosra@centrum.cz" ]
mosra@centrum.cz
9558c8140fd2ea8d887d8d891cc86b707d103db2
76a5686e643a6e2903eb17990a16b2bc40368fe9
/tool5-scanTest1/src/testApp.h
985122c9b52e9089030da5bda6f83d47df3dc4a2
[]
no_license
carlesgutierrez/HanRiver-openFrameworks
cb42aeaef06d6cf1d9679e2fb0cb3e629e1dcb0c
0fc4ba45846d9b9bfa67e3fcef674fbea7ba7a1d
refs/heads/master
2021-01-17T21:32:57.938974
2012-05-09T05:21:39
2012-05-09T05:21:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
809
h
#pragma once #include "ofMain.h" #include "ofxGrabCam.h" #include "ofxGraycode.h" #include "ofxOsc.h" #define SERVER_PORT 5588 using namespace ofxGraycode; class testApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void keyPressed (int key); void keyReleased(int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); void processInput(); void moveFrame(int distance); void moveThreshold(int distance); PayloadGraycode payload; ofVideoGrabber video; Decoder decoder; int previewFrame; ofImage capturePreview; ofxOscReceiver rx; };
[ "elliot.woods@gmail.com" ]
elliot.woods@gmail.com
c10711d3fb26b369f536bbce017cb529fb755c68
f4a9d73016203c51c178726572d8920e88ab7dfe
/source/patchers/Patcher_MimicNaming.h
666d75a3cef6ac0bf514d85c6ea2b5d0ee640ba1
[]
no_license
sokcuri/Noginogi-Party
ebb720992fbab1464870d1075eb2401605a3c3de
dc22cae03d456e1c900a45a5704de1e76e35d4c9
refs/heads/master
2021-01-02T09:33:57.896638
2015-02-22T01:39:39
2015-02-22T01:39:39
31,148,426
11
3
null
null
null
null
WINDOWS-1252
C++
false
false
738
h
#pragma once /* ¹Ì¹Í À̸§Ç¥ * PATCHES: STANDARD.dll * * CTRL+H "MimicNaming" */ #include "../Main.h" #include "../Singleton.h" #include "GenericPatcher.h" class CPatcher_MimicNaming : public IGenericPatcher { public: CPatcher_MimicNaming(); bool Uninstall( void ); bool Toggle( void ); bool ReadINI( void ); bool WriteINI( void ); static bool IsPatchEnabled(void); static bool PatchToggle(void); static bool PatchEnable(void); static bool PatchDisable(void); private: // Options static bool PatchEnabled; // Hook functions static void patchMimicNaming(void); // Variables for hook functions static LPBYTE addrIsPet; LPBYTE funcPointer; }; typedef Singleton<CPatcher_MimicNaming> SngPatcher_MimicNaming;
[ "sokcuri@naver.com" ]
sokcuri@naver.com
c0eea34ea7bb0c902e7a988e8a4eb64aea302d78
1ba30347b366f2555fbc4b75eb7d1c6c88e2ad40
/Chapter 17. 부분 합/CHRISTMAS - pg 602, 1st trial. 구현 실패 (책의 답과 내 풀이의 차이점을 정확히 모르겠음)/CHRISTMAS/main.cpp
a8896e848e1d7d9257d3eafafa4ccd8719ef0a0d
[]
no_license
piecemakerz/Algorithm_Problem_Solving_Strategies
2c3587bacf9dd65f18baa7abfaf16872c721a26b
13f7f7aefebe7184c5572e3884d512ff31c0d654
refs/heads/master
2021-01-02T08:49:16.563897
2018-09-26T14:44:47
2018-09-26T14:44:47
98,980,011
0
0
null
null
null
null
UHC
C++
false
false
3,827
cpp
#include <iostream> #include <vector> #include <cstring> #include <cstdio> #include <algorithm> using namespace std; //내 풀이 - 시간 초과가 발생한다. /* const int MAXN = 100000; int C, N, K; int box[MAXN]; vector<int> psum; // 부분합 //vector<vector<int>> psumsum; // 구간합 - 사용 시 최대 MAXN * MAXN 크기의 벡터가 만들어지므로 //스택 오버플로우가 발생한다. int cache[MAXN+1]; //배열 box의 부분합을 계산한다. vector<int> partialSum() { vector<int> ret(N); ret[0] = box[0]; for (int i = 1; i < N; i++) ret[i] = ret[i - 1] + box[i]; return ret; } //구간 합 int rangeSum(int a, int b) { if (a == 0) return psum[b]; return psum[b] - psum[a - 1]; } //1번 문제 - 한 번만 주문할 수 있을 시 가능한 주문 방법 int numOfWays() { int ways = 0; for (int i = 0; i < N; i++) for (int j = i; j < N; j++) if (rangeSum(i, j) % K == 0) ways = (ways+1)%20091101; return ways; } //2번 문제 - 여러 번 주문 가능 시 주문이 겹치지 않게 주문할 수 있는 최대 방법의 수 //select = 이번에 선택할 상자 int maxOrders(int select = 0) { if (select >= N) return 0; int& ret = cache[select]; // select번 상자부터 주문할 경우 주문할 수 있는 최대 주문 수 if (ret != -1) return ret; ret = 0; // 이번 상자부터 주문할 경우 for (int i = select; i < N; i++) { for (int j = i; j < N; j++) { if (rangeSum(i,j) % K == 0) ret = max(ret, 1 + maxOrders(j + 1)); } } return ret; } */ //책의 답 int C, N, K; const int MAXN = 100000; int D[MAXN]; //이 문제에서는 psum[-1], 즉 아무것도 고르지 않는 부분합도 //고려하므로 psum[0] = 0으로 놓고 실질적인 부분합을 psum[1]에서부터 //저장한다. 즉, psum[i] = (D[0]~D[i-1]까지의 합) % k이다. void partialSum(vector<int>& psum, int k) { psum[1] = D[0] % k; for (int i = 2; i < psum.size(); i++) psum[i] = (psum[i - 1] + D[i - 1]) % k; } //D[]의 부분 합 배열 psum[]과 k가 주어질 때, 몇 가지 방법으로 살 수 있는지 반환한다. //psum[]의 첫 번째 원소 전에 0을 삽입했다고 가정한다. int waysToBuy(const vector<int>& psum, int k) { const int MOD = 20091101; int ret = 0; //psum[]의 각 값을 몇 번이나 본 적 있는지 기록한다. //psum[]의 값 범위는 0~k-1이다. vector<long long> count(k, 0); for (int i = 0; i < psum.size(); i++) count[psum[i]]++; for (int i = 0; i < K; i++) if (count[i] >= 2) ret = (ret + ((count[i] * (count[i] - 1)) / 2)) % MOD; return ret; } //D[]의 부분 합 배열 psum[]과 k가 주어질 때, 몇 번이나 살 수 있는지 반환한다. //psum[]의 첫 번째 원소 전에 0을 삽입했다고 가정한다. int maxBuys(const vector<int>& psum, int k) { //ret[i] = 첫 번째 상자부터 i번째 상자까지 고려했을 때 살 수 있는 최대 횟수 vector<int> ret(psum.size(), 0); //prev[s] = psum[]이 s였던 마지막 위치 vector<int> prev(k, -1); for (int i = 0; i < psum.size(); i++) { //i번째 상자를 아예 고려하지 않는 경우 if (i > 0) ret[i] = ret[i - 1]; else ret[i] = 0; //psum[i]를 전에도 본 적이 있으면, prev[psum[i]] + 1부터 여기까지 쭉 사 본다. int loc = prev[psum[i]]; if (loc != -1) ret[i] = max(ret[i], ret[loc] + 1); //prev[]에 현재 위치를 기록한다. prev[psum[i]] = i; } return ret.back(); } int main(void) { cin >> C; for (int testCase = 0; testCase < C; testCase++) { memset(D, 0, sizeof(D)); scanf("%d %d", &N, &K); for (int i = 0; i < N; i++) scanf("%d", &D[i]); vector<int> psum(N + 1, 0); psum[0] = 0; partialSum(psum, K); vector<int>::iterator iter = psum.begin(); printf("%d %d\n", waysToBuy(psum, K), maxBuys(psum, K)); } return 0; }
[ "piecemakerz@naver.com" ]
piecemakerz@naver.com
4924cf1fb1b935629fd7c64217a9f5858d83087c
e06231c85286d9d78e3e57330282367a41b08cec
/src/Gui/Common/LinkLikeColumnDelegate.h
eb48fc3e14ed2135f5ac4bccff88ea842df05c2e
[ "MIT" ]
permissive
marcoinproject/marcoin-gui
53465d0295074565483c15f094a738f33548cacf
df0cc1f54e8688f8c8c38f193e888178114d433d
refs/heads/master
2020-03-17T07:44:56.870132
2019-06-05T13:02:01
2019-06-05T13:02:01
133,411,161
0
1
null
null
null
null
UTF-8
C++
false
false
704
h
/* * Copyright (c) 2018, The Marcoin Developers. * Portions Copyright (c) 2012-2017, The CryptoNote Developers, The Bytecoin Developers. * * This file is part of Marcoin. * * This file is subject to the terms and conditions defined in the * file 'LICENSE', which is part of this source code package. */ #pragma once #include <QStyledItemDelegate> namespace WalletGui { class LinkLikeColumnDelegate : public QStyledItemDelegate { Q_OBJECT Q_DISABLE_COPY(LinkLikeColumnDelegate) public: explicit LinkLikeColumnDelegate(QObject* _parent); ~LinkLikeColumnDelegate(); void paint(QPainter* _painter, const QStyleOptionViewItem& _option, const QModelIndex& _index) const override; }; }
[ "support@marcoinproject.com" ]
support@marcoinproject.com
75962ce0b4617c7010cbd2338eba14539ff86121
fca339684dfe174fa5fb075a4a323fd32bc673ab
/Test4_Code/Module_Code_Dependencies/m5_d12.cxx
23adbbdeac44ef79b556a12ce57fd60d4d5b5481
[]
no_license
Jwcob/BA21_MODULE_TESTS
e2e44869f44de420d64fb0fb37885d079e8b8395
0d8ab1551d01a59c6475c24f2717589545de5237
refs/heads/main
2023-05-13T01:09:50.418445
2021-05-25T23:28:08
2021-05-25T23:28:08
370,734,048
0
0
null
null
null
null
UTF-8
C++
false
false
21,614
cxx
export module m5_d12; import m1_d13; import m2_d13; export namespace m5d12_ns { int return0(){ int x = 0 * 2; x += x; return x; } int return1(){ int x = 1 * 2; x += x; return x; } int return2(){ int x = 2 * 2; x += x; return x; } int return3(){ int x = 3 * 2; x += x; return x; } int return4(){ int x = 4 * 2; x += x; return x; } int return5(){ int x = 5 * 2; x += x; return x; } int return6(){ int x = 6 * 2; x += x; return x; } int return7(){ int x = 7 * 2; x += x; return x; } int return8(){ int x = 8 * 2; x += x; return x; } int return9(){ int x = 9 * 2; x += x; return x; } int return10(){ int x = 10 * 2; x += x; return x; } int return11(){ int x = 11 * 2; x += x; return x; } int return12(){ int x = 12 * 2; x += x; return x; } int return13(){ int x = 13 * 2; x += x; return x; } int return14(){ int x = 14 * 2; x += x; return x; } int return15(){ int x = 15 * 2; x += x; return x; } int return16(){ int x = 16 * 2; x += x; return x; } int return17(){ int x = 17 * 2; x += x; return x; } int return18(){ int x = 18 * 2; x += x; return x; } int return19(){ int x = 19 * 2; x += x; return x; } int return20(){ int x = 20 * 2; x += x; return x; } int return21(){ int x = 21 * 2; x += x; return x; } int return22(){ int x = 22 * 2; x += x; return x; } int return23(){ int x = 23 * 2; x += x; return x; } int return24(){ int x = 24 * 2; x += x; return x; } int return25(){ int x = 25 * 2; x += x; return x; } int return26(){ int x = 26 * 2; x += x; return x; } int return27(){ int x = 27 * 2; x += x; return x; } int return28(){ int x = 28 * 2; x += x; return x; } int return29(){ int x = 29 * 2; x += x; return x; } int return30(){ int x = 30 * 2; x += x; return x; } int return31(){ int x = 31 * 2; x += x; return x; } int return32(){ int x = 32 * 2; x += x; return x; } int return33(){ int x = 33 * 2; x += x; return x; } int return34(){ int x = 34 * 2; x += x; return x; } int return35(){ int x = 35 * 2; x += x; return x; } int return36(){ int x = 36 * 2; x += x; return x; } int return37(){ int x = 37 * 2; x += x; return x; } int return38(){ int x = 38 * 2; x += x; return x; } int return39(){ int x = 39 * 2; x += x; return x; } int return40(){ int x = 40 * 2; x += x; return x; } int return41(){ int x = 41 * 2; x += x; return x; } int return42(){ int x = 42 * 2; x += x; return x; } int return43(){ int x = 43 * 2; x += x; return x; } int return44(){ int x = 44 * 2; x += x; return x; } int return45(){ int x = 45 * 2; x += x; return x; } int return46(){ int x = 46 * 2; x += x; return x; } int return47(){ int x = 47 * 2; x += x; return x; } int return48(){ int x = 48 * 2; x += x; return x; } int return49(){ int x = 49 * 2; x += x; return x; } int return50(){ int x = 50 * 2; x += x; return x; } int return51(){ int x = 51 * 2; x += x; return x; } int return52(){ int x = 52 * 2; x += x; return x; } int return53(){ int x = 53 * 2; x += x; return x; } int return54(){ int x = 54 * 2; x += x; return x; } int return55(){ int x = 55 * 2; x += x; return x; } int return56(){ int x = 56 * 2; x += x; return x; } int return57(){ int x = 57 * 2; x += x; return x; } int return58(){ int x = 58 * 2; x += x; return x; } int return59(){ int x = 59 * 2; x += x; return x; } int return60(){ int x = 60 * 2; x += x; return x; } int return61(){ int x = 61 * 2; x += x; return x; } int return62(){ int x = 62 * 2; x += x; return x; } int return63(){ int x = 63 * 2; x += x; return x; } int return64(){ int x = 64 * 2; x += x; return x; } int return65(){ int x = 65 * 2; x += x; return x; } int return66(){ int x = 66 * 2; x += x; return x; } int return67(){ int x = 67 * 2; x += x; return x; } int return68(){ int x = 68 * 2; x += x; return x; } int return69(){ int x = 69 * 2; x += x; return x; } int return70(){ int x = 70 * 2; x += x; return x; } int return71(){ int x = 71 * 2; x += x; return x; } int return72(){ int x = 72 * 2; x += x; return x; } int return73(){ int x = 73 * 2; x += x; return x; } int return74(){ int x = 74 * 2; x += x; return x; } int return75(){ int x = 75 * 2; x += x; return x; } int return76(){ int x = 76 * 2; x += x; return x; } int return77(){ int x = 77 * 2; x += x; return x; } int return78(){ int x = 78 * 2; x += x; return x; } int return79(){ int x = 79 * 2; x += x; return x; } int return80(){ int x = 80 * 2; x += x; return x; } int return81(){ int x = 81 * 2; x += x; return x; } int return82(){ int x = 82 * 2; x += x; return x; } int return83(){ int x = 83 * 2; x += x; return x; } int return84(){ int x = 84 * 2; x += x; return x; } int return85(){ int x = 85 * 2; x += x; return x; } int return86(){ int x = 86 * 2; x += x; return x; } int return87(){ int x = 87 * 2; x += x; return x; } int return88(){ int x = 88 * 2; x += x; return x; } int return89(){ int x = 89 * 2; x += x; return x; } int return90(){ int x = 90 * 2; x += x; return x; } int return91(){ int x = 91 * 2; x += x; return x; } int return92(){ int x = 92 * 2; x += x; return x; } int return93(){ int x = 93 * 2; x += x; return x; } int return94(){ int x = 94 * 2; x += x; return x; } int return95(){ int x = 95 * 2; x += x; return x; } int return96(){ int x = 96 * 2; x += x; return x; } int return97(){ int x = 97 * 2; x += x; return x; } int return98(){ int x = 98 * 2; x += x; return x; } int return99(){ int x = 99 * 2; x += x; return x; } int return100(){ int x = 100 * 2; x += x; return x; } int return101(){ int x = 101 * 2; x += x; return x; } int return102(){ int x = 102 * 2; x += x; return x; } int return103(){ int x = 103 * 2; x += x; return x; } int return104(){ int x = 104 * 2; x += x; return x; } int return105(){ int x = 105 * 2; x += x; return x; } int return106(){ int x = 106 * 2; x += x; return x; } int return107(){ int x = 107 * 2; x += x; return x; } int return108(){ int x = 108 * 2; x += x; return x; } int return109(){ int x = 109 * 2; x += x; return x; } int return110(){ int x = 110 * 2; x += x; return x; } int return111(){ int x = 111 * 2; x += x; return x; } int return112(){ int x = 112 * 2; x += x; return x; } int return113(){ int x = 113 * 2; x += x; return x; } int return114(){ int x = 114 * 2; x += x; return x; } int return115(){ int x = 115 * 2; x += x; return x; } int return116(){ int x = 116 * 2; x += x; return x; } int return117(){ int x = 117 * 2; x += x; return x; } int return118(){ int x = 118 * 2; x += x; return x; } int return119(){ int x = 119 * 2; x += x; return x; } int return120(){ int x = 120 * 2; x += x; return x; } int return121(){ int x = 121 * 2; x += x; return x; } int return122(){ int x = 122 * 2; x += x; return x; } int return123(){ int x = 123 * 2; x += x; return x; } int return124(){ int x = 124 * 2; x += x; return x; } int return125(){ int x = 125 * 2; x += x; return x; } int return126(){ int x = 126 * 2; x += x; return x; } int return127(){ int x = 127 * 2; x += x; return x; } int return128(){ int x = 128 * 2; x += x; return x; } int return129(){ int x = 129 * 2; x += x; return x; } int return130(){ int x = 130 * 2; x += x; return x; } int return131(){ int x = 131 * 2; x += x; return x; } int return132(){ int x = 132 * 2; x += x; return x; } int return133(){ int x = 133 * 2; x += x; return x; } int return134(){ int x = 134 * 2; x += x; return x; } int return135(){ int x = 135 * 2; x += x; return x; } int return136(){ int x = 136 * 2; x += x; return x; } int return137(){ int x = 137 * 2; x += x; return x; } int return138(){ int x = 138 * 2; x += x; return x; } int return139(){ int x = 139 * 2; x += x; return x; } int return140(){ int x = 140 * 2; x += x; return x; } int return141(){ int x = 141 * 2; x += x; return x; } int return142(){ int x = 142 * 2; x += x; return x; } int return143(){ int x = 143 * 2; x += x; return x; } int return144(){ int x = 144 * 2; x += x; return x; } int return145(){ int x = 145 * 2; x += x; return x; } int return146(){ int x = 146 * 2; x += x; return x; } int return147(){ int x = 147 * 2; x += x; return x; } int return148(){ int x = 148 * 2; x += x; return x; } int return149(){ int x = 149 * 2; x += x; return x; } int return150(){ int x = 150 * 2; x += x; return x; } int return151(){ int x = 151 * 2; x += x; return x; } int return152(){ int x = 152 * 2; x += x; return x; } int return153(){ int x = 153 * 2; x += x; return x; } int return154(){ int x = 154 * 2; x += x; return x; } int return155(){ int x = 155 * 2; x += x; return x; } int return156(){ int x = 156 * 2; x += x; return x; } int return157(){ int x = 157 * 2; x += x; return x; } int return158(){ int x = 158 * 2; x += x; return x; } int return159(){ int x = 159 * 2; x += x; return x; } int return160(){ int x = 160 * 2; x += x; return x; } int return161(){ int x = 161 * 2; x += x; return x; } int return162(){ int x = 162 * 2; x += x; return x; } int return163(){ int x = 163 * 2; x += x; return x; } int return164(){ int x = 164 * 2; x += x; return x; } int return165(){ int x = 165 * 2; x += x; return x; } int return166(){ int x = 166 * 2; x += x; return x; } int return167(){ int x = 167 * 2; x += x; return x; } int return168(){ int x = 168 * 2; x += x; return x; } int return169(){ int x = 169 * 2; x += x; return x; } int return170(){ int x = 170 * 2; x += x; return x; } int return171(){ int x = 171 * 2; x += x; return x; } int return172(){ int x = 172 * 2; x += x; return x; } int return173(){ int x = 173 * 2; x += x; return x; } int return174(){ int x = 174 * 2; x += x; return x; } int return175(){ int x = 175 * 2; x += x; return x; } int return176(){ int x = 176 * 2; x += x; return x; } int return177(){ int x = 177 * 2; x += x; return x; } int return178(){ int x = 178 * 2; x += x; return x; } int return179(){ int x = 179 * 2; x += x; return x; } int return180(){ int x = 180 * 2; x += x; return x; } int return181(){ int x = 181 * 2; x += x; return x; } int return182(){ int x = 182 * 2; x += x; return x; } int return183(){ int x = 183 * 2; x += x; return x; } int return184(){ int x = 184 * 2; x += x; return x; } int return185(){ int x = 185 * 2; x += x; return x; } int return186(){ int x = 186 * 2; x += x; return x; } int return187(){ int x = 187 * 2; x += x; return x; } int return188(){ int x = 188 * 2; x += x; return x; } int return189(){ int x = 189 * 2; x += x; return x; } int return190(){ int x = 190 * 2; x += x; return x; } int return191(){ int x = 191 * 2; x += x; return x; } int return192(){ int x = 192 * 2; x += x; return x; } int return193(){ int x = 193 * 2; x += x; return x; } int return194(){ int x = 194 * 2; x += x; return x; } int return195(){ int x = 195 * 2; x += x; return x; } int return196(){ int x = 196 * 2; x += x; return x; } int return197(){ int x = 197 * 2; x += x; return x; } int return198(){ int x = 198 * 2; x += x; return x; } int return199(){ int x = 199 * 2; x += x; return x; } int return200(){ int x = 200 * 2; x += x; return x; } int return201(){ int x = 201 * 2; x += x; return x; } int return202(){ int x = 202 * 2; x += x; return x; } int return203(){ int x = 203 * 2; x += x; return x; } int return204(){ int x = 204 * 2; x += x; return x; } int return205(){ int x = 205 * 2; x += x; return x; } int return206(){ int x = 206 * 2; x += x; return x; } int return207(){ int x = 207 * 2; x += x; return x; } int return208(){ int x = 208 * 2; x += x; return x; } int return209(){ int x = 209 * 2; x += x; return x; } int return210(){ int x = 210 * 2; x += x; return x; } int return211(){ int x = 211 * 2; x += x; return x; } int return212(){ int x = 212 * 2; x += x; return x; } int return213(){ int x = 213 * 2; x += x; return x; } int return214(){ int x = 214 * 2; x += x; return x; } int return215(){ int x = 215 * 2; x += x; return x; } int return216(){ int x = 216 * 2; x += x; return x; } int return217(){ int x = 217 * 2; x += x; return x; } int return218(){ int x = 218 * 2; x += x; return x; } int return219(){ int x = 219 * 2; x += x; return x; } int return220(){ int x = 220 * 2; x += x; return x; } int return221(){ int x = 221 * 2; x += x; return x; } int return222(){ int x = 222 * 2; x += x; return x; } int return223(){ int x = 223 * 2; x += x; return x; } int return224(){ int x = 224 * 2; x += x; return x; } int return225(){ int x = 225 * 2; x += x; return x; } int return226(){ int x = 226 * 2; x += x; return x; } int return227(){ int x = 227 * 2; x += x; return x; } int return228(){ int x = 228 * 2; x += x; return x; } int return229(){ int x = 229 * 2; x += x; return x; } int return230(){ int x = 230 * 2; x += x; return x; } int return231(){ int x = 231 * 2; x += x; return x; } int return232(){ int x = 232 * 2; x += x; return x; } int return233(){ int x = 233 * 2; x += x; return x; } int return234(){ int x = 234 * 2; x += x; return x; } int return235(){ int x = 235 * 2; x += x; return x; } int return236(){ int x = 236 * 2; x += x; return x; } int return237(){ int x = 237 * 2; x += x; return x; } int return238(){ int x = 238 * 2; x += x; return x; } int return239(){ int x = 239 * 2; x += x; return x; } int return240(){ int x = 240 * 2; x += x; return x; } int return241(){ int x = 241 * 2; x += x; return x; } int return242(){ int x = 242 * 2; x += x; return x; } int return243(){ int x = 243 * 2; x += x; return x; } int return244(){ int x = 244 * 2; x += x; return x; } int return245(){ int x = 245 * 2; x += x; return x; } int return246(){ int x = 246 * 2; x += x; return x; } int return247(){ int x = 247 * 2; x += x; return x; } int return248(){ int x = 248 * 2; x += x; return x; } int return249(){ int x = 249 * 2; x += x; return x; } }
[ "jacob.polanz@chello.at" ]
jacob.polanz@chello.at
519c55119dd8ac8f8ebcc7f1a45598d00c4d5361
3c3f398acb3e8fb32d3170bc2be2a5824fd670ed
/训练赛/图论/Frogs' Neighborhood.cpp
6fd7f3fcad03673a0536d391004a260311edfbd0
[]
no_license
im-cy/ACM-code
07d808adae18e900cd6021363bcf40a5726381d5
5b766ced1636212da4427bc1d5bac7174f73f3af
refs/heads/master
2022-11-23T20:56:37.786086
2020-07-20T15:06:18
2020-07-20T15:06:18
281,143,765
0
0
null
null
null
null
UTF-8
C++
false
false
1,029
cpp
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int sz = 200010; int n; struct node { int x,id; }num[sz]; bool cmp(node a,node b) { return a.x >= b.x; } int mp[21][21]; int main() { int T; scanf("%d",&T); while(T --) { memset(mp,0,sizeof(mp)); scanf("%d",&n); for(int i = 1 ; i <= n ; i ++) { scanf("%d",&num[i].x); num[i].id = i; } int k = 1; while(k <= n) { sort(num+k,num+n+1,cmp); if(num[k].x > n - k) break; int pos = 0; for(int i = 1 ; i <= num[k].x ; i ++) { if(num[k+i].x <= 0) break; pos = i; num[k+i].x --; mp[num[k].id][num[k+i].id] = 1 , mp[num[k+i].id][num[k].id] = 1; } if(pos < num[k].x) break; k ++; } if(k <= n) puts("NO"); else { puts("YES"); for(int i = 1 ; i <= n ; i ++) { for(int j = 1 ; j <= n ; j ++) { if(j != 1) printf(" "); printf("%d",mp[i][j]); } puts(""); } } if(T) puts(""); } return 0; }
[ "44048665+im-cy@users.noreply.github.com" ]
44048665+im-cy@users.noreply.github.com
df28ab3f2e22004637de8fb8d3bfca661fbb3b16
84dd296283499ea8f59b19c13238474bffc45926
/Alexey Frolov/Домашняя работа №2/Номер 8 слияние/Task 2.8 merge sort/listPoint.cpp
111e7b7cce1322852ff472ea6301377a19c0af37
[]
no_license
ElenaSmirnova/1c2013
e526f9aa2703a4efd95809cbd555627fe5cf4f86
3659c081634a93e2c005ae618efcc3f0df3708ae
refs/heads/master
2016-09-06T04:51:38.422949
2014-05-30T10:45:46
2014-05-30T10:45:46
32,135,801
0
0
null
null
null
null
UTF-8
C++
false
false
2,396
cpp
#include "stdafx.h" #include <iostream> #include "listPoint.h" using namespace std; typedef int ElementType; struct ListElement { int value; ListElement *next; }; struct ListPoint { ListElement *head; }; ListPoint *create() { ListPoint *result = new ListPoint; result->head = nullptr; return result; } ListElement *head(ListPoint *list) { return list->head; } ListElement *last(ListPoint *list) { return nullptr; } ListElement *next(ListPoint *list, ListElement *position) { return position->next; } ElementType returnValue(ListPoint *list, ListElement *position) { return position->value; } int sizeOfList(ListPoint *list) { if (head(list) == nullptr) return 0; int size = 0; PositionPoint temp = list->head; while (temp != nullptr) { temp = temp->next; size++; } return size; } ListElement *middle(ListPoint *list) { int middle = sizeOfList(list) / 2 - 1; ListElement *temp = list->head; while(middle > 0) { middle--; temp = temp->next; } return temp; } void insertToHead(ListPoint *list, ElementType element) { ListElement *newElement = new ListElement; newElement->value = element; newElement->next = list->head; list->head = newElement; } void insert(ListPoint *list, ElementType value, ListElement *position) { /*printList(list); cout << endl; cout << "!" << position << endl; system("pause"); if (sizeOfList(list) == 0) { insertToHead(list, value); return; } printList(list); cout << endl; cout << position << endl; system("pause");*/ ListElement *element = new ListElement; element->value = value; element->next = position->next; position->next = element; } void remove(ListPoint *list, PositionPoint position) { PositionPoint temp = position->next; position->next = position->next->next; delete temp; } void removeHead(ListPoint *list) { PositionPoint temp = list->head; list->head = list->head->next; delete temp; } void deleteList(ListPoint *list) { ListElement *temp = head(list); while (temp != nullptr) { ListElement *tempNext = temp; temp = next(list, temp); delete tempNext; } delete list; } void printList(ListPoint *list) { PositionPoint temp = list->head; while (temp != nullptr) { cout << temp->value << " "; temp = temp->next; } }
[ "lyoshafrosty@0f01eb16-6d9f-4518-cd9d-0c10718a35a1" ]
lyoshafrosty@0f01eb16-6d9f-4518-cd9d-0c10718a35a1
34a94390b66ed33437bb6581718e37121bd7d387
b38383846d082ec4e65ac18c1582f1ce231ea0b4
/Siv3D/include/Siv3D/Rectangle.hpp
06d9c4b2890d7c0da54e69c587cdd4becbd2e4a1
[ "MIT" ]
permissive
Siv3D/siv6
9c12427f470b65772f40504b1e5e5239a60bbe95
090e82b2f6398640638dfa43da3f829ba977d0e2
refs/heads/master
2021-02-07T05:12:41.108547
2020-10-25T05:27:11
2020-10-25T05:27:11
243,986,884
3
5
MIT
2020-09-27T14:32:38
2020-02-29T14:50:43
C++
UTF-8
C++
false
false
6,733
hpp
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2020 Ryo Suzuki // Copyright (c) 2016-2020 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include "Common.hpp" # include "PointVector.hpp" # include "ColorHSV.hpp" namespace s3d { /// @brief 長方形 /// @tparam SizeType 位置とサイズを表すベクトルの型 /// /// pos, tl() top() tr() /// +-----------------+ /// | | /// left() | | right() /// | | /// +-----------------+ /// bl() bottom() br() /// template <class SizeType> struct Rectangle { using position_type = SizeType; using size_type = SizeType; using value_type = typename size_type::value_type; SIV3D_DISABLE_MSVC_WARNINGS_PUSH(4201) union { struct { /// <summary> /// 長方形の左上の点の位置 /// </summary> position_type pos; /// <summary> /// 長方形のサイズ /// </summary> size_type size; }; struct { /// <summary> /// 長方形の左上の点の X 座標 /// </summary> value_type x; /// <summary> /// 長方形の左上の点の Y 座標 /// </summary> value_type y; /// <summary> /// 長方形の幅 /// </summary> value_type w; /// <summary> /// 長方形の高さ /// </summary> value_type h; }; }; SIV3D_DISABLE_MSVC_WARNINGS_POP() /// <summary> /// デフォルトコンストラクタ /// </summary> Rectangle() = default; /// <summary> /// 長方形を作成します。 /// </summary> /// <param name="_size"> /// 長方形の幅と高さ /// </param> SIV3D_NODISCARD_CXX20 explicit constexpr Rectangle(value_type _size) noexcept : pos(0, 0) , size(_size, _size) {} /// <summary> /// 長方形を作成します。 /// </summary> /// <param name="_w"> /// 長方形の幅 /// </param> /// <param name="_h"> /// 長方形の高さ /// </param> SIV3D_NODISCARD_CXX20 constexpr Rectangle(value_type _w, value_type _h) noexcept : pos(0, 0) , size(_w, _h) {} /// <summary> /// 長方形を作成します。 /// </summary> /// <param name="_size"> /// 長方形の大きさ /// </param> SIV3D_NODISCARD_CXX20 explicit constexpr Rectangle(size_type _size) noexcept : pos(0, 0) , size(_size) {} /// <summary> /// 長方形を作成します。 /// </summary> /// <param name="_w"> /// 長方形の左上の点の X 座標 /// </param> /// <param name="_h"> /// 長方形の左上の点の Y 座標 /// </param> /// <param name="_size"> /// 長方形の縦横の大きさ /// </param> SIV3D_NODISCARD_CXX20 constexpr Rectangle(value_type _x, value_type _y, value_type _size) noexcept : pos(_x, _y) , size(_size, _size) {} /// <summary> /// 長方形を作成します。 /// </summary> /// <param name="_w"> /// 長方形の左上の点の X 座標 /// </param> /// <param name="_h"> /// 長方形の左上の点の Y 座標 /// </param> /// <param name="_w"> /// 長方形の幅 /// </param> /// <param name="_h"> /// 長方形の高さ /// </param> SIV3D_NODISCARD_CXX20 constexpr Rectangle(value_type _x, value_type _y, value_type _w, value_type _h) noexcept : pos(_x, _y) , size(_w, _h) {} /// <summary> /// 長方形を作成します。 /// </summary> /// <param name="_w"> /// 長方形の左上の点の X 座標 /// </param> /// <param name="_h"> /// 長方形の左上の点の Y 座標 /// </param> /// <param name="_size"> /// 長方形の大きさ /// </param> SIV3D_NODISCARD_CXX20 constexpr Rectangle(value_type _x, value_type _y, size_type _size) noexcept : pos(_x, _y) , size(_size) {} /// <summary> /// 長方形を作成します。 /// </summary> /// <param name="_pos"> /// 長方形の左上の点の座標 /// </param> /// <param name="_size"> /// 長方形の大きさ /// </param> SIV3D_NODISCARD_CXX20 constexpr Rectangle(position_type _pos, value_type _size) noexcept : pos(_pos) , size(_size, _size) {} /// <summary> /// 長方形を作成します。 /// </summary> /// <param name="_pos"> /// 長方形の左上の点の座標 /// </param> /// <param name="_w"> /// 長方形の幅 /// </param> /// <param name="_h"> /// 長方形の高さ /// </param> SIV3D_NODISCARD_CXX20 constexpr Rectangle(position_type _pos, value_type _w, value_type _h) noexcept : pos(_pos) , size(_w, _h) {} /// <summary> /// 長方形を作成します。 /// </summary> /// <param name="_pos"> /// 長方形の左上の点の座標 /// </param> /// <param name="_size"> /// 長方形の大きさ /// </param> SIV3D_NODISCARD_CXX20 constexpr Rectangle(position_type _pos, size_type _size) noexcept : pos(_pos) , size(_size) {} /// <summary> /// 長方形を作成します。 /// </summary> /// <param name="r"> /// 長方形 /// </param> template <class Type> SIV3D_NODISCARD_CXX20 constexpr Rectangle(const Rectangle<Type>& r) noexcept : pos(static_cast<value_type>(r.x), static_cast<value_type>(r.y)) , size(static_cast<value_type>(r.w), static_cast<value_type>(r.h)) {} [[nodiscard]] friend constexpr bool operator ==(const Rectangle& lhs, const Rectangle& rhs) noexcept { return (lhs.pos == rhs.pos) && (lhs.size == rhs.size); } [[nodiscard]] friend constexpr bool operator !=(const Rectangle& lhs, const Rectangle& rhs) noexcept { return (lhs.pos != rhs.pos) || (lhs.size != rhs.size); } template <class CharType> friend std::basic_ostream<CharType>& operator <<(std::basic_ostream<CharType>& output, const Rectangle& value) { return output << CharType('(') << value.x << CharType(',') << CharType(' ') << value.y << CharType(',') << CharType(' ') << value.w << CharType(',') << CharType(' ') << value.h << CharType(')'); } template <class CharType> friend std::basic_istream<CharType>& operator >>(std::basic_istream<CharType>& input, Rectangle& value) { CharType unused; return input >> unused >> value.x >> unused >> value.y >> unused >> value.w >> unused >> value.h >> unused; } const Rectangle& draw(const ColorF& color = Palette::White) const; }; /// <summary> /// 長方形(要素が int 型) /// </summary> using Rect = Rectangle<Point>; /// <summary> /// 長方形(要素が double 型) /// </summary> using RectF = Rectangle<Vec2>; }
[ "reputeless+github@gmail.com" ]
reputeless+github@gmail.com
6d5a2863f2cebb99500cf82426c4b29fa1560ab1
49f82cebdec58904e599cdc37327fa667dd4c699
/源码/exec.cpp
8d3121da26d2fed02f393a50d682b90e35ee6c00
[]
no_license
visualxu/GKDsync
7a6bf6c9c4e4e0f133f4e84e705370d9dc14232f
a9f82f4ede63164cd48e6e0c76741b0c4181c748
refs/heads/master
2021-03-24T03:03:42.153965
2020-03-15T17:15:55
2020-03-15T17:15:55
247,509,291
2
0
null
null
null
null
UTF-8
C++
false
false
8,478
cpp
#include "exec.h" #include "end.h" #include "mainwindow.h" #include <QFile> #include <sys/types.h> #include <utime.h> #include <QTextCodec> void execlute::exec(QSqlQuery sql_query,QString *path2,QString *path1, QProgressDialog *dialog) { QFileInfo tmp_file("./share_dir"); int c = 0; if(tmp_file.absoluteFilePath() == (*path1).mid(0,tmp_file.absoluteFilePath().length())) { qDebug()<<*path1; c = 1; } int count = 0; QSqlQuery sql_query1 = sql_query; QFile file("./log.txt"); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { qDebug()<<file.errorString(); } QDir dir; QString d; sql_query.prepare("select * from fileinfo where status = ?");//add sql_query.bindValue(0,0); sql_query.exec(); while (sql_query.next()) { QString name = sql_query.value(0).toString(); int source = sql_query.value(3).toInt(); int time = sql_query.value(2).toInt(); QDateTime dtime = QDateTime::fromTime_t(time); if (source == 1) { QFileInfo fi = (*path1+name); if (time == 0) { if (!dir.exists(*path2+name)) { dir.mkpath(*path2+name); } } else { // QFileInfo fi = (*path1+name); utimbuf timekkk; timekkk.modtime = time; QFile::copy(fi.absoluteFilePath(),*path2+name); QByteArray s = (*path2+name).toUtf8(); char *filename; filename = s.data(); utime(filename,&timekkk); sql_query1.prepare("update fileinfo set time = ? where name = ?"); sql_query1.bindValue(0,fi.lastModified().toTime_t()); sql_query1.bindValue(1,name); sql_query1.exec(); } file.write("右边新增 "+name.toUtf8()+"时间:"+fi.lastModified().toString().toUtf8()+'\n'); } else if (source == 2){ QFileInfo fi = (*path2+name); if (time == 0) { if (!dir.exists(*path1+name)) { dir.mkpath(*path1+name); } } else { // QFileInfo fi = (*path2+name); utimbuf timekkk; timekkk.modtime = time; QFile::copy(fi.absoluteFilePath(),*path1+name); QByteArray s = (*path1+name).toUtf8(); char *filename; filename = s.data(); utime(filename,&timekkk); sql_query1.prepare("update fileinfo set time = ? where name = ?"); sql_query1.bindValue(0,fi.lastModified().toTime_t()); sql_query1.bindValue(1,name); sql_query1.exec(); if (c == 1) { QFileInfo file1(*path1+name); utimbuf buf; buf.modtime = file1.lastModified().toTime_t(); QByteArray s = (path2+name).toUtf8(); char *filename; filename = s.data(); utime(filename,&buf); sql_query1.prepare("update fileinfo set time = ? where name = ?"); sql_query1.bindValue(0,file1.lastModified().toTime_t()); sql_query1.bindValue(1,name); sql_query1.exec(); } } file.write("左边新增 "+name.toUtf8()+"时间:"+fi.lastModified().toString().toUtf8()+'\n'); } count++; dialog->setValue(count); QCoreApplication::processEvents(); QCoreApplication::processEvents(); if(dialog->wasCanceled()) return; } sql_query.prepare("select * from fileinfo where status = ?");//delete sql_query.bindValue(0,-1); sql_query.exec(); while (sql_query.next()) { QString name_1 = sql_query.value(0).toString(); int source = sql_query.value(3).toInt(); int time = sql_query.value(2).toInt(); if (source == 1) { QFileInfo fi(*path2+name_1); if (time == 0) { if (dir.exists(*path2+name_1)){ QString rdpath = *path2+name_1; rmd rmd1; rmd1.rmd_1(&rdpath); } } else { // QFileInfo fi(*path2+name_1); QFile::remove(fi.absoluteFilePath()); } file.write("右边删除 "+name_1.toUtf8()+"最后修改时间:"+fi.lastModified().toString().toUtf8()+'\n'); } if (source == 2) { QFileInfo fi(*path1+name_1); file.write("左边删除 "+name_1.toUtf8()+"最后修改时间:"+fi.lastModified().toString().toUtf8()+'\n'); if (time == 0) { if (dir.exists(*path1+name_1)) { // dir.rmpath(*path1+name_1); QString rdpath = *path1+name_1; rmd rmd1; rmd1.rmd_1(&rdpath); } } // if(!file else { // QFileInfo fi(*path1+name_1); QFile::remove(fi.absoluteFilePath()); } // file.write("左边删除 "+name_1.toUtf8()+"时间:"+fi.lastModified().toString().toUtf8()+'\n'); } count ++; dialog->setValue(count); QCoreApplication::processEvents(); QCoreApplication::processEvents(); if(dialog->wasCanceled()) return; } sql_query.prepare("select * from fileinfo where status = ?");//modify sql_query.bindValue(0,1); sql_query.exec(); // QSqlQuery sql_query1 = sql_query; while (sql_query.next()) { QString name = sql_query.value(0).toString(); // qDebug()<<name<<"modfify"; int time = sql_query.value(2).toInt(); int source = sql_query.value(3).toInt(); if (time != 0) { if (source == 1) { QFileInfo fi = (*path1+name); QFileInfo fi1 = (*path2+name); QFile::remove(fi1.absoluteFilePath()); QFile::copy(fi.absoluteFilePath(),*path2+name); utimbuf timekkk; timekkk.modtime = fi.lastModified().toTime_t(); QByteArray s = (*path2+name).toUtf8(); char *filename; filename = s.data(); utime(filename,&timekkk); file.write("右边修改 "+name.toUtf8()+"时间:"+fi.lastModified().toString().toUtf8()+'\n'); sql_query1.prepare("update fileinfo set time = ? where name = ?"); sql_query1.bindValue(0,fi.lastModified().toTime_t()); sql_query1.bindValue(1,name); sql_query1.exec(); } else { QFileInfo fi = (*path1+name); QFileInfo fi1 = (*path2+name); QFile::remove(fi.absoluteFilePath()); QFile::copy(fi1.absoluteFilePath(),*path1+name); utimbuf timekkk; timekkk.modtime = fi1.lastModified().toTime_t(); QByteArray s = (*path1+name).toUtf8(); char *filename; filename = s.data(); utime(filename,&timekkk); file.write("左边修改 "+name.toUtf8()+"时间:"+fi1.lastModified().toString().toUtf8()+'\n'); sql_query1.prepare("update fileinfo set time = ? where name = ?"); sql_query1.bindValue(0,fi1.lastModified().toTime_t()); sql_query1.bindValue(1,name); sql_query1.exec(); if (c == 1) { QFileInfo file1(*path1+name); utimbuf buf; buf.modtime = file1.lastModified().toTime_t(); QByteArray s = (*path2+name).toUtf8(); char *filename; filename = s.data(); utime(filename,&buf); sql_query1.prepare("update fileinfo set time = ? where name = ?"); sql_query1.bindValue(0,file1.lastModified().toTime_t()); sql_query1.bindValue(1,name); sql_query1.exec(); } } } count ++; dialog->setValue(count); QCoreApplication::processEvents(); if(dialog->wasCanceled()) return; } }
[ "wangxu20103817@qq.com" ]
wangxu20103817@qq.com
16b75a91e155b78217ce1007e843fba37d292731
28ea9a3d3357b9392a38e1b98e483faf52e517a6
/05_cpp/Serializer.hpp
e3b0fc5412f98bdc4b1adc64f18fe752d976faf5
[]
no_license
qmakar/made_2019_cpp
1cbaef5b682f509416c8b85642eb407d02115bce
d2eeb3a2b3e7bd20ac8ab8eb2cc921f1d6409261
refs/heads/master
2020-08-28T03:15:24.660182
2020-01-14T11:02:20
2020-01-14T11:02:20
217,572,069
1
0
null
null
null
null
UTF-8
C++
false
false
1,794
hpp
// // Serializer.hpp // 05_cpp // // Created by Qmakar on 16.11.2019. // Copyright © 2019 Qmakar. All rights reserved. // #ifndef Serializer_hpp #define Serializer_hpp #include "base.hpp" #include "CheckFunction.hpp" class Serializer { std::ostream& out_; static constexpr char Separator = ' '; public: explicit Serializer(std::ostream& out = std::cout) : out_(out) {} template <typename T, class = std::enable_if_t<has_serialize_v<T>>> Error save (T& object) { return object.serialize(*this); } template <class... Args> Error operator()(Args... args) { return process((args)...); } private: template <class T, class... Args> Error process(T val, Args... args) { if (process(val) != Error::NoError){ return Error::IsNotSerialized; }; return process((args)...); } template <class T> Error process(T val) { return Error::IsNotSerialized; } template <> Error process(uint64_t val) { out_ << val << Separator; return Error::NoError; } template <> Error process(bool val) { if (val){ out_ << "true" << Separator; } else{ out_ << "false" << Separator; } return Error::NoError; } }; template<typename T> struct IsSerialize { private: static int check(...); static Serializer a; template <class U> static auto check(U* u) -> decltype(u->serialize(a)); public: static constexpr bool value = IsSame<Error, decltype(IsSerialize<T>::check((T*) nullptr)) >::value; }; #endif /* Serializer_hpp */
[ "qmakar@gmail.com" ]
qmakar@gmail.com
8968c963ba3c11075f4f25e306916cdafc2a3861
378e2a63137fe83fe872182872dc0c723809b005
/UnityFix/Classes/Native/EasyAR_Unity_EasyAR_ObjectTargetBaseBehaviour958778738.h
8885f2b7acf6af5df8326796a6d9e1f51b1d88a8
[]
no_license
WenslowZhu/UnityTest
62c96676723eb2580fd9bf91c77eef03629be608
13a62f53124243101bb3ebba2a04cacadc135376
refs/heads/master
2020-12-02T07:50:26.328644
2019-04-20T07:44:40
2019-04-20T07:44:40
96,730,475
0
0
null
null
null
null
UTF-8
C++
false
false
8,787
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "EasyAR_Unity_EasyAR_TargetAbstractBehaviour1292968490.h" #include "EasyAR_Unity_EasyAR_StorageType2201494719.h" #include "UnityEngine_UnityEngine_Vector32243707580.h" // System.String struct String_t; // EasyAR.ObjectTarget struct ObjectTarget_t2086352254; // System.Collections.Generic.List`1<EasyAR.ObjectTrackerBaseBehaviour> struct List_1_t1659153283; // EasyAR.ObjectTrackerBaseBehaviour struct ObjectTrackerBaseBehaviour_t2290032151; // System.Action`3<EasyAR.ObjectTargetBaseBehaviour,EasyAR.ObjectTrackerBaseBehaviour,System.Boolean> struct Action_3_t3377464849; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // EasyAR.ObjectTargetBaseBehaviour struct ObjectTargetBaseBehaviour_t958778738 : public TargetAbstractBehaviour_t1292968490 { public: // EasyAR.StorageType EasyAR.ObjectTargetBaseBehaviour::Storage int32_t ___Storage_8; // System.String EasyAR.ObjectTargetBaseBehaviour::Path String_t* ___Path_9; // System.String EasyAR.ObjectTargetBaseBehaviour::Name String_t* ___Name_10; // System.Single EasyAR.ObjectTargetBaseBehaviour::Scale float ___Scale_11; // System.Boolean EasyAR.ObjectTargetBaseBehaviour::ActiveTargetOnStart bool ___ActiveTargetOnStart_12; // EasyAR.ObjectTarget EasyAR.ObjectTargetBaseBehaviour::Target ObjectTarget_t2086352254 * ___Target_13; // System.Collections.Generic.List`1<EasyAR.ObjectTrackerBaseBehaviour> EasyAR.ObjectTargetBaseBehaviour::loaders List_1_t1659153283 * ___loaders_14; // EasyAR.ObjectTrackerBaseBehaviour EasyAR.ObjectTargetBaseBehaviour::trackerBaseBehaviour ObjectTrackerBaseBehaviour_t2290032151 * ___trackerBaseBehaviour_15; // System.Boolean EasyAR.ObjectTargetBaseBehaviour::trackerBaseBehaviourHasSet bool ___trackerBaseBehaviourHasSet_16; // UnityEngine.Vector3 EasyAR.ObjectTargetBaseBehaviour::preScale Vector3_t2243707580 ___preScale_17; // System.Single EasyAR.ObjectTargetBaseBehaviour::preSize float ___preSize_18; // System.Boolean EasyAR.ObjectTargetBaseBehaviour::alreadysetup bool ___alreadysetup_19; // System.Action`3<EasyAR.ObjectTargetBaseBehaviour,EasyAR.ObjectTrackerBaseBehaviour,System.Boolean> EasyAR.ObjectTargetBaseBehaviour::TargetLoad Action_3_t3377464849 * ___TargetLoad_20; // System.Action`3<EasyAR.ObjectTargetBaseBehaviour,EasyAR.ObjectTrackerBaseBehaviour,System.Boolean> EasyAR.ObjectTargetBaseBehaviour::TargetUnload Action_3_t3377464849 * ___TargetUnload_21; public: inline static int32_t get_offset_of_Storage_8() { return static_cast<int32_t>(offsetof(ObjectTargetBaseBehaviour_t958778738, ___Storage_8)); } inline int32_t get_Storage_8() const { return ___Storage_8; } inline int32_t* get_address_of_Storage_8() { return &___Storage_8; } inline void set_Storage_8(int32_t value) { ___Storage_8 = value; } inline static int32_t get_offset_of_Path_9() { return static_cast<int32_t>(offsetof(ObjectTargetBaseBehaviour_t958778738, ___Path_9)); } inline String_t* get_Path_9() const { return ___Path_9; } inline String_t** get_address_of_Path_9() { return &___Path_9; } inline void set_Path_9(String_t* value) { ___Path_9 = value; Il2CppCodeGenWriteBarrier(&___Path_9, value); } inline static int32_t get_offset_of_Name_10() { return static_cast<int32_t>(offsetof(ObjectTargetBaseBehaviour_t958778738, ___Name_10)); } inline String_t* get_Name_10() const { return ___Name_10; } inline String_t** get_address_of_Name_10() { return &___Name_10; } inline void set_Name_10(String_t* value) { ___Name_10 = value; Il2CppCodeGenWriteBarrier(&___Name_10, value); } inline static int32_t get_offset_of_Scale_11() { return static_cast<int32_t>(offsetof(ObjectTargetBaseBehaviour_t958778738, ___Scale_11)); } inline float get_Scale_11() const { return ___Scale_11; } inline float* get_address_of_Scale_11() { return &___Scale_11; } inline void set_Scale_11(float value) { ___Scale_11 = value; } inline static int32_t get_offset_of_ActiveTargetOnStart_12() { return static_cast<int32_t>(offsetof(ObjectTargetBaseBehaviour_t958778738, ___ActiveTargetOnStart_12)); } inline bool get_ActiveTargetOnStart_12() const { return ___ActiveTargetOnStart_12; } inline bool* get_address_of_ActiveTargetOnStart_12() { return &___ActiveTargetOnStart_12; } inline void set_ActiveTargetOnStart_12(bool value) { ___ActiveTargetOnStart_12 = value; } inline static int32_t get_offset_of_Target_13() { return static_cast<int32_t>(offsetof(ObjectTargetBaseBehaviour_t958778738, ___Target_13)); } inline ObjectTarget_t2086352254 * get_Target_13() const { return ___Target_13; } inline ObjectTarget_t2086352254 ** get_address_of_Target_13() { return &___Target_13; } inline void set_Target_13(ObjectTarget_t2086352254 * value) { ___Target_13 = value; Il2CppCodeGenWriteBarrier(&___Target_13, value); } inline static int32_t get_offset_of_loaders_14() { return static_cast<int32_t>(offsetof(ObjectTargetBaseBehaviour_t958778738, ___loaders_14)); } inline List_1_t1659153283 * get_loaders_14() const { return ___loaders_14; } inline List_1_t1659153283 ** get_address_of_loaders_14() { return &___loaders_14; } inline void set_loaders_14(List_1_t1659153283 * value) { ___loaders_14 = value; Il2CppCodeGenWriteBarrier(&___loaders_14, value); } inline static int32_t get_offset_of_trackerBaseBehaviour_15() { return static_cast<int32_t>(offsetof(ObjectTargetBaseBehaviour_t958778738, ___trackerBaseBehaviour_15)); } inline ObjectTrackerBaseBehaviour_t2290032151 * get_trackerBaseBehaviour_15() const { return ___trackerBaseBehaviour_15; } inline ObjectTrackerBaseBehaviour_t2290032151 ** get_address_of_trackerBaseBehaviour_15() { return &___trackerBaseBehaviour_15; } inline void set_trackerBaseBehaviour_15(ObjectTrackerBaseBehaviour_t2290032151 * value) { ___trackerBaseBehaviour_15 = value; Il2CppCodeGenWriteBarrier(&___trackerBaseBehaviour_15, value); } inline static int32_t get_offset_of_trackerBaseBehaviourHasSet_16() { return static_cast<int32_t>(offsetof(ObjectTargetBaseBehaviour_t958778738, ___trackerBaseBehaviourHasSet_16)); } inline bool get_trackerBaseBehaviourHasSet_16() const { return ___trackerBaseBehaviourHasSet_16; } inline bool* get_address_of_trackerBaseBehaviourHasSet_16() { return &___trackerBaseBehaviourHasSet_16; } inline void set_trackerBaseBehaviourHasSet_16(bool value) { ___trackerBaseBehaviourHasSet_16 = value; } inline static int32_t get_offset_of_preScale_17() { return static_cast<int32_t>(offsetof(ObjectTargetBaseBehaviour_t958778738, ___preScale_17)); } inline Vector3_t2243707580 get_preScale_17() const { return ___preScale_17; } inline Vector3_t2243707580 * get_address_of_preScale_17() { return &___preScale_17; } inline void set_preScale_17(Vector3_t2243707580 value) { ___preScale_17 = value; } inline static int32_t get_offset_of_preSize_18() { return static_cast<int32_t>(offsetof(ObjectTargetBaseBehaviour_t958778738, ___preSize_18)); } inline float get_preSize_18() const { return ___preSize_18; } inline float* get_address_of_preSize_18() { return &___preSize_18; } inline void set_preSize_18(float value) { ___preSize_18 = value; } inline static int32_t get_offset_of_alreadysetup_19() { return static_cast<int32_t>(offsetof(ObjectTargetBaseBehaviour_t958778738, ___alreadysetup_19)); } inline bool get_alreadysetup_19() const { return ___alreadysetup_19; } inline bool* get_address_of_alreadysetup_19() { return &___alreadysetup_19; } inline void set_alreadysetup_19(bool value) { ___alreadysetup_19 = value; } inline static int32_t get_offset_of_TargetLoad_20() { return static_cast<int32_t>(offsetof(ObjectTargetBaseBehaviour_t958778738, ___TargetLoad_20)); } inline Action_3_t3377464849 * get_TargetLoad_20() const { return ___TargetLoad_20; } inline Action_3_t3377464849 ** get_address_of_TargetLoad_20() { return &___TargetLoad_20; } inline void set_TargetLoad_20(Action_3_t3377464849 * value) { ___TargetLoad_20 = value; Il2CppCodeGenWriteBarrier(&___TargetLoad_20, value); } inline static int32_t get_offset_of_TargetUnload_21() { return static_cast<int32_t>(offsetof(ObjectTargetBaseBehaviour_t958778738, ___TargetUnload_21)); } inline Action_3_t3377464849 * get_TargetUnload_21() const { return ___TargetUnload_21; } inline Action_3_t3377464849 ** get_address_of_TargetUnload_21() { return &___TargetUnload_21; } inline void set_TargetUnload_21(Action_3_t3377464849 * value) { ___TargetUnload_21 = value; Il2CppCodeGenWriteBarrier(&___TargetUnload_21, value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "wenslow.vip@gmail.com" ]
wenslow.vip@gmail.com
0da3e35a6869b7343ca0852655b5055952e7da90
810c1382e5dc5b21f29cc1d52c172ecf52d683d6
/src/samples/http_sync_async_server/main.cc
f6696fd4f9cd1c51793d1d91fb63a6a93d7970c6
[ "MIT" ]
permissive
cppexecutor/gexecutor
2aede42b3dc8ae4fcac0b4e974577113933c08ca
23ddc0fdc177af26d998bf2072b673249a58b376
refs/heads/dev
2021-01-01T17:21:14.831527
2015-10-09T22:19:25
2016-09-25T14:34:42
11,861,605
11
2
null
2015-10-13T13:55:42
2013-08-03T10:22:39
C++
UTF-8
C++
false
false
654
cc
/** * main.cc * Copyright Gaurav Rastogi, 2013 * Created on: May 4, 2014 * Author: grastogi */ #include "http_hybrid_server.h" #include <iostream> #include <glog/logging.h> #include <gflags/gflags.h> using namespace std; int main(int argc, char **argv) { google::InitGoogleLogging(argv[0]); FLAGS_logtostderr = 0; google::ParseCommandLineFlags(&argc, &argv, true); google::FlushLogFiles(google::GLOG_INFO); cout << "Starting Server" << std::endl; HTTPHybridServer httpd(FLAGS_num_sync_workers); cout << "Initializing\n"; httpd.Initialize(); cout << "Running server\n"; httpd.Run(); return 0; }
[ "cppexecutor@gmail.com" ]
cppexecutor@gmail.com
709b6cd469e8ad15eec09145cdffda5e2a6e0941
3dc86dd9a7a4159406724124cb280d6f5e5bda29
/Shared/Runtime/DocumentResource/DocumentResourceManager.cpp
cb9cbe4dd07b90b46d2cf937db81362b05a21e7c
[]
no_license
hamfirst/StormBrewerEngine
3e051fb6806277c8273031f0e9ab241659fafba4
491ff8e42022e01c43d72b6d7b4f76db439d8745
refs/heads/master
2023-03-17T02:23:34.827037
2023-03-10T17:24:23
2023-03-10T17:24:23
53,809,267
0
3
null
null
null
null
UTF-8
C++
false
false
2,947
cpp
#include "Foundation/FileSystem/Path.h" #include "Runtime/RuntimeCommon.h" #include "Runtime/DocumentResource/DocumentResourceManager.h" extern DocumentResourceLoader * g_DocumentResourceLoader; DocumentResourceManager g_DocumentResourceManager; DocumentResourceManager::DocumentResourceManager() : m_PendingDocumentLoad(0) { } DocumentResourceManager::~DocumentResourceManager() { ASSERT(m_Documents.size() == 0, "Not all document resources have unloaded properly"); } NullOptPtr<DocumentResourceBase> DocumentResourceManager::FindDocumentResource(uint32_t file_path_hash) { auto itr = m_Documents.find(file_path_hash); if (itr != m_Documents.end()) { return itr->second.get(); } return nullptr; } NotNullPtr<DocumentResourceBase> DocumentResourceManager::LoadDocumentResource(czstr file_path, std::unique_ptr<DocumentResourceBase>(*ResourceCreator)(Any &&, uint32_t, czstr)) { uint32_t path_hash = crc32lowercase(file_path); auto itr = m_Documents.find(path_hash); if (itr == m_Documents.end()) { m_PendingDocumentLoad = path_hash; m_PendingDocumentLoaded = false; auto load_data = g_DocumentResourceLoader->LoadResource(file_path, [](uint32_t path_hash, NullOptPtr<std::string> resource_data, void * user_ptr) { auto p_this = static_cast<DocumentResourceManager *>(user_ptr); p_this->HandleResourceLoadResult(path_hash, resource_data); }, this); auto resource = ResourceCreator(std::move(load_data), path_hash, file_path); resource->m_ResourceManager = this; auto result = m_Documents.emplace(std::make_pair(path_hash, std::move(resource))); m_PendingDocumentLoad = 0; if (m_PendingDocumentLoaded) { HandleResourceLoadResult(path_hash, m_PendingDocumentData.size() > 0 ? &m_PendingDocumentData : nullptr); m_PendingDocumentData.clear(); } return result.first->second.get(); } else { return itr->second.get(); } } void DocumentResourceManager::HandleResourceLoadResult(uint32_t path_hash, NullOptPtr<std::string> resource_data) { if (path_hash == m_PendingDocumentLoad) { if (resource_data) { m_PendingDocumentData = *resource_data; } else { m_PendingDocumentData.clear(); } m_PendingDocumentLoaded = true; return; } auto itr = m_Documents.find(path_hash); if (itr == m_Documents.end()) { return; } if (resource_data) { itr->second->OnDataLoadComplete(*resource_data); } else { itr->second->OnDataLoadComplete("{}"); } itr->second->CallAssetLoadCallbacks(); } void DocumentResourceManager::DestroyDocument(uint32_t path_hash) { auto itr = m_Documents.find(path_hash); if (itr == m_Documents.end()) { ASSERT(false, "Could not find document to destroy"); return; } g_DocumentResourceLoader->UnloadResource(path_hash, std::move(itr->second->m_LoadData)); m_Documents.erase(itr); }
[ "nick.weihs@gmail.com" ]
nick.weihs@gmail.com
14b1bfc6c148557502765413236c076ca4cd0f8e
a9ab72c3dd7fdfe8b6e0b1b5e296bf4c39b9989d
/binarySearchTree/leetcode108.cpp
34d5c37dce1810a53630c7db5d8ddeb01ef1d3d8
[]
no_license
keqhe/leetcode
cd82fc3d98b7fc71a9a08c5e438aa1f82737d76f
86b2a453255c909f94f9ea3be7f2a97a6680a854
refs/heads/master
2020-12-24T06:38:15.444432
2016-12-07T19:15:02
2016-12-07T19:15:02
48,405,123
0
0
null
null
null
null
UTF-8
C++
false
false
877
cpp
#include<iostream> #include<string> #include<vector> using namespace std; //108. Convert Sorted Array to Binary Search Tree struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: struct TreeNode * helper(vector<int> & nums, int left, int right) { if (left > right) return NULL; if (left == right) { struct TreeNode * p = new TreeNode(nums[left]); return p; } int mid = left + (right - left)/2; struct TreeNode * root = new TreeNode(nums[mid]); root->left = helper(nums, left, mid-1); root->right = helper(nums, mid+1, right); } TreeNode* sortedArrayToBST(vector<int>& nums) { return helper(nums, 0, nums.size()-1); } }; int main() { class Solution sn; return 0; }
[ "keqhe@cs.wisc.edu" ]
keqhe@cs.wisc.edu
3dea7516658a963b5108df90915f5193571f4d1d
8590dd09523ee4c7deea2e4bc8cab300f1118c8b
/ClasesIntroCPP/ClasesIntroCPP/List.h
34ba93865737cc0efb67361cac559b46a98a820a
[]
no_license
edsaedi/ClassesIntroCPP
d1e62bfff14a1eb79c2f190a8f47978a5c346444
f8fd5148f568347dbdd347486e44b7cf8e824755
refs/heads/master
2020-08-11T10:33:37.519243
2019-10-17T00:57:19
2019-10-17T00:57:19
214,550,534
0
0
null
null
null
null
UTF-8
C++
false
false
248
h
#pragma once template<class T> class List { private: T* array; int capacity; int count; public: List(); ~List(); void Add(T value); bool Remove(int index); int FindIndex(T value); T Search(int index); void Sort(); }; #include "List.tpp"
[ "edsaedi@gmail.com" ]
edsaedi@gmail.com
479bdd900600de75c19c0d7a7af091292e55adfd
4b26d36c69798e00886f47fa2f051ca837113c5c
/src/ProteinEvaluation/statistics.h
ac2d989f1d73618cf54063104e13c364411355b7
[]
no_license
nsarang/Protein-Sequence-Evolution
eb3d6442509ab92ff04b977cdeac5c3acb69efef
ed0755cfbce7634fba7d7c99e1121f2ad38c1de6
refs/heads/master
2022-07-05T13:43:28.853835
2020-01-24T22:34:54
2020-01-24T22:34:54
157,696,245
1
0
null
2022-06-21T23:14:16
2018-11-15T10:52:04
Jupyter Notebook
UTF-8
C++
false
false
719
h
#ifndef _STATISTIC_H #define _STATISTIC_H // #include <gsl/gsl_multifit.h> // #include <gsl/gsl_statistics_double.h> #include <vector> #include <tuple> #include <cassert> #include <algorithm> #include <numeric> #include <cmath> std::tuple<double, double> Mean_SD(std::vector<double> &vecInp); std::vector<double> OutlierElimination_IQR(std::vector<double> vecInp, double coef = 1.5); // int gsl_polynomialfit_robust(size_t n, size_t deg, // std::vector<double> &dx, std::vector<double> &dy, // double ret_coef[], double ret_cov[] = NULL, // const gsl_multifit_robust_type *robust_type = gsl_multifit_robust_bisquare); #endif
[ "nimasarang@gmail.com" ]
nimasarang@gmail.com
4798ad214693d3c807de6798148f2efa54e1448d
7121e3df80afdc58fdc10c664c08aee411a78181
/src/chromecast/renderer/cast_extensions_dispatcher_delegate.cc
94f876833751a2adaaf2ae46397ba120c9243978
[ "BSD-3-Clause" ]
permissive
ochrisoyea/AccessControlListsintheDOM
93d0a1f77f7f3af864d4a2942e4590af9065a7d8
9a8796f899592d236628f4d3007337ff5743c32f
refs/heads/master
2020-06-08T14:31:37.838842
2019-06-22T16:17:41
2019-06-22T16:17:41
193,242,663
0
0
null
2019-06-22T14:24:31
2019-06-22T14:24:31
null
UTF-8
C++
false
false
3,581
cc
// Copyright 2018 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 "chromecast/renderer/cast_extensions_dispatcher_delegate.h" #include <memory> #include "base/command_line.h" #include "base/feature_list.h" #include "base/sha1.h" #include "base/strings/string_number_conversions.h" #include "chromecast/renderer/grit/extensions_renderer_resources.h" #include "chromecast/renderer/extensions/automation_internal_custom_bindings.h" #include "components/version_info/version_info.h" #include "content/public/common/content_switches.h" #include "content/public/renderer/render_thread.h" #include "content/public/renderer/render_view.h" #include "extensions/common/constants.h" #include "extensions/common/extension.h" #include "extensions/common/extension_features.h" #include "extensions/common/features/feature_channel.h" #include "extensions/common/permissions/manifest_permission_set.h" #include "extensions/common/permissions/permission_set.h" #include "extensions/common/permissions/permissions_data.h" #include "extensions/common/switches.h" #include "extensions/renderer/bindings/api_bindings_system.h" #include "extensions/renderer/css_native_handler.h" #include "extensions/renderer/dispatcher.h" #include "extensions/renderer/i18n_custom_bindings.h" #include "extensions/renderer/lazy_background_page_native_handler.h" #include "extensions/renderer/native_extension_bindings_system.h" #include "extensions/renderer/native_handler.h" #include "extensions/renderer/resource_bundle_source_map.h" #include "extensions/renderer/script_context.h" #include "media/media_buildflags.h" #include "third_party/blink/public/platform/web_string.h" #include "third_party/blink/public/platform/web_url.h" #include "third_party/blink/public/web/web_security_policy.h" using extensions::NativeHandler; CastExtensionsDispatcherDelegate::CastExtensionsDispatcherDelegate() { } CastExtensionsDispatcherDelegate::~CastExtensionsDispatcherDelegate() { } void CastExtensionsDispatcherDelegate::InitOriginPermissions( const extensions::Extension* extension, bool is_extension_active) { // TODO(rmrossi): Stub } void CastExtensionsDispatcherDelegate::RegisterNativeHandlers( extensions::Dispatcher* dispatcher, extensions::ModuleSystem* module_system, extensions::ExtensionBindingsSystem* bindings_system, extensions::ScriptContext* context) { module_system->RegisterNativeHandler( "automationInternal", std::make_unique<extensions::cast::AutomationInternalCustomBindings>( context, bindings_system)); } void CastExtensionsDispatcherDelegate::PopulateSourceMap( extensions::ResourceBundleSourceMap* source_map) { // Custom bindings. source_map->RegisterSource("automation", IDR_AUTOMATION_CUSTOM_BINDINGS_JS); source_map->RegisterSource("automationEvent", IDR_AUTOMATION_EVENT_JS); source_map->RegisterSource("automationNode", IDR_AUTOMATION_NODE_JS); } void CastExtensionsDispatcherDelegate::RequireAdditionalModules( extensions::ScriptContext* context) { // TODO(rmrossi): Stub } void CastExtensionsDispatcherDelegate::OnActiveExtensionsUpdated( const std::set<std::string>& extension_ids) { // TODO(rmrossi): Stub } void CastExtensionsDispatcherDelegate::InitializeBindingsSystem( extensions::Dispatcher* dispatcher, extensions::NativeExtensionBindingsSystem* bindings_system) { DCHECK( base::FeatureList::IsEnabled(extensions::features::kNativeCrxBindings)); // TODO(rmrossi): Stub }
[ "heatherfarrar.ima@gmail.com" ]
heatherfarrar.ima@gmail.com
59d95d04c941cff3ac34df185a2af563c8fd67cc
0b22d789f780429757129a96207a0047e28aa1e4
/AGE/main.cpp
5db168de797c151385639544accdd79438764a4c
[]
no_license
dontpanic92/FoOTOo-Strike
9b9ddd6aec7e746cfbef5c7389f3d985ffca3447
0fcc44f7ff137d6d7491b742f206fa98144c0891
refs/heads/master
2020-12-03T09:13:23.217990
2016-03-02T17:05:39
2016-03-02T17:05:39
49,556,259
5
0
null
null
null
null
UTF-8
C++
false
false
153
cpp
#include "Engine.h" #include <iostream> using namespace std; int main() { AGE::Engine::GetInstance()->StartUp(); AGE::Engine::GetInstance()->Run(); }
[ "tuesdayslineara@gmail.com" ]
tuesdayslineara@gmail.com
d779ecfc25c8dda1d366d4d846bdb66daa5c8795
cd663601e099f4d8a359d6eddbb3e25f0328be09
/MetroidGame/Metroid/Zoomer.cpp
c7e934bb603034827f68109bd83b268fb429a5f5
[]
no_license
vanminhnguyenbmt/Metroid
dacb96f2d0d8d5b2bacb55a131d338516b1eca2c
450a0d70b977c363aa6194a8f31d3642b0f7e8b3
refs/heads/master
2021-08-23T08:55:40.541889
2017-12-04T11:32:19
2017-12-04T11:32:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,153
cpp
#include "Zoomer.h" #include"ImgDeath.h" Zoomer::Zoomer() { this->_type = ZOMMER; } void Zoomer::Init() { _y -= 3; HP = 20; ZUp(); SetAction(); } void Zoomer::Update(float time) { isColl = false;// kiem tra co va cham voi gach hay khong isCol = false;// kiem tra co va cham voi gach dat biet hay khong float nx = 0, ny = 0; for (int i = 0; i < Camera::getInstance()->listObjectOnCamera.size(); i++) { if (isCol) { break; } if (CColision::collision(this, Camera::getInstance()->listObjectOnCamera[i])) { OnCollision(Camera::getInstance()->listObjectOnCamera[i], nx, ny); } } if (!isCol) { if (!isColl && oldGround!=NULL) { if (_vx > 0) { ZRight(); _x = oldGround->Right(); } else if (_vx < 0) { ZLeft(); _x = oldGround->_x-_width; } else if (_vy > 0) { ZUp(); _y = oldGround->_y+_height; } else if (_vy < 0) { ZDown(); _y = oldGround->Bottom(); } } } _dx = _vx* time; _dy = _vy*time; _x += _dx; _y += _dy; } void Zoomer::Draw(float time) { lstAction[curAction].Draw(D3DXVECTOR3(_x, _y,0), RIGHT,time); } Zoomer::~Zoomer() { free(lstAction); } void Zoomer::OnCollision(GameplayObject* obj, int nx, int ny) { switch (obj->_type) { case BULLET: HP -= 5; if (HP == 0) { this->isDead = true; ImgDeath::getInstance()->Set(XCenter(), YCenter()); } break; case GROUND: if (_vx > 0 && YCenter()<obj->Top() && YCenter()>obj->Bottom()) { isCol = true; isColl = true; ZLeft(); _x = obj->_x - _width; _y = obj->Top(); oldGround = obj; break; } if (_vx < 0 && YCenter()<obj->Top() && YCenter()>obj->Bottom()) { isCol = true; isColl = true; ZRight(); _x = obj->Right(); _y = obj->_y; oldGround = obj; break; } if (_vy > 0 && XCenter() < obj->Right() && XCenter()>obj->Left()) { isCol = true; isColl = true; ZDown(); _x = obj->_x; _y = obj->Bottom(); oldGround = obj; break; } if (_vy < 0 && XCenter() < obj->Right() && XCenter()>obj->Left()) { isCol = true; isColl = true; ZUp(); _x = obj->_x; _y = obj->_y+_height; oldGround = obj; break; } oldGround = obj; isColl = true; default: break; } } void Zoomer::ZUp() { curAction = ZOOMER_UP; _vx = VX_ZOOMER; _vy = 0; _width = 16; _height = 16; } void Zoomer::ZDown() { curAction = ZOOMER_DOWN; _vy = 0; _vx = -VX_ZOOMER; _width = 16; _height = 16; } void Zoomer::ZLeft() { curAction = ZOOMER_LEFT; _vx = 0; _vy = -VY_ZOOMER; _height = 16; _width = 16; } void Zoomer::ZRight() { curAction = ZOOMER_RIGHT; _vx = 0; _vy = VY_ZOOMER; _height = 16; _width = 16; } void Zoomer::SetAction() { lstAction = new Animation[4]; lstAction[ZOOMER_UP].Create("src//img//enemy//zoomer//Zoomer_up.png", 36, 16, 2, 1.0f/4, RIGHT); lstAction[ZOOMER_DOWN].Create( "src//img//enemy//zoomer//Zoomer_down.png", 36, 16, 2, 1.0f / 4, RIGHT); lstAction[ZOOMER_LEFT].Create( "src//img//enemy//zoomer//Zoomer_left.png", 32, 18, 2, 1.0f / 4, RIGHT); lstAction[ZOOMER_RIGHT].Create( "src//img//enemy//zoomer//Zoomer_right.png", 32, 18, 2, 1.0f / 4, RIGHT); }
[ "tuvanthuan1996@gmail.com" ]
tuvanthuan1996@gmail.com
a4a2a19bd2eb82fc1604e83cb550dd1d22d14ba6
dba68ca53ce02985ed1b49f6813d578d24e94b27
/ProjectAtum/DataRenderLib/main/MeshRender.h
0e8b3fa3d5742965223df42b4bb2f0ee2f203b0f
[]
no_license
DeathRivals/OpenAo
afd6c1fe6ddc00e3765c290f485805a7b3e0db59
bf6be4ee29b1f08588fe7fd12c02c8df94d705f5
refs/heads/master
2021-02-15T18:23:37.814569
2020-03-04T14:39:38
2020-03-04T14:39:38
244,919,960
2
2
null
2020-03-04T14:22:07
2020-03-04T14:22:07
null
UHC
C++
false
false
1,579
h
// MeshRender.h: interface for the CMeshRender class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_MESHRENDER_H__28791450_5BD7_4A28_9A2B_736B3B0E6ED0__INCLUDED_) #define AFX_MESHRENDER_H__28791450_5BD7_4A28_9A2B_736B3B0E6ED0__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "AtumNode.h" #include "SkinnedMesh.h" class CMeshRender : public CAtumNode { public: CMeshRender(); virtual ~CMeshRender(); // 2009. 11. 23 by jskim 리소스 로딩 구조 변경 //virtual CSkinnedMesh* InitData(int nMeshIndex); virtual CSkinnedMesh* InitData(int nMeshIndex, int nType, D3DXVECTOR3 ObjScale = D3DXVECTOR3(1.0f, 1.0f, 1.0f));// 2012-05-21 by isshin 맵툴 개선 오브젝트 스케일 적용 //end 2009. 11. 23 by jskim 리소스 로딩 구조 변경 virtual void DeleteData(int nMeshIndex); virtual void RenderShadow(CAtumNode * pNode); virtual void Render(); virtual void Tick(float fElapsedTime); virtual HRESULT InitDeviceObjects(); virtual HRESULT RestoreDeviceObjects(); virtual HRESULT InvalidateDeviceObjects(); virtual HRESULT DeleteDeviceObjects(); map<int,CSkinnedMesh*> m_mapSkinnedMesh; // index : 12030100 ( 12 : degree, 03 : amor, 01 : unitKind ) protected: vector<int> m_vecLoadMeshIndex; // render중에 로딩이 되지 않은 경우 여기에 넣고 Tick에서 로딩한다. // DWORD m_dwNormalStateBlock; // DWORD m_dwAlphaBlendStateBlock; }; #endif // !defined(AFX_MESHRENDER_H__28791450_5BD7_4A28_9A2B_736B3B0E6ED0__INCLUDED_)
[ "guss@nemerian.fr" ]
guss@nemerian.fr
24ece759c892af2caf0ffb34b0bdfa821df66ffd
61c88c34e87e3be2cf3e3ba1e21407218e3a130f
/visionQT_test1/imageview.h
de232349b98b2f0a0b4a2e8d8372ac5135cbc4cf
[]
no_license
InkChan/3Dvision
af48285269251f39c068d5b8c72cf221a4f1e5bd
14fd49294241c36ad77342b04741d75db434d5bc
refs/heads/master
2020-06-02T11:42:50.428388
2019-08-05T10:45:49
2019-08-05T10:45:49
191,143,444
2
0
null
null
null
null
UTF-8
C++
false
false
683
h
#ifndef IMAGEVIEW_H #define IMAGEVIEW_H #include <qgraphicsview.h> #include <qevent.h> #include <qscrollbar.h> #include <qgraphicsitem.h> #include <qstyleoption.h> #include "mygraphicsscene.h" class ImageView : public QGraphicsView { Q_OBJECT public: ImageView(QGraphicsScene *scene,QWidget *parent); ImageView(/*QGraphicsScene *scene, */int left, QWidget *parent); QPointF getScenePos(QPoint point); ~ImageView(); signals: void mousePress(QPointF); void mouseMove(QPointF); void mouseRelease(QPointF); protected: void mousePressEvent(QMouseEvent *event); void mouseMoveEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); }; #endif // IMAGEVIEW_H
[ "1986140521@qq.com" ]
1986140521@qq.com
91075c0e24e76a54c6c0eda185cb81b743b50670
fbe68d84e97262d6d26dd65c704a7b50af2b3943
/third_party/retdec-3.2/include/retdec/bin2llvmir/providers/names.h
3c5ebe27281a1695a7207dfbc9ff0beba7b64298
[ "MIT", "GPL-1.0-or-later", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "OpenSSL", "WTFPL", "LGPL-2.1-only", "LicenseRef-scancode-openssl", "LicenseRef-scancode-ssleay-windows", "LGPL-2.0-or-later", "JSON", "Zlib", "NCSA", "LicenseRef-scancode-proprietary-license", "G...
permissive
thalium/icebox
c4e6573f2b4f0973b6c7bb0bf068fe9e795fdcfb
6f78952d58da52ea4f0e55b2ab297f28e80c1160
refs/heads/master
2022-08-14T00:19:36.984579
2022-02-22T13:10:31
2022-02-22T13:10:31
190,019,914
585
109
MIT
2022-01-13T20:58:15
2019-06-03T14:18:12
C++
UTF-8
C++
false
false
5,708
h
/** * @file include/retdec/bin2llvmir/providers/names.h * @brief Database of objects' names in binary. * @copyright (c) 2017 Avast Software, licensed under the MIT license */ #ifndef RETDEC_BIN2LLVMIR_PROVIDERS_NAMES_H #define RETDEC_BIN2LLVMIR_PROVIDERS_NAMES_H #include <map> #include <set> #include "retdec/bin2llvmir/providers/config.h" #include "retdec/bin2llvmir/providers/debugformat.h" #include "retdec/bin2llvmir/providers/demangler.h" #include "retdec/bin2llvmir/providers/fileimage.h" #include "retdec/bin2llvmir/providers/lti.h" #include "retdec/utils/address.h" namespace retdec { namespace bin2llvmir { namespace names { const std::string entryPointName = "entry_point"; const std::string generatedImportPrefix = "imported_function_ord_"; const std::string generatedFunctionPrefix = "function_"; const std::string generatedFunctionPrefixIDA = "ida_"; const std::string generatedFunctionPrefixUnk = "unknown_"; const std::string generatedTempVarPrefix = "v"; const std::string generatedBasicBlockPrefix = "dec_label_pc_"; const std::string generatedUndefFunctionPrefix = "__decompiler_undefined_function_"; const std::string generatedVtablePrefix = "vtable_"; const std::string asm2llvmGv = "_asm_program_counter"; const std::string pseudoCallFunction = "__pseudo_call"; const std::string pseudoReturnFunction = "__pseudo_return"; const std::string pseudoBranchFunction = "__pseudo_branch"; const std::string pseudoCondBranchFunction = "__pseudo_cond_branch"; const std::string pseudoX87dataLoadFunction = "__frontend_reg_load.fpr"; const std::string pseudoX87tagLoadFunction = "__frontend_reg_load.fpu_tag"; const std::string pseudoX87dataStoreFunction = "__frontend_reg_store.fpr"; const std::string pseudoX87tagStoreFunction = "__frontend_reg_store.fpu_tag"; std::string generateFunctionName(utils::Address a, bool ida = false); std::string generateFunctionNameUnknown(utils::Address a, bool ida = false); std::string generateBasicBlockName(utils::Address a); std::string generateTempVariableName(utils::Address a, unsigned cntr); std::string generateFunctionNameUndef(unsigned cntr); std::string generateVtableName(utils::Address a); } // namespace names /** * Representation of one name. */ class Name { public: /** * Name type and its priority. * Lower number -> higher priority. */ enum class eType { // This is not set automatically in this module -> for manual use // only - when some bin2llvmir part wants to really make sure // a certain name is used. HIGHEST_PRIORITY = 0, // Stuff from config. CONFIG_FUNCTION, CONFIG_GLOBAL, CONFIG_SEGMENT, // DEBUG_FUNCTION, DEBUG_GLOBAL, // Stuff from file image. IMPORT, EXPORT, SYMBOL_FUNCTION, SYMBOL_OBJECT, SYMBOL_FILE, SYMBOL_OTHER, STATIC_CODE, ENTRY_POINT, SECTION, IMPORT_GENERATED, // This is not set automatically in this module -> for manual use // only - when some bin2llvmir part wants to use some name if // nothing better is available. LOWEST_PRIORITY, // Invalid - somethingwent wrong, do not use this entry. INVALID, }; public: Name(); Name(Config* c, const std::string& name, eType type, Lti* lti = nullptr); operator std::string() const; explicit operator bool() const; bool operator<(const Name& o) const; const std::string& getName() const; eType getType() const; private: void fixPic32Mangling(); private: std::string _name; eType _type = eType::INVALID; bool _inLti = false; }; /** * Representation of all the names for one object. */ class Names { public: using iterator = typename std::set<Name>::iterator; public: bool addName( Config* c, const std::string& name, Name::eType type, Lti* lti = nullptr); const Name& getPreferredName(); iterator begin(); iterator end(); std::size_t size() const; bool empty() const; private: std::set<Name> _names; static Name _emptyName; }; /** * Names container. */ class NameContainer { public: NameContainer( llvm::Module* m, Config* c, DebugFormat* d, FileImage* i, demangler::CDemangler* dm, Lti* lti = nullptr); bool addNameForAddress( retdec::utils::Address a, const std::string& name, Name::eType type, Lti* lti = nullptr); const Names& getNamesForAddress(retdec::utils::Address a); const Name& getPreferredNameForAddress(retdec::utils::Address a); private: void initFromConfig(); void initFromDebug(); void initFromImage(); std::string getNameFromImportLibAndOrd( const std::string& libName, int ord); bool loadImportOrds(const std::string& libName); private: /// <ordinal number, function name> using ImportOrdMap = std::map<int, std::string>; private: llvm::Module* _module = nullptr; Config* _config = nullptr; DebugFormat* _debug = nullptr; FileImage* _image = nullptr; demangler::CDemangler* _demangler = nullptr; Lti* _lti = nullptr; std::map<retdec::utils::Address, Names> _data; /// <library name without suffix ".dll", map with ordinals> std::map<std::string, ImportOrdMap> _dllOrds; }; /** * Names provider. */ class NamesProvider { public: static NameContainer* addNames( llvm::Module* m, Config* c, DebugFormat* d, FileImage* i, demangler::CDemangler* dm, Lti* lti); static NameContainer* getNames(llvm::Module* m); static bool getNames(llvm::Module* m, NameContainer*& names); static void clear(); private: static std::map<llvm::Module*, NameContainer> _module2names; }; } // namespace bin2llvmir } // namespace retdec #endif
[ "benoit.amiaux@gmail.com" ]
benoit.amiaux@gmail.com
8bc8f0a787187736e6cba00d19b4f3b8d677ff07
148455c59bfd6c885e7367f9c8cf188d0c1e485d
/src/maple_me/src/dse.cpp
7f3ac83fde28acb86756c1b0a0e16b20cc179616
[]
no_license
guoqingiskid/OpenArkCompiler
a32fdc117ddc5a526f7d7d9bf1768cac7837c445
ec7085b2d73461a848bebc2d1e99e69619fcf3b9
refs/heads/master
2022-06-15T02:02:57.531937
2020-05-08T06:33:56
2020-05-08T06:33:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,724
cpp
/* * Copyright (c) [2019-2020] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under the Mulan PSL v1. * You can use this software according to the terms and conditions of the Mulan PSL v1. * You may obtain a copy of Mulan PSL v1 at: * * http://license.coscl.org.cn/MulanPSL * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR * FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v1 for more details. */ #include "dse.h" #include "ssa_mir_nodes.h" #include "ver_symbol.h" #include "ssa.h" #include "opcode_info.h" #include "mir_function.h" #include "utils.h" // This phase do dead store elimination. This optimization is done on SSA // version basis. // This optimization consider all stmt are not needed at first. The whole // algorithm is as follow: // 1. mark all stmt are not needed. init an empty worklist to put live node. // 2. mark some special stmts which has side effect as needed, such as // return/eh/call and some assigned stmts who have volatile fileds and so on. // Put all operands and mayUse nodes of the needed stmt into worklist. // 3. For the nodes in worklist mark the def stmt as needed just as step 2 and // pop the node from the worklist. // 4. Repeat step 3 until the worklist is empty. namespace maple { using namespace utils; bool DSE::ExprHasSideEffect(const BaseNode &expr) const { Opcode op = expr.GetOpCode(); if (kOpcodeInfo.HasSideEffect(op)) { return true; } // may throw exception if (op == OP_gcmallocjarray || op == OP_gcpermallocjarray) { return true; } // create a instance of interface if (op == OP_gcmalloc || op == OP_gcpermalloc) { auto &gcMallocNode = static_cast<const GCMallocNode&>(expr); MIRType *type = GlobalTables::GetTypeTable().GetTypeFromTyIdx(gcMallocNode.GetTyIdx()); return type->GetKind() == kTypeInterface; } return false; } bool DSE::ExprNonDeletable(const BaseNode &expr) const { if (ExprHasSideEffect(expr)) { return true; } switch (expr.GetOpCode()) { case OP_dread: { auto &dread = static_cast<const AddrofSSANode&>(expr); const MIRSymbol &sym = dread.GetMIRSymbol(); return sym.IsVolatile() || sym.IsTypeVolatile(dread.GetFieldID()); } case OP_iread: { auto &iread = static_cast<const IreadSSANode&>(expr); auto &ty = static_cast<const MIRPtrType&>(GetTypeFromTyIdx(iread.GetTyIdx())); return ty.IsPointedTypeVolatile(iread.GetFieldID()) || ExprNonDeletable(ToRef(iread.Opnd(0))); } case OP_regread: { auto &regreadNode = static_cast<const RegreadSSANode&>(expr); return (regreadNode.GetRegIdx() == -kSregThrownval); } case OP_intrinsicop: { auto &node = static_cast<const IntrinsicopNode&>(expr); const IntrinDesc &intrinDesc = node.GetIntrinDesc(); return (!intrinDesc.HasNoSideEffect()); } default: { break; } } for (size_t i = 0; i < expr.NumOpnds(); ++i) { if (ExprNonDeletable(ToRef(expr.Opnd(i)))) { return true; } } return false; } bool DSE::HasNonDeletableExpr(const StmtNode &stmt) const { Opcode op = stmt.GetOpCode(); switch (op) { case OP_dassign: { auto &node = static_cast<const DassignNode&>(stmt); const MIRSymbol &sym = ssaTab.GetStmtMIRSymbol(stmt); return (sym.IsVolatile() || sym.IsTypeVolatile(node.GetFieldID()) || ExprNonDeletable(ToRef(node.GetRHS()))); } case OP_regassign: { return ExprNonDeletable(ToRef(stmt.Opnd(0))); } // possible to throw exception case OP_maydassign: { return true; } case OP_iassign: { auto &node = static_cast<const IassignNode&>(stmt); auto &ty = static_cast<const MIRPtrType&>(GetTypeFromTyIdx(node.GetTyIdx())); return (ty.IsPointedTypeVolatile(node.GetFieldID()) || ExprNonDeletable(ToRef(node.Opnd(0))) || ExprNonDeletable(ToRef(node.GetRHS()))); } default: return false; } } bool DSE::StmtMustRequired(const StmtNode &stmt, const BB &bb) const { Opcode op = stmt.GetOpCode(); // special opcode stmt cannot be eliminated if (IsStmtMustRequire(op)) { return true; } // control flow in an infinite loop cannot be eliminated if (ControlFlowInInfiniteLoop(bb, op)) { return true; } return HasNonDeletableExpr(stmt); } void DSE::DumpStmt(const StmtNode &stmt, const std::string &msg) const { if (enableDebug) { LogInfo::MapleLogger() << msg; stmt.Dump(); } } void DSE::CheckRemoveCallAssignedReturn(StmtNode &stmt) { if (kOpcodeInfo.IsCallAssigned(stmt.GetOpCode())) { MapleVector<MustDefNode> &mustDefs = ssaTab.GetStmtMustDefNodes(stmt); for (auto &node : mustDefs) { if (IsSymbolLived(ToRef(node.GetResult()))) { continue; } DumpStmt(stmt, "**** DSE1 deleting return value assignment in: "); CallReturnVector *rets = stmt.GetCallReturnVector(); CHECK_FATAL(rets != nullptr, "null ptr check"); rets->clear(); mustDefs.clear(); break; } } } void DSE::OnRemoveBranchStmt(BB &bb, const StmtNode &stmt) { // switch is special, which can not be set to kBBFallthru if (IsBranch(stmt.GetOpCode()) && stmt.GetOpCode() != OP_switch) { // update BB pred/succ bb.SetKind(kBBFallthru); cfgUpdated = true; // tag cfg is changed LabelIdx labelIdx = (stmt.GetOpCode() == OP_goto) ? static_cast<const GotoNode&>(stmt).GetOffset() : static_cast<const CondGotoNode&>(stmt).GetOffset(); for (size_t i = 0; i < bb.GetSucc().size(); ++i) { if (bb.GetSucc(i)->GetBBLabel() == labelIdx) { BB *succBB = bb.GetSucc(i); bb.RemoveSucc(*succBB); break; } } } } void DSE::RemoveNotRequiredStmtsInBB(BB &bb) { for (auto &stmt : bb.GetStmtNodes()) { if (!IsStmtRequired(stmt)) { DumpStmt(stmt, "**** DSE1 deleting: "); OnRemoveBranchStmt(bb, stmt); bb.RemoveStmtNode(&stmt); continue; } CheckRemoveCallAssignedReturn(stmt); } } void DSE::PropagateUseLive(const VersionSt &vst) { if (IsSymbolLived(vst)) { return; } SetSymbolLived(vst); const BB *dfBB = vst.GetDefBB(); if (dfBB == nullptr) { return; } if (vst.GetDefType() == VersionSt::kAssign) { const StmtNode *assign = vst.GetAssignNode(); MarkStmtRequired(ToRef(assign), ToRef(dfBB)); } else if (vst.GetDefType() == VersionSt::kPhi) { const PhiNode *phi = vst.GetPhi(); ASSERT(phi->GetResult() == &vst, "MarkVst: wrong corresponding version st in phi"); MarkControlDependenceLive(ToRef(dfBB)); for (size_t i = 0; i < phi->GetPhiOpnds().size(); ++i) { const VersionSt *verSt = phi->GetPhiOpnds()[i]; AddToWorkList(verSt); } } else if (vst.GetDefType() == VersionSt::kMayDef) { const MayDefNode *mayDef = vst.GetMayDef(); ASSERT(mayDef->GetResult() == &vst, "MarkVst: wrong corresponding version st in maydef"); const VersionSt *verSt = mayDef->GetOpnd(); MarkStmtRequired(ToRef(mayDef->GetStmt()), ToRef(dfBB)); AddToWorkList(verSt); } else { const MustDefNode *mustDef = vst.GetMustDef(); ASSERT(mustDef->GetResult() == &vst, "MarkVst: wrong corresponding version st in mustDef"); MarkStmtRequired(ToRef(mustDef->GetStmt()), ToRef(dfBB)); } } void DSE::MarkLastGotoInPredBBRequired(const BB &bb) { for (auto predIt = bb.GetPred().begin(); predIt != bb.GetPred().end(); ++predIt) { const BB *predBB = *predIt; CHECK_NULL_FATAL(predBB); if (predBB == &bb || predBB->IsEmpty()) { continue; } const StmtNode &lastStmt = predBB->GetLast(); if (lastStmt.GetOpCode() == OP_goto) { MarkStmtRequired(lastStmt, ToRef(predBB)); } } } void DSE::MarkLastBranchStmtInPDomBBRequired(const BB &bb) { ASSERT(bb.GetBBId() < postDom.GetPdomFrontierSize(), "index out of range in DSE::MarkBBLive "); for (BBId pdomBBID : postDom.GetPdomFrontierItem(bb.GetBBId())) { const BB *cdBB = bbVec[pdomBBID]; CHECK_FATAL(cdBB != nullptr, "cd_bb is null in DSE::MarkLastBranchStmtInPDomBBRequired"); if (cdBB == &bb || cdBB->IsEmpty()) { continue; } const StmtNode &lastStmt = cdBB->GetLast(); Opcode op = lastStmt.GetOpCode(); if (IsBranch(op)) { MarkStmtRequired(lastStmt, ToRef(cdBB)); } } } void DSE::MarkLastBranchStmtInBBRequired(const BB &bb) { if (!bb.IsEmpty()) { // if bb's last stmt is a branch instruction, it is also needed const StmtNode &lastStmt = bb.GetLast(); if (IsBranch(lastStmt.GetOpCode())) { MarkStmtRequired(lastStmt, bb); } } } void DSE::MarkControlDependenceLive(const BB &bb) { if (bbRequired[bb.GetBBId()]) { return; } bbRequired[bb.GetBBId()] = true; MarkLastBranchStmtInBBRequired(bb); MarkLastBranchStmtInPDomBBRequired(bb); MarkLastGotoInPredBBRequired(bb); } void DSE::MarkSingleUseLive(const BaseNode &mirNode) { Opcode op = mirNode.GetOpCode(); switch (op) { case OP_dread: { auto &addrofSSANode = static_cast<const AddrofSSANode&>(mirNode); const VersionSt *verSt = addrofSSANode.GetSSAVar(); AddToWorkList(verSt); break; } case OP_regread: { auto &regreadSSANode = static_cast<const RegreadSSANode&>(mirNode); const VersionSt *verSt = regreadSSANode.GetSSAVar(); AddToWorkList(verSt); break; } case OP_iread: { auto &ireadSSANode = static_cast<const IreadSSANode&>(mirNode); const VersionSt *verSt = ireadSSANode.GetSSAVar(); CHECK_FATAL(verSt != nullptr, "DSE::MarkSingleUseLive: iread has no mayUse opnd"); AddToWorkList(verSt); if (!verSt->IsInitVersion()) { auto *mayDefList = SSAGenericGetMayDefsFromVersionSt(ToRef(verSt), ssaTab.GetStmtsSSAPart()); if (mayDefList != nullptr) { for (auto it = mayDefList->begin(); it != mayDefList->end(); ++it) { AddToWorkList(it->second.GetResult()); } } } MarkSingleUseLive(ToRef(mirNode.Opnd(0))); break; } default: { for (size_t i = 0; i < mirNode.NumOpnds(); ++i) { MarkSingleUseLive(ToRef(mirNode.Opnd(i))); } break; } } } void DSE::MarkStmtUseLive(const StmtNode &stmt) { for (size_t i = 0; i < stmt.NumOpnds(); ++i) { MarkSingleUseLive(ToRef(stmt.Opnd(i))); } if (kOpcodeInfo.HasSSAUse(stmt.GetOpCode())) { for (auto &pair : ssaTab.GetStmtMayUseNodes(stmt)) { const MayUseNode &mayUse = pair.second; AddToWorkList(mayUse.GetOpnd()); } } } void DSE::MarkStmtRequired(const StmtNode &stmt, const BB &bb) { if (IsStmtRequired(stmt)) { return; } SetStmtRequired(stmt); // save only one line comment StmtNode *prev = stmt.GetPrev(); if (prev != nullptr && prev->GetOpCode() == OP_comment) { SetStmtRequired(*prev); } MarkStmtUseLive(stmt); MarkControlDependenceLive(bb); } void DSE::MarkSpecialStmtRequired() { for (auto bIt = bbVec.rbegin(); bIt != bbVec.rend(); ++bIt) { auto *bb = *bIt; if (bb == nullptr) { continue; } for (auto itStmt = bb->GetStmtNodes().rbegin(); itStmt != bb->GetStmtNodes().rend(); ++itStmt) { if (StmtMustRequired(*itStmt, *bb)) { MarkStmtRequired(*itStmt, *bb); continue; } } } } void DSE::Init() { bbRequired[commonEntryBB.GetBBId()] = true; bbRequired[commonExitBB.GetBBId()] = true; } void DSE::DoDSE() { Init(); MarkSpecialStmtRequired(); PropagateLive(); RemoveNotRequiredStmts(); } } // namespace maple
[ "fuzhou@huawei.com" ]
fuzhou@huawei.com
2644dff4e2295e6f783948d197a48b6c382d2a93
73e4b5cb0db07f533c2c130c16bf7689beba5f51
/xlw/xlw/xlw/include/xlw/CellMatrix.h
9d4a23640edda2a6cb732955ae8fe4e6c342aa47
[]
no_license
Laeeth/d_excelsdk
f054dbcb6ef9fd16916d72ea06c2b7d3a433db13
2fc993a89c6f620233fd29ea6daf233b1985b4e9
refs/heads/master
2021-01-17T08:58:37.477963
2016-04-14T01:03:31
2016-04-14T01:03:31
38,217,895
11
3
null
null
null
null
UTF-8
C++
false
false
3,257
h
/* Copyright (C) 2006 Mark Joshi Copyright (C) 2007, 2008 Eric Ehlers Copyright (C) 2009 2011 Narinder S Claire Copyright (C) 2011 John Adcock This file is part of XLW, a free-software/open-source C++ wrapper of the Excel C API - http://xlw.sourceforge.net/ XLW is free software: you can redistribute it and/or modify it under the terms of the XLW license. You should have received a copy of the license along with this program; if not, please email xlw-users@lists.sf.net This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #ifndef CELL_MATRIX_H #define CELL_MATRIX_H #include <xlw/CellValue.h> #include "xlw/MyContainers.h" #include <string> #include <vector> namespace xlw { class CellMatrix { public: //Copy Constructor CellMatrix(const CellMatrix &theOther):pimpl(theOther.pimpl.copy()){} CellMatrix(size_t rows, size_t columns):pimpl(new CellMatrixImpl(rows, columns)){} CellMatrix():pimpl(new CellMatrixImpl()){} CellMatrix(double data):pimpl(new CellMatrixImpl(1,1)) { (*pimpl)(0,0)=data; } CellMatrix(const std::string & data):pimpl(new CellMatrixImpl(1,1)) { (*pimpl)(0,0)=data; } CellMatrix(const std::wstring & data):pimpl(new CellMatrixImpl(1,1)) { (*pimpl)(0,0)=data; } CellMatrix(const char* data):pimpl(new CellMatrixImpl(1,1)) { (*pimpl)(0,0)=std::string(data); } CellMatrix(const MyArray& data): pimpl(new CellMatrixImpl(ArrayTraits<MyArray>::size(data),1)) { for(size_t i(0); i < ArrayTraits<MyArray>::size(data); ++i) { (*pimpl)(i,0) = ArrayTraits<MyArray>::getAt(data,i); } } CellMatrix(const MyMatrix& data): pimpl(new CellMatrixImpl(MatrixTraits<MyMatrix>::rows(data),MatrixTraits<MyMatrix>::columns(data))) { for(size_t i(0); i < MatrixTraits<MyMatrix>::rows(data); ++i) { for(size_t j(0); j < MatrixTraits<MyMatrix>::columns(data); ++j) { (*pimpl)(i,j) = MatrixTraits<MyMatrix>::getAt(data,i,j); } } } CellMatrix(unsigned long data):pimpl(new CellMatrixImpl(1,1)) { (*pimpl)(0,0)=data; } CellMatrix(int data):pimpl(new CellMatrixImpl(1,1)) { (*pimpl)(0,0)=data; } CellMatrix & operator=(const CellMatrix &theOther) { CellMatrix temp(theOther); temp.swap(*this); return *this; } const CellValue& operator()(size_t i, size_t j) const { return pimpl->operator()(i,j); } CellValue& operator()(size_t i, size_t j) { return pimpl->operator()(i,j); } size_t RowsInStructure() const { return pimpl->RowsInStructure(); } size_t ColumnsInStructure() const { return pimpl->ColumnsInStructure(); } void PushBottom(const CellMatrix & newRows) { CellMatrix temp(*this); temp.pimpl->PushBottom(*(newRows.pimpl)); temp.swap(*this); } void swap(CellMatrix &theOther) { pimpl.swap(theOther.pimpl); } private: eshared_ptr<CellMatrix_pimpl_abstract> pimpl; }; inline CellMatrix MergeCellMatrices(const CellMatrix& Top, const CellMatrix& Bottom) { CellMatrix temp(Top); temp.PushBottom(Bottom); return temp; } } #endif
[ "laeeth@laeeth.com" ]
laeeth@laeeth.com
8a31b2777e33acf5ac82d056be27ac9e044b3d05
d9b1c78c5c0f15a91d7b4db7136567a9ec470a2e
/boost/numeric/meta_math/odd_or_even.hpp
96351b56afabc674832f4dbc1f2f5ea1e322aa72
[ "MTLL" ]
permissive
simunova/mtl4
eff9f8c0dca66cd2a3a2573b24a287be38f9f02a
09d8523d59baf5fdec29f3509a63babc2763af4a
refs/heads/master
2021-06-19T08:36:42.145155
2021-03-05T20:58:21
2021-03-05T20:58:21
177,810,098
28
18
null
2021-03-05T20:58:21
2019-03-26T14:53:13
C++
UTF-8
C++
false
false
783
hpp
// Software License for MTL // // Copyright (c) 2007 The Trustees of Indiana University. // 2008 Dresden University of Technology and the Trustees of Indiana University. // 2010 SimuNova UG (haftungsbeschränkt), www.simunova.com. // All rights reserved. // Authors: Shikhar Vashistha // // This file is part of the Matrix Template Library // // See also license.mtl.txt in the distribution. #ifndef META_MATH_ODD_OR_EVEN #define META_MATH_ODD_OR_EVEN namespace meta_math{ template <long long n> struct odd_or_even{ static long long const value = (n^1)&1==true ? 0 : 1; // 0 corresponds to even number and 1 corresponds to odd number. }; }// namespace meta_math #endif// META_MATH_ODD_OR_EVEN
[ "masteroftheirclassic@gmail.com" ]
masteroftheirclassic@gmail.com
153f793d215691768cddba187870c3114fe84e90
8b71e5bf7385f545ef5b2542d98655e5bfacb41c
/examples/backup/components/java/cca/cfd/LBSolverC2CxxSocketPlainPort.h
5a09efc99b92ffbca692f6780c01ee297c829f2e
[]
no_license
ascodt-users/ascodt-nightly
1494f695ffb6ef22c81a36c379beb9ec8837325f
35d8222c9ea39ece35987c97946fd9fd0f7e794a
refs/heads/master
2020-05-31T08:45:35.308852
2014-09-22T03:43:39
2014-09-22T03:43:39
10,525,634
0
0
null
null
null
null
UTF-8
C++
false
false
4,447
h
#ifndef CCA_CFD_LBSOLVERC2SOCKETPLAINPORT_H_ #define CCA_CFD_LBSOLVERC2SOCKETPLAINPORT_H_ #include <map> #include <string> extern "C" { #ifdef _WIN32 void CCA_CFD_LBSOLVERC2SOCKET_PLAIN_PORT_CREATE_CLIENT_INSTANCE(long long* ptr,char* host,int& port,int& buffer_size); void CCA_CFD_LBSOLVERC2SOCKET_PLAIN_PORT_CREATE_SERVER_INSTANCE(long long* ptr,int& port,int& buffer_size); void CCA_CFD_LBSOLVERC2SOCKET_PLAIN_PORT_DESTROY_INSTANCE(long long* ptr); #else void cca_cfd_lbsolverc2socket_plain_port_create_client_instance_(long long* ptr,char* host,int& port,int& buffer_size); void cca_cfd_lbsolverc2socket_plain_port_create_server_instance_(long long* ptr,int& port,int& buffer_size); void cca_cfd_lbsolverc2socket_plain_port_destroy_instance_(long long* ptr); #endif #ifdef _WIN32 void CCA_CFD_LBSOLVERC2SOCKET_PLAIN_PORT_SETUP(long long* ref,char* inputScenario); #else void cca_cfd_lbsolverc2socket_plain_port_setup_(long long* ref,char* inputScenario); #endif #ifdef _WIN32 void CCA_CFD_LBSOLVERC2SOCKET_PLAIN_PORT_SETUPCOMMFORNSREGION(long long* ref,int* startOfRegion,int* startOfRegion_len,int* endOfRegion,int* endOfRegion_len,char** commids,int* commids_len); #else void cca_cfd_lbsolverc2socket_plain_port_setupcommfornsregion_(long long* ref,int* startOfRegion,int* startOfRegion_len,int* endOfRegion,int* endOfRegion_len,char** commids,int* commids_len); #endif #ifdef _WIN32 void CCA_CFD_LBSOLVERC2SOCKET_PLAIN_PORT_SOLVE(long long* ref); #else void cca_cfd_lbsolverc2socket_plain_port_solve_(long long* ref); #endif #ifdef _WIN32 void CCA_CFD_LBSOLVERC2SOCKET_PLAIN_PORT_SOLVEONETIMESTEP(long long* ref); #else void cca_cfd_lbsolverc2socket_plain_port_solveonetimestep_(long long* ref); #endif #ifdef _WIN32 void CCA_CFD_LBSOLVERC2SOCKET_PLAIN_PORT_SETVELOCITIES(long long* ref,double* velocitiesX, int* velocitiesX_len,double* velocitiesY, int* velocitiesY_len,double* velocitiesZ, int* velocitiesZ_len); #else void cca_cfd_lbsolverc2socket_plain_port_setvelocities_(long long* ref,double* velocitiesX, int* velocitiesX_len,double* velocitiesY, int* velocitiesY_len,double* velocitiesZ, int* velocitiesZ_len); #endif #ifdef _WIN32 void CCA_CFD_LBSOLVERC2SOCKET_PLAIN_PORT_SETPRESSURE(long long* ref,double* pressure, int* pressure_len); #else void cca_cfd_lbsolverc2socket_plain_port_setpressure_(long long* ref,double* pressure, int* pressure_len); #endif #ifdef _WIN32 void CCA_CFD_LBSOLVERC2SOCKET_PLAIN_PORT_SETGRADIENTS(long long* ref,double* gradients, int* gradients_len); #else void cca_cfd_lbsolverc2socket_plain_port_setgradients_(long long* ref,double* gradients, int* gradients_len); #endif #ifdef _WIN32 void CCA_CFD_LBSOLVERC2SOCKET_PLAIN_PORT_CLOSELBPROFILES(long long* ref); #else void cca_cfd_lbsolverc2socket_plain_port_closelbprofiles_(long long* ref); #endif #ifdef _WIN32 void CCA_CFD_LBSOLVERC2SOCKET_PLAIN_PORT_PRINTLBDENSITY(long long* ref); #else void cca_cfd_lbsolverc2socket_plain_port_printlbdensity_(long long* ref); #endif #ifdef _WIN32 void CCA_CFD_LBSOLVERC2SOCKET_PLAIN_PORT_PRINTLBPROFILES(long long* ref); #else void cca_cfd_lbsolverc2socket_plain_port_printlbprofiles_(long long* ref); #endif #ifdef _WIN32 void CCA_CFD_LBSOLVERC2SOCKET_PLAIN_PORT_FORWARDVELOCITIES(long long* ref,int* keys,int* keys_len,int* offsets,int* offsets_len,int* flips,int* flips_len,double* values, int* values_len,int* componentSize,int* componentSize_len,int* ackn); #else void cca_cfd_lbsolverc2socket_plain_port_forwardvelocities_(long long* ref,int* keys,int* keys_len,int* offsets,int* offsets_len,int* flips,int* flips_len,double* values, int* values_len,int* componentSize,int* componentSize_len,int* ackn); #endif #ifdef _WIN32 void CCA_CFD_LBSOLVERC2SOCKET_PLAIN_PORT_FORWARDPRESSURE(long long* ref,int* keys,int* keys_len,int* offsets,int* offsets_len,int* flips,int* flips_len,double* values, int* values_len,int* ackn); #else void cca_cfd_lbsolverc2socket_plain_port_forwardpressure_(long long* ref,int* keys,int* keys_len,int* offsets,int* offsets_len,int* flips,int* flips_len,double* values, int* values_len,int* ackn); #endif #ifdef _WIN32 void CCA_CFD_LBSOLVERC2SOCKET_PLAIN_PORT_SYNCR(long long* ref,int* value); #else void cca_cfd_lbsolverc2socket_plain_port_syncr_(long long* ref,int* value); #endif #ifdef _WIN32 void CCA_CFD_LBSOLVERC2SOCKET_PLAIN_PORT_PLOT(long long* ref); #else void cca_cfd_lbsolverc2socket_plain_port_plot_(long long* ref); #endif } #endif
[ "atanasoa@atsccs55.informatik.tu-muenchen.de" ]
atanasoa@atsccs55.informatik.tu-muenchen.de
0f0cf344c2a77fb9d1ce78d78419d96f22665b47
fc5aa32d10f180830f58b545f7745af618db83e7
/src/main.cpp
b8f3d61fdda3a113af1c1a72bda0dcade79ee4ec
[ "MIT" ]
permissive
BurningMan44/SprintCoin
8499235ad9c15a81f975c4aa41eae5bc1559cfe8
eef26db0b4c04ec9aff10c40a2b676b374642c07
refs/heads/master
2021-07-21T18:17:26.640766
2017-10-28T17:45:22
2017-10-28T17:45:22
108,595,626
0
0
null
null
null
null
UTF-8
C++
false
false
295,835
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2014-2017 The Sprint Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "addrman.h" #include "alert.h" #include "arith_uint256.h" #include "chainparams.h" #include "checkpoints.h" #include "checkqueue.h" #include "consensus/consensus.h" #include "consensus/merkle.h" #include "consensus/validation.h" #include "hash.h" #include "init.h" #include "merkleblock.h" #include "net.h" #include "policy/policy.h" #include "pow.h" #include "primitives/block.h" #include "primitives/transaction.h" #include "script/script.h" #include "script/sigcache.h" #include "script/standard.h" #include "tinyformat.h" #include "txdb.h" #include "txmempool.h" #include "ui_interface.h" #include "undo.h" #include "util.h" #include "spork.h" #include "utilstrencodings.h" #include "validationinterface.h" #include "versionbits.h" #include "darksend.h" #include "governance.h" #include "instantx.h" #include "masternode-payments.h" #include "masternode-sync.h" #include "masternodeman.h" #include <sstream> #include <boost/algorithm/string/replace.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/lexical_cast.hpp> #include <boost/math/distributions/poisson.hpp> #include <boost/thread.hpp> #include "utilmoneystr.h" using namespace std; #if defined(NDEBUG) # error "Sprint Core cannot be compiled without assertions." #endif /** * Global state */ CCriticalSection cs_main; BlockMap mapBlockIndex; CChain chainActive; CBlockIndex *pindexBestHeader = NULL; int64_t nTimeBestReceived = 0; CWaitableCriticalSection csBestBlock; CConditionVariable cvBlockChange; int nScriptCheckThreads = 0; bool fImporting = false; bool fReindex = false; bool fTxIndex = true; bool fAddressIndex = false; bool fTimestampIndex = false; bool fSpentIndex = false; bool fHavePruned = false; bool fPruneMode = false; bool fIsBareMultisigStd = DEFAULT_PERMIT_BAREMULTISIG; bool fRequireStandard = true; unsigned int nBytesPerSigOp = DEFAULT_BYTES_PER_SIGOP; bool fCheckBlockIndex = false; bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED; size_t nCoinCacheUsage = 5000 * 300; uint64_t nPruneTarget = 0; bool fAlerts = DEFAULT_ALERTS; bool fEnableReplacement = DEFAULT_ENABLE_REPLACEMENT; /** Fees smaller than this (in duffs) are considered zero fee (for relaying, mining and transaction creation) */ CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE); CTxMemPool mempool(::minRelayTxFee); struct COrphanTx { CTransaction tx; NodeId fromPeer; }; map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(cs_main);; map<uint256, set<uint256> > mapOrphanTransactionsByPrev GUARDED_BY(cs_main);; map<uint256, int64_t> mapRejectedBlocks GUARDED_BY(cs_main); void EraseOrphansFor(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main); /** * Returns true if there are nRequired or more blocks of minVersion or above * in the last Consensus::Params::nMajorityWindow blocks, starting at pstart and going backwards. */ static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams); static void CheckBlockIndex(const Consensus::Params& consensusParams); /** Constant stuff for coinbase transactions we create: */ CScript COINBASE_FLAGS; const string strMessageMagic = "DarkCoin Signed Message:\n"; // Internal stuff namespace { struct CBlockIndexWorkComparator { bool operator()(CBlockIndex *pa, CBlockIndex *pb) const { // First sort by most total work, ... if (pa->nChainWork > pb->nChainWork) return false; if (pa->nChainWork < pb->nChainWork) return true; // ... then by earliest time received, ... if (pa->nSequenceId < pb->nSequenceId) return false; if (pa->nSequenceId > pb->nSequenceId) return true; // Use pointer address as tie breaker (should only happen with blocks // loaded from disk, as those all have id 0). if (pa < pb) return false; if (pa > pb) return true; // Identical blocks. return false; } }; CBlockIndex *pindexBestInvalid; /** * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be * missing the data for the block. */ set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates; /** Number of nodes with fSyncStarted. */ int nSyncStarted = 0; /** All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions. * Pruned nodes may have entries where B is missing data. */ multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked; CCriticalSection cs_LastBlockFile; std::vector<CBlockFileInfo> vinfoBlockFile; int nLastBlockFile = 0; /** Global flag to indicate we should check to see if there are * block/undo files that should be deleted. Set on startup * or if we allocate more file space when we're in prune mode */ bool fCheckForPruning = false; /** * Every received block is assigned a unique and increasing identifier, so we * know which one to give priority in case of a fork. */ CCriticalSection cs_nBlockSequenceId; /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */ uint32_t nBlockSequenceId = 1; /** * Sources of received blocks, saved to be able to send them reject * messages or ban them when processing happens afterwards. Protected by * cs_main. */ map<uint256, NodeId> mapBlockSource; /** * Filter for transactions that were recently rejected by * AcceptToMemoryPool. These are not rerequested until the chain tip * changes, at which point the entire filter is reset. Protected by * cs_main. * * Without this filter we'd be re-requesting txs from each of our peers, * increasing bandwidth consumption considerably. For instance, with 100 * peers, half of which relay a tx we don't accept, that might be a 50x * bandwidth increase. A flooding attacker attempting to roll-over the * filter using minimum-sized, 60byte, transactions might manage to send * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a * two minute window to send invs to us. * * Decreasing the false positive rate is fairly cheap, so we pick one in a * million to make it highly unlikely for users to have issues with this * filter. * * Memory used: 1.7MB */ boost::scoped_ptr<CRollingBloomFilter> recentRejects; uint256 hashRecentRejectsChainTip; /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */ struct QueuedBlock { uint256 hash; CBlockIndex* pindex; //!< Optional. bool fValidatedHeaders; //!< Whether this block has validated headers at the time of request. }; map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight; /** Number of preferable block download peers. */ int nPreferredDownload = 0; /** Dirty block index entries. */ set<CBlockIndex*> setDirtyBlockIndex; /** Dirty block file entries. */ set<int> setDirtyFileInfo; /** Number of peers from which we're downloading blocks. */ int nPeersWithValidatedDownloads = 0; } // anon namespace ////////////////////////////////////////////////////////////////////////////// // // Registration of network node signals. // namespace { struct CBlockReject { unsigned char chRejectCode; string strRejectReason; uint256 hashBlock; }; /** * Maintain validation-specific state about nodes, protected by cs_main, instead * by CNode's own locks. This simplifies asynchronous operation, where * processing of incoming data is done after the ProcessMessage call returns, * and we're no longer holding the node's locks. */ struct CNodeState { //! The peer's address CService address; //! Whether we have a fully established connection. bool fCurrentlyConnected; //! Accumulated misbehaviour score for this peer. int nMisbehavior; //! Whether this peer should be disconnected and banned (unless whitelisted). bool fShouldBan; //! String name of this peer (debugging/logging purposes). std::string name; //! List of asynchronously-determined block rejections to notify this peer about. std::vector<CBlockReject> rejects; //! The best known block we know this peer has announced. CBlockIndex *pindexBestKnownBlock; //! The hash of the last unknown block this peer has announced. uint256 hashLastUnknownBlock; //! The last full block we both have. CBlockIndex *pindexLastCommonBlock; //! The best header we have sent our peer. CBlockIndex *pindexBestHeaderSent; //! Whether we've started headers synchronization with this peer. bool fSyncStarted; //! Since when we're stalling block download progress (in microseconds), or 0. int64_t nStallingSince; list<QueuedBlock> vBlocksInFlight; //! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty. int64_t nDownloadingSince; int nBlocksInFlight; int nBlocksInFlightValidHeaders; //! Whether we consider this a preferred download peer. bool fPreferredDownload; //! Whether this peer wants invs or headers (when possible) for block announcements. bool fPreferHeaders; CNodeState() { fCurrentlyConnected = false; nMisbehavior = 0; fShouldBan = false; pindexBestKnownBlock = NULL; hashLastUnknownBlock.SetNull(); pindexLastCommonBlock = NULL; pindexBestHeaderSent = NULL; fSyncStarted = false; nStallingSince = 0; nDownloadingSince = 0; nBlocksInFlight = 0; nBlocksInFlightValidHeaders = 0; fPreferredDownload = false; fPreferHeaders = false; } }; /** Map maintaining per-node state. Requires cs_main. */ map<NodeId, CNodeState> mapNodeState; // Requires cs_main. CNodeState *State(NodeId pnode) { map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode); if (it == mapNodeState.end()) return NULL; return &it->second; } int GetHeight() { LOCK(cs_main); return chainActive.Height(); } void UpdatePreferredDownload(CNode* node, CNodeState* state) { nPreferredDownload -= state->fPreferredDownload; // Whether this node should be marked as a preferred download node. state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient; nPreferredDownload += state->fPreferredDownload; } void InitializeNode(NodeId nodeid, const CNode *pnode) { LOCK(cs_main); CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second; state.name = pnode->addrName; state.address = pnode->addr; } void FinalizeNode(NodeId nodeid) { LOCK(cs_main); CNodeState *state = State(nodeid); if (state->fSyncStarted) nSyncStarted--; if (state->nMisbehavior == 0 && state->fCurrentlyConnected) { AddressCurrentlyConnected(state->address); } BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight) { mapBlocksInFlight.erase(entry.hash); } EraseOrphansFor(nodeid); nPreferredDownload -= state->fPreferredDownload; nPeersWithValidatedDownloads -= (state->nBlocksInFlightValidHeaders != 0); assert(nPeersWithValidatedDownloads >= 0); mapNodeState.erase(nodeid); if (mapNodeState.empty()) { // Do a consistency check after the last peer is removed. assert(mapBlocksInFlight.empty()); assert(nPreferredDownload == 0); assert(nPeersWithValidatedDownloads == 0); } } // Requires cs_main. // Returns a bool indicating whether we requested this block. bool MarkBlockAsReceived(const uint256& hash) { map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash); if (itInFlight != mapBlocksInFlight.end()) { CNodeState *state = State(itInFlight->second.first); state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders; if (state->nBlocksInFlightValidHeaders == 0 && itInFlight->second.second->fValidatedHeaders) { // Last validated block on the queue was received. nPeersWithValidatedDownloads--; } if (state->vBlocksInFlight.begin() == itInFlight->second.second) { // First block on the queue was received, update the start download time for the next one state->nDownloadingSince = std::max(state->nDownloadingSince, GetTimeMicros()); } state->vBlocksInFlight.erase(itInFlight->second.second); state->nBlocksInFlight--; state->nStallingSince = 0; mapBlocksInFlight.erase(itInFlight); return true; } return false; } // Requires cs_main. void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Params& consensusParams, CBlockIndex *pindex = NULL) { CNodeState *state = State(nodeid); assert(state != NULL); // Make sure it's not listed somewhere already. MarkBlockAsReceived(hash); QueuedBlock newentry = {hash, pindex, pindex != NULL}; list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry); state->nBlocksInFlight++; state->nBlocksInFlightValidHeaders += newentry.fValidatedHeaders; if (state->nBlocksInFlight == 1) { // We're starting a block download (batch) from this peer. state->nDownloadingSince = GetTimeMicros(); } if (state->nBlocksInFlightValidHeaders == 1 && pindex != NULL) { nPeersWithValidatedDownloads++; } mapBlocksInFlight[hash] = std::make_pair(nodeid, it); } /** Check whether the last unknown block a peer advertised is not yet known. */ void ProcessBlockAvailability(NodeId nodeid) { CNodeState *state = State(nodeid); assert(state != NULL); if (!state->hashLastUnknownBlock.IsNull()) { BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock); if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) { if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork) state->pindexBestKnownBlock = itOld->second; state->hashLastUnknownBlock.SetNull(); } } } /** Update tracking information about which blocks a peer is assumed to have. */ void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) { CNodeState *state = State(nodeid); assert(state != NULL); ProcessBlockAvailability(nodeid); BlockMap::iterator it = mapBlockIndex.find(hash); if (it != mapBlockIndex.end() && it->second->nChainWork > 0) { // An actually better block was announced. if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork) state->pindexBestKnownBlock = it->second; } else { // An unknown block was announced; just assume that the latest one is the best one. state->hashLastUnknownBlock = hash; } } // Requires cs_main bool CanDirectFetch(const Consensus::Params &consensusParams) { return chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - consensusParams.nPowTargetSpacing * 20; } // Requires cs_main bool PeerHasHeader(CNodeState *state, CBlockIndex *pindex) { if (state->pindexBestKnownBlock && pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight)) return true; if (state->pindexBestHeaderSent && pindex == state->pindexBestHeaderSent->GetAncestor(pindex->nHeight)) return true; return false; } /** Find the last common ancestor two blocks have. * Both pa and pb must be non-NULL. */ CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) { if (pa->nHeight > pb->nHeight) { pa = pa->GetAncestor(pb->nHeight); } else if (pb->nHeight > pa->nHeight) { pb = pb->GetAncestor(pa->nHeight); } while (pa != pb && pa && pb) { pa = pa->pprev; pb = pb->pprev; } // Eventually all chain branches meet at the genesis block. assert(pa == pb); return pa; } /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has * at most count entries. */ void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) { if (count == 0) return; vBlocks.reserve(vBlocks.size() + count); CNodeState *state = State(nodeid); assert(state != NULL); // Make sure pindexBestKnownBlock is up to date, we'll need it. ProcessBlockAvailability(nodeid); if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) { // This peer has nothing interesting. return; } if (state->pindexLastCommonBlock == NULL) { // Bootstrap quickly by guessing a parent of our best tip is the forking point. // Guessing wrong in either direction is not a problem. state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())]; } // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor // of its current tip anymore. Go back enough to fix that. state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock); if (state->pindexLastCommonBlock == state->pindexBestKnownBlock) return; std::vector<CBlockIndex*> vToFetch; CBlockIndex *pindexWalk = state->pindexLastCommonBlock; // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to // download that next block if the window were 1 larger. int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW; int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1); NodeId waitingfor = -1; while (pindexWalk->nHeight < nMaxHeight) { // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive // as iterating over ~100 CBlockIndex* entries anyway. int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128)); vToFetch.resize(nToFetch); pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch); vToFetch[nToFetch - 1] = pindexWalk; for (unsigned int i = nToFetch - 1; i > 0; i--) { vToFetch[i - 1] = vToFetch[i]->pprev; } // Iterate over those blocks in vToFetch (in forward direction), adding the ones that // are not yet downloaded and not in flight to vBlocks. In the mean time, update // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's // already part of our chain (and therefore don't need it even if pruned). BOOST_FOREACH(CBlockIndex* pindex, vToFetch) { if (!pindex->IsValid(BLOCK_VALID_TREE)) { // We consider the chain that this peer is on invalid. return; } if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) { if (pindex->nChainTx) state->pindexLastCommonBlock = pindex; } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) { // The block is not already downloaded, and not yet in flight. if (pindex->nHeight > nWindowEnd) { // We reached the end of the window. if (vBlocks.size() == 0 && waitingfor != nodeid) { // We aren't able to fetch anything, but we would be if the download window was one larger. nodeStaller = waitingfor; } return; } vBlocks.push_back(pindex); if (vBlocks.size() == count) { return; } } else if (waitingfor == -1) { // This is the first already-in-flight block. waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first; } } } } } // anon namespace bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) { LOCK(cs_main); CNodeState *state = State(nodeid); if (state == NULL) return false; stats.nMisbehavior = state->nMisbehavior; stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1; stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1; BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) { if (queue.pindex) stats.vHeightInFlight.push_back(queue.pindex->nHeight); } return true; } void RegisterNodeSignals(CNodeSignals& nodeSignals) { nodeSignals.GetHeight.connect(&GetHeight); nodeSignals.ProcessMessages.connect(&ProcessMessages); nodeSignals.SendMessages.connect(&SendMessages); nodeSignals.InitializeNode.connect(&InitializeNode); nodeSignals.FinalizeNode.connect(&FinalizeNode); } void UnregisterNodeSignals(CNodeSignals& nodeSignals) { nodeSignals.GetHeight.disconnect(&GetHeight); nodeSignals.ProcessMessages.disconnect(&ProcessMessages); nodeSignals.SendMessages.disconnect(&SendMessages); nodeSignals.InitializeNode.disconnect(&InitializeNode); nodeSignals.FinalizeNode.disconnect(&FinalizeNode); } CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator) { // Find the first block the caller has in the main chain BOOST_FOREACH(const uint256& hash, locator.vHave) { BlockMap::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (chain.Contains(pindex)) return pindex; } } return chain.Genesis(); } CCoinsViewCache *pcoinsTip = NULL; CBlockTreeDB *pblocktree = NULL; ////////////////////////////////////////////////////////////////////////////// // // mapOrphanTransactions // bool AddOrphanTx(const CTransaction& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { uint256 hash = tx.GetHash(); if (mapOrphanTransactions.count(hash)) return false; // Ignore big transactions, to avoid a // send-big-orphans memory exhaustion attack. If a peer has a legitimate // large transaction with a missing parent then we assume // it will rebroadcast it later, after the parent transaction(s) // have been mined or received. // 10,000 orphans, each of which is at most 5,000 bytes big is // at most 500 megabytes of orphans: unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION); if (sz > 5000) { LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString()); return false; } mapOrphanTransactions[hash].tx = tx; mapOrphanTransactions[hash].fromPeer = peer; BOOST_FOREACH(const CTxIn& txin, tx.vin) mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash); LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(), mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size()); return true; } void static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash); if (it == mapOrphanTransactions.end()) return; BOOST_FOREACH(const CTxIn& txin, it->second.tx.vin) { map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash); if (itPrev == mapOrphanTransactionsByPrev.end()) continue; itPrev->second.erase(hash); if (itPrev->second.empty()) mapOrphanTransactionsByPrev.erase(itPrev); } mapOrphanTransactions.erase(it); } void EraseOrphansFor(NodeId peer) { int nErased = 0; map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin(); while (iter != mapOrphanTransactions.end()) { map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid if (maybeErase->second.fromPeer == peer) { EraseOrphanTx(maybeErase->second.tx.GetHash()); ++nErased; } } if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer); } unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { unsigned int nEvicted = 0; while (mapOrphanTransactions.size() > nMaxOrphans) { // Evict a random orphan: uint256 randomhash = GetRandHash(); map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash); if (it == mapOrphanTransactions.end()) it = mapOrphanTransactions.begin(); EraseOrphanTx(it->first); ++nEvicted; } return nEvicted; } bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime) { if (tx.nLockTime == 0) return true; if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime)) return true; BOOST_FOREACH(const CTxIn& txin, tx.vin) { if (!(txin.nSequence == CTxIn::SEQUENCE_FINAL)) return false; } return true; } bool CheckFinalTx(const CTransaction &tx, int flags) { AssertLockHeld(cs_main); // By convention a negative value for flags indicates that the // current network-enforced consensus rules should be used. In // a future soft-fork scenario that would mean checking which // rules would be enforced for the next block and setting the // appropriate flags. At the present time no soft-forks are // scheduled, so no flags are set. flags = std::max(flags, 0); // CheckFinalTx() uses chainActive.Height()+1 to evaluate // nLockTime because when IsFinalTx() is called within // CBlock::AcceptBlock(), the height of the block *being* // evaluated is what is used. Thus if we want to know if a // transaction can be part of the *next* block, we need to call // IsFinalTx() with one more than chainActive.Height(). const int nBlockHeight = chainActive.Height() + 1; // BIP113 will require that time-locked transactions have nLockTime set to // less than the median time of the previous block they're contained in. // When the next block is created its previous block will be the current // chain tip, so we use that to calculate the median time passed to // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set. const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST) ? chainActive.Tip()->GetMedianTimePast() : GetAdjustedTime(); return IsFinalTx(tx, nBlockHeight, nBlockTime); } /** * Calculates the block height and previous block's median time past at * which the transaction will be considered final in the context of BIP 68. * Also removes from the vector of input heights any entries which did not * correspond to sequence locked inputs as they do not affect the calculation. */ static std::pair<int, int64_t> CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block) { assert(prevHeights->size() == tx.vin.size()); // Will be set to the equivalent height- and time-based nLockTime // values that would be necessary to satisfy all relative lock- // time constraints given our view of block chain history. // The semantics of nLockTime are the last invalid height/time, so // use -1 to have the effect of any height or time being valid. int nMinHeight = -1; int64_t nMinTime = -1; // tx.nVersion is signed integer so requires cast to unsigned otherwise // we would be doing a signed comparison and half the range of nVersion // wouldn't support BIP 68. bool fEnforceBIP68 = static_cast<uint32_t>(tx.nVersion) >= 2 && flags & LOCKTIME_VERIFY_SEQUENCE; // Do not enforce sequence numbers as a relative lock time // unless we have been instructed to if (!fEnforceBIP68) { return std::make_pair(nMinHeight, nMinTime); } for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) { const CTxIn& txin = tx.vin[txinIndex]; // Sequence numbers with the most significant bit set are not // treated as relative lock-times, nor are they given any // consensus-enforced meaning at this point. if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) { // The height of this input is not relevant for sequence locks (*prevHeights)[txinIndex] = 0; continue; } int nCoinHeight = (*prevHeights)[txinIndex]; if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) { int64_t nCoinTime = block.GetAncestor(std::max(nCoinHeight-1, 0))->GetMedianTimePast(); // NOTE: Subtract 1 to maintain nLockTime semantics // BIP 68 relative lock times have the semantics of calculating // the first block or time at which the transaction would be // valid. When calculating the effective block time or height // for the entire transaction, we switch to using the // semantics of nLockTime which is the last invalid block // time or height. Thus we subtract 1 from the calculated // time or height. // Time-based relative lock-times are measured from the // smallest allowed timestamp of the block containing the // txout being spent, which is the median time past of the // block prior. nMinTime = std::max(nMinTime, nCoinTime + (int64_t)((txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) << CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) - 1); } else { nMinHeight = std::max(nMinHeight, nCoinHeight + (int)(txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) - 1); } } return std::make_pair(nMinHeight, nMinTime); } static bool EvaluateSequenceLocks(const CBlockIndex& block, std::pair<int, int64_t> lockPair) { assert(block.pprev); int64_t nBlockTime = block.pprev->GetMedianTimePast(); if (lockPair.first >= block.nHeight || lockPair.second >= nBlockTime) return false; return true; } bool SequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block) { return EvaluateSequenceLocks(block, CalculateSequenceLocks(tx, flags, prevHeights, block)); } bool TestLockPointValidity(const LockPoints* lp) { AssertLockHeld(cs_main); assert(lp); // If there are relative lock times then the maxInputBlock will be set // If there are no relative lock times, the LockPoints don't depend on the chain if (lp->maxInputBlock) { // Check whether chainActive is an extension of the block at which the LockPoints // calculation was valid. If not LockPoints are no longer valid if (!chainActive.Contains(lp->maxInputBlock)) { return false; } } // LockPoints still valid return true; } bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp, bool useExistingLockPoints) { AssertLockHeld(cs_main); AssertLockHeld(mempool.cs); CBlockIndex* tip = chainActive.Tip(); CBlockIndex index; index.pprev = tip; // CheckSequenceLocks() uses chainActive.Height()+1 to evaluate // height based locks because when SequenceLocks() is called within // ConnectBlock(), the height of the block *being* // evaluated is what is used. // Thus if we want to know if a transaction can be part of the // *next* block, we need to use one more than chainActive.Height() index.nHeight = tip->nHeight + 1; std::pair<int, int64_t> lockPair; if (useExistingLockPoints) { assert(lp); lockPair.first = lp->height; lockPair.second = lp->time; } else { // pcoinsTip contains the UTXO set for chainActive.Tip() CCoinsViewMemPool viewMemPool(pcoinsTip, mempool); std::vector<int> prevheights; prevheights.resize(tx.vin.size()); for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) { const CTxIn& txin = tx.vin[txinIndex]; CCoins coins; if (!viewMemPool.GetCoins(txin.prevout.hash, coins)) { return error("%s: Missing input", __func__); } if (coins.nHeight == MEMPOOL_HEIGHT) { // Assume all mempool transaction confirm in the next block prevheights[txinIndex] = tip->nHeight + 1; } else { prevheights[txinIndex] = coins.nHeight; } } lockPair = CalculateSequenceLocks(tx, flags, &prevheights, index); if (lp) { lp->height = lockPair.first; lp->time = lockPair.second; // Also store the hash of the block with the highest height of // all the blocks which have sequence locked prevouts. // This hash needs to still be on the chain // for these LockPoint calculations to be valid // Note: It is impossible to correctly calculate a maxInputBlock // if any of the sequence locked inputs depend on unconfirmed txs, // except in the special case where the relative lock time/height // is 0, which is equivalent to no sequence lock. Since we assume // input height of tip+1 for mempool txs and test the resulting // lockPair from CalculateSequenceLocks against tip+1. We know // EvaluateSequenceLocks will fail if there was a non-zero sequence // lock on a mempool input, so we can use the return value of // CheckSequenceLocks to indicate the LockPoints validity int maxInputHeight = 0; BOOST_FOREACH(int height, prevheights) { // Can ignore mempool inputs since we'll fail if they had non-zero locks if (height != tip->nHeight+1) { maxInputHeight = std::max(maxInputHeight, height); } } lp->maxInputBlock = tip->GetAncestor(maxInputHeight); } } return EvaluateSequenceLocks(index, lockPair); } unsigned int GetLegacySigOpCount(const CTransaction& tx) { unsigned int nSigOps = 0; BOOST_FOREACH(const CTxIn& txin, tx.vin) { nSigOps += txin.scriptSig.GetSigOpCount(false); } BOOST_FOREACH(const CTxOut& txout, tx.vout) { nSigOps += txout.scriptPubKey.GetSigOpCount(false); } return nSigOps; } unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs) { if (tx.IsCoinBase()) return 0; unsigned int nSigOps = 0; for (unsigned int i = 0; i < tx.vin.size(); i++) { const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]); if (prevout.scriptPubKey.IsPayToScriptHash()) nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig); } return nSigOps; } int GetUTXOHeight(const COutPoint& outpoint) { LOCK(cs_main); CCoins coins; if(!pcoinsTip->GetCoins(outpoint.hash, coins) || (unsigned int)outpoint.n>=coins.vout.size() || coins.vout[outpoint.n].IsNull()) { return -1; } return coins.nHeight; } int GetInputAge(const CTxIn &txin) { CCoinsView viewDummy; CCoinsViewCache view(&viewDummy); { LOCK(mempool.cs); CCoinsViewMemPool viewMempool(pcoinsTip, mempool); view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view const CCoins* coins = view.AccessCoins(txin.prevout.hash); if (coins) { if(coins->nHeight < 0) return 0; return chainActive.Height() - coins->nHeight + 1; } else { return -1; } } } int GetInputAgeIX(const uint256 &nTXHash, const CTxIn &txin) { int nResult = GetInputAge(txin); if(nResult < 0) return -1; if (nResult < 6 && instantsend.IsLockedInstantSendTransaction(nTXHash)) return nInstantSendDepth + nResult; return nResult; } int GetIXConfirmations(const uint256 &nTXHash) { if (instantsend.IsLockedInstantSendTransaction(nTXHash)) return nInstantSendDepth; return 0; } bool CheckTransaction(const CTransaction& tx, CValidationState &state) { // Basic checks that don't depend on any context if (tx.vin.empty()) return state.DoS(10, false, REJECT_INVALID, "bad-txns-vin-empty"); if (tx.vout.empty()) return state.DoS(10, false, REJECT_INVALID, "bad-txns-vout-empty"); // Size limits if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) return state.DoS(100, false, REJECT_INVALID, "bad-txns-oversize"); // Check for negative or overflow output values CAmount nValueOut = 0; BOOST_FOREACH(const CTxOut& txout, tx.vout) { if (txout.nValue < 0) return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-negative"); if (txout.nValue > MAX_MONEY) return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-toolarge"); nValueOut += txout.nValue; if (!MoneyRange(nValueOut)) return state.DoS(100, false, REJECT_INVALID, "bad-txns-txouttotal-toolarge"); } // Check for duplicate inputs set<COutPoint> vInOutPoints; BOOST_FOREACH(const CTxIn& txin, tx.vin) { if (vInOutPoints.count(txin.prevout)) return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputs-duplicate"); vInOutPoints.insert(txin.prevout); } if (tx.IsCoinBase()) { if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100) return state.DoS(100, false, REJECT_INVALID, "bad-cb-length"); } else { BOOST_FOREACH(const CTxIn& txin, tx.vin) if (txin.prevout.IsNull()) return state.DoS(10, false, REJECT_INVALID, "bad-txns-prevout-null"); } return true; } void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) { int expired = pool.Expire(GetTime() - age); if (expired != 0) LogPrint("mempool", "Expired %i transactions from the memory pool\n", expired); std::vector<uint256> vNoSpendsRemaining; pool.TrimToSize(limit, &vNoSpendsRemaining); BOOST_FOREACH(const uint256& removed, vNoSpendsRemaining) pcoinsTip->Uncache(removed); } /** Convert CValidationState to a human-readable message for logging */ std::string FormatStateMessage(const CValidationState &state) { return strprintf("%s%s (code %i)", state.GetRejectReason(), state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(), state.GetRejectCode()); } bool AcceptToMemoryPoolWorker(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree, bool* pfMissingInputs, bool fOverrideMempoolLimit, bool fRejectAbsurdFee, std::vector<uint256>& vHashTxnToUncache, bool fDryRun) { AssertLockHeld(cs_main); if (pfMissingInputs) *pfMissingInputs = false; if (!CheckTransaction(tx, state)) return false; // Coinbase is only valid in a block, not as a loose transaction if (tx.IsCoinBase()) return state.DoS(100, false, REJECT_INVALID, "coinbase"); // Rather not work on nonstandard transactions (unless -testnet/-regtest) string reason; if (fRequireStandard && !IsStandardTx(tx, reason)) return state.DoS(0, false, REJECT_NONSTANDARD, reason); // Don't relay version 2 transactions until CSV is active, and we can be // sure that such transactions will be mined (unless we're on // -testnet/-regtest). const CChainParams& chainparams = Params(); if (fRequireStandard && tx.nVersion >= 2 && VersionBitsTipState(chainparams.GetConsensus(), Consensus::DEPLOYMENT_CSV) != THRESHOLD_ACTIVE) { return state.DoS(0, false, REJECT_NONSTANDARD, "premature-version2-tx"); } // Only accept nLockTime-using transactions that can be mined in the next // block; we don't want our mempool filled up with transactions that can't // be mined yet. if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS)) return state.DoS(0, false, REJECT_NONSTANDARD, "non-final"); // is it already in the memory pool? uint256 hash = tx.GetHash(); if (pool.exists(hash)) return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-in-mempool"); // If this is a Transaction Lock Request check to see if it's valid if(instantsend.HasTxLockRequest(hash) && !CTxLockRequest(tx).IsValid()) return state.DoS(10, error("AcceptToMemoryPool : CTxLockRequest %s is invalid", hash.ToString()), REJECT_INVALID, "bad-txlockrequest"); // Check for conflicts with a completed Transaction Lock BOOST_FOREACH(const CTxIn &txin, tx.vin) { uint256 hashLocked; if(instantsend.GetLockedOutPointTxHash(txin.prevout, hashLocked) && hash != hashLocked) return state.DoS(10, error("AcceptToMemoryPool : Transaction %s conflicts with completed Transaction Lock %s", hash.ToString(), hashLocked.ToString()), REJECT_INVALID, "tx-txlock-conflict"); } // Check for conflicts with in-memory transactions set<uint256> setConflicts; { LOCK(pool.cs); // protect pool.mapNextTx BOOST_FOREACH(const CTxIn &txin, tx.vin) { if (pool.mapNextTx.count(txin.prevout)) { const CTransaction *ptxConflicting = pool.mapNextTx[txin.prevout].ptx; if (!setConflicts.count(ptxConflicting->GetHash())) { // InstantSend txes are not replacable if(instantsend.HasTxLockRequest(ptxConflicting->GetHash())) { // this tx conflicts with a Transaction Lock Request candidate return state.DoS(0, error("AcceptToMemoryPool : Transaction %s conflicts with Transaction Lock Request %s", hash.ToString(), ptxConflicting->GetHash().ToString()), REJECT_INVALID, "tx-txlockreq-mempool-conflict"); } else if (instantsend.HasTxLockRequest(hash)) { // this tx is a tx lock request and it conflicts with a normal tx return state.DoS(0, error("AcceptToMemoryPool : Transaction Lock Request %s conflicts with transaction %s", hash.ToString(), ptxConflicting->GetHash().ToString()), REJECT_INVALID, "txlockreq-tx-mempool-conflict"); } // Allow opt-out of transaction replacement by setting // nSequence >= maxint-1 on all inputs. // // maxint-1 is picked to still allow use of nLockTime by // non-replacable transactions. All inputs rather than just one // is for the sake of multi-party protocols, where we don't // want a single party to be able to disable replacement. // // The opt-out ignores descendants as anyone relying on // first-seen mempool behavior should be checking all // unconfirmed ancestors anyway; doing otherwise is hopelessly // insecure. bool fReplacementOptOut = true; if (fEnableReplacement) { BOOST_FOREACH(const CTxIn &txin, ptxConflicting->vin) { if (txin.nSequence < std::numeric_limits<unsigned int>::max()-1) { fReplacementOptOut = false; break; } } } if (fReplacementOptOut) return state.Invalid(false, REJECT_CONFLICT, "txn-mempool-conflict"); setConflicts.insert(ptxConflicting->GetHash()); } } } } { CCoinsView dummy; CCoinsViewCache view(&dummy); CAmount nValueIn = 0; LockPoints lp; { LOCK(pool.cs); CCoinsViewMemPool viewMemPool(pcoinsTip, pool); view.SetBackend(viewMemPool); // do we already have it? bool fHadTxInCache = pcoinsTip->HaveCoinsInCache(hash); if (view.HaveCoins(hash)) { if (!fHadTxInCache) vHashTxnToUncache.push_back(hash); return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-known"); } // do all inputs exist? // Note that this does not check for the presence of actual outputs (see the next check for that), // and only helps with filling in pfMissingInputs (to determine missing vs spent). BOOST_FOREACH(const CTxIn txin, tx.vin) { if (!pcoinsTip->HaveCoinsInCache(txin.prevout.hash)) vHashTxnToUncache.push_back(txin.prevout.hash); if (!view.HaveCoins(txin.prevout.hash)) { if (pfMissingInputs) *pfMissingInputs = true; return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid() } } // are the actual inputs available? if (!view.HaveInputs(tx)) return state.Invalid(false, REJECT_DUPLICATE, "bad-txns-inputs-spent"); // Bring the best block into scope view.GetBestBlock(); nValueIn = view.GetValueIn(tx); // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool view.SetBackend(dummy); // Only accept BIP68 sequence locked transactions that can be mined in the next // block; we don't want our mempool filled up with transactions that can't // be mined yet. // Must keep pool.cs for this unless we change CheckSequenceLocks to take a // CoinsViewCache instead of create its own if (!CheckSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp)) return state.DoS(0, false, REJECT_NONSTANDARD, "non-BIP68-final"); } // Check for non-standard pay-to-script-hash in inputs if (fRequireStandard && !AreInputsStandard(tx, view)) return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs"); unsigned int nSigOps = GetLegacySigOpCount(tx); nSigOps += GetP2SHSigOpCount(tx, view); CAmount nValueOut = tx.GetValueOut(); CAmount nFees = nValueIn-nValueOut; // nModifiedFees includes any fee deltas from PrioritiseTransaction CAmount nModifiedFees = nFees; double nPriorityDummy = 0; pool.ApplyDeltas(hash, nPriorityDummy, nModifiedFees); CAmount inChainInputValue; double dPriority = view.GetPriority(tx, chainActive.Height(), inChainInputValue); // Keep track of transactions that spend a coinbase, which we re-scan // during reorgs to ensure COINBASE_MATURITY is still met. bool fSpendsCoinbase = false; BOOST_FOREACH(const CTxIn &txin, tx.vin) { const CCoins *coins = view.AccessCoins(txin.prevout.hash); if (coins->IsCoinBase()) { fSpendsCoinbase = true; break; } } CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height(), pool.HasNoInputsOf(tx), inChainInputValue, fSpendsCoinbase, nSigOps, lp); unsigned int nSize = entry.GetTxSize(); // Check that the transaction doesn't have an excessive number of // sigops, making it impossible to mine. Since the coinbase transaction // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than // merely non-standard transaction. if ((nSigOps > MAX_STANDARD_TX_SIGOPS) || (nBytesPerSigOp && nSigOps > nSize / nBytesPerSigOp)) return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false, strprintf("%d", nSigOps)); CAmount mempoolRejectFee = pool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize); if (mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) { return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nFees, mempoolRejectFee)); } else if (GetBoolArg("-relaypriority", DEFAULT_RELAYPRIORITY) && nModifiedFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(entry.GetPriority(chainActive.Height() + 1))) { // Require that free transactions have sufficient priority to be mined in the next block. return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority"); } // Continuously rate-limit free (really, very-low-fee) transactions // This mitigates 'penny-flooding' -- sending thousands of free transactions just to // be annoying or make others' transactions take longer to confirm. if (fLimitFree && nModifiedFees < ::minRelayTxFee.GetFee(nSize)) { static CCriticalSection csFreeLimiter; static double dFreeCount; static int64_t nLastTime; int64_t nNow = GetTime(); LOCK(csFreeLimiter); // Use an exponentially decaying ~10-minute window: dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime)); nLastTime = nNow; // -limitfreerelay unit is thousand-bytes-per-minute // At default rate it would take over a month to fill 1GB if (dFreeCount >= GetArg("-limitfreerelay", DEFAULT_LIMITFREERELAY) * 10 * 1000) return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "rate limited free transaction"); LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize); dFreeCount += nSize; } if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000) return state.Invalid(false, REJECT_HIGHFEE, "absurdly-high-fee", strprintf("%d > %d", nFees, ::minRelayTxFee.GetFee(nSize) * 10000)); // Calculate in-mempool ancestors, up to a limit. CTxMemPool::setEntries setAncestors; size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT); size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000; size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT); size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000; std::string errString; if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) { return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", false, errString); } // A transaction that spends outputs that would be replaced by it is invalid. Now // that we have the set of all ancestors we can detect this // pathological case by making sure setConflicts and setAncestors don't // intersect. BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors) { const uint256 &hashAncestor = ancestorIt->GetTx().GetHash(); if (setConflicts.count(hashAncestor)) { return state.DoS(10, error("AcceptToMemoryPool: %s spends conflicting transaction %s", hash.ToString(), hashAncestor.ToString()), REJECT_INVALID, "bad-txns-spends-conflicting-tx"); } } // Check if it's economically rational to mine this transaction rather // than the ones it replaces. CAmount nConflictingFees = 0; size_t nConflictingSize = 0; uint64_t nConflictingCount = 0; CTxMemPool::setEntries allConflicting; // If we don't hold the lock allConflicting might be incomplete; the // subsequent RemoveStaged() and addUnchecked() calls don't guarantee // mempool consistency for us. LOCK(pool.cs); if (setConflicts.size()) { CFeeRate newFeeRate(nModifiedFees, nSize); set<uint256> setConflictsParents; const int maxDescendantsToVisit = 100; CTxMemPool::setEntries setIterConflicting; BOOST_FOREACH(const uint256 &hashConflicting, setConflicts) { CTxMemPool::txiter mi = pool.mapTx.find(hashConflicting); if (mi == pool.mapTx.end()) continue; // Save these to avoid repeated lookups setIterConflicting.insert(mi); // If this entry is "dirty", then we don't have descendant // state for this transaction, which means we probably have // lots of in-mempool descendants. // Don't allow replacements of dirty transactions, to ensure // that we don't spend too much time walking descendants. // This should be rare. if (mi->IsDirty()) { return state.DoS(0, error("AcceptToMemoryPool: rejecting replacement %s; cannot replace tx %s with untracked descendants", hash.ToString(), mi->GetTx().GetHash().ToString()), REJECT_NONSTANDARD, "too many potential replacements"); } // Don't allow the replacement to reduce the feerate of the // mempool. // // We usually don't want to accept replacements with lower // feerates than what they replaced as that would lower the // feerate of the next block. Requiring that the feerate always // be increased is also an easy-to-reason about way to prevent // DoS attacks via replacements. // // The mining code doesn't (currently) take children into // account (CPFP) so we only consider the feerates of // transactions being directly replaced, not their indirect // descendants. While that does mean high feerate children are // ignored when deciding whether or not to replace, we do // require the replacement to pay more overall fees too, // mitigating most cases. CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize()); if (newFeeRate <= oldFeeRate) { return state.DoS(0, error("AcceptToMemoryPool: rejecting replacement %s; new feerate %s <= old feerate %s", hash.ToString(), newFeeRate.ToString(), oldFeeRate.ToString()), REJECT_INSUFFICIENTFEE, "insufficient fee"); } BOOST_FOREACH(const CTxIn &txin, mi->GetTx().vin) { setConflictsParents.insert(txin.prevout.hash); } nConflictingCount += mi->GetCountWithDescendants(); } // This potentially overestimates the number of actual descendants // but we just want to be conservative to avoid doing too much // work. if (nConflictingCount <= maxDescendantsToVisit) { // If not too many to replace, then calculate the set of // transactions that would have to be evicted BOOST_FOREACH(CTxMemPool::txiter it, setIterConflicting) { pool.CalculateDescendants(it, allConflicting); } BOOST_FOREACH(CTxMemPool::txiter it, allConflicting) { nConflictingFees += it->GetModifiedFee(); nConflictingSize += it->GetTxSize(); } } else { return state.DoS(0, error("AcceptToMemoryPool: rejecting replacement %s; too many potential replacements (%d > %d)\n", hash.ToString(), nConflictingCount, maxDescendantsToVisit), REJECT_NONSTANDARD, "too many potential replacements"); } for (unsigned int j = 0; j < tx.vin.size(); j++) { // We don't want to accept replacements that require low // feerate junk to be mined first. Ideally we'd keep track of // the ancestor feerates and make the decision based on that, // but for now requiring all new inputs to be confirmed works. if (!setConflictsParents.count(tx.vin[j].prevout.hash)) { // Rather than check the UTXO set - potentially expensive - // it's cheaper to just check if the new input refers to a // tx that's in the mempool. if (pool.mapTx.find(tx.vin[j].prevout.hash) != pool.mapTx.end()) return state.DoS(0, error("AcceptToMemoryPool: replacement %s adds unconfirmed input, idx %d", hash.ToString(), j), REJECT_NONSTANDARD, "replacement-adds-unconfirmed"); } } // The replacement must pay greater fees than the transactions it // replaces - if we did the bandwidth used by those conflicting // transactions would not be paid for. if (nModifiedFees < nConflictingFees) { return state.DoS(0, error("AcceptToMemoryPool: rejecting replacement %s, less fees than conflicting txs; %s < %s", hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)), REJECT_INSUFFICIENTFEE, "insufficient fee"); } // Finally in addition to paying more fees than the conflicts the // new transaction must pay for its own bandwidth. CAmount nDeltaFees = nModifiedFees - nConflictingFees; if (nDeltaFees < ::minRelayTxFee.GetFee(nSize)) { return state.DoS(0, error("AcceptToMemoryPool: rejecting replacement %s, not enough additional fees to relay; %s < %s", hash.ToString(), FormatMoney(nDeltaFees), FormatMoney(::minRelayTxFee.GetFee(nSize))), REJECT_INSUFFICIENTFEE, "insufficient fee"); } } // If we aren't going to actually accept it but just were verifying it, we are fine already if(fDryRun) return true; // Check against previous transactions // This is done last to help prevent CPU exhaustion denial-of-service attacks. if (!CheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true)) return false; // Check again against just the consensus-critical mandatory script // verification flags, in case of bugs in the standard flags that cause // transactions to pass as valid when they're actually invalid. For // instance the STRICTENC flag was incorrectly allowing certain // CHECKSIG NOT scripts to pass, even though they were invalid. // // There is a similar check in CreateNewBlock() to prevent creating // invalid blocks, however allowing such transactions into the mempool // can be exploited as a DoS attack. if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true)) { return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s, %s", __func__, hash.ToString(), FormatStateMessage(state)); } // Remove conflicting transactions from the mempool BOOST_FOREACH(const CTxMemPool::txiter it, allConflicting) { LogPrint("mempool", "replacing tx %s with %s for %s BTC additional fees, %d delta bytes\n", it->GetTx().GetHash().ToString(), hash.ToString(), FormatMoney(nModifiedFees - nConflictingFees), (int)nSize - (int)nConflictingSize); } pool.RemoveStaged(allConflicting); // Store transaction in memory pool.addUnchecked(hash, entry, setAncestors, !IsInitialBlockDownload()); // Add memory address index if (fAddressIndex) { pool.addAddressIndex(entry, view); } // Add memory spent index if (fSpentIndex) { pool.addSpentIndex(entry, view); } // trim mempool and check if tx was trimmed if (!fOverrideMempoolLimit) { LimitMempoolSize(pool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60); if (!pool.exists(hash)) return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool full"); } } if(!fDryRun) SyncWithWallets(tx, NULL); return true; } bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree, bool* pfMissingInputs, bool fOverrideMempoolLimit, bool fRejectAbsurdFee, bool fDryRun) { std::vector<uint256> vHashTxToUncache; bool res = AcceptToMemoryPoolWorker(pool, state, tx, fLimitFree, pfMissingInputs, fOverrideMempoolLimit, fRejectAbsurdFee, vHashTxToUncache, fDryRun); if (!res || fDryRun) { if(!res) LogPrint("mempool", "%s: %s %s\n", __func__, tx.GetHash().ToString(), state.GetRejectReason()); BOOST_FOREACH(const uint256& hashTx, vHashTxToUncache) pcoinsTip->Uncache(hashTx); } return res; } bool GetTimestampIndex(const unsigned int &high, const unsigned int &low, std::vector<uint256> &hashes) { if (!fTimestampIndex) return error("Timestamp index not enabled"); if (!pblocktree->ReadTimestampIndex(high, low, hashes)) return error("Unable to get hashes for timestamps"); return true; } bool GetSpentIndex(CSpentIndexKey &key, CSpentIndexValue &value) { if (!fSpentIndex) return false; if (mempool.getSpentIndex(key, value)) return true; if (!pblocktree->ReadSpentIndex(key, value)) return false; return true; } bool GetAddressIndex(uint160 addressHash, int type, std::vector<std::pair<CAddressIndexKey, CAmount> > &addressIndex, int start, int end) { if (!fAddressIndex) return error("address index not enabled"); if (!pblocktree->ReadAddressIndex(addressHash, type, addressIndex, start, end)) return error("unable to get txids for address"); return true; } bool GetAddressUnspent(uint160 addressHash, int type, std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > &unspentOutputs) { if (!fAddressIndex) return error("address index not enabled"); if (!pblocktree->ReadAddressUnspentIndex(addressHash, type, unspentOutputs)) return error("unable to get txids for address"); return true; } /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */ bool GetTransaction(const uint256 &hash, CTransaction &txOut, const Consensus::Params& consensusParams, uint256 &hashBlock, bool fAllowSlow) { CBlockIndex *pindexSlow = NULL; LOCK(cs_main); if (mempool.lookup(hash, txOut)) { return true; } if (fTxIndex) { CDiskTxPos postx; if (pblocktree->ReadTxIndex(hash, postx)) { CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION); if (file.IsNull()) return error("%s: OpenBlockFile failed", __func__); CBlockHeader header; try { file >> header; fseek(file.Get(), postx.nTxOffset, SEEK_CUR); file >> txOut; } catch (const std::exception& e) { return error("%s: Deserialize or I/O error - %s", __func__, e.what()); } hashBlock = header.GetHash(); if (txOut.GetHash() != hash) return error("%s: txid mismatch", __func__); return true; } } if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it int nHeight = -1; { CCoinsViewCache &view = *pcoinsTip; const CCoins* coins = view.AccessCoins(hash); if (coins) nHeight = coins->nHeight; } if (nHeight > 0) pindexSlow = chainActive[nHeight]; } if (pindexSlow) { CBlock block; if (ReadBlockFromDisk(block, pindexSlow, consensusParams)) { BOOST_FOREACH(const CTransaction &tx, block.vtx) { if (tx.GetHash() == hash) { txOut = tx; hashBlock = pindexSlow->GetBlockHash(); return true; } } } } return false; } ////////////////////////////////////////////////////////////////////////////// // // CBlock and CBlockIndex // bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart) { // Open history file to append CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION); if (fileout.IsNull()) return error("WriteBlockToDisk: OpenBlockFile failed"); // Write index header unsigned int nSize = fileout.GetSerializeSize(block); fileout << FLATDATA(messageStart) << nSize; // Write block long fileOutPos = ftell(fileout.Get()); if (fileOutPos < 0) return error("WriteBlockToDisk: ftell failed"); pos.nPos = (unsigned int)fileOutPos; fileout << block; return true; } bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams) { block.SetNull(); // Open history file to read CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION); if (filein.IsNull()) return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString()); // Read block try { filein >> block; } catch (const std::exception& e) { return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString()); } // Check the header if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams)) return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString()); return true; } bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams) { if (!ReadBlockFromDisk(block, pindex->GetBlockPos(), consensusParams)) return false; if (block.GetHash() != pindex->GetBlockHash()) return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s", pindex->ToString(), pindex->GetBlockPos().ToString()); return true; } double ConvertBitsToDouble(unsigned int nBits) { int nShift = (nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } /* NOTE: unlike bitcoin we are using PREVIOUS block height here, might be a good idea to change this to use prev bits but current height to avoid confusion. */ CAmount GetBlockSubsidy(int nPrevBits, int nPrevHeight, const Consensus::Params& consensusParams, bool fSuperblockPartOnly) { double dDiff; CAmount nSubsidyBase; if (nPrevHeight <= 4500 && Params().NetworkIDString() == CBaseChainParams::MAIN) { /* a bug which caused diff to not be correctly calculated */ dDiff = (double)0x0000ffff / (double)(nPrevBits & 0x00ffffff); } else { dDiff = ConvertBitsToDouble(nPrevBits); } if (nPrevHeight < 5465) { // Early ages... // 1111/((x+1)^2) nSubsidyBase = (1111.0 / (pow((dDiff+1.0),2.0))); if(nSubsidyBase > 500) nSubsidyBase = 500; else if(nSubsidyBase < 1) nSubsidyBase = 1; } else if (nPrevHeight < 17000 || (dDiff <= 75 && nPrevHeight < 24000)) { // CPU mining era // 11111/(((x+51)/6)^2) nSubsidyBase = (11111.0 / (pow((dDiff+51.0)/6.0,2.0))); if(nSubsidyBase > 500) nSubsidyBase = 500; else if(nSubsidyBase < 25) nSubsidyBase = 25; } else { // GPU/ASIC mining era // 2222222/(((x+2600)/9)^2) nSubsidyBase = (2222222.0 / (pow((dDiff+2600.0)/9.0,2.0))); if(nSubsidyBase > 25) nSubsidyBase = 25; else if(nSubsidyBase < 5) nSubsidyBase = 5; } // LogPrintf("height %u diff %4.2f reward %d\n", nPrevHeight, dDiff, nSubsidyBase); CAmount nSubsidy = nSubsidyBase * COIN; // yearly decline of production by ~7.1% per year, projected ~18M coins max by year 2050+. for (int i = consensusParams.nSubsidyHalvingInterval; i <= nPrevHeight; i += consensusParams.nSubsidyHalvingInterval) { nSubsidy -= nSubsidy/14; } // Hard fork to reduce the block reward by 10 extra percent (allowing budget/superblocks) CAmount nSuperblockPart = (nPrevHeight > consensusParams.nBudgetPaymentsStartBlock) ? nSubsidy/10 : 0; return fSuperblockPartOnly ? nSuperblockPart : nSubsidy - nSuperblockPart; } CAmount GetMasternodePayment(int nHeight, CAmount blockValue) { CAmount ret = blockValue/5; // start at 20% int nMNPIBlock = Params().GetConsensus().nMasternodePaymentsIncreaseBlock; int nMNPIPeriod = Params().GetConsensus().nMasternodePaymentsIncreasePeriod; // mainnet: if(nHeight > nMNPIBlock) ret += blockValue / 20; // 158000 - 25.0% - 2014-10-24 if(nHeight > nMNPIBlock+(nMNPIPeriod* 1)) ret += blockValue / 20; // 175280 - 30.0% - 2014-11-25 if(nHeight > nMNPIBlock+(nMNPIPeriod* 2)) ret += blockValue / 20; // 192560 - 35.0% - 2014-12-26 if(nHeight > nMNPIBlock+(nMNPIPeriod* 3)) ret += blockValue / 40; // 209840 - 37.5% - 2015-01-26 if(nHeight > nMNPIBlock+(nMNPIPeriod* 4)) ret += blockValue / 40; // 227120 - 40.0% - 2015-02-27 if(nHeight > nMNPIBlock+(nMNPIPeriod* 5)) ret += blockValue / 40; // 244400 - 42.5% - 2015-03-30 if(nHeight > nMNPIBlock+(nMNPIPeriod* 6)) ret += blockValue / 40; // 261680 - 45.0% - 2015-05-01 if(nHeight > nMNPIBlock+(nMNPIPeriod* 7)) ret += blockValue / 40; // 278960 - 47.5% - 2015-06-01 if(nHeight > nMNPIBlock+(nMNPIPeriod* 9)) ret += blockValue / 40; // 313520 - 50.0% - 2015-08-03 return ret; } bool IsInitialBlockDownload() { static bool lockIBDState = false; if (lockIBDState) return false; if (fImporting || fReindex) return true; LOCK(cs_main); const CChainParams& chainParams = Params(); if (fCheckpointsEnabled && chainActive.Height() < Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints())) return true; bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 || std::max(chainActive.Tip()->GetBlockTime(), pindexBestHeader->GetBlockTime()) < GetTime() - chainParams.MaxTipAge()); if (!state) lockIBDState = true; return state; } bool fLargeWorkForkFound = false; bool fLargeWorkInvalidChainFound = false; CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL; void CheckForkWarningConditions() { AssertLockHeld(cs_main); // Before we get past initial download, we cannot reliably alert about forks // (we assume we don't get stuck on a fork before the last checkpoint) if (IsInitialBlockDownload()) return; // If our best fork is no longer within 72 blocks (+/- 3 hours if no one mines it) // of our head, drop it if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72) pindexBestForkTip = NULL; if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6))) { if (!fLargeWorkForkFound && pindexBestForkBase) { if(pindexBestForkBase->phashBlock){ std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") + pindexBestForkBase->phashBlock->ToString() + std::string("'"); CAlert::Notify(warning, true); } } if (pindexBestForkTip && pindexBestForkBase) { if(pindexBestForkBase->phashBlock){ LogPrintf("%s: Warning: Large valid fork found\n forking the chain at height %d (%s)\n lasting to height %d (%s).\nChain state database corruption likely.\n", __func__, pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(), pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString()); fLargeWorkForkFound = true; } } else { if(pindexBestInvalid->nHeight > chainActive.Height() + 6) LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__); else LogPrintf("%s: Warning: Found invalid chain which has higher work (at least ~6 blocks worth of work) than our best chain.\nChain state database corruption likely.\n", __func__); fLargeWorkInvalidChainFound = true; } } else { fLargeWorkForkFound = false; fLargeWorkInvalidChainFound = false; } } void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip) { AssertLockHeld(cs_main); // If we are on a fork that is sufficiently large, set a warning flag CBlockIndex* pfork = pindexNewForkTip; CBlockIndex* plonger = chainActive.Tip(); while (pfork && pfork != plonger) { while (plonger && plonger->nHeight > pfork->nHeight) plonger = plonger->pprev; if (pfork == plonger) break; pfork = pfork->pprev; } // We define a condition where we should warn the user about as a fork of at least 7 blocks // with a tip within 72 blocks (+/- 3 hours if no one mines it) of ours // or a chain that is entirely longer than ours and invalid (note that this should be detected by both) // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network // hash rate operating on the fork. // We define it this way because it allows us to only store the highest fork tip (+ base) which meets // the 7-block condition and from this always have the most-likely-to-cause-warning fork if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) && pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) && chainActive.Height() - pindexNewForkTip->nHeight < 72) { pindexBestForkTip = pindexNewForkTip; pindexBestForkBase = pfork; } CheckForkWarningConditions(); } // Requires cs_main. void Misbehaving(NodeId pnode, int howmuch) { if (howmuch == 0) return; CNodeState *state = State(pnode); if (state == NULL) return; state->nMisbehavior += howmuch; int banscore = GetArg("-banscore", DEFAULT_BANSCORE_THRESHOLD); if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore) { LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior); state->fShouldBan = true; } else LogPrintf("%s: %s (%d -> %d)\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior); } void static InvalidChainFound(CBlockIndex* pindexNew) { if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork) pindexBestInvalid = pindexNew; LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__, pindexNew->GetBlockHash().ToString(), pindexNew->nHeight, log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexNew->GetBlockTime())); CBlockIndex *tip = chainActive.Tip(); assert (tip); LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__, tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime())); CheckForkWarningConditions(); } void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) { int nDoS = 0; if (state.IsInvalid(nDoS)) { std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash()); if (it != mapBlockSource.end() && State(it->second)) { assert (state.GetRejectCode() < REJECT_INTERNAL); // Blocks are never rejected with internal reject codes CBlockReject reject = {(unsigned char)state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()}; State(it->second)->rejects.push_back(reject); if (nDoS > 0) Misbehaving(it->second, nDoS); } } if (!state.CorruptionPossible()) { pindex->nStatus |= BLOCK_FAILED_VALID; setDirtyBlockIndex.insert(pindex); setBlockIndexCandidates.erase(pindex); InvalidChainFound(pindex); } } void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight) { // mark inputs spent if (!tx.IsCoinBase()) { txundo.vprevout.reserve(tx.vin.size()); BOOST_FOREACH(const CTxIn &txin, tx.vin) { CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash); unsigned nPos = txin.prevout.n; if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull()) assert(false); // mark an outpoint spent, and construct undo information txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos])); coins->Spend(nPos); if (coins->vout.size() == 0) { CTxInUndo& undo = txundo.vprevout.back(); undo.nHeight = coins->nHeight; undo.fCoinBase = coins->fCoinBase; undo.nVersion = coins->nVersion; } } // add outputs inputs.ModifyNewCoins(tx.GetHash())->FromTx(tx, nHeight); } else { // add outputs for coinbase tx // In this case call the full ModifyCoins which will do a database // lookup to be sure the coins do not already exist otherwise we do not // know whether to mark them fresh or not. We want the duplicate coinbases // before BIP30 to still be properly overwritten. inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight); } } void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight) { CTxUndo txundo; UpdateCoins(tx, state, inputs, txundo, nHeight); } bool CScriptCheck::operator()() { const CScript &scriptSig = ptxTo->vin[nIn].scriptSig; if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) { return false; } return true; } int GetSpendHeight(const CCoinsViewCache& inputs) { LOCK(cs_main); CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second; return pindexPrev->nHeight + 1; } namespace Consensus { bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight) { // This doesn't trigger the DoS code on purpose; if it did, it would make it easier // for an attacker to attempt to split the network. if (!inputs.HaveInputs(tx)) return state.Invalid(false, 0, "", "Inputs unavailable"); CAmount nValueIn = 0; CAmount nFees = 0; for (unsigned int i = 0; i < tx.vin.size(); i++) { const COutPoint &prevout = tx.vin[i].prevout; const CCoins *coins = inputs.AccessCoins(prevout.hash); assert(coins); // If prev is coinbase, check that it's matured if (coins->IsCoinBase()) { if (nSpendHeight - coins->nHeight < COINBASE_MATURITY) return state.Invalid(false, REJECT_INVALID, "bad-txns-premature-spend-of-coinbase", strprintf("tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight)); } // Check for negative or overflow input values nValueIn += coins->vout[prevout.n].nValue; if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn)) return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputvalues-outofrange"); } if (nValueIn < tx.GetValueOut()) return state.DoS(100, false, REJECT_INVALID, "bad-txns-in-belowout", false, strprintf("value in (%s) < value out (%s)", FormatMoney(nValueIn), FormatMoney(tx.GetValueOut()))); // Tally transaction fees CAmount nTxFee = nValueIn - tx.GetValueOut(); if (nTxFee < 0) return state.DoS(100, false, REJECT_INVALID, "bad-txns-fee-negative"); nFees += nTxFee; if (!MoneyRange(nFees)) return state.DoS(100, false, REJECT_INVALID, "bad-txns-fee-outofrange"); return true; } }// namespace Consensus bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, std::vector<CScriptCheck> *pvChecks) { if (!tx.IsCoinBase()) { if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs))) return false; if (pvChecks) pvChecks->reserve(tx.vin.size()); // The first loop above does all the inexpensive checks. // Only if ALL inputs pass do we perform expensive ECDSA signature checks. // Helps prevent CPU exhaustion attacks. // Skip ECDSA signature verification when connecting blocks // before the last block chain checkpoint. This is safe because block merkle hashes are // still computed and checked, and any change will be caught at the next checkpoint. if (fScriptChecks) { for (unsigned int i = 0; i < tx.vin.size(); i++) { const COutPoint &prevout = tx.vin[i].prevout; const CCoins* coins = inputs.AccessCoins(prevout.hash); assert(coins); // Verify signature CScriptCheck check(*coins, tx, i, flags, cacheStore); if (pvChecks) { pvChecks->push_back(CScriptCheck()); check.swap(pvChecks->back()); } else if (!check()) { if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) { // Check whether the failure was caused by a // non-mandatory script verification check, such as // non-standard DER encodings or non-null dummy // arguments; if so, don't trigger DoS protection to // avoid splitting the network between upgraded and // non-upgraded nodes. CScriptCheck check2(*coins, tx, i, flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore); if (check2()) return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError()))); } // Failures of other flags indicate a transaction that is // invalid in new blocks, e.g. a invalid P2SH. We DoS ban // such nodes as they are not following the protocol. That // said during an upgrade careful thought should be taken // as to the correct behavior - we may want to continue // peering with non-upgraded nodes even after a soft-fork // super-majority vote has passed. return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError()))); } } } } return true; } namespace { bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart) { // Open history file to append CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION); if (fileout.IsNull()) return error("%s: OpenUndoFile failed", __func__); // Write index header unsigned int nSize = fileout.GetSerializeSize(blockundo); fileout << FLATDATA(messageStart) << nSize; // Write undo data long fileOutPos = ftell(fileout.Get()); if (fileOutPos < 0) return error("%s: ftell failed", __func__); pos.nPos = (unsigned int)fileOutPos; fileout << blockundo; // calculate & write checksum CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION); hasher << hashBlock; hasher << blockundo; fileout << hasher.GetHash(); return true; } bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock) { // Open history file to read CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION); if (filein.IsNull()) return error("%s: OpenBlockFile failed", __func__); // Read block uint256 hashChecksum; try { filein >> blockundo; filein >> hashChecksum; } catch (const std::exception& e) { return error("%s: Deserialize or I/O error - %s", __func__, e.what()); } // Verify checksum CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION); hasher << hashBlock; hasher << blockundo; if (hashChecksum != hasher.GetHash()) return error("%s: Checksum mismatch", __func__); return true; } /** Abort with a message */ bool AbortNode(const std::string& strMessage, const std::string& userMessage="") { strMiscWarning = strMessage; LogPrintf("*** %s\n", strMessage); uiInterface.ThreadSafeMessageBox( userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage, "", CClientUIInterface::MSG_ERROR); StartShutdown(); return false; } bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="") { AbortNode(strMessage, userMessage); return state.Error(strMessage); } } // anon namespace /** * Apply the undo operation of a CTxInUndo to the given chain state. * @param undo The undo object. * @param view The coins view to which to apply the changes. * @param out The out point that corresponds to the tx input. * @return True on success. */ static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out) { bool fClean = true; CCoinsModifier coins = view.ModifyCoins(out.hash); if (undo.nHeight != 0) { // undo data contains height: this is the last output of the prevout tx being spent if (!coins->IsPruned()) fClean = fClean && error("%s: undo data overwriting existing transaction", __func__); coins->Clear(); coins->fCoinBase = undo.fCoinBase; coins->nHeight = undo.nHeight; coins->nVersion = undo.nVersion; } else { if (coins->IsPruned()) fClean = fClean && error("%s: undo data adding output to missing transaction", __func__); } if (coins->IsAvailable(out.n)) fClean = fClean && error("%s: undo data overwriting existing output", __func__); if (coins->vout.size() < out.n+1) coins->vout.resize(out.n+1); coins->vout[out.n] = undo.txout; return fClean; } bool DisconnectBlock(const CBlock& block, CValidationState& state, const CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean) { assert(pindex->GetBlockHash() == view.GetBestBlock()); if (pfClean) *pfClean = false; bool fClean = true; CBlockUndo blockUndo; CDiskBlockPos pos = pindex->GetUndoPos(); if (pos.IsNull()) return error("DisconnectBlock(): no undo data available"); if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash())) return error("DisconnectBlock(): failure reading undo data"); if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) return error("DisconnectBlock(): block and undo data inconsistent"); std::vector<std::pair<CAddressIndexKey, CAmount> > addressIndex; std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > addressUnspentIndex; std::vector<std::pair<CSpentIndexKey, CSpentIndexValue> > spentIndex; // undo transactions in reverse order for (int i = block.vtx.size() - 1; i >= 0; i--) { const CTransaction &tx = block.vtx[i]; uint256 hash = tx.GetHash(); if (fAddressIndex) { for (unsigned int k = tx.vout.size(); k-- > 0;) { const CTxOut &out = tx.vout[k]; if (out.scriptPubKey.IsPayToScriptHash()) { vector<unsigned char> hashBytes(out.scriptPubKey.begin()+2, out.scriptPubKey.begin()+22); // undo receiving activity addressIndex.push_back(make_pair(CAddressIndexKey(2, uint160(hashBytes), pindex->nHeight, i, hash, k, false), out.nValue)); // undo unspent index addressUnspentIndex.push_back(make_pair(CAddressUnspentKey(2, uint160(hashBytes), hash, k), CAddressUnspentValue())); } else if (out.scriptPubKey.IsPayToPublicKeyHash()) { vector<unsigned char> hashBytes(out.scriptPubKey.begin()+3, out.scriptPubKey.begin()+23); // undo receiving activity addressIndex.push_back(make_pair(CAddressIndexKey(1, uint160(hashBytes), pindex->nHeight, i, hash, k, false), out.nValue)); // undo unspent index addressUnspentIndex.push_back(make_pair(CAddressUnspentKey(1, uint160(hashBytes), hash, k), CAddressUnspentValue())); } else { continue; } } } // Check that all outputs are available and match the outputs in the block itself // exactly. { CCoinsModifier outs = view.ModifyCoins(hash); outs->ClearUnspendable(); CCoins outsBlock(tx, pindex->nHeight); // The CCoins serialization does not serialize negative numbers. // No network rules currently depend on the version here, so an inconsistency is harmless // but it must be corrected before txout nversion ever influences a network rule. if (outsBlock.nVersion < 0) outs->nVersion = outsBlock.nVersion; if (*outs != outsBlock) fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted"); // remove outputs outs->Clear(); } // restore inputs if (i > 0) { // not coinbases const CTxUndo &txundo = blockUndo.vtxundo[i-1]; if (txundo.vprevout.size() != tx.vin.size()) return error("DisconnectBlock(): transaction and undo data inconsistent"); for (unsigned int j = tx.vin.size(); j-- > 0;) { const COutPoint &out = tx.vin[j].prevout; const CTxInUndo &undo = txundo.vprevout[j]; if (!ApplyTxInUndo(undo, view, out)) fClean = false; const CTxIn input = tx.vin[j]; if (fSpentIndex) { // undo and delete the spent index spentIndex.push_back(make_pair(CSpentIndexKey(input.prevout.hash, input.prevout.n), CSpentIndexValue())); } if (fAddressIndex) { const CTxOut &prevout = view.GetOutputFor(tx.vin[j]); if (prevout.scriptPubKey.IsPayToScriptHash()) { vector<unsigned char> hashBytes(prevout.scriptPubKey.begin()+2, prevout.scriptPubKey.begin()+22); // undo spending activity addressIndex.push_back(make_pair(CAddressIndexKey(2, uint160(hashBytes), pindex->nHeight, i, hash, j, true), prevout.nValue * -1)); // restore unspent index addressUnspentIndex.push_back(make_pair(CAddressUnspentKey(2, uint160(hashBytes), input.prevout.hash, input.prevout.n), CAddressUnspentValue(prevout.nValue, prevout.scriptPubKey, undo.nHeight))); } else if (prevout.scriptPubKey.IsPayToPublicKeyHash()) { vector<unsigned char> hashBytes(prevout.scriptPubKey.begin()+3, prevout.scriptPubKey.begin()+23); // undo spending activity addressIndex.push_back(make_pair(CAddressIndexKey(1, uint160(hashBytes), pindex->nHeight, i, hash, j, true), prevout.nValue * -1)); // restore unspent index addressUnspentIndex.push_back(make_pair(CAddressUnspentKey(1, uint160(hashBytes), input.prevout.hash, input.prevout.n), CAddressUnspentValue(prevout.nValue, prevout.scriptPubKey, undo.nHeight))); } else { continue; } } } } } // move best block pointer to prevout block view.SetBestBlock(pindex->pprev->GetBlockHash()); if (pfClean) { *pfClean = fClean; return true; } if (fAddressIndex) { if (!pblocktree->EraseAddressIndex(addressIndex)) { return AbortNode(state, "Failed to delete address index"); } if (!pblocktree->UpdateAddressUnspentIndex(addressUnspentIndex)) { return AbortNode(state, "Failed to write address unspent index"); } } return fClean; } void static FlushBlockFile(bool fFinalize = false) { LOCK(cs_LastBlockFile); CDiskBlockPos posOld(nLastBlockFile, 0); FILE *fileOld = OpenBlockFile(posOld); if (fileOld) { if (fFinalize) TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize); FileCommit(fileOld); fclose(fileOld); } fileOld = OpenUndoFile(posOld); if (fileOld) { if (fFinalize) TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize); FileCommit(fileOld); fclose(fileOld); } } bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize); static CCheckQueue<CScriptCheck> scriptcheckqueue(128); void ThreadScriptCheck() { RenameThread("sprint-scriptch"); scriptcheckqueue.Thread(); } // // Called periodically asynchronously; alerts if it smells like // we're being fed a bad chain (blocks being generated much // too slowly or too quickly). // void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader, int64_t nPowTargetSpacing) { if (bestHeader == NULL || initialDownloadCheck()) return; static int64_t lastAlertTime = 0; int64_t now = GetAdjustedTime(); if (lastAlertTime > now-60*60*24) return; // Alert at most once per day const int SPAN_HOURS=1; // was 4h in bitcoin but we have 4x faster blocks const int SPAN_SECONDS=SPAN_HOURS*60*60; int BLOCKS_EXPECTED = SPAN_SECONDS / nPowTargetSpacing; boost::math::poisson_distribution<double> poisson(BLOCKS_EXPECTED); std::string strWarning; int64_t startTime = GetAdjustedTime()-SPAN_SECONDS; LOCK(cs); const CBlockIndex* i = bestHeader; int nBlocks = 0; while (i->GetBlockTime() >= startTime) { ++nBlocks; i = i->pprev; if (i == NULL) return; // Ran out of chain, we must not be fully sync'ed } // How likely is it to find that many by chance? double p = boost::math::pdf(poisson, nBlocks); LogPrint("partitioncheck", "%s: Found %d blocks in the last %d hours\n", __func__, nBlocks, SPAN_HOURS); LogPrint("partitioncheck", "%s: likelihood: %g\n", __func__, p); // Aim for one false-positive about every fifty years of normal running: const int FIFTY_YEARS = 50*365*24*60*60; double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS); if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED) { // Many fewer blocks than expected: alert! strWarning = strprintf(_("WARNING: check your network connection, %d blocks received in the last %d hours (%d expected)"), nBlocks, SPAN_HOURS, BLOCKS_EXPECTED); } else if (p <= alertThreshold && nBlocks > BLOCKS_EXPECTED) { // Many more blocks than expected: alert! strWarning = strprintf(_("WARNING: abnormally high number of blocks generated, %d blocks received in the last %d hours (%d expected)"), nBlocks, SPAN_HOURS, BLOCKS_EXPECTED); } if (!strWarning.empty()) { strMiscWarning = strWarning; CAlert::Notify(strWarning, true); lastAlertTime = now; } } // Protected by cs_main static VersionBitsCache versionbitscache; int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params) { LOCK(cs_main); int32_t nVersion = VERSIONBITS_TOP_BITS; for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) { ThresholdState state = VersionBitsState(pindexPrev, params, (Consensus::DeploymentPos)i, versionbitscache); if (state == THRESHOLD_LOCKED_IN || state == THRESHOLD_STARTED) { nVersion |= VersionBitsMask(params, (Consensus::DeploymentPos)i); } } return nVersion; } bool GetBlockHash(uint256& hashRet, int nBlockHeight) { LOCK(cs_main); if(chainActive.Tip() == NULL) return false; if(nBlockHeight < -1 || nBlockHeight > chainActive.Height()) return false; if(nBlockHeight == -1) nBlockHeight = chainActive.Height(); hashRet = chainActive[nBlockHeight]->GetBlockHash(); return true; } /** * Threshold condition checker that triggers when unknown versionbits are seen on the network. */ class WarningBitsConditionChecker : public AbstractThresholdConditionChecker { private: int bit; public: WarningBitsConditionChecker(int bitIn) : bit(bitIn) {} int64_t BeginTime(const Consensus::Params& params) const { return 0; } int64_t EndTime(const Consensus::Params& params) const { return std::numeric_limits<int64_t>::max(); } int Period(const Consensus::Params& params) const { return params.nMinerConfirmationWindow; } int Threshold(const Consensus::Params& params) const { return params.nRuleChangeActivationThreshold; } bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const { return ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) && ((pindex->nVersion >> bit) & 1) != 0 && ((ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0; } }; // Protected by cs_main static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS]; static int64_t nTimeCheck = 0; static int64_t nTimeForks = 0; static int64_t nTimeVerify = 0; static int64_t nTimeConnect = 0; static int64_t nTimeIndex = 0; static int64_t nTimeCallbacks = 0; static int64_t nTimeTotal = 0; bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck) { const CChainParams& chainparams = Params(); AssertLockHeld(cs_main); int64_t nTimeStart = GetTimeMicros(); // Check it again in case a previous version let a bad block in if (!CheckBlock(block, state, !fJustCheck, !fJustCheck)) return false; // verify that the view's current state corresponds to the previous block uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash(); assert(hashPrevBlock == view.GetBestBlock()); // Special case for the genesis block, skipping connection of its transactions // (its coinbase is unspendable) if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) { if (!fJustCheck) view.SetBestBlock(pindex->GetBlockHash()); return true; } bool fScriptChecks = true; if (fCheckpointsEnabled) { CBlockIndex *pindexLastCheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints()); if (pindexLastCheckpoint && pindexLastCheckpoint->GetAncestor(pindex->nHeight) == pindex) { // This block is an ancestor of a checkpoint: disable script checks fScriptChecks = false; } } int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart; LogPrint("bench", " - Sanity checks: %.2fms [%.2fs]\n", 0.001 * (nTime1 - nTimeStart), nTimeCheck * 0.000001); // Do not allow blocks that contain transactions which 'overwrite' older transactions, // unless those are already completely spent. // If such overwrites are allowed, coinbases and transactions depending upon those // can be duplicated to remove the ability to spend the first instance -- even after // being sent to another address. // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information. // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool // already refuses previously-known transaction ids entirely. // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC. // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the // two in the chain that violate it. This prevents exploiting the issue against nodes during their // initial block download. bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash. !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) || (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721"))); // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further // duplicate transactions descending from the known pairs either. // If we're on the known chain at height greater than where BIP34 activated, we can save the db accesses needed for the BIP30 check. CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height); //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond. fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash)); if (fEnforceBIP30) { BOOST_FOREACH(const CTransaction& tx, block.vtx) { const CCoins* coins = view.AccessCoins(tx.GetHash()); if (coins && !coins->IsPruned()) return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"), REJECT_INVALID, "bad-txns-BIP30"); } } // BIP16 didn't become active until Apr 1 2012 int64_t nBIP16SwitchTime = 1333238400; bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime); unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE; // Start enforcing the DERSIG (BIP66) rules, for block.nVersion=3 blocks, // when 75% of the network has upgraded: if (block.nVersion >= 3 && IsSuperMajority(3, pindex->pprev, chainparams.GetConsensus().nMajorityEnforceBlockUpgrade, chainparams.GetConsensus())) { flags |= SCRIPT_VERIFY_DERSIG; } // Start enforcing CHECKLOCKTIMEVERIFY, (BIP65) for block.nVersion=4 // blocks, when 75% of the network has upgraded: if (block.nVersion >= 4 && IsSuperMajority(4, pindex->pprev, chainparams.GetConsensus().nMajorityEnforceBlockUpgrade, chainparams.GetConsensus())) { flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY; } // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic. int nLockTimeFlags = 0; if (VersionBitsState(pindex->pprev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) { flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY; nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE; } int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1; LogPrint("bench", " - Fork checks: %.2fms [%.2fs]\n", 0.001 * (nTime2 - nTime1), nTimeForks * 0.000001); CBlockUndo blockundo; CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL); std::vector<int> prevheights; CAmount nFees = 0; int nInputs = 0; unsigned int nSigOps = 0; CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size())); std::vector<std::pair<uint256, CDiskTxPos> > vPos; vPos.reserve(block.vtx.size()); blockundo.vtxundo.reserve(block.vtx.size() - 1); std::vector<std::pair<CAddressIndexKey, CAmount> > addressIndex; std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > addressUnspentIndex; std::vector<std::pair<CSpentIndexKey, CSpentIndexValue> > spentIndex; for (unsigned int i = 0; i < block.vtx.size(); i++) { const CTransaction &tx = block.vtx[i]; const uint256 txhash = tx.GetHash(); nInputs += tx.vin.size(); nSigOps += GetLegacySigOpCount(tx); if (nSigOps > MAX_BLOCK_SIGOPS) return state.DoS(100, error("ConnectBlock(): too many sigops"), REJECT_INVALID, "bad-blk-sigops"); if (!tx.IsCoinBase()) { if (!view.HaveInputs(tx)) return state.DoS(100, error("ConnectBlock(): inputs missing/spent"), REJECT_INVALID, "bad-txns-inputs-missingorspent"); // Check that transaction is BIP68 final // BIP68 lock checks (as opposed to nLockTime checks) must // be in ConnectBlock because they require the UTXO set prevheights.resize(tx.vin.size()); for (size_t j = 0; j < tx.vin.size(); j++) { prevheights[j] = view.AccessCoins(tx.vin[j].prevout.hash)->nHeight; } if (!SequenceLocks(tx, nLockTimeFlags, &prevheights, *pindex)) { return state.DoS(100, error("%s: contains a non-BIP68-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal"); } if (fAddressIndex || fSpentIndex) { for (size_t j = 0; j < tx.vin.size(); j++) { const CTxIn input = tx.vin[j]; const CTxOut &prevout = view.GetOutputFor(tx.vin[j]); uint160 hashBytes; int addressType; if (prevout.scriptPubKey.IsPayToScriptHash()) { hashBytes = uint160(vector <unsigned char>(prevout.scriptPubKey.begin()+2, prevout.scriptPubKey.begin()+22)); addressType = 2; } else if (prevout.scriptPubKey.IsPayToPublicKeyHash()) { hashBytes = uint160(vector <unsigned char>(prevout.scriptPubKey.begin()+3, prevout.scriptPubKey.begin()+23)); addressType = 1; } else { hashBytes.SetNull(); addressType = 0; } if (fAddressIndex && addressType > 0) { // record spending activity addressIndex.push_back(make_pair(CAddressIndexKey(addressType, hashBytes, pindex->nHeight, i, txhash, j, true), prevout.nValue * -1)); // remove address from unspent index addressUnspentIndex.push_back(make_pair(CAddressUnspentKey(addressType, hashBytes, input.prevout.hash, input.prevout.n), CAddressUnspentValue())); } if (fSpentIndex) { // add the spent index to determine the txid and input that spent an output // and to find the amount and address from an input spentIndex.push_back(make_pair(CSpentIndexKey(input.prevout.hash, input.prevout.n), CSpentIndexValue(txhash, j, pindex->nHeight, prevout.nValue, addressType, hashBytes))); } } } if (fStrictPayToScriptHash) { // Add in sigops done by pay-to-script-hash inputs; // this is to prevent a "rogue miner" from creating // an incredibly-expensive-to-validate block. nSigOps += GetP2SHSigOpCount(tx, view); if (nSigOps > MAX_BLOCK_SIGOPS) return state.DoS(100, error("ConnectBlock(): too many sigops"), REJECT_INVALID, "bad-blk-sigops"); } nFees += view.GetValueIn(tx)-tx.GetValueOut(); std::vector<CScriptCheck> vChecks; bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */ if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, nScriptCheckThreads ? &vChecks : NULL)) return error("ConnectBlock(): CheckInputs on %s failed with %s", tx.GetHash().ToString(), FormatStateMessage(state)); control.Add(vChecks); } if (fAddressIndex) { for (unsigned int k = 0; k < tx.vout.size(); k++) { const CTxOut &out = tx.vout[k]; if (out.scriptPubKey.IsPayToScriptHash()) { vector<unsigned char> hashBytes(out.scriptPubKey.begin()+2, out.scriptPubKey.begin()+22); // record receiving activity addressIndex.push_back(make_pair(CAddressIndexKey(2, uint160(hashBytes), pindex->nHeight, i, txhash, k, false), out.nValue)); // record unspent output addressUnspentIndex.push_back(make_pair(CAddressUnspentKey(2, uint160(hashBytes), txhash, k), CAddressUnspentValue(out.nValue, out.scriptPubKey, pindex->nHeight))); } else if (out.scriptPubKey.IsPayToPublicKeyHash()) { vector<unsigned char> hashBytes(out.scriptPubKey.begin()+3, out.scriptPubKey.begin()+23); // record receiving activity addressIndex.push_back(make_pair(CAddressIndexKey(1, uint160(hashBytes), pindex->nHeight, i, txhash, k, false), out.nValue)); // record unspent output addressUnspentIndex.push_back(make_pair(CAddressUnspentKey(1, uint160(hashBytes), txhash, k), CAddressUnspentValue(out.nValue, out.scriptPubKey, pindex->nHeight))); } else { continue; } } } CTxUndo undoDummy; if (i > 0) { blockundo.vtxundo.push_back(CTxUndo()); } UpdateCoins(tx, state, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight); vPos.push_back(std::make_pair(tx.GetHash(), pos)); pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION); } int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2; LogPrint("bench", " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block.vtx.size(), 0.001 * (nTime3 - nTime2), 0.001 * (nTime3 - nTime2) / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime3 - nTime2) / (nInputs-1), nTimeConnect * 0.000001); // SPRINT : MODIFIED TO CHECK MASTERNODE PAYMENTS AND SUPERBLOCKS // It's possible that we simply don't have enough data and this could fail // (i.e. block itself could be a correct one and we need to store it), // that's why this is in ConnectBlock. Could be the other way around however - // the peer who sent us this block is missing some data and wasn't able // to recognize that block is actually invalid. // TODO: resync data (both ways?) and try to reprocess this block later. CAmount blockReward = nFees + GetBlockSubsidy(pindex->pprev->nBits, pindex->pprev->nHeight, chainparams.GetConsensus()); std::string strError = ""; if (!IsBlockValueValid(block, pindex->nHeight, blockReward, strError)) { return state.DoS(0, error("ConnectBlock(SPRINT): %s", strError), REJECT_INVALID, "bad-cb-amount"); } if (!IsBlockPayeeValid(block.vtx[0], pindex->nHeight, blockReward)) { mapRejectedBlocks.insert(make_pair(block.GetHash(), GetTime())); return state.DoS(0, error("ConnectBlock(SPRINT): couldn't find masternode or superblock payments"), REJECT_INVALID, "bad-cb-payee"); } // END SPRINT if (!control.Wait()) return state.DoS(100, false); int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2; LogPrint("bench", " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs - 1, 0.001 * (nTime4 - nTime2), nInputs <= 1 ? 0 : 0.001 * (nTime4 - nTime2) / (nInputs-1), nTimeVerify * 0.000001); if (fJustCheck) return true; // Write undo information to disk if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS)) { if (pindex->GetUndoPos().IsNull()) { CDiskBlockPos pos; if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40)) return error("ConnectBlock(): FindUndoPos failed"); if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart())) return AbortNode(state, "Failed to write undo data"); // update nUndoPos in block index pindex->nUndoPos = pos.nPos; pindex->nStatus |= BLOCK_HAVE_UNDO; } pindex->RaiseValidity(BLOCK_VALID_SCRIPTS); setDirtyBlockIndex.insert(pindex); } if (fTxIndex) if (!pblocktree->WriteTxIndex(vPos)) return AbortNode(state, "Failed to write transaction index"); if (fAddressIndex) { if (!pblocktree->WriteAddressIndex(addressIndex)) { return AbortNode(state, "Failed to write address index"); } if (!pblocktree->UpdateAddressUnspentIndex(addressUnspentIndex)) { return AbortNode(state, "Failed to write address unspent index"); } } if (fSpentIndex) if (!pblocktree->UpdateSpentIndex(spentIndex)) return AbortNode(state, "Failed to write transaction index"); if (fTimestampIndex) if (!pblocktree->WriteTimestampIndex(CTimestampIndexKey(pindex->nTime, pindex->GetBlockHash()))) return AbortNode(state, "Failed to write timestamp index"); // add this block to the view's block chain view.SetBestBlock(pindex->GetBlockHash()); int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4; LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime5 - nTime4), nTimeIndex * 0.000001); // Watch for changes to the previous coinbase transaction. static uint256 hashPrevBestCoinBase; GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase); hashPrevBestCoinBase = block.vtx[0].GetHash(); int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5; LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime6 - nTime5), nTimeCallbacks * 0.000001); return true; } enum FlushStateMode { FLUSH_STATE_NONE, FLUSH_STATE_IF_NEEDED, FLUSH_STATE_PERIODIC, FLUSH_STATE_ALWAYS }; /** * Update the on-disk chain state. * The caches and indexes are flushed depending on the mode we're called with * if they're too large, if it's been a while since the last write, * or always and in all cases if we're in prune mode and are deleting files. */ bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) { const CChainParams& chainparams = Params(); LOCK2(cs_main, cs_LastBlockFile); static int64_t nLastWrite = 0; static int64_t nLastFlush = 0; static int64_t nLastSetChain = 0; std::set<int> setFilesToPrune; bool fFlushForPrune = false; try { if (fPruneMode && fCheckForPruning && !fReindex) { FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight()); fCheckForPruning = false; if (!setFilesToPrune.empty()) { fFlushForPrune = true; if (!fHavePruned) { pblocktree->WriteFlag("prunedblockfiles", true); fHavePruned = true; } } } int64_t nNow = GetTimeMicros(); // Avoid writing/flushing immediately after startup. if (nLastWrite == 0) { nLastWrite = nNow; } if (nLastFlush == 0) { nLastFlush = nNow; } if (nLastSetChain == 0) { nLastSetChain = nNow; } size_t cacheSize = pcoinsTip->DynamicMemoryUsage(); // The cache is large and close to the limit, but we have time now (not in the middle of a block processing). bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage; // The cache is over the limit, we have to write now. bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage; // It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash. bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000; // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage. bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000; // Combine all conditions that result in a full cache flush. bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune; // Write blocks and block index to disk. if (fDoFullFlush || fPeriodicWrite) { // Depend on nMinDiskSpace to ensure we can write block index if (!CheckDiskSpace(0)) return state.Error("out of disk space"); // First make sure all block and undo data is flushed to disk. FlushBlockFile(); // Then update all block file information (which may refer to block and undo files). { std::vector<std::pair<int, const CBlockFileInfo*> > vFiles; vFiles.reserve(setDirtyFileInfo.size()); for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) { vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it])); setDirtyFileInfo.erase(it++); } std::vector<const CBlockIndex*> vBlocks; vBlocks.reserve(setDirtyBlockIndex.size()); for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) { vBlocks.push_back(*it); setDirtyBlockIndex.erase(it++); } if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) { return AbortNode(state, "Files to write to block index database"); } } // Finally remove any pruned files if (fFlushForPrune) UnlinkPrunedFiles(setFilesToPrune); nLastWrite = nNow; } // Flush best chain related state. This can only be done if the blocks / block index write was also done. if (fDoFullFlush) { // Typical CCoins structures on disk are around 128 bytes in size. // Pushing a new one to the database can cause it to be written // twice (once in the log, and once in the tables). This is already // an overestimation, as most will delete an existing entry or // overwrite one. Still, use a conservative safety factor of 2. if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize())) return state.Error("out of disk space"); // Flush the chainstate (which may refer to block index entries). if (!pcoinsTip->Flush()) return AbortNode(state, "Failed to write to coin database"); nLastFlush = nNow; } if (fDoFullFlush || ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) { // Update best block in wallet (so we can detect restored wallets). GetMainSignals().SetBestChain(chainActive.GetLocator()); nLastSetChain = nNow; } } catch (const std::runtime_error& e) { return AbortNode(state, std::string("System error while flushing: ") + e.what()); } return true; } void FlushStateToDisk() { CValidationState state; FlushStateToDisk(state, FLUSH_STATE_ALWAYS); } void PruneAndFlush() { CValidationState state; fCheckForPruning = true; FlushStateToDisk(state, FLUSH_STATE_NONE); } /** Update chainActive and related internal data structures. */ void static UpdateTip(CBlockIndex *pindexNew) { const CChainParams& chainParams = Params(); chainActive.SetTip(pindexNew); // New best block nTimeBestReceived = GetTime(); mempool.AddTransactionsUpdated(1); LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__, chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx, DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()), Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize()); cvBlockChange.notify_all(); // Check the version of the last 100 blocks to see if we need to upgrade: static bool fWarned = false; if (!IsInitialBlockDownload()) { int nUpgraded = 0; const CBlockIndex* pindex = chainActive.Tip(); for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) { WarningBitsConditionChecker checker(bit); ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]); if (state == THRESHOLD_ACTIVE || state == THRESHOLD_LOCKED_IN) { if (state == THRESHOLD_ACTIVE) { strMiscWarning = strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit); if (!fWarned) { CAlert::Notify(strMiscWarning, true); fWarned = true; } } else { LogPrintf("%s: unknown new rules are about to activate (versionbit %i)\n", __func__, bit); } } } for (int i = 0; i < 100 && pindex != NULL; i++) { int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus()); if (pindex->nVersion > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0) ++nUpgraded; pindex = pindex->pprev; } if (nUpgraded > 0) LogPrintf("%s: %d of last 100 blocks have unexpected version\n", __func__, nUpgraded); if (nUpgraded > 100/2) { // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user: strMiscWarning = _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect"); if (!fWarned) { CAlert::Notify(strMiscWarning, true); fWarned = true; } } } } /** Disconnect chainActive's tip. You probably want to call mempool.removeForReorg and manually re-limit mempool size after this, with cs_main held. */ bool static DisconnectTip(CValidationState& state, const Consensus::Params& consensusParams) { CBlockIndex *pindexDelete = chainActive.Tip(); assert(pindexDelete); // Read block from disk. CBlock block; if (!ReadBlockFromDisk(block, pindexDelete, consensusParams)) return AbortNode(state, "Failed to read block"); // Apply the block atomically to the chain state. int64_t nStart = GetTimeMicros(); { CCoinsViewCache view(pcoinsTip); if (!DisconnectBlock(block, state, pindexDelete, view)) return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString()); assert(view.Flush()); } LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001); // Write the chain state to disk, if necessary. if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED)) return false; // Resurrect mempool transactions from the disconnected block. std::vector<uint256> vHashUpdate; BOOST_FOREACH(const CTransaction &tx, block.vtx) { // ignore validation errors in resurrected transactions list<CTransaction> removed; CValidationState stateDummy; if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL, true)) { mempool.remove(tx, removed, true); } else if (mempool.exists(tx.GetHash())) { vHashUpdate.push_back(tx.GetHash()); } } // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have // no in-mempool children, which is generally not true when adding // previously-confirmed transactions back to the mempool. // UpdateTransactionsFromBlock finds descendants of any transactions in this // block that were added back and cleans up the mempool state. mempool.UpdateTransactionsFromBlock(vHashUpdate); // Update chainActive and related variables. UpdateTip(pindexDelete->pprev); // Let wallets know transactions went from 1-confirmed to // 0-confirmed or conflicted: BOOST_FOREACH(const CTransaction &tx, block.vtx) { SyncWithWallets(tx, NULL); } return true; } static int64_t nTimeReadFromDisk = 0; static int64_t nTimeConnectTotal = 0; static int64_t nTimeFlush = 0; static int64_t nTimeChainState = 0; static int64_t nTimePostConnect = 0; /** * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock * corresponding to pindexNew, to bypass loading it again from disk. */ bool static ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const CBlock* pblock) { assert(pindexNew->pprev == chainActive.Tip()); // Read block from disk. int64_t nTime1 = GetTimeMicros(); CBlock block; if (!pblock) { if (!ReadBlockFromDisk(block, pindexNew, chainparams.GetConsensus())) return AbortNode(state, "Failed to read block"); pblock = &block; } // Apply the block atomically to the chain state. int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1; int64_t nTime3; LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001); { CCoinsViewCache view(pcoinsTip); bool rv = ConnectBlock(*pblock, state, pindexNew, view); GetMainSignals().BlockChecked(*pblock, state); if (!rv) { if (state.IsInvalid()) InvalidBlockFound(pindexNew, state); return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString()); } mapBlockSource.erase(pindexNew->GetBlockHash()); nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2; LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001); assert(view.Flush()); } int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3; LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001); // Write the chain state to disk, if necessary. if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED)) return false; int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4; LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001); // Remove conflicting transactions from the mempool. list<CTransaction> txConflicted; mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload()); // Update chainActive & related variables. UpdateTip(pindexNew); // Tell wallet about transactions that went from mempool // to conflicted: BOOST_FOREACH(const CTransaction &tx, txConflicted) { SyncWithWallets(tx, NULL); } // ... and about transactions that got confirmed: BOOST_FOREACH(const CTransaction &tx, pblock->vtx) { SyncWithWallets(tx, pblock); } int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1; LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001); LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001); return true; } bool DisconnectBlocks(int blocks) { LOCK(cs_main); CValidationState state; const CChainParams& chainparams = Params(); LogPrintf("DisconnectBlocks -- Got command to replay %d blocks\n", blocks); for(int i = 0; i < blocks; i++) { if(!DisconnectTip(state, chainparams.GetConsensus()) || !state.IsValid()) { return false; } } return true; } void ReprocessBlocks(int nBlocks) { LOCK(cs_main); std::map<uint256, int64_t>::iterator it = mapRejectedBlocks.begin(); while(it != mapRejectedBlocks.end()){ //use a window twice as large as is usual for the nBlocks we want to reset if((*it).second > GetTime() - (nBlocks*60*5)) { BlockMap::iterator mi = mapBlockIndex.find((*it).first); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; LogPrintf("ReprocessBlocks -- %s\n", (*it).first.ToString()); CValidationState state; ReconsiderBlock(state, pindex); } } ++it; } DisconnectBlocks(nBlocks); CValidationState state; ActivateBestChain(state, Params()); } /** * Return the tip of the chain with the most work in it, that isn't * known to be invalid (it's however far from certain to be valid). */ static CBlockIndex* FindMostWorkChain() { do { CBlockIndex *pindexNew = NULL; // Find the best candidate header. { std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin(); if (it == setBlockIndexCandidates.rend()) return NULL; pindexNew = *it; } // Check whether all blocks on the path between the currently active chain and the candidate are valid. // Just going until the active chain is an optimization, as we know all blocks in it are valid already. CBlockIndex *pindexTest = pindexNew; bool fInvalidAncestor = false; while (pindexTest && !chainActive.Contains(pindexTest)) { assert(pindexTest->nChainTx || pindexTest->nHeight == 0); // Pruned nodes may have entries in setBlockIndexCandidates for // which block files have been deleted. Remove those as candidates // for the most work chain if we come across them; we can't switch // to a chain unless we have all the non-active-chain parent blocks. bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK; bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA); if (fFailedChain || fMissingData) { // Candidate chain is not usable (either invalid or missing data) if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork)) pindexBestInvalid = pindexNew; CBlockIndex *pindexFailed = pindexNew; // Remove the entire chain from the set. while (pindexTest != pindexFailed) { if (fFailedChain) { pindexFailed->nStatus |= BLOCK_FAILED_CHILD; } else if (fMissingData) { // If we're missing data, then add back to mapBlocksUnlinked, // so that if the block arrives in the future we can try adding // to setBlockIndexCandidates again. mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed)); } setBlockIndexCandidates.erase(pindexFailed); pindexFailed = pindexFailed->pprev; } setBlockIndexCandidates.erase(pindexTest); fInvalidAncestor = true; break; } pindexTest = pindexTest->pprev; } if (!fInvalidAncestor) return pindexNew; } while(true); } /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */ static void PruneBlockIndexCandidates() { // Note that we can't delete the current block itself, as we may need to return to it later in case a // reorganization to a better block fails. std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin(); while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) { setBlockIndexCandidates.erase(it++); } // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates. assert(!setBlockIndexCandidates.empty()); } /** * Try to make some progress towards making pindexMostWork the active block. * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork. */ static bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const CBlock* pblock) { AssertLockHeld(cs_main); bool fInvalidFound = false; const CBlockIndex *pindexOldTip = chainActive.Tip(); const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork); // Disconnect active blocks which are no longer in the best chain. bool fBlocksDisconnected = false; while (chainActive.Tip() && chainActive.Tip() != pindexFork) { if (!DisconnectTip(state, chainparams.GetConsensus())) return false; fBlocksDisconnected = true; } // Build list of new blocks to connect. std::vector<CBlockIndex*> vpindexToConnect; bool fContinue = true; int nHeight = pindexFork ? pindexFork->nHeight : -1; while (fContinue && nHeight != pindexMostWork->nHeight) { // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need // a few blocks along the way. int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight); vpindexToConnect.clear(); vpindexToConnect.reserve(nTargetHeight - nHeight); CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight); while (pindexIter && pindexIter->nHeight != nHeight) { vpindexToConnect.push_back(pindexIter); pindexIter = pindexIter->pprev; } nHeight = nTargetHeight; // Connect new blocks. BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) { if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) { if (state.IsInvalid()) { // The block violates a consensus rule. if (!state.CorruptionPossible()) InvalidChainFound(vpindexToConnect.back()); state = CValidationState(); fInvalidFound = true; fContinue = false; break; } else { // A system error occurred (disk space, database error, ...). return false; } } else { PruneBlockIndexCandidates(); if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) { // We're in a better position than we were. Return temporarily to release the lock. fContinue = false; break; } } } } if (fBlocksDisconnected) { mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS); LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60); } mempool.check(pcoinsTip); // Callbacks/notifications for a new best chain. if (fInvalidFound) CheckForkWarningConditionsOnNewFork(vpindexToConnect.back()); else CheckForkWarningConditions(); return true; } /** * Make the best chain active, in multiple steps. The result is either failure * or an activated best chain. pblock is either NULL or a pointer to a block * that is already loaded (to avoid loading it again from disk). */ bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, const CBlock *pblock) { CBlockIndex *pindexMostWork = NULL; do { boost::this_thread::interruption_point(); if (ShutdownRequested()) break; CBlockIndex *pindexNewTip = NULL; const CBlockIndex *pindexFork; bool fInitialDownload; { LOCK(cs_main); CBlockIndex *pindexOldTip = chainActive.Tip(); pindexMostWork = FindMostWorkChain(); // Whether we have anything to do at all. if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip()) return true; if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL)) return false; pindexNewTip = chainActive.Tip(); pindexFork = chainActive.FindFork(pindexOldTip); fInitialDownload = IsInitialBlockDownload(); } // When we reach this point, we switched to a new tip (stored in pindexNewTip). // Notifications/callbacks that can run without cs_main // Always notify the UI if a new block tip was connected if (pindexFork != pindexNewTip) { uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip); if (!fInitialDownload) { // Find the hashes of all blocks that weren't previously in the best chain. std::vector<uint256> vHashes; CBlockIndex *pindexToAnnounce = pindexNewTip; while (pindexToAnnounce != pindexFork) { vHashes.push_back(pindexToAnnounce->GetBlockHash()); pindexToAnnounce = pindexToAnnounce->pprev; if (vHashes.size() == MAX_BLOCKS_TO_ANNOUNCE) { // Limit announcements in case of a huge reorganization. // Rely on the peer's synchronization mechanism in that case. break; } } // Relay inventory, but don't relay old inventory during initial block download. int nBlockEstimate = 0; if (fCheckpointsEnabled) nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints()); { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate)) { BOOST_REVERSE_FOREACH(const uint256& hash, vHashes) { pnode->PushBlockHash(hash); } } } } // Notify external listeners about the new tip. if (!vHashes.empty()) { GetMainSignals().UpdatedBlockTip(pindexNewTip); } } } } while(pindexMostWork != chainActive.Tip()); CheckBlockIndex(chainparams.GetConsensus()); // Write changes periodically to disk, after relay. if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) { return false; } return true; } bool InvalidateBlock(CValidationState& state, const Consensus::Params& consensusParams, CBlockIndex *pindex) { AssertLockHeld(cs_main); // Mark the block itself as invalid. pindex->nStatus |= BLOCK_FAILED_VALID; setDirtyBlockIndex.insert(pindex); setBlockIndexCandidates.erase(pindex); while (chainActive.Contains(pindex)) { CBlockIndex *pindexWalk = chainActive.Tip(); pindexWalk->nStatus |= BLOCK_FAILED_CHILD; setDirtyBlockIndex.insert(pindexWalk); setBlockIndexCandidates.erase(pindexWalk); // ActivateBestChain considers blocks already in chainActive // unconditionally valid already, so force disconnect away from it. if (!DisconnectTip(state, consensusParams)) { mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS); return false; } } LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60); // The resulting new best tip may not be in setBlockIndexCandidates anymore, so // add it again. BlockMap::iterator it = mapBlockIndex.begin(); while (it != mapBlockIndex.end()) { if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) { setBlockIndexCandidates.insert(it->second); } it++; } InvalidChainFound(pindex); mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS); return true; } bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) { AssertLockHeld(cs_main); int nHeight = pindex->nHeight; // Remove the invalidity flag from this block and all its descendants. BlockMap::iterator it = mapBlockIndex.begin(); while (it != mapBlockIndex.end()) { if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) { it->second->nStatus &= ~BLOCK_FAILED_MASK; setDirtyBlockIndex.insert(it->second); if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) { setBlockIndexCandidates.insert(it->second); } if (it->second == pindexBestInvalid) { // Reset invalid block marker if it was pointing to one of those. pindexBestInvalid = NULL; } } it++; } // Remove the invalidity flag from all ancestors too. while (pindex != NULL) { if (pindex->nStatus & BLOCK_FAILED_MASK) { pindex->nStatus &= ~BLOCK_FAILED_MASK; setDirtyBlockIndex.insert(pindex); } pindex = pindex->pprev; } return true; } CBlockIndex* AddToBlockIndex(const CBlockHeader& block) { // Check for duplicate uint256 hash = block.GetHash(); BlockMap::iterator it = mapBlockIndex.find(hash); if (it != mapBlockIndex.end()) return it->second; // Construct new block index object CBlockIndex* pindexNew = new CBlockIndex(block); assert(pindexNew); // We assign the sequence id to blocks only when the full data is available, // to avoid miners withholding blocks but broadcasting headers, to get a // competitive advantage. pindexNew->nSequenceId = 0; BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first; pindexNew->phashBlock = &((*mi).first); BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock); if (miPrev != mapBlockIndex.end()) { pindexNew->pprev = (*miPrev).second; pindexNew->nHeight = pindexNew->pprev->nHeight + 1; pindexNew->BuildSkip(); } pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew); pindexNew->RaiseValidity(BLOCK_VALID_TREE); if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork) pindexBestHeader = pindexNew; setDirtyBlockIndex.insert(pindexNew); return pindexNew; } /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */ bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos) { pindexNew->nTx = block.vtx.size(); pindexNew->nChainTx = 0; pindexNew->nFile = pos.nFile; pindexNew->nDataPos = pos.nPos; pindexNew->nUndoPos = 0; pindexNew->nStatus |= BLOCK_HAVE_DATA; pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS); setDirtyBlockIndex.insert(pindexNew); if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) { // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS. deque<CBlockIndex*> queue; queue.push_back(pindexNew); // Recursively process any descendant blocks that now may be eligible to be connected. while (!queue.empty()) { CBlockIndex *pindex = queue.front(); queue.pop_front(); pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx; { LOCK(cs_nBlockSequenceId); pindex->nSequenceId = nBlockSequenceId++; } if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) { setBlockIndexCandidates.insert(pindex); } std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex); while (range.first != range.second) { std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first; queue.push_back(it->second); range.first++; mapBlocksUnlinked.erase(it); } } } else { if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) { mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew)); } } return true; } bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false) { LOCK(cs_LastBlockFile); unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile; if (vinfoBlockFile.size() <= nFile) { vinfoBlockFile.resize(nFile + 1); } if (!fKnown) { while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) { nFile++; if (vinfoBlockFile.size() <= nFile) { vinfoBlockFile.resize(nFile + 1); } } pos.nFile = nFile; pos.nPos = vinfoBlockFile[nFile].nSize; } if ((int)nFile != nLastBlockFile) { if (!fKnown) { LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString()); } FlushBlockFile(!fKnown); nLastBlockFile = nFile; } vinfoBlockFile[nFile].AddBlock(nHeight, nTime); if (fKnown) vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize); else vinfoBlockFile[nFile].nSize += nAddSize; if (!fKnown) { unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE; unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE; if (nNewChunks > nOldChunks) { if (fPruneMode) fCheckForPruning = true; if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) { FILE *file = OpenBlockFile(pos); if (file) { LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile); AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos); fclose(file); } } else return state.Error("out of disk space"); } } setDirtyFileInfo.insert(nFile); return true; } bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize) { pos.nFile = nFile; LOCK(cs_LastBlockFile); unsigned int nNewSize; pos.nPos = vinfoBlockFile[nFile].nUndoSize; nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize; setDirtyFileInfo.insert(nFile); unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE; unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE; if (nNewChunks > nOldChunks) { if (fPruneMode) fCheckForPruning = true; if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) { FILE *file = OpenUndoFile(pos); if (file) { LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile); AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos); fclose(file); } } else return state.Error("out of disk space"); } return true; } bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW) { // Check proof of work matches claimed amount if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus())) return state.DoS(50, error("CheckBlockHeader(): proof of work failed"), REJECT_INVALID, "high-hash"); // Check timestamp if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60) return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"), REJECT_INVALID, "time-too-new"); return true; } bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot) { // These are checks that are independent of context. if (block.fChecked) return true; // Check that the header is valid (particularly PoW). This is mostly // redundant with the call in AcceptBlockHeader. if (!CheckBlockHeader(block, state, fCheckPOW)) return false; // Check the merkle root. if (fCheckMerkleRoot) { bool mutated; uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated); if (block.hashMerkleRoot != hashMerkleRoot2) return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"), REJECT_INVALID, "bad-txnmrklroot", true); // Check for merkle tree malleability (CVE-2012-2459): repeating sequences // of transactions in a block without affecting the merkle root of a block, // while still invalidating it. if (mutated) return state.DoS(100, error("CheckBlock(): duplicate transaction"), REJECT_INVALID, "bad-txns-duplicate", true); } // All potential-corruption validation must be done before we do any // transaction validation, as otherwise we may mark the header as invalid // because we receive the wrong transactions for it. // Size limits if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) return state.DoS(100, error("CheckBlock(): size limits failed"), REJECT_INVALID, "bad-blk-length"); // First transaction must be coinbase, the rest must not be if (block.vtx.empty() || !block.vtx[0].IsCoinBase()) return state.DoS(100, error("CheckBlock(): first tx is not coinbase"), REJECT_INVALID, "bad-cb-missing"); for (unsigned int i = 1; i < block.vtx.size(); i++) if (block.vtx[i].IsCoinBase()) return state.DoS(100, error("CheckBlock(): more than one coinbase"), REJECT_INVALID, "bad-cb-multiple"); // SPRINT : CHECK TRANSACTIONS FOR INSTANTSEND if(sporkManager.IsSporkActive(SPORK_3_INSTANTSEND_BLOCK_FILTERING)) { // We should never accept block which conflicts with completed transaction lock, // that's why this is in CheckBlock unlike coinbase payee/amount. // Require other nodes to comply, send them some data in case they are missing it. BOOST_FOREACH(const CTransaction& tx, block.vtx) { // skip coinbase, it has no inputs if (tx.IsCoinBase()) continue; // LOOK FOR TRANSACTION LOCK IN OUR MAP OF OUTPOINTS BOOST_FOREACH(const CTxIn& txin, tx.vin) { uint256 hashLocked; if(instantsend.GetLockedOutPointTxHash(txin.prevout, hashLocked) && hashLocked != tx.GetHash()) { // Every node which relayed this block to us must invalidate it // but they probably need more data. // Relay corresponding transaction lock request and all its votes // to let other nodes complete the lock. instantsend.Relay(hashLocked); LOCK(cs_main); mapRejectedBlocks.insert(make_pair(block.GetHash(), GetTime())); return state.DoS(0, error("CheckBlock(SPRINT): transaction %s conflicts with transaction lock %s", tx.GetHash().ToString(), hashLocked.ToString()), REJECT_INVALID, "conflict-tx-lock"); } } } } else { LogPrintf("CheckBlock(SPRINT): spork is off, skipping transaction locking checks\n"); } // END SPRINT // Check transactions BOOST_FOREACH(const CTransaction& tx, block.vtx) if (!CheckTransaction(tx, state)) return error("CheckBlock(): CheckTransaction of %s failed with %s", tx.GetHash().ToString(), FormatStateMessage(state)); unsigned int nSigOps = 0; BOOST_FOREACH(const CTransaction& tx, block.vtx) { nSigOps += GetLegacySigOpCount(tx); } if (nSigOps > MAX_BLOCK_SIGOPS) return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"), REJECT_INVALID, "bad-blk-sigops"); if (fCheckPOW && fCheckMerkleRoot) block.fChecked = true; return true; } static bool CheckIndexAgainstCheckpoint(const CBlockIndex* pindexPrev, CValidationState& state, const CChainParams& chainparams, const uint256& hash) { if (*pindexPrev->phashBlock == chainparams.GetConsensus().hashGenesisBlock) return true; int nHeight = pindexPrev->nHeight+1; // Don't accept any forks from the main chain prior to last checkpoint CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints()); if (pcheckpoint && nHeight < pcheckpoint->nHeight) return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight)); return true; } bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev) { const Consensus::Params& consensusParams = Params().GetConsensus(); int nHeight = pindexPrev->nHeight + 1; // Check proof of work if(Params().NetworkIDString() == CBaseChainParams::MAIN && nHeight <= 68589){ // architecture issues with DGW v1 and v2) unsigned int nBitsNext = GetNextWorkRequired(pindexPrev, &block, consensusParams); double n1 = ConvertBitsToDouble(block.nBits); double n2 = ConvertBitsToDouble(nBitsNext); if (abs(n1-n2) > n1*0.5) return state.DoS(100, error("%s : incorrect proof of work (DGW pre-fork) - %f %f %f at %d", __func__, abs(n1-n2), n1, n2, nHeight), REJECT_INVALID, "bad-diffbits"); } else { if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams)) return state.DoS(100, error("%s : incorrect proof of work at %d", __func__, nHeight), REJECT_INVALID, "bad-diffbits"); } // Check timestamp against prev if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast()) return state.Invalid(error("%s: block's timestamp is too early", __func__), REJECT_INVALID, "time-too-old"); // Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded: if (block.nVersion < 2 && IsSuperMajority(2, pindexPrev, consensusParams.nMajorityRejectBlockOutdated, consensusParams)) return state.Invalid(error("%s: rejected nVersion=1 block", __func__), REJECT_OBSOLETE, "bad-version"); // Reject block.nVersion=2 blocks when 95% (75% on testnet) of the network has upgraded: if (block.nVersion < 3 && IsSuperMajority(3, pindexPrev, consensusParams.nMajorityRejectBlockOutdated, consensusParams)) return state.Invalid(error("%s: rejected nVersion=2 block", __func__), REJECT_OBSOLETE, "bad-version"); // Reject block.nVersion=3 blocks when 95% (75% on testnet) of the network has upgraded: if (block.nVersion < 4 && IsSuperMajority(4, pindexPrev, consensusParams.nMajorityRejectBlockOutdated, consensusParams)) return state.Invalid(error("%s : rejected nVersion=3 block", __func__), REJECT_OBSOLETE, "bad-version"); return true; } bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev) { const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1; const Consensus::Params& consensusParams = Params().GetConsensus(); // Start enforcing BIP113 (Median Time Past) using versionbits logic. int nLockTimeFlags = 0; if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) { nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST; } int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST) ? pindexPrev->GetMedianTimePast() : block.GetBlockTime(); // Check that all transactions are finalized BOOST_FOREACH(const CTransaction& tx, block.vtx) { if (!IsFinalTx(tx, nHeight, nLockTimeCutoff)) { return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal"); } } // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet): if (block.nVersion >= 2 && IsSuperMajority(2, pindexPrev, consensusParams.nMajorityEnforceBlockUpgrade, consensusParams)) { CScript expect = CScript() << nHeight; if (block.vtx[0].vin[0].scriptSig.size() < expect.size() || !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) { return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height"); } } return true; } static bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex=NULL) { AssertLockHeld(cs_main); // Check for duplicate uint256 hash = block.GetHash(); BlockMap::iterator miSelf = mapBlockIndex.find(hash); CBlockIndex *pindex = NULL; // TODO : ENABLE BLOCK CACHE IN SPECIFIC CASES if (hash != chainparams.GetConsensus().hashGenesisBlock) { if (miSelf != mapBlockIndex.end()) { // Block header is already known. pindex = miSelf->second; if (ppindex) *ppindex = pindex; if (pindex->nStatus & BLOCK_FAILED_MASK) return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate"); return true; } if (!CheckBlockHeader(block, state)) return false; // Get prev block index CBlockIndex* pindexPrev = NULL; BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock); if (mi == mapBlockIndex.end()) return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk"); pindexPrev = (*mi).second; if (pindexPrev->nStatus & BLOCK_FAILED_MASK) return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk"); assert(pindexPrev); if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, hash)) return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str()); if (!ContextualCheckBlockHeader(block, state, pindexPrev)) return false; } if (pindex == NULL) pindex = AddToBlockIndex(block); if (ppindex) *ppindex = pindex; return true; } /** Store block on disk. If dbp is non-NULL, the file is known to already reside on disk */ static bool AcceptBlock(const CBlock& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, CDiskBlockPos* dbp) { AssertLockHeld(cs_main); CBlockIndex *&pindex = *ppindex; if (!AcceptBlockHeader(block, state, chainparams, &pindex)) return false; // Try to process all requested blocks that we don't have, but only // process an unrequested block if it's new and has enough work to // advance our tip, and isn't too many blocks ahead. bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA; bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true); // Blocks that are too out-of-order needlessly limit the effectiveness of // pruning, because pruning will not delete block files that contain any // blocks which are too close in height to the tip. Apply this test // regardless of whether pruning is enabled; it should generally be safe to // not process unrequested blocks. bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP)); // TODO: deal better with return value and error conditions for duplicate // and unrequested blocks. if (fAlreadyHave) return true; if (!fRequested) { // If we didn't ask for it: if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned if (!fHasMoreWork) return true; // Don't process less-work chains if (fTooFarAhead) return true; // Block height is too high } if ((!CheckBlock(block, state)) || !ContextualCheckBlock(block, state, pindex->pprev)) { if (state.IsInvalid() && !state.CorruptionPossible()) { pindex->nStatus |= BLOCK_FAILED_VALID; setDirtyBlockIndex.insert(pindex); } return false; } int nHeight = pindex->nHeight; // Write block to history file try { unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION); CDiskBlockPos blockPos; if (dbp != NULL) blockPos = *dbp; if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL)) return error("AcceptBlock(): FindBlockPos failed"); if (dbp == NULL) if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) AbortNode(state, "Failed to write block"); if (!ReceivedBlockTransactions(block, state, pindex, blockPos)) return error("AcceptBlock(): ReceivedBlockTransactions failed"); } catch (const std::runtime_error& e) { return AbortNode(state, std::string("System error: ") + e.what()); } if (fCheckForPruning) FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files return true; } static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams) { unsigned int nFound = 0; for (int i = 0; i < consensusParams.nMajorityWindow && nFound < nRequired && pstart != NULL; i++) { if (pstart->nVersion >= minVersion) ++nFound; pstart = pstart->pprev; } return (nFound >= nRequired); } bool ProcessNewBlock(CValidationState& state, const CChainParams& chainparams, const CNode* pfrom, const CBlock* pblock, bool fForceProcessing, CDiskBlockPos* dbp) { // Preliminary checks bool checked = CheckBlock(*pblock, state); { LOCK(cs_main); bool fRequested = MarkBlockAsReceived(pblock->GetHash()); fRequested |= fForceProcessing; if (!checked) { return error("%s: CheckBlock FAILED", __func__); } // Store to disk CBlockIndex *pindex = NULL; bool ret = AcceptBlock(*pblock, state, chainparams, &pindex, fRequested, dbp); if (pindex && pfrom) { mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId(); } CheckBlockIndex(chainparams.GetConsensus()); if (!ret) return error("%s: AcceptBlock FAILED", __func__); } if (!ActivateBestChain(state, chainparams, pblock)) return error("%s: ActivateBestChain failed", __func__); masternodeSync.IsBlockchainSynced(true); LogPrintf("%s : ACCEPTED\n", __func__); return true; } bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot) { AssertLockHeld(cs_main); assert(pindexPrev && pindexPrev == chainActive.Tip()); if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, block.GetHash())) return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str()); CCoinsViewCache viewNew(pcoinsTip); CBlockIndex indexDummy(block); indexDummy.pprev = pindexPrev; indexDummy.nHeight = pindexPrev->nHeight + 1; // NOTE: CheckBlockHeader is called by CheckBlock if (!ContextualCheckBlockHeader(block, state, pindexPrev)) return false; if (!CheckBlock(block, state, fCheckPOW, fCheckMerkleRoot)) return false; if (!ContextualCheckBlock(block, state, pindexPrev)) return false; if (!ConnectBlock(block, state, &indexDummy, viewNew, true)) return false; assert(state.IsValid()); return true; } /** * BLOCK PRUNING CODE */ /* Calculate the amount of disk space the block & undo files currently use */ uint64_t CalculateCurrentUsage() { uint64_t retval = 0; BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) { retval += file.nSize + file.nUndoSize; } return retval; } /* Prune a block file (modify associated database entries)*/ void PruneOneBlockFile(const int fileNumber) { for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) { CBlockIndex* pindex = it->second; if (pindex->nFile == fileNumber) { pindex->nStatus &= ~BLOCK_HAVE_DATA; pindex->nStatus &= ~BLOCK_HAVE_UNDO; pindex->nFile = 0; pindex->nDataPos = 0; pindex->nUndoPos = 0; setDirtyBlockIndex.insert(pindex); // Prune from mapBlocksUnlinked -- any block we prune would have // to be downloaded again in order to consider its chain, at which // point it would be considered as a candidate for // mapBlocksUnlinked or setBlockIndexCandidates. std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev); while (range.first != range.second) { std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first; range.first++; if (it->second == pindex) { mapBlocksUnlinked.erase(it); } } } } vinfoBlockFile[fileNumber].SetNull(); setDirtyFileInfo.insert(fileNumber); } void UnlinkPrunedFiles(std::set<int>& setFilesToPrune) { for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) { CDiskBlockPos pos(*it, 0); boost::filesystem::remove(GetBlockPosFilename(pos, "blk")); boost::filesystem::remove(GetBlockPosFilename(pos, "rev")); LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it); } } /* Calculate the block/rev files that should be deleted to remain under target*/ void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight) { LOCK2(cs_main, cs_LastBlockFile); if (chainActive.Tip() == NULL || nPruneTarget == 0) { return; } if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) { return; } unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP; uint64_t nCurrentUsage = CalculateCurrentUsage(); // We don't check to prune until after we've allocated new space for files // So we should leave a buffer under our target to account for another allocation // before the next pruning. uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE; uint64_t nBytesToPrune; int count=0; if (nCurrentUsage + nBuffer >= nPruneTarget) { for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) { nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize; if (vinfoBlockFile[fileNumber].nSize == 0) continue; if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target? break; // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune) continue; PruneOneBlockFile(fileNumber); // Queue up the files for removal setFilesToPrune.insert(fileNumber); nCurrentUsage -= nBytesToPrune; count++; } } LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n", nPruneTarget/1024/1024, nCurrentUsage/1024/1024, ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024, nLastBlockWeCanPrune, count); } bool CheckDiskSpace(uint64_t nAdditionalBytes) { uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available; // Check for nMinDiskSpace bytes (currently 50MB) if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes) return AbortNode("Disk space is low!", _("Error: Disk space is low!")); return true; } FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly) { if (pos.IsNull()) return NULL; boost::filesystem::path path = GetBlockPosFilename(pos, prefix); boost::filesystem::create_directories(path.parent_path()); FILE* file = fopen(path.string().c_str(), "rb+"); if (!file && !fReadOnly) file = fopen(path.string().c_str(), "wb+"); if (!file) { LogPrintf("Unable to open file %s\n", path.string()); return NULL; } if (pos.nPos) { if (fseek(file, pos.nPos, SEEK_SET)) { LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string()); fclose(file); return NULL; } } return file; } FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) { return OpenDiskFile(pos, "blk", fReadOnly); } FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) { return OpenDiskFile(pos, "rev", fReadOnly); } boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix) { return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile); } CBlockIndex * InsertBlockIndex(uint256 hash) { if (hash.IsNull()) return NULL; // Return existing BlockMap::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) return (*mi).second; // Create new CBlockIndex* pindexNew = new CBlockIndex(); if (!pindexNew) throw runtime_error("LoadBlockIndex(): new CBlockIndex failed"); mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first; pindexNew->phashBlock = &((*mi).first); return pindexNew; } bool static LoadBlockIndexDB() { const CChainParams& chainparams = Params(); if (!pblocktree->LoadBlockIndexGuts()) return false; boost::this_thread::interruption_point(); // Calculate nChainWork vector<pair<int, CBlockIndex*> > vSortedByHeight; vSortedByHeight.reserve(mapBlockIndex.size()); BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex) { CBlockIndex* pindex = item.second; vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex)); } sort(vSortedByHeight.begin(), vSortedByHeight.end()); BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight) { CBlockIndex* pindex = item.second; pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex); // We can link the chain of blocks for which we've received transactions at some point. // Pruned nodes may have deleted the block. if (pindex->nTx > 0) { if (pindex->pprev) { if (pindex->pprev->nChainTx) { pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx; } else { pindex->nChainTx = 0; mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex)); } } else { pindex->nChainTx = pindex->nTx; } } if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL)) setBlockIndexCandidates.insert(pindex); if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork)) pindexBestInvalid = pindex; if (pindex->pprev) pindex->BuildSkip(); if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex))) pindexBestHeader = pindex; } // Load block file info pblocktree->ReadLastBlockFile(nLastBlockFile); vinfoBlockFile.resize(nLastBlockFile + 1); LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile); for (int nFile = 0; nFile <= nLastBlockFile; nFile++) { pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]); } LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString()); for (int nFile = nLastBlockFile + 1; true; nFile++) { CBlockFileInfo info; if (pblocktree->ReadBlockFileInfo(nFile, info)) { vinfoBlockFile.push_back(info); } else { break; } } // Check presence of blk files LogPrintf("Checking all blk files are present...\n"); set<int> setBlkDataFiles; BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex) { CBlockIndex* pindex = item.second; if (pindex->nStatus & BLOCK_HAVE_DATA) { setBlkDataFiles.insert(pindex->nFile); } } for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++) { CDiskBlockPos pos(*it, 0); if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) { return false; } } // Check whether we have ever pruned block & undo files pblocktree->ReadFlag("prunedblockfiles", fHavePruned); if (fHavePruned) LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n"); // Check whether we need to continue reindexing bool fReindexing = false; pblocktree->ReadReindexing(fReindexing); fReindex |= fReindexing; // Check whether we have a transaction index pblocktree->ReadFlag("txindex", fTxIndex); LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled"); // Check whether we have an address index pblocktree->ReadFlag("addressindex", fAddressIndex); LogPrintf("%s: address index %s\n", __func__, fAddressIndex ? "enabled" : "disabled"); // Check whether we have a timestamp index pblocktree->ReadFlag("timestampindex", fTimestampIndex); LogPrintf("%s: timestamp index %s\n", __func__, fTimestampIndex ? "enabled" : "disabled"); // Check whether we have a spent index pblocktree->ReadFlag("spentindex", fSpentIndex); LogPrintf("%s: spent index %s\n", __func__, fSpentIndex ? "enabled" : "disabled"); // Load pointer to end of best chain BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock()); if (it == mapBlockIndex.end()) return true; chainActive.SetTip(it->second); PruneBlockIndexCandidates(); LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__, chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()), Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip())); return true; } CVerifyDB::CVerifyDB() { uiInterface.ShowProgress(_("Verifying blocks..."), 0); } CVerifyDB::~CVerifyDB() { uiInterface.ShowProgress("", 100); } bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth) { LOCK(cs_main); if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL) return true; // Verify blocks in the best chain if (nCheckDepth <= 0) nCheckDepth = 1000000000; // suffices until the year 19000 if (nCheckDepth > chainActive.Height()) nCheckDepth = chainActive.Height(); nCheckLevel = std::max(0, std::min(4, nCheckLevel)); LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel); CCoinsViewCache coins(coinsview); CBlockIndex* pindexState = chainActive.Tip(); CBlockIndex* pindexFailure = NULL; int nGoodTransactions = 0; CValidationState state; for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev) { boost::this_thread::interruption_point(); uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))))); if (pindex->nHeight < chainActive.Height()-nCheckDepth) break; CBlock block; // check level 0: read from disk if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus())) return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString()); // check level 1: verify block validity if (nCheckLevel >= 1 && !CheckBlock(block, state)) return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); // check level 2: verify undo validity if (nCheckLevel >= 2 && pindex) { CBlockUndo undo; CDiskBlockPos pos = pindex->GetUndoPos(); if (!pos.IsNull()) { if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash())) return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); } } // check level 3: check for inconsistencies during memory-only disconnect of tip blocks if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) { bool fClean = true; if (!DisconnectBlock(block, state, pindex, coins, &fClean)) return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString()); pindexState = pindex->pprev; if (!fClean) { nGoodTransactions = 0; pindexFailure = pindex; } else nGoodTransactions += block.vtx.size(); } if (ShutdownRequested()) return true; } if (pindexFailure) return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions); // check level 4: try reconnecting blocks if (nCheckLevel >= 4) { CBlockIndex *pindex = pindexState; while (pindex != chainActive.Tip()) { boost::this_thread::interruption_point(); uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50)))); pindex = chainActive.Next(pindex); CBlock block; if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus())) return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString()); if (!ConnectBlock(block, state, pindex, coins)) return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString()); } } LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions); return true; } void UnloadBlockIndex() { LOCK(cs_main); setBlockIndexCandidates.clear(); chainActive.SetTip(NULL); pindexBestInvalid = NULL; pindexBestHeader = NULL; mempool.clear(); mapOrphanTransactions.clear(); mapOrphanTransactionsByPrev.clear(); nSyncStarted = 0; mapBlocksUnlinked.clear(); vinfoBlockFile.clear(); nLastBlockFile = 0; nBlockSequenceId = 1; mapBlockSource.clear(); mapBlocksInFlight.clear(); nPreferredDownload = 0; setDirtyBlockIndex.clear(); setDirtyFileInfo.clear(); mapNodeState.clear(); recentRejects.reset(NULL); versionbitscache.Clear(); for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) { warningcache[b].clear(); } BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) { delete entry.second; } mapBlockIndex.clear(); fHavePruned = false; } bool LoadBlockIndex() { // Load block index from databases if (!fReindex && !LoadBlockIndexDB()) return false; return true; } bool InitBlockIndex(const CChainParams& chainparams) { LOCK(cs_main); // Initialize global variables that cannot be constructed at startup. recentRejects.reset(new CRollingBloomFilter(120000, 0.000001)); // Check whether we're already initialized if (chainActive.Genesis() != NULL) return true; // Use the provided setting for -txindex in the new database fTxIndex = GetBoolArg("-txindex", DEFAULT_TXINDEX); pblocktree->WriteFlag("txindex", fTxIndex); // Use the provided setting for -addressindex in the new database fAddressIndex = GetBoolArg("-addressindex", DEFAULT_ADDRESSINDEX); pblocktree->WriteFlag("addressindex", fAddressIndex); // Use the provided setting for -timestampindex in the new database fTimestampIndex = GetBoolArg("-timestampindex", DEFAULT_TIMESTAMPINDEX); pblocktree->WriteFlag("timestampindex", fTimestampIndex); fSpentIndex = GetBoolArg("-spentindex", DEFAULT_SPENTINDEX); pblocktree->WriteFlag("spentindex", fSpentIndex); LogPrintf("Initializing databases...\n"); // Only add the genesis block if not reindexing (in which case we reuse the one already on disk) if (!fReindex) { try { CBlock &block = const_cast<CBlock&>(chainparams.GenesisBlock()); // Start new block file unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION); CDiskBlockPos blockPos; CValidationState state; if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime())) return error("LoadBlockIndex(): FindBlockPos failed"); if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) return error("LoadBlockIndex(): writing genesis block to disk failed"); CBlockIndex *pindex = AddToBlockIndex(block); if (!ReceivedBlockTransactions(block, state, pindex, blockPos)) return error("LoadBlockIndex(): genesis block not accepted"); if (!ActivateBestChain(state, chainparams, &block)) return error("LoadBlockIndex(): genesis block cannot be activated"); // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data return FlushStateToDisk(state, FLUSH_STATE_ALWAYS); } catch (const std::runtime_error& e) { return error("LoadBlockIndex(): failed to initialize block database: %s", e.what()); } } return true; } bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp) { // Map of disk positions for blocks with unknown parent (only used for reindex) static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent; int64_t nStart = GetTimeMillis(); int nLoaded = 0; try { // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION); uint64_t nRewind = blkdat.GetPos(); while (!blkdat.eof()) { boost::this_thread::interruption_point(); blkdat.SetPos(nRewind); nRewind++; // start one byte further next time, in case of failure blkdat.SetLimit(); // remove former limit unsigned int nSize = 0; try { // locate a header unsigned char buf[MESSAGE_START_SIZE]; blkdat.FindByte(chainparams.MessageStart()[0]); nRewind = blkdat.GetPos()+1; blkdat >> FLATDATA(buf); if (memcmp(buf, chainparams.MessageStart(), MESSAGE_START_SIZE)) continue; // read size blkdat >> nSize; if (nSize < 80 || nSize > MAX_BLOCK_SIZE) continue; } catch (const std::exception&) { // no valid block header found; don't complain break; } try { // read block uint64_t nBlockPos = blkdat.GetPos(); if (dbp) dbp->nPos = nBlockPos; blkdat.SetLimit(nBlockPos + nSize); blkdat.SetPos(nBlockPos); CBlock block; blkdat >> block; nRewind = blkdat.GetPos(); // detect out of order blocks, and store them for later uint256 hash = block.GetHash(); if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) { LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(), block.hashPrevBlock.ToString()); if (dbp) mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp)); continue; } // process in case the block isn't known yet if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) { CValidationState state; if (ProcessNewBlock(state, chainparams, NULL, &block, true, dbp)) nLoaded++; if (state.IsError()) break; } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) { LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight); } // Recursively process earlier encountered successors of this block deque<uint256> queue; queue.push_back(hash); while (!queue.empty()) { uint256 head = queue.front(); queue.pop_front(); std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head); while (range.first != range.second) { std::multimap<uint256, CDiskBlockPos>::iterator it = range.first; if (ReadBlockFromDisk(block, it->second, chainparams.GetConsensus())) { LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(), head.ToString()); CValidationState dummy; if (ProcessNewBlock(dummy, chainparams, NULL, &block, true, &it->second)) { nLoaded++; queue.push_back(block.GetHash()); } } range.first++; mapBlocksUnknownParent.erase(it); } } } catch (const std::exception& e) { LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what()); } } } catch (const std::runtime_error& e) { AbortNode(std::string("System error: ") + e.what()); } if (nLoaded > 0) LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart); return nLoaded > 0; } void static CheckBlockIndex(const Consensus::Params& consensusParams) { if (!fCheckBlockIndex) { return; } LOCK(cs_main); // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain, // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when // iterating the block tree require that chainActive has been initialized.) if (chainActive.Height() < 0) { assert(mapBlockIndex.size() <= 1); return; } // Build forward-pointing map of the entire block tree. std::multimap<CBlockIndex*,CBlockIndex*> forward; for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) { forward.insert(std::make_pair(it->second->pprev, it->second)); } assert(forward.size() == mapBlockIndex.size()); std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL); CBlockIndex *pindex = rangeGenesis.first->second; rangeGenesis.first++; assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL. // Iterate over the entire block tree, using depth-first search. // Along the way, remember whether there are blocks on the path from genesis // block being explored which are the first to have certain properties. size_t nNodes = 0; int nHeight = 0; CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid. CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA. CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0. CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not). CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not). CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not). CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not). while (pindex != NULL) { nNodes++; if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex; if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex; if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex; if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex; if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex; if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex; if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex; // Begin: actual consistency checks. if (pindex->pprev == NULL) { // Genesis block checks. assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match. assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block. } if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred). // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred. if (!fHavePruned) { // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0)); assert(pindexFirstMissing == pindexFirstNeverProcessed); } else { // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0); } if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA); assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent. // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set. assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned). assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0)); assert(pindex->nHeight == nHeight); // nHeight must be consistent. assert(pindex->pprev == NULL || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's. assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks. assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid if (pindexFirstInvalid == NULL) { // Checks for not-invalid blocks. assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents. } if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) { if (pindexFirstInvalid == NULL) { // If this block sorts at least as good as the current tip and // is valid and we have all data for its parents, it must be in // setBlockIndexCandidates. chainActive.Tip() must also be there // even if some data has been pruned. if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) { assert(setBlockIndexCandidates.count(pindex)); } // If some parent is missing, then it could be that this block was in // setBlockIndexCandidates but had to be removed because of the missing data. // In this case it must be in mapBlocksUnlinked -- see test below. } } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates. assert(setBlockIndexCandidates.count(pindex) == 0); } // Check whether this block is in mapBlocksUnlinked. std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev); bool foundInUnlinked = false; while (rangeUnlinked.first != rangeUnlinked.second) { assert(rangeUnlinked.first->first == pindex->pprev); if (rangeUnlinked.first->second == pindex) { foundInUnlinked = true; break; } rangeUnlinked.first++; } if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) { // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked. assert(foundInUnlinked); } if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked. if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) { // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent. assert(fHavePruned); // We must have pruned. // This block may have entered mapBlocksUnlinked if: // - it has a descendant that at some point had more work than the // tip, and // - we tried switching to that descendant but were missing // data for some intermediate block between chainActive and the // tip. // So if this block is itself better than chainActive.Tip() and it wasn't in // setBlockIndexCandidates, then it must be in mapBlocksUnlinked. if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) { if (pindexFirstInvalid == NULL) { assert(foundInUnlinked); } } } // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow // End: actual consistency checks. // Try descending into the first subnode. std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex); if (range.first != range.second) { // A subnode was found. pindex = range.first->second; nHeight++; continue; } // This is a leaf node. // Move upwards until we reach a node of which we have not yet visited the last child. while (pindex) { // We are going to either move to a parent or a sibling of pindex. // If pindex was the first with a certain property, unset the corresponding variable. if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL; if (pindex == pindexFirstMissing) pindexFirstMissing = NULL; if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL; if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL; if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL; if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL; if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL; // Find our parent. CBlockIndex* pindexPar = pindex->pprev; // Find which child we just visited. std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar); while (rangePar.first->second != pindex) { assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child. rangePar.first++; } // Proceed to the next one. rangePar.first++; if (rangePar.first != rangePar.second) { // Move to the sibling. pindex = rangePar.first->second; break; } else { // Move up further. pindex = pindexPar; nHeight--; continue; } } } // Check that we actually traversed the entire map. assert(nNodes == forward.size()); } ////////////////////////////////////////////////////////////////////////////// // // CAlert // std::string GetWarnings(const std::string& strFor) { int nPriority = 0; string strStatusBar; string strRPC; string strGUI; if (!CLIENT_VERSION_IS_RELEASE) { strStatusBar = "This is a pre-release test build - use at your own risk - do not use for mining or merchant applications"; strGUI = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications"); } if (GetBoolArg("-testsafemode", DEFAULT_TESTSAFEMODE)) strStatusBar = strRPC = strGUI = "testsafemode enabled"; // Misc warnings like out of disk space and clock is wrong if (strMiscWarning != "") { nPriority = 1000; strStatusBar = strGUI = strMiscWarning; } if (fLargeWorkForkFound) { nPriority = 2000; strStatusBar = strRPC = "Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues."; strGUI = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues."); } else if (fLargeWorkInvalidChainFound) { nPriority = 2000; strStatusBar = strRPC = "Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade."; strGUI = _("Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade."); } // Alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.AppliesToMe() && alert.nPriority > nPriority) { nPriority = alert.nPriority; strStatusBar = strGUI = alert.strStatusBar; } } } if (strFor == "gui") return strGUI; else if (strFor == "statusbar") return strStatusBar; else if (strFor == "rpc") return strRPC; assert(!"GetWarnings(): invalid parameter"); return "error"; } ////////////////////////////////////////////////////////////////////////////// // // Messages // bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { switch (inv.type) { case MSG_TX: { assert(recentRejects); if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip) { // If the chain tip has changed previously rejected transactions // might be now valid, e.g. due to a nLockTime'd tx becoming valid, // or a double-spend. Reset the rejects filter and give those // txs a second chance. hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash(); recentRejects->reset(); } return recentRejects->contains(inv.hash) || mempool.exists(inv.hash) || mapOrphanTransactions.count(inv.hash) || pcoinsTip->HaveCoins(inv.hash); } case MSG_BLOCK: return mapBlockIndex.count(inv.hash); /* Sprint Related Inventory Messages -- We shouldn't update the sync times for each of the messages when we already have it. We're going to be asking many nodes upfront for the full inventory list, so we'll get duplicates of these. We want to only update the time on new hits, so that we can time out appropriately if needed. */ case MSG_TXLOCK_REQUEST: return instantsend.AlreadyHave(inv.hash); case MSG_TXLOCK_VOTE: return instantsend.AlreadyHave(inv.hash); case MSG_SPORK: return mapSporks.count(inv.hash); case MSG_MASTERNODE_PAYMENT_VOTE: return mnpayments.mapMasternodePaymentVotes.count(inv.hash); case MSG_MASTERNODE_PAYMENT_BLOCK: { BlockMap::iterator mi = mapBlockIndex.find(inv.hash); return mi != mapBlockIndex.end() && mnpayments.mapMasternodeBlocks.find(mi->second->nHeight) != mnpayments.mapMasternodeBlocks.end(); } case MSG_MASTERNODE_ANNOUNCE: return mnodeman.mapSeenMasternodeBroadcast.count(inv.hash) && !mnodeman.IsMnbRecoveryRequested(inv.hash); case MSG_MASTERNODE_PING: return mnodeman.mapSeenMasternodePing.count(inv.hash); case MSG_DSTX: return mapDarksendBroadcastTxes.count(inv.hash); case MSG_GOVERNANCE_OBJECT: case MSG_GOVERNANCE_OBJECT_VOTE: return ! governance.ConfirmInventoryRequest(inv); case MSG_MASTERNODE_VERIFY: return mnodeman.mapSeenMasternodeVerification.count(inv.hash); } // Don't know what it is, just say we already got one return true; } void static ProcessGetData(CNode* pfrom, const Consensus::Params& consensusParams) { std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin(); vector<CInv> vNotFound; LOCK(cs_main); while (it != pfrom->vRecvGetData.end()) { // Don't bother if send buffer is too full to respond anyway if (pfrom->nSendSize >= SendBufferSize()) break; const CInv &inv = *it; LogPrint("net", "ProcessGetData -- inv = %s\n", inv.ToString()); { boost::this_thread::interruption_point(); it++; if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK) { bool send = false; BlockMap::iterator mi = mapBlockIndex.find(inv.hash); if (mi != mapBlockIndex.end()) { if (chainActive.Contains(mi->second)) { send = true; } else { static const int nOneMonth = 30 * 24 * 60 * 60; // To prevent fingerprinting attacks, only send blocks outside of the active // chain if they are valid, and no more than a month older (both in time, and in // best equivalent proof of work) than the best header chain we know about. send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) && (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) && (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, consensusParams) < nOneMonth); if (!send) { LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId()); } } } // disconnect node in case we have reached the outbound limit for serving historical blocks // never disconnect whitelisted nodes static const int nOneWeek = 7 * 24 * 60 * 60; // assume > 1 week = historical if (send && CNode::OutboundTargetReached(true) && ( ((pindexBestHeader != NULL) && (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() > nOneWeek)) || inv.type == MSG_FILTERED_BLOCK) && !pfrom->fWhitelisted) { LogPrint("net", "historical block serving limit reached, disconnect peer=%d\n", pfrom->GetId()); //disconnect node pfrom->fDisconnect = true; send = false; } // Pruned nodes may have deleted the block, so check whether // it's available before trying to send. if (send && (mi->second->nStatus & BLOCK_HAVE_DATA)) { // Send block from disk CBlock block; if (!ReadBlockFromDisk(block, (*mi).second, consensusParams)) assert(!"cannot load block from disk"); if (inv.type == MSG_BLOCK) pfrom->PushMessage(NetMsgType::BLOCK, block); else // MSG_FILTERED_BLOCK) { LOCK(pfrom->cs_filter); if (pfrom->pfilter) { CMerkleBlock merkleBlock(block, *pfrom->pfilter); pfrom->PushMessage(NetMsgType::MERKLEBLOCK, merkleBlock); // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see // This avoids hurting performance by pointlessly requiring a round-trip // Note that there is currently no way for a node to request any single transactions we didn't send here - // they must either disconnect and retry or request the full block. // Thus, the protocol spec specified allows for us to provide duplicate txn here, // however we MUST always provide at least what the remote peer needs typedef std::pair<unsigned int, uint256> PairType; BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn) pfrom->PushMessage(NetMsgType::TX, block.vtx[pair.first]); } // else // no response } // Trigger the peer node to send a getblocks request for the next batch of inventory if (inv.hash == pfrom->hashContinue) { // Bypass PushInventory, this must send even if redundant, // and we want it right after the last block so they don't // wait for other stuff first. vector<CInv> vInv; vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash())); pfrom->PushMessage(NetMsgType::INV, vInv); pfrom->hashContinue.SetNull(); } } } else if (inv.IsKnownType()) { // Send stream from relay memory bool pushed = false; { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); { LOCK(cs_mapRelay); map<CInv, CDataStream>::iterator mi = mapRelay.find(inv); if (mi != mapRelay.end()) { ss += (*mi).second; pushed = true; } } if(pushed) pfrom->PushMessage(inv.GetCommand(), ss); } if (!pushed && inv.type == MSG_TX) { CTransaction tx; if (mempool.lookup(inv.hash, tx)) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(1000); ss << tx; pfrom->PushMessage(NetMsgType::TX, ss); pushed = true; } } if (!pushed && inv.type == MSG_TXLOCK_REQUEST) { CTxLockRequest txLockRequest; if(instantsend.GetTxLockRequest(inv.hash, txLockRequest)) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(1000); ss << txLockRequest; pfrom->PushMessage(NetMsgType::TXLOCKREQUEST, ss); pushed = true; } } if (!pushed && inv.type == MSG_TXLOCK_VOTE) { CTxLockVote vote; if(instantsend.GetTxLockVote(inv.hash, vote)) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(1000); ss << vote; pfrom->PushMessage(NetMsgType::TXLOCKVOTE, ss); pushed = true; } } if (!pushed && inv.type == MSG_SPORK) { if(mapSporks.count(inv.hash)) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(1000); ss << mapSporks[inv.hash]; pfrom->PushMessage(NetMsgType::SPORK, ss); pushed = true; } } if (!pushed && inv.type == MSG_MASTERNODE_PAYMENT_VOTE) { if(mnpayments.HasVerifiedPaymentVote(inv.hash)) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(1000); ss << mnpayments.mapMasternodePaymentVotes[inv.hash]; pfrom->PushMessage(NetMsgType::MASTERNODEPAYMENTVOTE, ss); pushed = true; } } if (!pushed && inv.type == MSG_MASTERNODE_PAYMENT_BLOCK) { BlockMap::iterator mi = mapBlockIndex.find(inv.hash); LOCK(cs_mapMasternodeBlocks); if (mi != mapBlockIndex.end() && mnpayments.mapMasternodeBlocks.count(mi->second->nHeight)) { BOOST_FOREACH(CMasternodePayee& payee, mnpayments.mapMasternodeBlocks[mi->second->nHeight].vecPayees) { std::vector<uint256> vecVoteHashes = payee.GetVoteHashes(); BOOST_FOREACH(uint256& hash, vecVoteHashes) { if(mnpayments.HasVerifiedPaymentVote(hash)) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(1000); ss << mnpayments.mapMasternodePaymentVotes[hash]; pfrom->PushMessage(NetMsgType::MASTERNODEPAYMENTVOTE, ss); } } } pushed = true; } } if (!pushed && inv.type == MSG_MASTERNODE_ANNOUNCE) { if(mnodeman.mapSeenMasternodeBroadcast.count(inv.hash)){ CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(1000); ss << mnodeman.mapSeenMasternodeBroadcast[inv.hash].second; pfrom->PushMessage(NetMsgType::MNANNOUNCE, ss); pushed = true; } } if (!pushed && inv.type == MSG_MASTERNODE_PING) { if(mnodeman.mapSeenMasternodePing.count(inv.hash)) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(1000); ss << mnodeman.mapSeenMasternodePing[inv.hash]; pfrom->PushMessage(NetMsgType::MNPING, ss); pushed = true; } } if (!pushed && inv.type == MSG_DSTX) { if(mapDarksendBroadcastTxes.count(inv.hash)) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(1000); ss << mapDarksendBroadcastTxes[inv.hash]; pfrom->PushMessage(NetMsgType::DSTX, ss); pushed = true; } } if (!pushed && inv.type == MSG_GOVERNANCE_OBJECT) { LogPrint("net", "ProcessGetData -- MSG_GOVERNANCE_OBJECT: inv = %s\n", inv.ToString()); CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); bool topush = false; { if(governance.HaveObjectForHash(inv.hash)) { ss.reserve(1000); if(governance.SerializeObjectForHash(inv.hash, ss)) { topush = true; } } } LogPrint("net", "ProcessGetData -- MSG_GOVERNANCE_OBJECT: topush = %d, inv = %s\n", topush, inv.ToString()); if(topush) { pfrom->PushMessage(NetMsgType::MNGOVERNANCEOBJECT, ss); pushed = true; } } if (!pushed && inv.type == MSG_GOVERNANCE_OBJECT_VOTE) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); bool topush = false; { if(governance.HaveVoteForHash(inv.hash)) { ss.reserve(1000); if(governance.SerializeVoteForHash(inv.hash, ss)) { topush = true; } } } if(topush) { LogPrint("net", "ProcessGetData -- pushing: inv = %s\n", inv.ToString()); pfrom->PushMessage(NetMsgType::MNGOVERNANCEOBJECTVOTE, ss); pushed = true; } } if (!pushed && inv.type == MSG_MASTERNODE_VERIFY) { if(mnodeman.mapSeenMasternodeVerification.count(inv.hash)) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(1000); ss << mnodeman.mapSeenMasternodeVerification[inv.hash]; pfrom->PushMessage(NetMsgType::MNVERIFY, ss); pushed = true; } } if (!pushed) vNotFound.push_back(inv); } // Track requests for our stuff. GetMainSignals().Inventory(inv.hash); if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK) break; } } pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it); if (!vNotFound.empty()) { // Let the peer know that we didn't find what it asked for, so it doesn't // have to wait around forever. Currently only SPV clients actually care // about this message: it's needed when they are recursively walking the // dependencies of relevant unconfirmed transactions. SPV clients want to // do that because they want to know about (and store and rebroadcast and // risk analyze) the dependencies of transactions relevant to them, without // having to download the entire memory pool. pfrom->PushMessage(NetMsgType::NOTFOUND, vNotFound); } } bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived) { const CChainParams& chainparams = Params(); RandAddSeedPerfmon(); LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id); if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0) { LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n"); return true; } if (!(nLocalServices & NODE_BLOOM) && (strCommand == NetMsgType::FILTERLOAD || strCommand == NetMsgType::FILTERADD || strCommand == NetMsgType::FILTERCLEAR)) { if (pfrom->nVersion >= NO_BLOOM_VERSION) { Misbehaving(pfrom->GetId(), 100); return false; } else if (GetBoolArg("-enforcenodebloom", false)) { pfrom->fDisconnect = true; return false; } } if (strCommand == NetMsgType::VERSION) { // Each connection can only send one version message if (pfrom->nVersion != 0) { pfrom->PushMessage(NetMsgType::REJECT, strCommand, REJECT_DUPLICATE, string("Duplicate version message")); Misbehaving(pfrom->GetId(), 1); return false; } int64_t nTime; CAddress addrMe; CAddress addrFrom; uint64_t nNonce = 1; vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe; if (pfrom->nVersion < MIN_PEER_PROTO_VERSION) { // disconnect from peers older than this proto version LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion); pfrom->PushMessage(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE, strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION)); pfrom->fDisconnect = true; return false; } if (pfrom->nVersion == 10300) pfrom->nVersion = 300; if (!vRecv.empty()) vRecv >> addrFrom >> nNonce; if (!vRecv.empty()) { vRecv >> LIMITED_STRING(pfrom->strSubVer, MAX_SUBVERSION_LENGTH); pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer); } if (!vRecv.empty()) vRecv >> pfrom->nStartingHeight; if (!vRecv.empty()) vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message else pfrom->fRelayTxes = true; // Disconnect if we connected to ourself if (nNonce == nLocalHostNonce && nNonce > 1) { LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString()); pfrom->fDisconnect = true; return true; } pfrom->addrLocal = addrMe; if (pfrom->fInbound && addrMe.IsRoutable()) { SeenLocal(addrMe); } // Be shy and don't send version until we hear if (pfrom->fInbound) pfrom->PushVersion(); pfrom->fClient = !(pfrom->nServices & NODE_NETWORK); CNodeState* pNodeState = NULL; { LOCK(cs_main); pNodeState = State(pfrom->GetId()); assert(pNodeState); } // Potentially mark this peer as a preferred download peer. UpdatePreferredDownload(pfrom, pNodeState); // Change version pfrom->PushMessage(NetMsgType::VERACK); pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); if (!pfrom->fInbound) { // Advertise our address if (fListen && !IsInitialBlockDownload()) { CAddress addr = GetLocalAddress(&pfrom->addr); if (addr.IsRoutable()) { LogPrintf("ProcessMessages: advertising address %s\n", addr.ToString()); pfrom->PushAddress(addr); } else if (IsPeerAddrLocalGood(pfrom)) { addr.SetIP(pfrom->addrLocal); LogPrintf("ProcessMessages: advertising address %s\n", addr.ToString()); pfrom->PushAddress(addr); } } // Get recent addresses if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000) { pfrom->PushMessage(NetMsgType::GETADDR); pfrom->fGetAddr = true; } addrman.Good(pfrom->addr); } else { if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom) { addrman.Add(addrFrom, addrFrom); addrman.Good(addrFrom); } } // Relay alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) item.second.RelayTo(pfrom); } pfrom->fSuccessfullyConnected = true; string remoteAddr; if (fLogIPs) remoteAddr = ", peeraddr=" + pfrom->addr.ToString(); LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n", pfrom->cleanSubVer, pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString(), pfrom->id, remoteAddr); int64_t nTimeOffset = nTime - GetTime(); pfrom->nTimeOffset = nTimeOffset; AddTimeData(pfrom->addr, nTimeOffset); } else if (pfrom->nVersion == 0) { // Must have a version message before anything else Misbehaving(pfrom->GetId(), 1); return false; } else if (strCommand == NetMsgType::VERACK) { pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); // Mark this node as currently connected, so we update its timestamp later. if (pfrom->fNetworkNode) { LOCK(cs_main); State(pfrom->GetId())->fCurrentlyConnected = true; } if (pfrom->nVersion >= SENDHEADERS_VERSION) { // Tell our peer we prefer to receive headers rather than inv's // We send this to non-NODE NETWORK peers as well, because even // non-NODE NETWORK peers can announce blocks (such as pruning // nodes) pfrom->PushMessage(NetMsgType::SENDHEADERS); } } else if (strCommand == NetMsgType::ADDR) { vector<CAddress> vAddr; vRecv >> vAddr; // Don't want addr from older versions unless seeding if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000) return true; if (vAddr.size() > 1000) { Misbehaving(pfrom->GetId(), 20); return error("message addr size() = %u", vAddr.size()); } // Store the new addresses vector<CAddress> vAddrOk; int64_t nNow = GetAdjustedTime(); int64_t nSince = nNow - 10 * 60; BOOST_FOREACH(CAddress& addr, vAddr) { boost::this_thread::interruption_point(); if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60) addr.nTime = nNow - 5 * 24 * 60 * 60; pfrom->AddAddressKnown(addr); bool fReachable = IsReachable(addr); if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable()) { // Relay to a limited number of other nodes { LOCK(cs_vNodes); // Use deterministic randomness to send to the same nodes for 24 hours // at a time so the addrKnowns of the chosen nodes prevent repeats static uint256 hashSalt; if (hashSalt.IsNull()) hashSalt = GetRandHash(); uint64_t hashAddr = addr.GetHash(); uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60))); hashRand = Hash(BEGIN(hashRand), END(hashRand)); multimap<uint256, CNode*> mapMix; BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->nVersion < CADDR_TIME_VERSION) continue; unsigned int nPointer; memcpy(&nPointer, &pnode, sizeof(nPointer)); uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer); hashKey = Hash(BEGIN(hashKey), END(hashKey)); mapMix.insert(make_pair(hashKey, pnode)); } int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s) for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi) ((*mi).second)->PushAddress(addr); } } // Do not store addresses outside our network if (fReachable) vAddrOk.push_back(addr); } addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60); if (vAddr.size() < 1000) pfrom->fGetAddr = false; if (pfrom->fOneShot) pfrom->fDisconnect = true; } else if (strCommand == NetMsgType::SENDHEADERS) { LOCK(cs_main); State(pfrom->GetId())->fPreferHeaders = true; } else if (strCommand == NetMsgType::INV) { vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > MAX_INV_SZ) { Misbehaving(pfrom->GetId(), 20); return error("message inv size() = %u", vInv.size()); } bool fBlocksOnly = GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY); // Allow whitelisted peers to send data other than blocks in blocks only mode if whitelistrelay is true if (pfrom->fWhitelisted && GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY)) fBlocksOnly = false; LOCK(cs_main); std::vector<CInv> vToFetch; for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { const CInv &inv = vInv[nInv]; if(!inv.IsKnownType()) { LogPrint("net", "got inv of unknown type %d: %s peer=%d\n", inv.type, inv.hash.ToString(), pfrom->id); continue; } boost::this_thread::interruption_point(); pfrom->AddInventoryKnown(inv); bool fAlreadyHave = AlreadyHave(inv); LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id); if (inv.type == MSG_BLOCK) { UpdateBlockAvailability(pfrom->GetId(), inv.hash); if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) { // First request the headers preceding the announced block. In the normal fully-synced // case where a new block is announced that succeeds the current tip (no reorganization), // there are no such headers. // Secondly, and only when we are close to being synced, we request the announced block directly, // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the // time the block arrives, the header chain leading up to it is already validated. Not // doing this will result in the received block being rejected as an orphan in case it is // not a direct successor. pfrom->PushMessage(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), inv.hash); CNodeState *nodestate = State(pfrom->GetId()); if (CanDirectFetch(chainparams.GetConsensus()) && nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) { vToFetch.push_back(inv); // Mark block as in flight already, even though the actual "getdata" message only goes out // later (within the same cs_main lock, though). MarkBlockAsInFlight(pfrom->GetId(), inv.hash, chainparams.GetConsensus()); } LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id); } } else { if (fBlocksOnly) LogPrint("net", "transaction (%s) inv sent in violation of protocol peer=%d\n", inv.hash.ToString(), pfrom->id); else if (!fAlreadyHave && !fImporting && !fReindex && !IsInitialBlockDownload()) pfrom->AskFor(inv); } // Track requests for our stuff GetMainSignals().Inventory(inv.hash); if (pfrom->nSendSize > (SendBufferSize() * 2)) { Misbehaving(pfrom->GetId(), 50); return error("send buffer size() = %u", pfrom->nSendSize); } } if (!vToFetch.empty()) pfrom->PushMessage(NetMsgType::GETDATA, vToFetch); } else if (strCommand == NetMsgType::GETDATA) { vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > MAX_INV_SZ) { Misbehaving(pfrom->GetId(), 20); return error("message getdata size() = %u", vInv.size()); } if (fDebug || (vInv.size() != 1)) LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id); if ((fDebug && vInv.size() > 0) || (vInv.size() == 1)) LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id); pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end()); ProcessGetData(pfrom, chainparams.GetConsensus()); } else if (strCommand == NetMsgType::GETBLOCKS) { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; LOCK(cs_main); // Find the last block the caller has in the main chain CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator); // Send the rest of the chain if (pindex) pindex = chainActive.Next(pindex); int nLimit = 500; LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id); for (; pindex; pindex = chainActive.Next(pindex)) { if (pindex->GetBlockHash() == hashStop) { LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); break; } // If pruning, don't inv blocks unless we have on disk and are likely to still have // for some reasonable time window (1 hour) that block relay might require. const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / chainparams.GetConsensus().nPowTargetSpacing; if (fPruneMode && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= chainActive.Tip()->nHeight - nPrunedBlocksLikelyToHave)) { LogPrint("net", " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); break; } pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash())); if (--nLimit <= 0) { // When this block is requested, we'll send an inv that'll // trigger the peer to getblocks the next batch of inventory. LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); pfrom->hashContinue = pindex->GetBlockHash(); break; } } } else if (strCommand == NetMsgType::GETHEADERS) { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; LOCK(cs_main); if (IsInitialBlockDownload() && !pfrom->fWhitelisted) { LogPrint("net", "Ignoring getheaders from peer=%d because node is in initial block download\n", pfrom->id); return true; } CNodeState *nodestate = State(pfrom->GetId()); CBlockIndex* pindex = NULL; if (locator.IsNull()) { // If locator is null, return the hashStop block BlockMap::iterator mi = mapBlockIndex.find(hashStop); if (mi == mapBlockIndex.end()) return true; pindex = (*mi).second; } else { // Find the last block the caller has in the main chain pindex = FindForkInGlobalIndex(chainActive, locator); if (pindex) pindex = chainActive.Next(pindex); } // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end vector<CBlock> vHeaders; int nLimit = MAX_HEADERS_RESULTS; LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id); for (; pindex; pindex = chainActive.Next(pindex)) { vHeaders.push_back(pindex->GetBlockHeader()); if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) break; } // pindex can be NULL either if we sent chainActive.Tip() OR // if our peer has chainActive.Tip() (and thus we are sending an empty // headers message). In both cases it's safe to update // pindexBestHeaderSent to be our tip. nodestate->pindexBestHeaderSent = pindex ? pindex : chainActive.Tip(); pfrom->PushMessage(NetMsgType::HEADERS, vHeaders); } else if (strCommand == NetMsgType::TX || strCommand == NetMsgType::DSTX || strCommand == NetMsgType::TXLOCKREQUEST) { // Stop processing the transaction early if // We are in blocks only mode and peer is either not whitelisted or whitelistrelay is off if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) && (!pfrom->fWhitelisted || !GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY))) { LogPrint("net", "transaction sent in violation of protocol peer=%d\n", pfrom->id); return true; } vector<uint256> vWorkQueue; vector<uint256> vEraseQueue; CTransaction tx; CTxLockRequest txLockRequest; CDarksendBroadcastTx dstx; int nInvType = MSG_TX; // Read data and assign inv type if(strCommand == NetMsgType::TX) { vRecv >> tx; } else if(strCommand == NetMsgType::TXLOCKREQUEST) { vRecv >> txLockRequest; tx = txLockRequest; nInvType = MSG_TXLOCK_REQUEST; } else if (strCommand == NetMsgType::DSTX) { vRecv >> dstx; tx = dstx.tx; nInvType = MSG_DSTX; } CInv inv(nInvType, tx.GetHash()); pfrom->AddInventoryKnown(inv); pfrom->setAskFor.erase(inv.hash); // Process custom logic, no matter if tx will be accepted to mempool later or not if (strCommand == NetMsgType::TXLOCKREQUEST) { if(!instantsend.ProcessTxLockRequest(txLockRequest)) { LogPrint("instantsend", "TXLOCKREQUEST -- failed %s\n", txLockRequest.GetHash().ToString()); return false; } } else if (strCommand == NetMsgType::DSTX) { uint256 hashTx = tx.GetHash(); if(mapDarksendBroadcastTxes.count(hashTx)) { LogPrint("privatesend", "DSTX -- Already have %s, skipping...\n", hashTx.ToString()); return true; // not an error } CMasternode* pmn = mnodeman.Find(dstx.vin); if(pmn == NULL) { LogPrint("privatesend", "DSTX -- Can't find masternode %s to verify %s\n", dstx.vin.prevout.ToStringShort(), hashTx.ToString()); return false; } if(!pmn->fAllowMixingTx) { LogPrint("privatesend", "DSTX -- Masternode %s is sending too many transactions %s\n", dstx.vin.prevout.ToStringShort(), hashTx.ToString()); return true; // TODO: Not an error? Could it be that someone is relaying old DSTXes // we have no idea about (e.g we were offline)? How to handle them? } if(!dstx.CheckSignature(pmn->pubKeyMasternode)) { LogPrint("privatesend", "DSTX -- CheckSignature() failed for %s\n", hashTx.ToString()); return false; } LogPrintf("DSTX -- Got Masternode transaction %s\n", hashTx.ToString()); mempool.PrioritiseTransaction(hashTx, hashTx.ToString(), 1000, 0.1*COIN); pmn->fAllowMixingTx = false; } LOCK(cs_main); bool fMissingInputs = false; CValidationState state; mapAlreadyAskedFor.erase(inv.hash); if (!AlreadyHave(inv) && AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs)) { // Process custom txes, this changes AlreadyHave to "true" if (strCommand == NetMsgType::DSTX) { LogPrintf("DSTX -- Masternode transaction accepted, txid=%s, peer=%d\n", tx.GetHash().ToString(), pfrom->id); mapDarksendBroadcastTxes.insert(make_pair(tx.GetHash(), dstx)); } else if (strCommand == NetMsgType::TXLOCKREQUEST) { LogPrintf("TXLOCKREQUEST -- Transaction Lock Request accepted, txid=%s, peer=%d\n", tx.GetHash().ToString(), pfrom->id); instantsend.AcceptLockRequest(txLockRequest); } mempool.check(pcoinsTip); RelayTransaction(tx); vWorkQueue.push_back(inv.hash); LogPrint("mempool", "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n", pfrom->id, tx.GetHash().ToString(), mempool.size(), mempool.DynamicMemoryUsage() / 1000); // Recursively process any orphan transactions that depended on this one set<NodeId> setMisbehaving; for (unsigned int i = 0; i < vWorkQueue.size(); i++) { map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]); if (itByPrev == mapOrphanTransactionsByPrev.end()) continue; for (set<uint256>::iterator mi = itByPrev->second.begin(); mi != itByPrev->second.end(); ++mi) { const uint256& orphanHash = *mi; const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx; NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer; bool fMissingInputs2 = false; // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get // anyone relaying LegitTxX banned) CValidationState stateDummy; if (setMisbehaving.count(fromPeer)) continue; if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2)) { LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString()); RelayTransaction(orphanTx); vWorkQueue.push_back(orphanHash); vEraseQueue.push_back(orphanHash); } else if (!fMissingInputs2) { int nDos = 0; if (stateDummy.IsInvalid(nDos) && nDos > 0) { // Punish peer that gave us an invalid orphan tx Misbehaving(fromPeer, nDos); setMisbehaving.insert(fromPeer); LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString()); } // Has inputs but not accepted to mempool // Probably non-standard or insufficient fee/priority LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString()); vEraseQueue.push_back(orphanHash); assert(recentRejects); recentRejects->insert(orphanHash); } mempool.check(pcoinsTip); } } BOOST_FOREACH(uint256 hash, vEraseQueue) EraseOrphanTx(hash); } else if (fMissingInputs) { AddOrphanTx(tx, pfrom->GetId()); // DoS prevention: do not allow mapOrphanTransactions to grow unbounded unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS)); unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx); if (nEvicted > 0) LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted); } else { assert(recentRejects); recentRejects->insert(tx.GetHash()); if (strCommand == NetMsgType::TXLOCKREQUEST && !AlreadyHave(inv)) { // i.e. AcceptToMemoryPool failed, probably because it's conflicting // with existing normal tx or tx lock for another tx. For the same tx lock // AlreadyHave would have return "true" already. // It's the first time we failed for this tx lock request, // this should switch AlreadyHave to "true". instantsend.RejectLockRequest(txLockRequest); // this lets other nodes to create lock request candidate i.e. // this allows multiple conflicting lock requests to compete for votes RelayTransaction(tx); } if (pfrom->fWhitelisted && GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) { // Always relay transactions received from whitelisted peers, even // if they were already in the mempool or rejected from it due // to policy, allowing the node to function as a gateway for // nodes hidden behind it. // // Never relay transactions that we would assign a non-zero DoS // score for, as we expect peers to do the same with us in that // case. int nDoS = 0; if (!state.IsInvalid(nDoS) || nDoS == 0) { LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->id); RelayTransaction(tx); } else { LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s)\n", tx.GetHash().ToString(), pfrom->id, FormatStateMessage(state)); } } } int nDoS = 0; if (state.IsInvalid(nDoS)) { LogPrint("mempoolrej", "%s from peer=%d was not accepted: %s\n", tx.GetHash().ToString(), pfrom->id, FormatStateMessage(state)); if (state.GetRejectCode() < REJECT_INTERNAL) // Never send AcceptToMemoryPool's internal codes over P2P pfrom->PushMessage(NetMsgType::REJECT, strCommand, (unsigned char)state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash); if (nDoS > 0) Misbehaving(pfrom->GetId(), nDoS); } FlushStateToDisk(state, FLUSH_STATE_PERIODIC); } else if (strCommand == NetMsgType::HEADERS && !fImporting && !fReindex) // Ignore headers received while importing { std::vector<CBlockHeader> headers; // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks. unsigned int nCount = ReadCompactSize(vRecv); if (nCount > MAX_HEADERS_RESULTS) { Misbehaving(pfrom->GetId(), 20); return error("headers message size = %u", nCount); } headers.resize(nCount); for (unsigned int n = 0; n < nCount; n++) { vRecv >> headers[n]; ReadCompactSize(vRecv); // ignore tx count; assume it is 0. } LOCK(cs_main); if (nCount == 0) { // Nothing interesting. Stop asking this peers for more headers. return true; } CBlockIndex *pindexLast = NULL; BOOST_FOREACH(const CBlockHeader& header, headers) { CValidationState state; if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) { Misbehaving(pfrom->GetId(), 20); return error("non-continuous headers sequence"); } if (!AcceptBlockHeader(header, state, chainparams, &pindexLast)) { int nDoS; if (state.IsInvalid(nDoS)) { if (nDoS > 0) Misbehaving(pfrom->GetId(), nDoS); std::string strError = "invalid header received " + header.GetHash().ToString(); return error(strError.c_str()); } } } if (pindexLast) UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash()); if (nCount == MAX_HEADERS_RESULTS && pindexLast) { // Headers message had its maximum size; the peer may have more headers. // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue // from there instead. LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight); pfrom->PushMessage(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexLast), uint256()); } bool fCanDirectFetch = CanDirectFetch(chainparams.GetConsensus()); CNodeState *nodestate = State(pfrom->GetId()); // If this set of headers is valid and ends in a block with at least as // much work as our tip, download as much as possible. if (fCanDirectFetch && pindexLast->IsValid(BLOCK_VALID_TREE) && chainActive.Tip()->nChainWork <= pindexLast->nChainWork) { vector<CBlockIndex *> vToFetch; CBlockIndex *pindexWalk = pindexLast; // Calculate all the blocks we'd need to switch to pindexLast, up to a limit. while (pindexWalk && !chainActive.Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) { if (!(pindexWalk->nStatus & BLOCK_HAVE_DATA) && !mapBlocksInFlight.count(pindexWalk->GetBlockHash())) { // We don't have this block, and it's not yet in flight. vToFetch.push_back(pindexWalk); } pindexWalk = pindexWalk->pprev; } // If pindexWalk still isn't on our main chain, we're looking at a // very large reorg at a time we think we're close to caught up to // the main chain -- this shouldn't really happen. Bail out on the // direct fetch and rely on parallel download instead. if (!chainActive.Contains(pindexWalk)) { LogPrint("net", "Large reorg, won't direct fetch to %s (%d)\n", pindexLast->GetBlockHash().ToString(), pindexLast->nHeight); } else { vector<CInv> vGetData; // Download as much as possible, from earliest to latest. BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vToFetch) { if (nodestate->nBlocksInFlight >= MAX_BLOCKS_IN_TRANSIT_PER_PEER) { // Can't download any more from this peer break; } vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash())); MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), chainparams.GetConsensus(), pindex); LogPrint("net", "Requesting block %s from peer=%d\n", pindex->GetBlockHash().ToString(), pfrom->id); } if (vGetData.size() > 1) { LogPrint("net", "Downloading blocks toward %s (%d) via headers direct fetch\n", pindexLast->GetBlockHash().ToString(), pindexLast->nHeight); } if (vGetData.size() > 0) { pfrom->PushMessage(NetMsgType::GETDATA, vGetData); } } } CheckBlockIndex(chainparams.GetConsensus()); } else if (strCommand == NetMsgType::BLOCK && !fImporting && !fReindex) // Ignore blocks received while importing { CBlock block; vRecv >> block; CInv inv(MSG_BLOCK, block.GetHash()); LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id); pfrom->AddInventoryKnown(inv); CValidationState state; // Process all blocks from whitelisted peers, even if not requested, // unless we're still syncing with the network. // Such an unrequested block may still be processed, subject to the // conditions in AcceptBlock(). bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload(); ProcessNewBlock(state, chainparams, pfrom, &block, forceProcessing, NULL); int nDoS; if (state.IsInvalid(nDoS)) { assert (state.GetRejectCode() < REJECT_INTERNAL); // Blocks are never rejected with internal reject codes pfrom->PushMessage(NetMsgType::REJECT, strCommand, (unsigned char)state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash); if (nDoS > 0) { LOCK(cs_main); Misbehaving(pfrom->GetId(), nDoS); } } } else if (strCommand == NetMsgType::GETADDR) { // This asymmetric behavior for inbound and outbound connections was introduced // to prevent a fingerprinting attack: an attacker can send specific fake addresses // to users' AddrMan and later request them by sending getaddr messages. // Making nodes which are behind NAT and can only make outgoing connections ignore // the getaddr message mitigates the attack. if (!pfrom->fInbound) { LogPrint("net", "Ignoring \"getaddr\" from outbound connection. peer=%d\n", pfrom->id); return true; } pfrom->vAddrToSend.clear(); vector<CAddress> vAddr = addrman.GetAddr(); BOOST_FOREACH(const CAddress &addr, vAddr) pfrom->PushAddress(addr); } else if (strCommand == NetMsgType::MEMPOOL) { if (CNode::OutboundTargetReached(false) && !pfrom->fWhitelisted) { LogPrint("net", "mempool request with bandwidth limit reached, disconnect peer=%d\n", pfrom->GetId()); pfrom->fDisconnect = true; return true; } LOCK2(cs_main, pfrom->cs_filter); std::vector<uint256> vtxid; mempool.queryHashes(vtxid); vector<CInv> vInv; BOOST_FOREACH(uint256& hash, vtxid) { CInv inv(MSG_TX, hash); if (pfrom->pfilter) { CTransaction tx; bool fInMemPool = mempool.lookup(hash, tx); if (!fInMemPool) continue; // another thread removed since queryHashes, maybe... if (!pfrom->pfilter->IsRelevantAndUpdate(tx)) continue; } vInv.push_back(inv); if (vInv.size() == MAX_INV_SZ) { pfrom->PushMessage(NetMsgType::INV, vInv); vInv.clear(); } } if (vInv.size() > 0) pfrom->PushMessage(NetMsgType::INV, vInv); } else if (strCommand == NetMsgType::PING) { if (pfrom->nVersion > BIP0031_VERSION) { uint64_t nonce = 0; vRecv >> nonce; // Echo the message back with the nonce. This allows for two useful features: // // 1) A remote node can quickly check if the connection is operational // 2) Remote nodes can measure the latency of the network thread. If this node // is overloaded it won't respond to pings quickly and the remote node can // avoid sending us more work, like chain download requests. // // The nonce stops the remote getting confused between different pings: without // it, if the remote node sends a ping once per second and this node takes 5 // seconds to respond to each, the 5th ping the remote sends would appear to // return very quickly. pfrom->PushMessage(NetMsgType::PONG, nonce); } } else if (strCommand == NetMsgType::PONG) { int64_t pingUsecEnd = nTimeReceived; uint64_t nonce = 0; size_t nAvail = vRecv.in_avail(); bool bPingFinished = false; std::string sProblem; if (nAvail >= sizeof(nonce)) { vRecv >> nonce; // Only process pong message if there is an outstanding ping (old ping without nonce should never pong) if (pfrom->nPingNonceSent != 0) { if (nonce == pfrom->nPingNonceSent) { // Matching pong received, this ping is no longer outstanding bPingFinished = true; int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart; if (pingUsecTime > 0) { // Successful ping time measurement, replace previous pfrom->nPingUsecTime = pingUsecTime; pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime, pingUsecTime); } else { // This should never happen sProblem = "Timing mishap"; } } else { // Nonce mismatches are normal when pings are overlapping sProblem = "Nonce mismatch"; if (nonce == 0) { // This is most likely a bug in another implementation somewhere; cancel this ping bPingFinished = true; sProblem = "Nonce zero"; } } } else { sProblem = "Unsolicited pong without ping"; } } else { // This is most likely a bug in another implementation somewhere; cancel this ping bPingFinished = true; sProblem = "Short payload"; } if (!(sProblem.empty())) { LogPrint("net", "pong peer=%d: %s, %x expected, %x received, %u bytes\n", pfrom->id, sProblem, pfrom->nPingNonceSent, nonce, nAvail); } if (bPingFinished) { pfrom->nPingNonceSent = 0; } } else if (fAlerts && strCommand == NetMsgType::ALERT) { CAlert alert; vRecv >> alert; uint256 alertHash = alert.GetHash(); if (pfrom->setKnown.count(alertHash) == 0) { if (alert.ProcessAlert(chainparams.AlertKey())) { // Relay pfrom->setKnown.insert(alertHash); { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) alert.RelayTo(pnode); } } else { // Small DoS penalty so peers that send us lots of // duplicate/expired/invalid-signature/whatever alerts // eventually get banned. // This isn't a Misbehaving(100) (immediate ban) because the // peer might be an older or different implementation with // a different signature key, etc. Misbehaving(pfrom->GetId(), 10); } } } else if (strCommand == NetMsgType::FILTERLOAD) { CBloomFilter filter; vRecv >> filter; if (!filter.IsWithinSizeConstraints()) // There is no excuse for sending a too-large filter Misbehaving(pfrom->GetId(), 100); else { LOCK(pfrom->cs_filter); delete pfrom->pfilter; pfrom->pfilter = new CBloomFilter(filter); pfrom->pfilter->UpdateEmptyFull(); } pfrom->fRelayTxes = true; } else if (strCommand == NetMsgType::FILTERADD) { vector<unsigned char> vData; vRecv >> vData; // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object, // and thus, the maximum size any matched object can have) in a filteradd message if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) { Misbehaving(pfrom->GetId(), 100); } else { LOCK(pfrom->cs_filter); if (pfrom->pfilter) pfrom->pfilter->insert(vData); else Misbehaving(pfrom->GetId(), 100); } } else if (strCommand == NetMsgType::FILTERCLEAR) { LOCK(pfrom->cs_filter); delete pfrom->pfilter; pfrom->pfilter = new CBloomFilter(); pfrom->fRelayTxes = true; } else if (strCommand == NetMsgType::REJECT) { if (fDebug) { try { string strMsg; unsigned char ccode; string strReason; vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH); ostringstream ss; ss << strMsg << " code " << itostr(ccode) << ": " << strReason; if (strMsg == NetMsgType::BLOCK || strMsg == NetMsgType::TX) { uint256 hash; vRecv >> hash; ss << ": hash " << hash.ToString(); } LogPrint("net", "Reject %s\n", SanitizeString(ss.str())); } catch (const std::ios_base::failure&) { // Avoid feedback loops by preventing reject messages from triggering a new reject message. LogPrint("net", "Unparseable reject message received\n"); } } } else { bool found = false; const std::vector<std::string> &allMessages = getAllNetMessageTypes(); BOOST_FOREACH(const std::string msg, allMessages) { if(msg == strCommand) { found = true; break; } } if (found) { //probably one the extensions darkSendPool.ProcessMessage(pfrom, strCommand, vRecv); mnodeman.ProcessMessage(pfrom, strCommand, vRecv); mnpayments.ProcessMessage(pfrom, strCommand, vRecv); instantsend.ProcessMessage(pfrom, strCommand, vRecv); sporkManager.ProcessSpork(pfrom, strCommand, vRecv); masternodeSync.ProcessMessage(pfrom, strCommand, vRecv); governance.ProcessMessage(pfrom, strCommand, vRecv); } else { // Ignore unknown commands for extensibility LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id); } } return true; } // requires LOCK(cs_vRecvMsg) bool ProcessMessages(CNode* pfrom) { const CChainParams& chainparams = Params(); //if (fDebug) // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size()); // // Message format // (4) message start // (12) command // (4) size // (4) checksum // (x) data // bool fOk = true; if (!pfrom->vRecvGetData.empty()) ProcessGetData(pfrom, chainparams.GetConsensus()); // this maintains the order of responses if (!pfrom->vRecvGetData.empty()) return fOk; std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin(); while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) { // Don't bother if send buffer is too full to respond anyway if (pfrom->nSendSize >= SendBufferSize()) break; // get next message CNetMessage& msg = *it; //if (fDebug) // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__, // msg.hdr.nMessageSize, msg.vRecv.size(), // msg.complete() ? "Y" : "N"); // end, if an incomplete message is found if (!msg.complete()) break; // at this point, any failure means we can delete the current message it++; // Scan for message start if (memcmp(msg.hdr.pchMessageStart, chainparams.MessageStart(), MESSAGE_START_SIZE) != 0) { LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id); fOk = false; break; } // Read header CMessageHeader& hdr = msg.hdr; if (!hdr.IsValid(chainparams.MessageStart())) { LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id); continue; } string strCommand = hdr.GetCommand(); // Message size unsigned int nMessageSize = hdr.nMessageSize; // Checksum CDataStream& vRecv = msg.vRecv; uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize); unsigned int nChecksum = ReadLE32((unsigned char*)&hash); if (nChecksum != hdr.nChecksum) { LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__, SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum); continue; } // Process message bool fRet = false; try { fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime); boost::this_thread::interruption_point(); } catch (const std::ios_base::failure& e) { pfrom->PushMessage(NetMsgType::REJECT, strCommand, REJECT_MALFORMED, string("error parsing message")); if (strstr(e.what(), "end of data")) { // Allow exceptions from under-length message on vRecv LogPrintf("%s(%s, %u bytes): Exception '%s' caught, normally caused by a message being shorter than its stated length\n", __func__, SanitizeString(strCommand), nMessageSize, e.what()); } else if (strstr(e.what(), "size too large")) { // Allow exceptions from over-long size LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what()); } else { PrintExceptionContinue(&e, "ProcessMessages()"); } } catch (const boost::thread_interrupted&) { throw; } catch (const std::exception& e) { PrintExceptionContinue(&e, "ProcessMessages()"); } catch (...) { PrintExceptionContinue(NULL, "ProcessMessages()"); } if (!fRet) LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id); break; } // In case the connection got shut down, its receive buffer was wiped if (!pfrom->fDisconnect) pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it); return fOk; } bool SendMessages(CNode* pto) { const Consensus::Params& consensusParams = Params().GetConsensus(); { // Don't send anything until we get its version message if (pto->nVersion == 0) return true; // // Message: ping // bool pingSend = false; if (pto->fPingQueued) { // RPC ping request by user pingSend = true; } if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) { // Ping automatically sent as a latency probe & keepalive. pingSend = true; } if (pingSend) { uint64_t nonce = 0; while (nonce == 0) { GetRandBytes((unsigned char*)&nonce, sizeof(nonce)); } pto->fPingQueued = false; pto->nPingUsecStart = GetTimeMicros(); if (pto->nVersion > BIP0031_VERSION) { pto->nPingNonceSent = nonce; pto->PushMessage(NetMsgType::PING, nonce); } else { // Peer is too old to support ping command with nonce, pong will never arrive. pto->nPingNonceSent = 0; pto->PushMessage(NetMsgType::PING); } } TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState() if (!lockMain) return true; // Address refresh broadcast int64_t nNow = GetTimeMicros(); if (!IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow) { AdvertiseLocal(pto); pto->nNextLocalAddrSend = PoissonNextSend(nNow, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL); } // // Message: addr // if (pto->nNextAddrSend < nNow) { pto->nNextAddrSend = PoissonNextSend(nNow, AVG_ADDRESS_BROADCAST_INTERVAL); vector<CAddress> vAddr; vAddr.reserve(pto->vAddrToSend.size()); BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend) { if (!pto->addrKnown.contains(addr.GetKey())) { pto->addrKnown.insert(addr.GetKey()); vAddr.push_back(addr); // receiver rejects addr messages larger than 1000 if (vAddr.size() >= 1000) { pto->PushMessage(NetMsgType::ADDR, vAddr); vAddr.clear(); } } } pto->vAddrToSend.clear(); if (!vAddr.empty()) pto->PushMessage(NetMsgType::ADDR, vAddr); } CNodeState &state = *State(pto->GetId()); if (state.fShouldBan) { if (pto->fWhitelisted) LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString()); else { pto->fDisconnect = true; if (pto->addr.IsLocal()) LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString()); else { CNode::Ban(pto->addr, BanReasonNodeMisbehaving); } } state.fShouldBan = false; } BOOST_FOREACH(const CBlockReject& reject, state.rejects) pto->PushMessage(NetMsgType::REJECT, (string)NetMsgType::BLOCK, reject.chRejectCode, reject.strRejectReason, reject.hashBlock); state.rejects.clear(); // Start block sync if (pindexBestHeader == NULL) pindexBestHeader = chainActive.Tip(); bool fFetch = state.fPreferredDownload || (nPreferredDownload == 0 && !pto->fClient && !pto->fOneShot); // Download if this is a nice peer, or we have no nice peers and this one might do. if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) { // Only actively request headers from a single peer, unless we're close to end of initial download. if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 6 * 60 * 60) { // NOTE: was "close to today" and 24h in Bitcoin state.fSyncStarted = true; nSyncStarted++; const CBlockIndex *pindexStart = pindexBestHeader; /* If possible, start at the block preceding the currently best known header. This ensures that we always get a non-empty list of headers back as long as the peer is up-to-date. With a non-empty response, we can initialise the peer's known best block. This wouldn't be possible if we requested starting at pindexBestHeader and got back an empty response. */ if (pindexStart->pprev) pindexStart = pindexStart->pprev; LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight); pto->PushMessage(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexStart), uint256()); } } // Resend wallet transactions that haven't gotten in a block yet // Except during reindex, importing and IBD, when old wallet // transactions become unconfirmed and spams other nodes. if (!fReindex && !fImporting && !IsInitialBlockDownload()) { GetMainSignals().Broadcast(nTimeBestReceived); } // // Try sending block announcements via headers // { // If we have less than MAX_BLOCKS_TO_ANNOUNCE in our // list of block hashes we're relaying, and our peer wants // headers announcements, then find the first header // not yet known to our peer but would connect, and send. // If no header would connect, or if we have too many // blocks, or if the peer doesn't want headers, just // add all to the inv queue. LOCK(pto->cs_inventory); vector<CBlock> vHeaders; bool fRevertToInv = (!state.fPreferHeaders || pto->vBlockHashesToAnnounce.size() > MAX_BLOCKS_TO_ANNOUNCE); CBlockIndex *pBestIndex = NULL; // last header queued for delivery ProcessBlockAvailability(pto->id); // ensure pindexBestKnownBlock is up-to-date if (!fRevertToInv) { bool fFoundStartingHeader = false; // Try to find first header that our peer doesn't have, and // then send all headers past that one. If we come across any // headers that aren't on chainActive, give up. BOOST_FOREACH(const uint256 &hash, pto->vBlockHashesToAnnounce) { BlockMap::iterator mi = mapBlockIndex.find(hash); assert(mi != mapBlockIndex.end()); CBlockIndex *pindex = mi->second; if (chainActive[pindex->nHeight] != pindex) { // Bail out if we reorged away from this block fRevertToInv = true; break; } if (pBestIndex != NULL && pindex->pprev != pBestIndex) { // This means that the list of blocks to announce don't // connect to each other. // This shouldn't really be possible to hit during // regular operation (because reorgs should take us to // a chain that has some block not on the prior chain, // which should be caught by the prior check), but one // way this could happen is by using invalidateblock / // reconsiderblock repeatedly on the tip, causing it to // be added multiple times to vBlockHashesToAnnounce. // Robustly deal with this rare situation by reverting // to an inv. fRevertToInv = true; break; } pBestIndex = pindex; if (fFoundStartingHeader) { // add this to the headers message vHeaders.push_back(pindex->GetBlockHeader()); } else if (PeerHasHeader(&state, pindex)) { continue; // keep looking for the first new block } else if (pindex->pprev == NULL || PeerHasHeader(&state, pindex->pprev)) { // Peer doesn't have this header but they do have the prior one. // Start sending headers. fFoundStartingHeader = true; vHeaders.push_back(pindex->GetBlockHeader()); } else { // Peer doesn't have this header or the prior one -- nothing will // connect, so bail out. fRevertToInv = true; break; } } } if (fRevertToInv) { // If falling back to using an inv, just try to inv the tip. // The last entry in vBlockHashesToAnnounce was our tip at some point // in the past. if (!pto->vBlockHashesToAnnounce.empty()) { const uint256 &hashToAnnounce = pto->vBlockHashesToAnnounce.back(); BlockMap::iterator mi = mapBlockIndex.find(hashToAnnounce); assert(mi != mapBlockIndex.end()); CBlockIndex *pindex = mi->second; // Warn if we're announcing a block that is not on the main chain. // This should be very rare and could be optimized out. // Just log for now. if (chainActive[pindex->nHeight] != pindex) { LogPrint("net", "Announcing block %s not on main chain (tip=%s)\n", hashToAnnounce.ToString(), chainActive.Tip()->GetBlockHash().ToString()); } // If the peer announced this block to us, don't inv it back. // (Since block announcements may not be via inv's, we can't solely rely on // setInventoryKnown to track this.) if (!PeerHasHeader(&state, pindex)) { pto->PushInventory(CInv(MSG_BLOCK, hashToAnnounce)); LogPrint("net", "%s: sending inv peer=%d hash=%s\n", __func__, pto->id, hashToAnnounce.ToString()); } } } else if (!vHeaders.empty()) { if (vHeaders.size() > 1) { LogPrint("net", "%s: %u headers, range (%s, %s), to peer=%d\n", __func__, vHeaders.size(), vHeaders.front().GetHash().ToString(), vHeaders.back().GetHash().ToString(), pto->id); } else { LogPrint("net", "%s: sending header %s to peer=%d\n", __func__, vHeaders.front().GetHash().ToString(), pto->id); } pto->PushMessage(NetMsgType::HEADERS, vHeaders); state.pindexBestHeaderSent = pBestIndex; } pto->vBlockHashesToAnnounce.clear(); } // // Message: inventory // vector<CInv> vInv; vector<CInv> vInvWait; { bool fSendTrickle = pto->fWhitelisted; if (pto->nNextInvSend < nNow) { fSendTrickle = true; pto->nNextInvSend = PoissonNextSend(nNow, AVG_INVENTORY_BROADCAST_INTERVAL); } LOCK(pto->cs_inventory); vInv.reserve(std::min<size_t>(1000, pto->vInventoryToSend.size())); vInvWait.reserve(pto->vInventoryToSend.size()); BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend) { if (inv.type == MSG_TX && pto->filterInventoryKnown.contains(inv.hash)) continue; // trickle out tx inv to protect privacy if (inv.type == MSG_TX && !fSendTrickle) { // 1/4 of tx invs blast to all immediately static uint256 hashSalt; if (hashSalt.IsNull()) hashSalt = GetRandHash(); uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt)); hashRand = Hash(BEGIN(hashRand), END(hashRand)); bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0); if (fTrickleWait) { LogPrint("net", "SendMessages -- queued inv(vInvWait): %s index=%d peer=%d\n", inv.ToString(), vInvWait.size(), pto->id); vInvWait.push_back(inv); continue; } } pto->filterInventoryKnown.insert(inv.hash); LogPrint("net", "SendMessages -- queued inv: %s index=%d peer=%d\n", inv.ToString(), vInv.size(), pto->id); vInv.push_back(inv); if (vInv.size() >= 1000) { LogPrint("net", "SendMessages -- pushing inv's: count=%d peer=%d\n", vInv.size(), pto->id); pto->PushMessage(NetMsgType::INV, vInv); vInv.clear(); } } pto->vInventoryToSend = vInvWait; } if (!vInv.empty()) { LogPrint("net", "SendMessages -- pushing tailing inv's: count=%d peer=%d\n", vInv.size(), pto->id); pto->PushMessage(NetMsgType::INV, vInv); } // Detect whether we're stalling nNow = GetTimeMicros(); if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) { // Stalling only triggers when the block download window cannot move. During normal steady state, // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection // should only happen during initial block download. LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id); pto->fDisconnect = true; } // In case there is a block that has been in flight from this peer for 2 + 0.5 * N times the block interval // (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout. // We compensate for other peers to prevent killing off peers due to our own downstream link // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes // to unreasonably increase our timeout. if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0) { QueuedBlock &queuedBlock = state.vBlocksInFlight.front(); int nOtherPeersWithValidatedDownloads = nPeersWithValidatedDownloads - (state.nBlocksInFlightValidHeaders > 0); if (nNow > state.nDownloadingSince + consensusParams.nPowTargetSpacing * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) { LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id); pto->fDisconnect = true; } } // // Message: getdata (blocks) // vector<CInv> vGetData; if (!pto->fDisconnect && !pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) { vector<CBlockIndex*> vToDownload; NodeId staller = -1; FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller); BOOST_FOREACH(CBlockIndex *pindex, vToDownload) { vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash())); MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex); LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(), pindex->nHeight, pto->id); } if (state.nBlocksInFlight == 0 && staller != -1) { if (State(staller)->nStallingSince == 0) { State(staller)->nStallingSince = nNow; LogPrint("net", "Stall started peer=%d\n", staller); } } } // // Message: getdata (non-blocks) // int64_t nFirst = -1; if(!pto->mapAskFor.empty()) { nFirst = (*pto->mapAskFor.begin()).first; } LogPrint("net", "SendMessages (mapAskFor) -- before loop: nNow = %d, nFirst = %d\n", nNow, nFirst); while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow) { const CInv& inv = (*pto->mapAskFor.begin()).second; LogPrint("net", "SendMessages (mapAskFor) -- inv = %s peer=%d\n", inv.ToString(), pto->id); if (!AlreadyHave(inv)) { if (fDebug) LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id); vGetData.push_back(inv); if (vGetData.size() >= 1000) { pto->PushMessage(NetMsgType::GETDATA, vGetData); vGetData.clear(); } } else { //If we're not going to ask, don't expect a response. LogPrint("net", "SendMessages -- already have inv = %s peer=%d\n", inv.ToString(), pto->id); pto->setAskFor.erase(inv.hash); } pto->mapAskFor.erase(pto->mapAskFor.begin()); } if (!vGetData.empty()) pto->PushMessage(NetMsgType::GETDATA, vGetData); } return true; } std::string CBlockFileInfo::ToString() const { return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst), DateTimeStrFormat("%Y-%m-%d", nTimeLast)); } ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos) { LOCK(cs_main); return VersionBitsState(chainActive.Tip(), params, pos, versionbitscache); } class CMainCleanup { public: CMainCleanup() {} ~CMainCleanup() { // block headers BlockMap::iterator it1 = mapBlockIndex.begin(); for (; it1 != mapBlockIndex.end(); it1++) delete (*it1).second; mapBlockIndex.clear(); // orphan transactions mapOrphanTransactions.clear(); mapOrphanTransactionsByPrev.clear(); } } instance_of_cmaincleanup;
[ "happymeal1316@gmail.com" ]
happymeal1316@gmail.com
a11aeda738a84bf5fb8e93be128ed507b8a821c3
ed0fb471daca59daa6255d75d4c68508e58e3454
/test/search/test_octree.cpp
eb65d405676eeb2f1b9bd14988029ad7153bd63e
[ "BSD-3-Clause" ]
permissive
mujin/pcl
ec9de205e1ee5940fd0a55a012733984a0bb1ff2
9a13da19c792ce1f9dfcb752bc92300f40270bec
refs/heads/master
2023-06-09T13:49:51.928549
2022-04-18T01:03:29
2022-04-18T01:03:29
32,294,758
4
2
NOASSERTION
2023-05-09T03:41:42
2015-03-16T01:43:16
C++
UTF-8
C++
false
false
12,881
cpp
/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, Willow Garage, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * 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 copyright holder(s) nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * */ #include <gtest/gtest.h> #include <vector> #include <stdio.h> #include <pcl/common/time.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/search/pcl_search.h> using namespace std; using namespace pcl; using namespace octree; // helper class for priority queue class prioPointQueueEntry { public: prioPointQueueEntry () { } prioPointQueueEntry (PointXYZ& point_arg, double pointDistance_arg, int pointIdx_arg) { point_ = point_arg; pointDistance_ = pointDistance_arg; pointIdx_ = pointIdx_arg; } bool operator< (const prioPointQueueEntry& rhs_arg) const { return (this->pointDistance_ < rhs_arg.pointDistance_); } PointXYZ point_; double pointDistance_;int pointIdx_; }; TEST (PCL, Octree_Pointcloud_Nearest_K_Neighbour_Search) { const unsigned int test_runs = 1; unsigned int test_id; // instantiate point cloud PointCloud<PointXYZ>::Ptr cloudIn (new PointCloud<PointXYZ> ()); size_t i; srand (static_cast<unsigned int> (time (NULL))); unsigned int K; std::priority_queue<prioPointQueueEntry, pcl::PointCloud<prioPointQueueEntry>::VectorType> pointCandidates; // create octree pcl::search::Search<PointXYZ>* octree = new pcl::search::Octree<PointXYZ> (0.1); std::vector<int> k_indices; std::vector<float> k_sqr_distances; std::vector<int> k_indices_bruteforce; std::vector<float> k_sqr_distances_bruteforce; for (test_id = 0; test_id < test_runs; test_id++) { // define a random search point PointXYZ searchPoint (static_cast<float> (10.0 * (rand () / static_cast<double> (RAND_MAX))), static_cast<float> (10.0 * (rand () / static_cast<double> (RAND_MAX))), static_cast<float> (10.0 * (rand () / static_cast<double> (RAND_MAX)))); K = 1 + rand () % 10; // generate point cloud cloudIn->width = 1000; cloudIn->height = 1; cloudIn->points.resize (cloudIn->width * cloudIn->height); for (i = 0; i < 1000; i++) { cloudIn->points[i] = PointXYZ (static_cast<float> (5.0 * (rand () / static_cast<double> (RAND_MAX))), static_cast<float> (10.0 * (rand () / static_cast<double> (RAND_MAX))), static_cast<float> (10.0 * (rand () / static_cast<double> (RAND_MAX)))); } double pointDist; k_indices.clear (); k_sqr_distances.clear (); k_indices_bruteforce.clear (); k_sqr_distances_bruteforce.clear (); // push all points and their distance to the search point into a priority queue - bruteforce approach. for (i = 0; i < cloudIn->points.size (); i++) { pointDist = ((cloudIn->points[i].x - searchPoint.x) * (cloudIn->points[i].x - searchPoint.x) + (cloudIn->points[i].y - searchPoint.y) * (cloudIn->points[i].y - searchPoint.y) + (cloudIn->points[i].z - searchPoint.z) * (cloudIn->points[i].z - searchPoint.z)); prioPointQueueEntry pointEntry (cloudIn->points[i], pointDist, static_cast<int> (i)); pointCandidates.push (pointEntry); } // pop priority queue until we have the nearest K elements while (pointCandidates.size () > K) pointCandidates.pop (); // copy results into vectors unsigned idx = static_cast<unsigned> (pointCandidates.size ()); k_indices_bruteforce.resize (idx); k_sqr_distances_bruteforce.resize (idx); while (pointCandidates.size ()) { --idx; k_indices_bruteforce [idx] = pointCandidates.top ().pointIdx_; k_sqr_distances_bruteforce [idx] = static_cast<float> (pointCandidates.top ().pointDistance_); pointCandidates.pop (); } // octree nearest neighbor search octree->setInputCloud (cloudIn); octree->nearestKSearch (searchPoint, static_cast<int> (K), k_indices, k_sqr_distances); ASSERT_EQ ( k_indices.size() , k_indices_bruteforce.size() ); // compare nearest neighbor results of octree with bruteforce search i = 0; while (k_indices_bruteforce.size ()) { ASSERT_EQ ( k_indices.back() , k_indices_bruteforce.back() ); EXPECT_NEAR (k_sqr_distances.back(), k_sqr_distances_bruteforce.back(), 1e-4); k_indices_bruteforce.pop_back(); k_indices.pop_back(); k_sqr_distances_bruteforce.pop_back(); k_sqr_distances.pop_back(); } } } #if 0 TEST (PCL, Octree_Pointcloud_Approx_Nearest_Neighbour_Search) { const unsigned int test_runs = 100; unsigned int test_id; unsigned int bestMatchCount = 0; // instantiate point cloud PointCloud<PointXYZ>::Ptr cloudIn (new PointCloud<PointXYZ> ()); size_t i; srand (time (NULL)); double voxelResolution = 0.1; // create octree pcl::search::Search<PointXYZ>* octree = new pcl::search::Octree<PointXYZ> (voxelResolution); for (test_id = 0; test_id < test_runs; test_id++) { // define a random search point PointXYZ searchPoint (10.0 * ((double)rand () / (double)RAND_MAX), 10.0 * ((double)rand () / (double)RAND_MAX), 10.0 * ((double)rand () / (double)RAND_MAX)); // generate point cloud cloudIn->width = 1000; cloudIn->height = 1; cloudIn->points.resize (cloudIn->width * cloudIn->height); for (i = 0; i < 1000; i++) cloudIn->points[i] = PointXYZ (5.0 * ((double)rand () / (double)RAND_MAX), 10.0 * ((double)rand () / (double)RAND_MAX), 10.0 * ((double)rand () / (double)RAND_MAX)); // brute force search double pointDist; double BFdistance = numeric_limits<double>::max (); int BFindex = 0; for (i = 0; i < cloudIn->points.size (); i++) { pointDist = ((cloudIn->points[i].x - searchPoint.x) * (cloudIn->points[i].x - searchPoint.x) + (cloudIn->points[i].y - searchPoint.y) * (cloudIn->points[i].y - searchPoint.y) + (cloudIn->points[i].z - searchPoint.z) * (cloudIn->points[i].z - searchPoint.z)); if (pointDist < BFdistance) { BFindex = i; BFdistance = pointDist; } } int ANNindex; float ANNdistance; octree->setInputCloud (cloudIn); octree->approxNearestSearch (searchPoint, ANNindex, ANNdistance); if (BFindex == ANNindex) { EXPECT_NEAR (ANNdistance, BFdistance, 1e-4); bestMatchCount++; } } // we should have found the absolute nearest neighbor at least once //ASSERT_EQ ( (bestMatchCount > 0) , true); } #endif #if 0 TEST (PCL, Octree_RadiusSearch_GPU) { PointCloud<PointXYZ>::Ptr cloudIn (new PointCloud<PointXYZ> ()); // generate point cloud data cloudIn->width = 1000; cloudIn->height = 1; cloudIn->points.resize (cloudIn->width * cloudIn->height); int i=0; for (i = 0; i < 1000; i++) { cloudIn->points[i] = PointXYZ (10.0 * ((double)rand () / (double)RAND_MAX), 10.0 * ((double)rand () / (double)RAND_MAX), 5.0 * ((double)rand () / (double)RAND_MAX)); } Search<PointXYZ>* octree = new pcl::octree::OctreeWrapper<PointXYZ>(0.1f); octree->setInputCloud(cloudIn); std::vector <PointXYZ > point; const PointXYZ searchPoint (10.0 * ((double)rand () / (double)RAND_MAX), 10.0 * ((double)rand () / (double)RAND_MAX), 10.0 * ((double)rand () / (double)RAND_MAX)); point.push_back(searchPoint); point.push_back(searchPoint); point.push_back(searchPoint); double searchRadius = 5.0 * ((double)rand () / (double)RAND_MAX); double radius =5; vector < double > radiuses; radiuses.push_back(radius); radiuses.push_back(radius); radiuses.push_back(radius); std::vector<std::vector<int> > k_indices; std::vector<std::vector<float> > k_distances; int max_nn = -1; octree->radiusSearch (point, radiuses, k_indices,k_distances,max_nn ); } #endif TEST (PCL, Octree_Pointcloud_Neighbours_Within_Radius_Search) { const unsigned int test_runs = 100; unsigned int test_id; // instantiate point clouds PointCloud<PointXYZ>::Ptr cloudIn (new PointCloud<PointXYZ> ()); PointCloud<PointXYZ>::Ptr cloudOut (new PointCloud<PointXYZ> ()); size_t i; srand (static_cast<unsigned int> (time (NULL))); for (test_id = 0; test_id < test_runs; test_id++) { // define a random search point PointXYZ searchPoint (static_cast<float> (10.0 * (rand () / static_cast<double> (RAND_MAX))), static_cast<float> (10.0 * (rand () / static_cast<double> (RAND_MAX))), static_cast<float> (10.0 * (rand () / static_cast<double> (RAND_MAX)))); cloudIn->width = 1000; cloudIn->height = 1; cloudIn->points.resize (cloudIn->width * cloudIn->height); // generate point cloud data for (i = 0; i < 1000; i++) { cloudIn->points[i] = PointXYZ (static_cast<float> (10.0 * (rand () / static_cast<double> (RAND_MAX))), static_cast<float> (10.0 * (rand () / static_cast<double> (RAND_MAX))), static_cast<float> (5.0 * (rand () / static_cast<double> (RAND_MAX)))); } pcl::search::Search<PointXYZ>* octree = new pcl::search::Octree<PointXYZ> (0.001); // build octree double pointDist; double searchRadius = 5.0 * rand () / static_cast<double> (RAND_MAX); // bruteforce radius search vector<int> cloudSearchBruteforce; for (i = 0; i < cloudIn->points.size (); i++) { pointDist = sqrt ( (cloudIn->points[i].x - searchPoint.x) * (cloudIn->points[i].x - searchPoint.x) + (cloudIn->points[i].y - searchPoint.y) * (cloudIn->points[i].y - searchPoint.y) + (cloudIn->points[i].z - searchPoint.z) * (cloudIn->points[i].z - searchPoint.z)); if (pointDist <= searchRadius) { // add point candidates to vector list cloudSearchBruteforce.push_back (static_cast<int> (i)); } } vector<int> cloudNWRSearch; vector<float> cloudNWRRadius; // execute octree radius search octree->setInputCloud (cloudIn); octree->radiusSearch (searchPoint, searchRadius, cloudNWRSearch, cloudNWRRadius); ASSERT_EQ ( cloudNWRRadius.size() , cloudSearchBruteforce.size()); // check if result from octree radius search can be also found in bruteforce search std::vector<int>::const_iterator current = cloudNWRSearch.begin(); while (current != cloudNWRSearch.end()) { pointDist = sqrt ( (cloudIn->points[*current].x-searchPoint.x) * (cloudIn->points[*current].x-searchPoint.x) + (cloudIn->points[*current].y-searchPoint.y) * (cloudIn->points[*current].y-searchPoint.y) + (cloudIn->points[*current].z-searchPoint.z) * (cloudIn->points[*current].z-searchPoint.z) ); ASSERT_EQ ( (pointDist<=searchRadius) , true); ++current; } // check if result limitation works octree->radiusSearch(searchPoint, searchRadius, cloudNWRSearch, cloudNWRRadius, 5); ASSERT_EQ ( cloudNWRRadius.size() <= 5, true); } } /* ---[ */ int main (int argc, char** argv) { testing::InitGoogleTest (&argc, argv); return (RUN_ALL_TESTS ()); } /* ]--- */
[ "radu.b.rusu@gmail.com" ]
radu.b.rusu@gmail.com
9ffbd418b8d96fad558b35d35e8f22e065b4723c
6ea6691636a1a5072f12efe0aad9d778d32f126c
/OGLplus_build/implement/oglplus/enums/buffer_target_range.ipp
fccddc9672b3cc41fbb30eec2e5e588832b93bfa
[ "BSL-1.0" ]
permissive
pm990320/OpenGLLearning
6c63234da5f00193bf3799ee4b97b16bd14cdc6b
d4f83a047dbfe816631d59ea1115176514d9fad6
refs/heads/master
2021-01-10T06:21:34.592102
2014-07-04T10:42:52
2014-07-04T10:42:52
54,271,323
1
0
null
null
null
null
UTF-8
C++
false
false
1,903
ipp
/* * .file oglplus/enums/buffer_target_range.ipp * * Automatically generated header file. DO NOT modify manually, * edit 'source/enums/oglplus/buffer_target.txt' instead. * * Copyright 2010-2014 Matus Chochlik. 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) */ namespace enums { OGLPLUS_LIB_FUNC aux::CastIterRange< const GLenum*, BufferTarget > ValueRange_(BufferTarget*) #if (!OGLPLUS_LINK_LIBRARY || defined(OGLPLUS_IMPLEMENTING_LIBRARY)) && \ !defined(OGLPLUS_IMPL_EVR_BUFFERTARGET) #define OGLPLUS_IMPL_EVR_BUFFERTARGET { static const GLenum _values[] = { #if defined GL_ARRAY_BUFFER GL_ARRAY_BUFFER, #endif #if defined GL_ATOMIC_COUNTER_BUFFER GL_ATOMIC_COUNTER_BUFFER, #endif #if defined GL_COPY_READ_BUFFER GL_COPY_READ_BUFFER, #endif #if defined GL_COPY_WRITE_BUFFER GL_COPY_WRITE_BUFFER, #endif #if defined GL_DISPATCH_INDIRECT_BUFFER GL_DISPATCH_INDIRECT_BUFFER, #endif #if defined GL_DRAW_INDIRECT_BUFFER GL_DRAW_INDIRECT_BUFFER, #endif #if defined GL_ELEMENT_ARRAY_BUFFER GL_ELEMENT_ARRAY_BUFFER, #endif #if defined GL_PIXEL_PACK_BUFFER GL_PIXEL_PACK_BUFFER, #endif #if defined GL_PIXEL_UNPACK_BUFFER GL_PIXEL_UNPACK_BUFFER, #endif #if defined GL_SHADER_STORAGE_BUFFER GL_SHADER_STORAGE_BUFFER, #endif #if defined GL_TEXTURE_BUFFER GL_TEXTURE_BUFFER, #endif #if defined GL_TRANSFORM_FEEDBACK_BUFFER GL_TRANSFORM_FEEDBACK_BUFFER, #endif #if defined GL_UNIFORM_BUFFER GL_UNIFORM_BUFFER, #endif #if defined GL_QUERY_BUFFER GL_QUERY_BUFFER, #endif #if defined GL_PARAMETER_BUFFER_ARB GL_PARAMETER_BUFFER_ARB, #endif #if defined GL_EXTERNAL_VIRTUAL_MEMORY_BUFFER_AMD GL_EXTERNAL_VIRTUAL_MEMORY_BUFFER_AMD, #endif 0 }; return aux::CastIterRange< const GLenum*, BufferTarget >(_values, _values+sizeof(_values)/sizeof(_values[0])-1); } #else ; #endif } // namespace enums
[ "patmenlove@gmail.com" ]
patmenlove@gmail.com
fbd2f6cf1dfdc63ad73984eb8238aaa933438005
115bbe1de6e32f09b1f36829eb046ed261527897
/4.21.cpp
1d03d56286c116af46d697e7358d68fd26b31a57
[]
no_license
Rani-Zz/cppPrimer
8c8283dbfd90af1a06c7fef5984d108b455262bc
5c65446648665e7b1d316907f792485dc32d8b80
refs/heads/master
2020-03-28T19:27:44.128711
2019-01-25T04:29:54
2019-01-25T04:29:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
311
cpp
#include<iostream> #include<string> #include<vector> #include "Sales_item.h" using namespace std; int main() { vector<int> vec{ 1,2,3,4,5,6 }; for (auto &i : vec) { i = i % 2 == 0 ? i * 2 : i; } for (auto it = vec.begin(); it != vec.end(); ++it) { cout << *it << " "; } cout << endl; return 0; }
[ "850150293@qq.com" ]
850150293@qq.com
9ce8448f82ea71111be290942e6cfe3ecb16510d
84c46ac1bb139e0fabcb22e3088a8b82f60a14ac
/firstperson/Game.cpp
4c31da829540ed76a5ce53366553f8cacef0d4fa
[]
no_license
sho3la/Opengl-Game4
9c7b1c01db8500d7abcbc2c365d92fbd07f631e9
3b08beb9b53b011a7ff6b271c6864635173569b9
refs/heads/master
2021-01-21T11:30:24.280844
2017-05-18T22:30:19
2017-05-18T22:30:19
91,744,389
2
1
null
null
null
null
UTF-8
C++
false
false
6,828
cpp
#include"Game.h" #include "Geometry.h" #include "OGL.h" #include <glm.hpp> #include <iostream> #include "Helper.h" using namespace std; using namespace glm; GLFWwindow* wind; //init,,, Game::Game() { auto windowpos = OGL::get()->getWindowSize(); OGL::get()->setMousePosition(windowpos.x/2,windowpos.y/2); //_turnOnMouseCamera = false; wind = OGL::get()->getwindow(); _Shader = std::make_shared<Shader>("Model.vertexshader", "Model.fragmentshader"); auto _skyboxShader = std::make_shared<Shader>("Skybox.vertexshader", "Skybox.fragmentshader"); sky.setShader(_skyboxShader); _ground = new Ground(20,20); _walls = Ground::loadFile("res/map.txt"); enemylight.intensity = 1; enemylight.color = vec3(1,0,1); enemylight.position = vec3(0,3,0); playerLight.position = camera.getPosition(); playerLight.intensity = 1; playerLight.color = vec3(1,1,1); enemyPosition = vec3(2.25,1.6,15.4); enemyPosTarget = enemyPosition; monsterRotate = vec3(-90,0,180); model_m = glm::translate(enemyPosition) * glm::rotate(-90.0f,vec3(1.0f,0.0f,0.0f)) *glm::rotate(180.0f,vec3(0.0f,0.0f,1.0f)) * glm::scale(vec3(0.025f,0.025f,0.025f)); //load model file.. mymodel.LoadModel("res/drfreak/drfreak.md2"); //set curent animation to play.. model_anim_state = mymodel.StartAnimation(animType_t::CROUCH_WALK); //load animation shader. animatedModelShader.LoadProgram(); camera.setPosition(vec3(0.5,1.76,0.5)); bul = new Bullet(_Shader); bulletLight.color = vec3(0,1,1); bulletLight.intensity = 1; bulletLight.position = vec3(50,50,0); //very high point } Game::~Game() { delete _ground; delete _walls; delete bul; } void Game::setupShaderUniforms(ShaderPtr shdr) { shdr->setUniform("TxSampler",0); shdr->setUniform("NrmSampler",1); shdr->setUniform("ViewMatrix",camera.getViewMatrix()); //do the lights here shdr->setUniform("eyePos",camera.getPosition()); shdr->setUniform("playerLightPosition",playerLight.position); shdr->setUniform("playerLightColor",playerLight.color); shdr->setUniform("playerLightIntensity",playerLight.intensity); shdr->setUniform("monsterLightPosition",enemylight.position); shdr->setUniform("monsterLightColor",enemylight.color); shdr->setUniform("monsterLightIntensity",enemylight.intensity); shdr->setUniform("BulletLightPosition",bulletLight.position); shdr->setUniform("BulletLightColor",bulletLight.color); shdr->setUniform("BulletLightIntensity",bulletLight.intensity); } void Game::update(double delta) { cameraMouseMovement(0,0); //moving the light with the camera. enemylight.position = enemyPosition; playerLight.position = camera.getPosition(); if(bul->fired) bulletLight.position = bul->getpos(); mymodel.UpdateAnimation(&model_anim_state,delta / 1000); enemyMovment(); auto mmx = glm::rotate(monsterRotate.x,vec3(1,0,0)); auto mmy = glm::rotate(monsterRotate.y,vec3(0,1,0)); auto mmz = glm::rotate(monsterRotate.z,vec3(0,0,1)); auto mmr = mmx*mmy*mmz; model_m = glm::translate(enemyPosition) * mmr * glm::scale(vec3(0.025f,0.025f,0.025f)); if( glfwGetKey(wind, GLFW_KEY_W)) { camera.Walk(0.1); if(_walls->Collide(camera.getPosition())) camera.Walk(-0.1); } if( glfwGetKey(wind, GLFW_KEY_S)) { camera.Walk(-0.1); if(_walls->Collide(camera.getPosition())) camera.Walk(0.1); } if( glfwGetKey(wind, GLFW_KEY_A)) { camera.Strafe(-0.1); if(_walls->Collide(camera.getPosition())) camera.Strafe(0.1); } if( glfwGetKey(wind, GLFW_KEY_D)) { camera.Strafe(0.1); if(_walls->Collide(camera.getPosition())) camera.Strafe(-0.1); } if( glfwGetKey(wind, GLFW_KEY_ESCAPE)) { OGL::get()->shutdown(); } if( glfwGetKey(wind, GLFW_KEY_SPACE)) { bul->Setpos(glm::vec3(camera.getPosition().x,1.6,camera.getPosition().z)); bul->setDir(camera.getLookDirection()); bul->fired = true; } // prevent camera to move on y axis just xz plane.. if(camera.getPosition().y > 1.76 || camera.getPosition().y < 1.76 ) { camera.setPosition(glm::vec3(camera.getPosition().x, 1.76 , camera.getPosition().z)); } if(bul->Collide(enemyPosition) && bul->fired) { system("cls"); printf("\n"); printf(" YOU WIN ^____^ \n"); printf("\n"); OGL::get()->shutdown(); } bul->Update(); camera.updateViewMatrix(); } void Game::render() { glm::mat4 VP = camera.getProjectionMatrix()*camera.getViewMatrix(); sky.draw(VP); _ground->draw(VP); _walls->draw(VP); bul->draw(VP); animatedModelShader.UseProgram(); animatedModelShader.BindVPMatrix(&VP[0][0]); animatedModelShader.BindModelMatrix(&model_m[0][0]); mymodel.RenderModel(&model_anim_state,&animatedModelShader); } void Game::enemyMovment() { int rnd = rand()%4; vec3 bpos = enemyPosition; if(enemyPosTarget == enemyPosition) { if(rnd == 1) { enemyPosTarget.x += 1; enemyDirection = Direction::NORTH; monsterRotate.z = 0; }else if(rnd==2) { enemyPosTarget.x -= 1; enemyDirection = Direction::SOUTH; monsterRotate.z = 180; }else if(rnd==3) { enemyPosTarget.z += 1; enemyDirection = Direction::EAST; monsterRotate.z = 270; }else if(rnd==0){ enemyPosTarget.z -= 1; enemyDirection = Direction::WEST; monsterRotate.z = 90; } if(_walls->Collide(enemyPosTarget)) enemyPosTarget = enemyPosition; //bpos = monsterPosTarget; }else{ if(enemyDirection == Direction::NORTH){ bpos.x += 0.05; }else if(enemyDirection == Direction::SOUTH){ bpos.x -= 0.05; }else if(enemyDirection == Direction::EAST){ bpos.z += 0.05; }else if(enemyDirection == Direction::WEST){ bpos.z -= 0.05; } } enemyPosition = bpos; if(_walls->Collide(bpos)){ enemyPosTarget = enemyPosition; if(enemyDirection == Direction::NORTH){ enemyPosTarget.x -= 0.5; }else if(enemyDirection == Direction::SOUTH){ enemyPosTarget.x += 0.5; }else if(enemyDirection == Direction::EAST){ enemyPosTarget.z -= 0.5; }else if(enemyDirection == Direction::WEST){ enemyPosTarget.z += 0.5; } enemyPosition = enemyPosTarget; }else{ } } void Game::handleMouseMotion(GLFWwindow* window,int x, int y) { mousePosition = vec2(x,y); } void Game::cameraMouseMovement(int x, int y) { auto windowSize = OGL::get()->getWindowSize(); if (mousePosition.x != windowSize.x/2 || mousePosition.y != windowSize.y/2) { double mouseSpeed = 0.005; //it is just there to speed up or slow down the movements. double movedDistanceX; double movedDistanceY; movedDistanceX = double(windowSize.x/2 - mousePosition.x)*mouseSpeed; movedDistanceY = double(windowSize.y/2 - mousePosition.y)*mouseSpeed; camera.Yaw(movedDistanceX); camera.Pitch(movedDistanceY); camera.updateViewMatrix(); mousePosition.x = windowSize.x/2; mousePosition.y = windowSize.y/2; OGL::get()->setMousePosition(mousePosition.x,mousePosition.y); } }
[ "mohamed_sh3lan61@yahoo.com" ]
mohamed_sh3lan61@yahoo.com
db389deb5b73330cf8559af0f7a1cbf0fd304734
bf5a2f114426fcdad8996684985330e91c2592ec
/archives/乐学archive/2019年数据结构与算法设计A(C++描述)/39 图书系统.cpp
20adf72b943ba99cb2880a3922a3e97b6116a482
[ "Unlicense" ]
permissive
everything411/BIT_Exercises
9e0c02a724bfd2fa58424a3cbab04ab2b537db51
2d0e31dca2b9607dce0bb43340ebeaa2c42c4a43
refs/heads/master
2021-06-03T10:06:22.259395
2020-06-05T03:07:24
2020-06-05T03:07:24
153,399,890
0
0
null
null
null
null
UTF-8
C++
false
false
1,455
cpp
#include <iostream> using namespace std; // 书号、书名、出版社和定价 struct book { int id; char name[100]; char publisher[100]; double price; void book_in(void) { scanf("%d%s%s%lf", &id, name, publisher, &price); } void book_out(void) { printf("Num:%d\nBookName:%s\nBookConcern:%s\nPrice:", id, name, publisher); cout << price << endl; } // book(/* args */); // ~book(); }; // 姓名、年龄和写作时间 struct author { char name[100]; int age; int year; int month; int day; void author_in(void) { scanf("%s%d%d%d%d", name, &age, &year, &month, &day); } void author_out(void) { printf("AuthorName:%s\nAuthorAge:%d\nPrintTime:%d-%d-%d\n", name, age, year, month, day); // cout << price << endl; } // author(/* args */); // ~author(); }; // 书籍系统名称,及一个可以显示系统名称、书名、作者、作者年龄、出版社和定价等数据的函数 struct book_sys : book, author { char sys_name[100]; void sys_in(void) { scanf("%s", sys_name); book_in(); author_in(); } void sys_out(void) { printf("SysName:%s\n", sys_name); book_out(); author_out(); } // book_sys(/* args */); // ~book_sys(); }; int main(void) { book_sys demo; demo.sys_in(); demo.sys_out(); return 0; }
[ "everything411@163.com" ]
everything411@163.com
0ee3edee114420d19322429f3d130525780a6e69
182322f4f2800f851754bb1bcb85fd4f9fc324ea
/pcca/2016winter/cf_gym_100324/pd.cpp
28462d509eb9db5868950fef41633ec52a939283
[]
no_license
Tocknicsu/oj
66100fe94d76b6fe8d1bd3019f5ada9d686c1753
e84d6c87f3e8c0443a27e8efc749ea4b569a6c91
refs/heads/master
2021-01-17T08:12:32.510731
2016-04-18T02:09:04
2016-04-18T02:09:16
32,704,322
2
1
null
null
null
null
UTF-8
C++
false
false
838
cpp
#include <bits/stdc++.h> using namespace std; string start, _end; unordered_set<string> m; bool dfs(string now, int depth){ if(now == _end) return true; if(depth == 4){ return false; } else { for(int i = 0 ; i < (int)now.size() ; i++){ for(int j = i + 2; j < (int)now.size() ; j++){ string a = now.substr(0, i); string b = now.substr(i, j - i); string c = now.substr(j, now.size() - j); reverse(b.begin(), b.end()); if(dfs(a + b + c, depth+1)){ return true; } } } return false; } } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cin >> start >> _end; cout << (dfs(start, 0)?"Similar":"Different") << endl; return 0; }
[ "wingemerald@gmail.com" ]
wingemerald@gmail.com
e362c18003f73e45662625ba8c7d8c0f12d9d93e
2d5052e3781102e63f787d5c30ecf6218b1ae6a2
/AlliedUITest/AlliedUITest/src/AlliedUI/AlliedUIDefine.h
8cbc2ba2bb950f8041a09115d15cedad9d0d750e
[]
no_license
bvhoang91/hoang-hiep
d0b25af172241030d2fcc0b13de62adad967dd47
a734fa9fc10188652606253879cb91c9397cc264
refs/heads/master
2021-01-02T22:57:02.764557
2017-08-05T15:14:58
2017-08-05T15:14:58
99,430,055
0
0
null
null
null
null
UTF-8
C++
false
false
647
h
#pragma once #include "windef.h" namespace AlliedUI { enum enBorderStyle { BORDER_STYLE_NORMAL = 0, BORDER_STYLE_DOT, BORDER_STYLE_DASH, BORDER_STYLE_DASH_DOT }; typedef struct BorderColor { COLORREF top; COLORREF left; COLORREF right; COLORREF bottom; } BorderColor; typedef struct BorderRadius { int topleft; int topright; int bottomleft; int bottomright; } BorderRadius; typedef struct BorderWidth { int top; int left; int right; int bottom; } BorderWidth; typedef struct BorderStyle { enBorderStyle top; enBorderStyle left; enBorderStyle right; enBorderStyle bottom; } BorderStyle; }
[ "bvhoang91@gmail.com" ]
bvhoang91@gmail.com
8e9aa0ee11235184f98e22d39cb05e823b85192f
3d14f17273aa51c7e8c1403a8b1d53175941d0f1
/depends/storage/src/storage/common/bloom-filter.h
726cbea6af39b75f0612281e900c98e41e9f1535
[ "LicenseRef-scancode-unknown", "MIT", "BSD-4-Clause-UC", "BSD-3-Clause", "ISC", "bzip2-1.0.6", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "BSD-4-Clause", "Artistic-2.0", "PostgreSQL" ]
permissive
chiyang10000/hawq
3341d705aa0b6922a6439b71bb09fced7d890066
74ce659bc0696faa8bb7f6943931f5a4f4daf2af
refs/heads/master
2023-03-26T13:37:56.325334
2021-03-16T03:54:44
2021-03-17T05:33:31
110,235,661
0
0
Apache-2.0
2021-03-02T07:16:11
2017-11-10T10:37:11
C
UTF-8
C++
false
false
5,564
h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #ifndef STORAGE_SRC_STORAGE_COMMON_BLOOM_FILTER_H_ #define STORAGE_SRC_STORAGE_COMMON_BLOOM_FILTER_H_ #include <algorithm> #include <cassert> #include <cmath> #include "dbcommon/hash/fast-hash.h" namespace storage { class MyBitSet { public: explicit MyBitSet(int64_t bits) : ownData(true) { length = static_cast<int64_t>( ceil(static_cast<double>(bits) / static_cast<double>(64))); data = new uint64_t[length]; clear(); } MyBitSet(uint64_t *data, int64_t size) : data(data), length(size) { assert(data != nullptr && length > 0); } ~MyBitSet() { if (ownData) { delete data; } } typedef std::unique_ptr<MyBitSet> uptr; void set(int64_t index) { assert(index >= 0); data[index >> 6] |= (1L << index); } bool get(int64_t index) { assert(index >= 0); return (data[index >> 6] & (1L << index)) != 0; } uint64_t *getData() { return data; } int64_t size() { return length; } void clear() { memset(data, 0, size() * 8); } private: uint64_t *data = nullptr; int64_t length = 0; bool ownData = false; }; class BloomFilter { public: explicit BloomFilter(int64_t expectedEntry) : kExpectedEntry(expectedEntry) { assert(kExpectedEntry > 0 && "expectedEntries should be > 0"); assert(kDefaultFpp > 0.0 && kDefaultFpp < 1.0 && "False positive probability should be > 0.0 & < 1.0"); int64_t nb = optimalNumOfBits(kExpectedEntry, kDefaultFpp); numBits = nb + 64 - (nb % 64); numHashFunctions = optimalNumOfHashFunctions(kExpectedEntry, numBits); bitSet.reset(new MyBitSet(numBits)); } BloomFilter(uint64_t *bits, int64_t size, uint32_t numFuncs) { bitSet.reset(new MyBitSet(bits, size)); numBits = size * 64; numHashFunctions = numFuncs; } virtual ~BloomFilter() {} typedef std::unique_ptr<BloomFilter> uptr; void addInt(int64_t val) { addHash(getIntegerHash(val)); } bool testInt(int64_t val) { return testHash(getIntegerHash(val)); } void addDouble(double val) { addInt(doubleToRawBits(val)); } bool testDouble(double val) { return testInt(doubleToRawBits(val)); } void addString(const char *buffer, uint64_t len) { int64_t hash64 = static_cast<int64_t>(murmur3.hash64(buffer, len)); addHash(hash64); } bool testString(const char *buffer, uint64_t len) { int64_t hash64 = static_cast<int64_t>(murmur3.hash64(buffer, len)); return testHash(hash64); } uint64_t *getBitSet() { return bitSet->getData(); } int64_t size() { return bitSet->size(); } void reset() { bitSet->clear(); } uint32_t getNumHashFunctions() { return numHashFunctions; } private: int64_t optimalNumOfBits(int64_t n, double p) { auto ln2 = std::log(2); return static_cast<int64_t>(std::ceil(-(n * std::log(p) / ln2 / ln2))); } uint32_t optimalNumOfHashFunctions(int64_t n, int64_t m) { auto frac = static_cast<double>(m) / static_cast<double>(n); return static_cast<uint32_t>(std::ceil(frac * std::log(2))); } int64_t getIntegerHash(int64_t key) { key = (~key) + (key << 21); // key = (key << 21) - key - 1; key = key ^ (key >> 24); key = (key + (key << 3)) + (key << 8); // key * 265 key = key ^ (key >> 14); key = (key + (key << 2)) + (key << 4); // key * 21 key = key ^ (key >> 28); key = key + (key << 31); return key; } void addHash(int64_t hash64) { int64_t hash1 = hash64; int64_t hash2 = static_cast<int64_t>(static_cast<uint64_t>(hash64) >> 32); for (uint32_t i = 1; i <= numHashFunctions; ++i) { int64_t combinedHash = hash1 + (i * hash2); // hashcode should be positive, flip all the bits if it's negative if (combinedHash < 0) { combinedHash = ~combinedHash; } int64_t pos = combinedHash % numBits; bitSet->set(pos); } } bool testHash(int64_t hash64) { int64_t hash1 = hash64; int64_t hash2 = static_cast<int64_t>(static_cast<uint64_t>(hash64) >> 32); for (uint32_t i = 1; i <= numHashFunctions; ++i) { int64_t combinedHash = hash1 + (i * hash2); // hashcode should be positive, flip all the bits if it's negative if (combinedHash < 0) { combinedHash = ~combinedHash; } int64_t pos = combinedHash % numBits; if (!bitSet->get(pos)) { return false; } } return true; } int64_t doubleToRawBits(double val) { int64_t bits; memcpy(&bits, &val, sizeof(bits)); return bits; } private: int64_t numBits = 0; uint32_t numHashFunctions = 0; int64_t kExpectedEntry = 0; MyBitSet::uptr bitSet = nullptr; const double kDefaultFpp = 0.05; dbcommon::Murmur3 murmur3; }; } // namespace storage #endif // STORAGE_SRC_STORAGE_COMMON_BLOOM_FILTER_H_
[ "huor@apache.org" ]
huor@apache.org
3fcbc2fb8ed8d9dad5719a11495470cbea20b9ac
575c78d3b7a2fe90f4f0624d963bd6111dfca309
/deps/libIGL/tests/include/igl/is_irregular_vertex.cpp
843f81d14e9be1c5e105a6419b20be4d7e6a0101
[ "GPL-3.0-only", "MPL-2.0", "MIT" ]
permissive
g-gisbert/Inpainting-Holes-In-Folded-Fabric-Meshes
1898a35a848f9f16a99653c7c1e95ab0941755cd
ccce75215b742a1c971008c4f1a889bd85b6c74d
refs/heads/main
2023-08-19T08:49:47.829392
2023-08-18T13:55:11
2023-08-18T13:55:11
648,992,474
5
2
MIT
2023-07-21T15:34:49
2023-06-03T12:45:00
C++
UTF-8
C++
false
false
537
cpp
#include <test_common.h> #include <igl/is_irregular_vertex.h> TEST_CASE("is_irregular_vertex: simple", "[igl]") { Eigen::MatrixXd V; Eigen::MatrixXi F; // Known "bad" mesh (many boundaries + irregular vertices, non-manifold) igl::read_triangle_mesh(test_common::data_path("truck.obj"), V, F); std::vector<bool> vec = igl::is_irregular_vertex(V,F); // some vertices are irregular thus the sum over all vertices should evaluate to true REQUIRE(std::any_of(vec.begin(),vec.end(), [](bool v) { return v; })); }
[ "gisbert.guillaume1997@gmail.com" ]
gisbert.guillaume1997@gmail.com
68a79591d6ade01288cf16fc6bb0476557e163f8
c3e1fce7a720bb66a3814123727b6f835b54c8fd
/src/voglcore/vogl_jpgd.h
70008c15915e2541cd83288e35ce607ae7340098
[ "MIT" ]
permissive
isabella232/vogl
6df37b32eb5c484a461b50eb50b75f2a95ffb733
172a86d9c4ee08dccbf4e342caa1ba63f1ea2b0e
refs/heads/master
2022-04-18T21:11:14.760227
2014-03-14T21:55:20
2014-03-14T21:55:20
482,027,147
0
0
MIT
2022-04-16T02:59:09
2022-04-15T16:59:45
null
UTF-8
C++
false
false
16,519
h
/************************************************************************** * * Copyright 2013-2014 RAD Game Tools and Valve Software * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC * All Rights Reserved. * * 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. * **************************************************************************/ // jpgd.h - C++ class for JPEG decompression. // Public domain, Rich Geldreich <richgel99@gmail.com> #ifndef JPEG_DECODER_H #define JPEG_DECODER_H #include "vogl_core.h" #include <stdlib.h> #include <stdio.h> #include <setjmp.h> #ifdef _MSC_VER #define JPGD_NORETURN __declspec(noreturn) #elif defined(__GNUC__) #define JPGD_NORETURN __attribute__((noreturn)) #else #define JPGD_NORETURN #endif namespace jpgd { typedef unsigned char uint8; typedef signed short int16; typedef unsigned short uint16; typedef unsigned int uint; typedef signed int int32; // Loads a JPEG image from a memory buffer or a file. // req_comps can be 1 (grayscale), 3 (RGB), or 4 (RGBA). // On return, width/height will be set to the image's dimensions, and actual_comps will be set to the either 1 (grayscale) or 3 (RGB). // Notes: For more control over where and how the source data is read, see the decompress_jpeg_image_from_stream() function below, or call the jpeg_decoder class directly. // Requesting a 8 or 32bpp image is currently a little faster than 24bpp because the jpeg_decoder class itself currently always unpacks to either 8 or 32bpp. unsigned char *decompress_jpeg_image_from_memory(const unsigned char *pSrc_data, int src_data_size, int *width, int *height, int *actual_comps, int req_comps); unsigned char *decompress_jpeg_image_from_file(const char *pSrc_filename, int *width, int *height, int *actual_comps, int req_comps); // Success/failure error codes. enum jpgd_status { JPGD_SUCCESS = 0, JPGD_FAILED = -1, JPGD_DONE = 1, JPGD_BAD_DHT_COUNTS = -256, JPGD_BAD_DHT_INDEX, JPGD_BAD_DHT_MARKER, JPGD_BAD_DQT_MARKER, JPGD_BAD_DQT_TABLE, JPGD_BAD_PRECISION, JPGD_BAD_HEIGHT, JPGD_BAD_WIDTH, JPGD_TOO_MANY_COMPONENTS, JPGD_BAD_SOF_LENGTH, JPGD_BAD_VARIABLE_MARKER, JPGD_BAD_DRI_LENGTH, JPGD_BAD_SOS_LENGTH, JPGD_BAD_SOS_COMP_ID, JPGD_W_EXTRA_BYTES_BEFORE_MARKER, JPGD_NO_ARITHMITIC_SUPPORT, JPGD_UNEXPECTED_MARKER, JPGD_NOT_JPEG, JPGD_UNSUPPORTED_MARKER, JPGD_BAD_DQT_LENGTH, JPGD_TOO_MANY_BLOCKS, JPGD_UNDEFINED_QUANT_TABLE, JPGD_UNDEFINED_HUFF_TABLE, JPGD_NOT_SINGLE_SCAN, JPGD_UNSUPPORTED_COLORSPACE, JPGD_UNSUPPORTED_SAMP_FACTORS, JPGD_DECODE_ERROR, JPGD_BAD_RESTART_MARKER, JPGD_ASSERTION_ERROR, JPGD_BAD_SOS_SPECTRAL, JPGD_BAD_SOS_SUCCESSIVE, JPGD_STREAM_READ, JPGD_NOTENOUGHMEM }; // Input stream interface. // Derive from this class to read input data from sources other than files or memory. Set m_eof_flag to true when no more data is available. // The decoder is rather greedy: it will keep on calling this method until its internal input buffer is full, or until the EOF flag is set. // It the input stream contains data after the JPEG stream's EOI (end of image) marker it will probably be pulled into the internal buffer. // Call the get_total_bytes_read() method to determine the actual size of the JPEG stream after successful decoding. class jpeg_decoder_stream { public: jpeg_decoder_stream() { } virtual ~jpeg_decoder_stream() { } // The read() method is called when the internal input buffer is empty. // Parameters: // pBuf - input buffer // max_bytes_to_read - maximum bytes that can be written to pBuf // pEOF_flag - set this to true if at end of stream (no more bytes remaining) // Returns -1 on error, otherwise return the number of bytes actually written to the buffer (which may be 0). // Notes: This method will be called in a loop until you set *pEOF_flag to true or the internal buffer is full. virtual int read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag) = 0; }; // stdio FILE stream class. class jpeg_decoder_file_stream : public jpeg_decoder_stream { jpeg_decoder_file_stream(const jpeg_decoder_file_stream &); jpeg_decoder_file_stream &operator=(const jpeg_decoder_file_stream &); FILE *m_pFile; bool m_eof_flag, m_error_flag; public: jpeg_decoder_file_stream(); virtual ~jpeg_decoder_file_stream(); bool open(const char *Pfilename); void close(); virtual int read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag); }; // Memory stream class. class jpeg_decoder_mem_stream : public jpeg_decoder_stream { const uint8 *m_pSrc_data; uint m_ofs, m_size; public: jpeg_decoder_mem_stream() : m_pSrc_data(NULL), m_ofs(0), m_size(0) { } jpeg_decoder_mem_stream(const uint8 *pSrc_data, uint size) : m_pSrc_data(pSrc_data), m_ofs(0), m_size(size) { } virtual ~jpeg_decoder_mem_stream() { } bool open(const uint8 *pSrc_data, uint size); void close() { m_pSrc_data = NULL; m_ofs = 0; m_size = 0; } virtual int read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag); }; // Loads JPEG file from a jpeg_decoder_stream. unsigned char *decompress_jpeg_image_from_stream(jpeg_decoder_stream *pStream, int *width, int *height, int *actual_comps, int req_comps); enum { JPGD_IN_BUF_SIZE = 8192, JPGD_MAX_BLOCKS_PER_MCU = 10, JPGD_MAX_HUFF_TABLES = 8, JPGD_MAX_QUANT_TABLES = 4, JPGD_MAX_COMPONENTS = 4, JPGD_MAX_COMPS_IN_SCAN = 4, JPGD_MAX_BLOCKS_PER_ROW = 8192, JPGD_MAX_HEIGHT = 16384, JPGD_MAX_WIDTH = 16384 }; typedef int16 jpgd_quant_t; typedef int16 jpgd_block_t; class jpeg_decoder { public: // Call get_error_code() after constructing to determine if the stream is valid or not. You may call the get_width(), get_height(), etc. // methods after the constructor is called. You may then either destruct the object, or begin decoding the image by calling begin_decoding(), then decode() on each scanline. jpeg_decoder(jpeg_decoder_stream *pStream); ~jpeg_decoder(); // Call this method after constructing the object to begin decompression. // If JPGD_SUCCESS is returned you may then call decode() on each scanline. int begin_decoding(); // Returns the next scan line. // For grayscale images, pScan_line will point to a buffer containing 8-bit pixels (get_bytes_per_pixel() will return 1). // Otherwise, it will always point to a buffer containing 32-bit RGBA pixels (A will always be 255, and get_bytes_per_pixel() will return 4). // Returns JPGD_SUCCESS if a scan line has been returned. // Returns JPGD_DONE if all scan lines have been returned. // Returns JPGD_FAILED if an error occurred. Call get_error_code() for a more info. int decode(const void **pScan_line, uint *pScan_line_len); inline jpgd_status get_error_code() const { return m_error_code; } inline int get_width() const { return m_image_x_size; } inline int get_height() const { return m_image_y_size; } inline int get_num_components() const { return m_comps_in_frame; } inline int get_bytes_per_pixel() const { return m_dest_bytes_per_pixel; } inline int get_bytes_per_scan_line() const { return m_image_x_size * get_bytes_per_pixel(); } // Returns the total number of bytes actually consumed by the decoder (which should equal the actual size of the JPEG file). inline int get_total_bytes_read() const { return m_total_bytes_read; } private: jpeg_decoder(const jpeg_decoder &); jpeg_decoder &operator=(const jpeg_decoder &); typedef void (*pDecode_block_func)(jpeg_decoder *, int, int, int); struct huff_tables { bool ac_table; uint look_up[256]; uint look_up2[256]; uint8 code_size[256]; uint tree[512]; }; struct coeff_buf { uint8 *pData; int block_num_x, block_num_y; int block_len_x, block_len_y; int block_size; }; struct mem_block { mem_block *m_pNext; size_t m_used_count; size_t m_size; char m_data[1]; }; jmp_buf m_jmp_state; mem_block *m_pMem_blocks; int m_image_x_size; int m_image_y_size; jpeg_decoder_stream *m_pStream; int m_progressive_flag; uint8 m_huff_ac[JPGD_MAX_HUFF_TABLES]; uint8 *m_huff_num[JPGD_MAX_HUFF_TABLES]; // pointer to number of Huffman codes per bit size uint8 *m_huff_val[JPGD_MAX_HUFF_TABLES]; // pointer to Huffman codes per bit size jpgd_quant_t *m_quant[JPGD_MAX_QUANT_TABLES]; // pointer to quantization tables int m_scan_type; // Gray, Yh1v1, Yh1v2, Yh2v1, Yh2v2 (CMYK111, CMYK4114 no longer supported) int m_comps_in_frame; // # of components in frame int m_comp_h_samp[JPGD_MAX_COMPONENTS]; // component's horizontal sampling factor int m_comp_v_samp[JPGD_MAX_COMPONENTS]; // component's vertical sampling factor int m_comp_quant[JPGD_MAX_COMPONENTS]; // component's quantization table selector int m_comp_ident[JPGD_MAX_COMPONENTS]; // component's ID int m_comp_h_blocks[JPGD_MAX_COMPONENTS]; int m_comp_v_blocks[JPGD_MAX_COMPONENTS]; int m_comps_in_scan; // # of components in scan int m_comp_list[JPGD_MAX_COMPS_IN_SCAN]; // components in this scan int m_comp_dc_tab[JPGD_MAX_COMPONENTS]; // component's DC Huffman coding table selector int m_comp_ac_tab[JPGD_MAX_COMPONENTS]; // component's AC Huffman coding table selector int m_spectral_start; // spectral selection start int m_spectral_end; // spectral selection end int m_successive_low; // successive approximation low int m_successive_high; // successive approximation high int m_max_mcu_x_size; // MCU's max. X size in pixels int m_max_mcu_y_size; // MCU's max. Y size in pixels int m_blocks_per_mcu; int m_max_blocks_per_row; int m_mcus_per_row, m_mcus_per_col; int m_mcu_org[JPGD_MAX_BLOCKS_PER_MCU]; int m_total_lines_left; // total # lines left in image int m_mcu_lines_left; // total # lines left in this MCU int m_real_dest_bytes_per_scan_line; int m_dest_bytes_per_scan_line; // rounded up int m_dest_bytes_per_pixel; // 4 (RGB) or 1 (Y) huff_tables *m_pHuff_tabs[JPGD_MAX_HUFF_TABLES]; coeff_buf *m_dc_coeffs[JPGD_MAX_COMPONENTS]; coeff_buf *m_ac_coeffs[JPGD_MAX_COMPONENTS]; int m_eob_run; int m_block_y_mcu[JPGD_MAX_COMPONENTS]; uint8 *m_pIn_buf_ofs; int m_in_buf_left; int m_tem_flag; bool m_eof_flag; uint8 m_in_buf_pad_start[128]; uint8 m_in_buf[JPGD_IN_BUF_SIZE + 128]; uint8 m_in_buf_pad_end[128]; int m_bits_left; uint m_bit_buf; int m_restart_interval; int m_restarts_left; int m_next_restart_num; int m_max_mcus_per_row; int m_max_blocks_per_mcu; int m_expanded_blocks_per_mcu; int m_expanded_blocks_per_row; int m_expanded_blocks_per_component; bool m_freq_domain_chroma_upsample; int m_max_mcus_per_col; uint m_last_dc_val[JPGD_MAX_COMPONENTS]; jpgd_block_t *m_pMCU_coefficients; int m_mcu_block_max_zag[JPGD_MAX_BLOCKS_PER_MCU]; uint8 *m_pSample_buf; int m_crr[256]; int m_cbb[256]; int m_crg[256]; int m_cbg[256]; uint8 *m_pScan_line_0; uint8 *m_pScan_line_1; jpgd_status m_error_code; bool m_ready_flag; int m_total_bytes_read; void free_all_blocks(); JPGD_NORETURN void stop_decoding(jpgd_status status); void *alloc(size_t n, bool zero = false); void word_clear(void *p, uint16 c, uint n); void prep_in_buffer(); void read_dht_marker(); void read_dqt_marker(); void read_sof_marker(); void skip_variable_marker(); void read_dri_marker(); void read_sos_marker(); int next_marker(); int process_markers(); void locate_soi_marker(); void locate_sof_marker(); int locate_sos_marker(); void init(jpeg_decoder_stream *pStream); void create_look_ups(); void fix_in_buffer(); void transform_mcu(int mcu_row); void transform_mcu_expand(int mcu_row); coeff_buf *coeff_buf_open(int block_num_x, int block_num_y, int block_len_x, int block_len_y); inline jpgd_block_t *coeff_buf_getp(coeff_buf *cb, int block_x, int block_y); void load_next_row(); void decode_next_row(); void make_huff_table(int index, huff_tables *pH); void check_quant_tables(); void check_huff_tables(); void calc_mcu_block_order(); int init_scan(); void init_frame(); void process_restart(); void decode_scan(pDecode_block_func decode_block_func); void init_progressive(); void init_sequential(); void decode_start(); void decode_init(jpeg_decoder_stream *pStream); void H2V2Convert(); void H2V1Convert(); void H1V2Convert(); void H1V1Convert(); void gray_convert(); void expanded_convert(); void find_eoi(); inline uint get_char(); inline uint get_char(bool *pPadding_flag); inline void stuff_char(uint8 q); inline uint8 get_octet(); inline uint get_bits(int num_bits); inline uint get_bits_no_markers(int numbits); inline int huff_decode(huff_tables *pH); inline int huff_decode(huff_tables *pH, int &extrabits); static inline uint8 clamp(int i); static void decode_block_dc_first(jpeg_decoder *pD, int component_id, int block_x, int block_y); static void decode_block_dc_refine(jpeg_decoder *pD, int component_id, int block_x, int block_y); static void decode_block_ac_first(jpeg_decoder *pD, int component_id, int block_x, int block_y); static void decode_block_ac_refine(jpeg_decoder *pD, int component_id, int block_x, int block_y); }; } // namespace jpgd #endif // JPEG_DECODER_H
[ "mikesart@gmail.com" ]
mikesart@gmail.com
15f904dafa33ab3f233cbb5665e6377f6544d303
5372f584b390af72ca62f1e5bad455ff6f4ff42a
/Generator/GeneratorManagerBox.cxx
2757bee8920bdd75ee660d899dfb0772c93e7c2f
[]
no_license
preghenella/o2sim
cefcdf5f8548689df0e0e44e9e05b24c81c8e7d6
2ecc90e5d90b3afda16cba5668dbe35890f4a7a4
refs/heads/master
2021-01-16T19:28:06.773184
2017-09-18T12:04:05
2017-09-18T12:04:05
100,174,914
0
0
null
null
null
null
UTF-8
C++
false
false
4,501
cxx
// Copyright CERN and copyright holders of ALICE O2. This software is // distributed under the terms of the GNU General Public License v3 (GPL // Version 3), copied verbatim in the file "COPYING". // // See https://alice-o2.web.cern.ch/ for full licensing information. // // In applying this license CERN does not waive the privileges and immunities // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. /// \author R+Preghenella - August 2017 #include "GeneratorManagerBox.h" #include "FairBoxGenerator.h" namespace o2sim { /*****************************************************************/ /*****************************************************************/ GeneratorManagerBox::GeneratorManagerBox() : GeneratorManagerDelegate() { /** deafult constructor **/ /** register values **/ RegisterValue("multiplicity"); RegisterValue("pdg_code"); RegisterValue("momentum"); RegisterValue("pt"); RegisterValue("ekin"); RegisterValue("phi", "0., 360."); RegisterValue("eta"); RegisterValue("rapidity"); RegisterValue("theta"); RegisterValue("vertex_xyz"); RegisterValue("debug", "false"); } /*****************************************************************/ FairGenerator * GeneratorManagerBox::Init() const { /** init **/ Int_t multiplicity, pdg_code; Double_t momentum[2], pt[2], ekin[2], phi[2], eta[2], rapidity[2], theta[2], vertex_xyz[3]; /** multiplicity **/ if (!GetValue("multiplicity", multiplicity) || multiplicity < 1) { LOG(ERROR) << "Invalid multiplicity" << std::endl; return NULL; } /** pdg code **/ if (!GetValue("pdg_code", pdg_code) || pdg_code == 0) { LOG(ERROR) << "Invalid PDG code" << std::endl; return NULL; } /** create generator **/ FairBoxGenerator *generator = new FairBoxGenerator(); generator->SetMultiplicity(multiplicity); generator->SetPDGType(pdg_code); /** setup generator **/ /** momentum **/ if (!IsNull("momentum")) { if (!GetValue("momentum", momentum, 2) || momentum[0] > momentum[1]) { LOG(ERROR) << "Invalid momentum range" << std::endl; return NULL; } generator->SetPRange(momentum[0], momentum[1]); } /** pt **/ if (!IsNull("pt")) { if (!GetValue("pt", pt, 2) || pt[0] > pt[1]) { LOG(ERROR) << "Invalid pt range" << std::endl; return NULL; } generator->SetPtRange(pt[0], pt[1]); } /** E kinetic **/ if (!IsNull("ekin")) { if (!GetValue("ekin", ekin, 2) || ekin[0] > ekin[1]) { LOG(ERROR) << "Invalid ekin range" << std::endl; return NULL; } generator->SetEkinRange(ekin[0], ekin[1]); } /** phi **/ if (!IsNull("phi")) { if (!GetValue("phi", phi, 2) || phi[0] > phi[1] || phi[0] < 0. || phi[1] > 360.) { LOG(ERROR) << "Invalid phi range" << std::endl; return NULL; } generator->SetPhiRange(phi[0], phi[1]); } /** eta **/ if (!IsNull("eta")) { if (!GetValue("eta", eta, 2) || eta[0] > eta[1]) { LOG(ERROR) << "Invalid eta range" << std::endl; return NULL; } generator->SetEtaRange(eta[0], eta[1]); } /** rapidity **/ if (!IsNull("rapidity")) { if (!GetValue("rapidity", rapidity, 2) || rapidity[0] > rapidity[1]) { LOG(ERROR) << "Invalid rapidity range" << std::endl; return NULL; } generator->SetYRange(rapidity[0], rapidity[1]); } /** theta **/ if (!IsNull("theta")) { if (!GetValue("theta", theta, 2) || theta[0] > theta[1]) { LOG(ERROR) << "Invalid theta range" << std::endl; return NULL; } generator->SetEtaRange(theta[0], theta[1]); } /** vertex_xyz **/ if (!IsNull("vertex_xyz")) { if (!GetValue("vertex_xyz", vertex_xyz, 3)) { LOG(ERROR) << "Invalid vertex_xyz" << std::endl; return NULL; } generator->SetXYZ(vertex_xyz[0], vertex_xyz[1], vertex_xyz[2]); } /** debug **/ if (IsValue("debug", "true")) { generator->SetDebug(kTRUE); } /** success **/ return generator; } /*****************************************************************/ Bool_t GeneratorManagerBox::Terminate() const { /** terminate **/ /** success **/ return kTRUE; } /*****************************************************************/ /*****************************************************************/ } /** namespace o2sim **/
[ "preghenella@bo.infn.it" ]
preghenella@bo.infn.it
5fe830ca44c21780e72fa9cc6cac040e7e71d875
4fbd844113ec9d8c526d5f186274b40ad5502aa3
/algorithms/cpp/minimum_number_of_arrows_to_burst_balloons.cpp
909c9d7ae0c01f681fda166cabf4fe4628450802
[]
no_license
capric8416/leetcode
51f9bdc3fa26b010e8a1e8203a7e1bcd70ace9e1
503b2e303b10a455be9596c31975ee7973819a3c
refs/heads/master
2022-07-16T21:41:07.492706
2020-04-22T06:18:16
2020-04-22T06:18:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,191
cpp
/* There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it's horizontal, y-coordinates don't matter and hence the x-coordinates of start and end of the diameter suffice. Start is always smaller than end. There will be at most 104 balloons. An arrow can be shot up exactly vertically from different points along the x-axis. A balloon with xstart and xend bursts by an arrow shot at x if xstart ≤ x ≤ xend. There is no limit to the number of arrows that can be shot. An arrow once shot keeps travelling up infinitely. The problem is to find the minimum number of arrows that must be shot to burst all balloons. Example: Input: [[10,16], [2,8], [1,6], [7,12]] Output: 2 Explanation: One way is to shoot one arrow for example at x = 6 (bursting the balloons [2,8] and [1,6]) and another arrow at x = 11 (bursting the other two balloons). */ /* ==================== body ==================== */ class Solution { public: int findMinArrowShots(vector<pair<int, int>>& points) { } }; /* ==================== body ==================== */
[ "capric8416@gmail.com" ]
capric8416@gmail.com
402429c9c5b8d21adfea9c9ec49479e7fef573eb
b3c4963d3ea6638873518f1d8c0494b690d873b0
/Src/Library/Graph/Graph.h
0c3e714f7ad1336eea561740d79db2d79941d318
[ "MIT" ]
permissive
DanWatkins/ValpineCompiler
ee89aa84d2ac54cb7adc6689b55ede0427f11cfb
a65f2817bb890e2a976c8b046966e76806e655f3
refs/heads/master
2021-01-13T10:29:41.122181
2015-03-30T01:33:23
2015-03-30T01:33:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
935
h
//==================================================================================================================| // Created 2015.01.29 by Daniel L. Watkins // // Copyright (C) 2015 Valpineware // This file is licensed under the MIT License. //==================================================================================================================| #ifndef _vc_graph_Graph_h #define _vc_graph_Graph_h #include "Statement.h" #include "Preprocessor.h" #include "Function.h" #include "ControlStructure.h" #include "Block.h" #include "Class.h" #include "Variable.h" #include "Expression.h" namespace vc { namespace graph { /** * @brief An in-memory representation of a Valpine source file using a graph like data structure. */ class Graph { public: Block& block() { return mBlock; } const Block& block() const { return mBlock; } //TODO we need a move constructor private: Block mBlock; }; }} #endif
[ "dwatkins@valpineware.com" ]
dwatkins@valpineware.com
f99551f930557e1cdfec87c575f2c74c618333cf
a92ba9f8efdff7751e5e8a1368aec94049d646f6
/atcoder/agc001/A.cpp
e34362a336cc95f2caa4cb9d6d2ce42b1bed115b
[]
no_license
bleh05/compprog
1e880897a964f572d9cda975cad63850ef7a6125
3996fea5689e36b0a163f55224d39b8029ce7558
refs/heads/master
2023-05-31T20:27:33.738419
2021-01-28T20:43:00
2021-07-15T04:55:51
323,463,058
0
0
null
null
null
null
UTF-8
C++
false
false
600
cpp
// Problem: A - BBQ Easy // Contest: AtCoder - AtCoder Grand Contest 001 // URL: https://atcoder.jp/contests/agc001/tasks/agc001_a // Memory Limit: 256 MB // Time Limit: 2000 ms // Powered by CP Editor (https://github.com/cpeditor/cpeditor) #include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; int arr[2 * n]; for (int i = 0; i < 2 * n; i++) { cin >> arr[i]; } sort(arr, arr + 2 * n); int sum = 0; for (int i = 0; i < n; i++) { sum += arr[i * 2]; } cout << sum << endl; }
[ "qinxiaoying@gmail.com" ]
qinxiaoying@gmail.com
30eeb8a560251ec0e3d485fe107210ecc785d84f
6736c015a5b43c895ffd20029b86b687dc1ce1d0
/src/masternode-sync.h
30bed3628cdc16dd5c3f9b63b7f7359bdf35c092
[ "MIT" ]
permissive
MixAir/MIACore
611c31b37f726d4234f70be2eaebae4652ee4542
99311b712d1c99e1b9559702015a915dc9738d4f
refs/heads/master
2020-03-27T16:13:23.376832
2018-09-08T13:02:40
2018-09-08T13:02:40
146,767,183
1
1
MIT
2018-09-06T13:29:47
2018-08-30T15:06:43
C++
UTF-8
C++
false
false
3,063
h
// Copyright (c) 2014-2017 The MIA Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef MASTERNODE_SYNC_H #define MASTERNODE_SYNC_H #include "chain.h" #include "net.h" #include <univalue.h> class CMasternodeSync; static const int MASTERNODE_SYNC_FAILED = -1; static const int MASTERNODE_SYNC_INITIAL = 0; // sync just started, was reset recently or still in IDB static const int MASTERNODE_SYNC_WAITING = 1; // waiting after initial to see if we can get more headers/blocks static const int MASTERNODE_SYNC_LIST = 2; static const int MASTERNODE_SYNC_MNW = 3; static const int MASTERNODE_SYNC_GOVERNANCE = 4; static const int MASTERNODE_SYNC_GOVOBJ = 10; static const int MASTERNODE_SYNC_GOVOBJ_VOTE = 11; static const int MASTERNODE_SYNC_FINISHED = 999; static const int MASTERNODE_SYNC_TICK_SECONDS = 6; static const int MASTERNODE_SYNC_TIMEOUT_SECONDS = 30; // our blocks are 2.5 minutes so 30 seconds should be fine static const int MASTERNODE_SYNC_ENOUGH_PEERS = 6; extern CMasternodeSync masternodeSync; // // CMasternodeSync : Sync masternode assets in stages // class CMasternodeSync { private: // Keep track of current asset int nRequestedMasternodeAssets; // Count peers we've requested the asset from int nRequestedMasternodeAttempt; // Time when current masternode asset sync started int64_t nTimeAssetSyncStarted; // ... last bumped int64_t nTimeLastBumped; // ... or failed int64_t nTimeLastFailure; void Fail(); void ClearFulfilledRequests(CConnman& connman); public: CMasternodeSync() { Reset(); } void SendGovernanceSyncRequest(CNode* pnode, CConnman& connman); bool IsFailed() { return nRequestedMasternodeAssets == MASTERNODE_SYNC_FAILED; } bool IsBlockchainSynced() { return nRequestedMasternodeAssets > MASTERNODE_SYNC_WAITING; } bool IsMasternodeListSynced() { return nRequestedMasternodeAssets > MASTERNODE_SYNC_LIST; } bool IsWinnersListSynced() { return nRequestedMasternodeAssets > MASTERNODE_SYNC_MNW; } bool IsSynced() { return nRequestedMasternodeAssets == MASTERNODE_SYNC_FINISHED; } int GetAssetID() { return nRequestedMasternodeAssets; } int GetAttempt() { return nRequestedMasternodeAttempt; } void BumpAssetLastTime(std::string strFuncName); int64_t GetAssetStartTime() { return nTimeAssetSyncStarted; } std::string GetAssetName(); std::string GetSyncStatus(); void Reset(); void SwitchToNextAsset(CConnman& connman); void ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv); void ProcessTick(CConnman& connman); void AcceptedBlockHeader(const CBlockIndex *pindexNew); void NotifyHeaderTip(const CBlockIndex *pindexNew, bool fInitialDownload, CConnman& connman); void UpdatedBlockTip(const CBlockIndex *pindexNew, bool fInitialDownload, CConnman& connman); }; #endif
[ "mixairdev@protonmail.com" ]
mixairdev@protonmail.com
8c012261135e4f425c7d8d919d67f669f0e99e9d
ede39dd3b4eff4a4b5bad0a70918295170845cbd
/base/trace_event/memory_dump_request_args.h
fe7b0b935f785b7a30142168632d006d9c812842
[ "BSD-3-Clause" ]
permissive
fujunwei/chromium-crosswalk
9ae06862337e49061d49b932fc049f460463d5c3
24a582e5655871d72348c18f77ead355cc32126e
refs/heads/master
2022-10-18T22:20:24.494151
2015-04-02T10:55:14
2015-05-22T05:56:53
37,062,999
1
0
null
2015-06-08T11:30:41
2015-06-08T11:30:41
null
UTF-8
C++
false
false
1,478
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 BASE_TRACE_EVENT_MEMORY_DUMP_REQUEST_H_ #define BASE_TRACE_EVENT_MEMORY_DUMP_REQUEST_H_ // This file defines the types and structs used to issue memory dump requests. // These are also used in the IPCs for coordinating inter-process memory dumps. #include "base/base_export.h" #include "base/callback.h" namespace base { namespace trace_event { // Captures the reason why a memory dump is being requested. This is to allow // selective enabling of dumps, filtering and post-processing. enum class MemoryDumpType { TASK_BEGIN, // Dumping memory at the beginning of a message-loop task. TASK_END, // Dumping memory at the ending of a message-loop task. PERIODIC_INTERVAL, // Dumping memory at periodic intervals. EXPLICITLY_TRIGGERED, // Non maskable dump request. LAST = EXPLICITLY_TRIGGERED // For IPC macros. }; using MemoryDumpCallback = Callback<void(uint64 dump_guid, bool status)>; struct BASE_EXPORT MemoryDumpRequestArgs { // Globally unique identifier. In multi-process dumps, all processes issue a // local dump with the same guid. This allows the trace importers to // reconstruct the global dump. uint64 dump_guid; MemoryDumpType dump_type; }; } // namespace trace_event } // namespace base #endif // BASE_TRACE_EVENT_MEMORY_DUMP_REQUEST_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
d03241e10e62e2fc12b48a3a95ed92ca594ea948
165fa8269cc3e97b875153e2ed1c1845ceeaa489
/examples/Files/Files.ino
f7f585a6194eb698e5718a289bfb4b536d7c491f
[]
no_license
baggio63446333/SD
ec0686695162a95da4080d57b37af63e681d5133
60d07bcd39e3838c2220a163ab8cf6d92d0a657f
refs/heads/master
2020-09-02T13:45:06.183408
2019-11-03T03:49:29
2019-11-03T03:49:29
219,234,613
0
0
null
null
null
null
UTF-8
C++
false
false
1,565
ino
/* SD card basic file example This example shows how to create and destroy an SD card file The circuit: * SD card attached to SPI bus as follows: ** MOSI - pin 11 ** MISO - pin 12 ** CLK - pin 13 ** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN) created Nov 2010 by David A. Mellis modified 9 Apr 2012 by Tom Igoe This example code is in the public domain. */ #include <SD.h> File myFile; void setup() { // Open serial communications and wait for port to open: Serial.begin(115200); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } Serial.print("Initializing SD card..."); if (!SD.begin(4)) { Serial.println("initialization failed!"); while (1); } Serial.println("initialization done."); if (SD.exists("example.txt")) { Serial.println("example.txt exists."); } else { Serial.println("example.txt doesn't exist."); } // open a new file and immediately close it: Serial.println("Creating example.txt..."); myFile = SD.open("example.txt", FILE_WRITE); myFile.close(); // Check to see if the file exists: if (SD.exists("example.txt")) { Serial.println("example.txt exists."); } else { Serial.println("example.txt doesn't exist."); } // delete the file: Serial.println("Removing example.txt..."); SD.remove("example.txt"); if (SD.exists("example.txt")) { Serial.println("example.txt exists."); } else { Serial.println("example.txt doesn't exist."); } } void loop() { // nothing happens after setup finishes. }
[ "55774994+baggio63446333@users.noreply.github.com" ]
55774994+baggio63446333@users.noreply.github.com
f3d290d28dc587679ffefa6630034847d72632a6
aad28fa1140e713c8591db5a383ac5f6605f743b
/242 John, Bruce and beer/John, Bruce and beer.cpp
c8d2695a0a6981f26d4dc288d60d787d1bb671a4
[]
no_license
DaniilMuntyan/Solutions_e-olymp
d7ad45357d4f999c853efefcd47c39bc17e33664
7a318572e13f2e6103a2ade49c8ce9c5210caad9
refs/heads/master
2021-02-28T15:22:58.506994
2020-03-07T21:42:50
2020-03-07T21:42:50
245,708,666
3
0
null
null
null
null
UTF-8
C++
false
false
218
cpp
#include <bits/stdc++.h> using namespace std; int main() { long double a,b,c,sum; cin >> a >> b >> c; sum = a+b; a/=c; b/=c; a+=b; cout <<setprecision(0) << fixed << a-0.499 << endl; }
[ "daniilmuntjan@gmail.com" ]
daniilmuntjan@gmail.com
b348d39b168f3b7026aecd08ca7e0c4efd8d0f06
e96db2790a6e826f33c715d4f4f24c408ebc8857
/UI/ofxUICustomDDL.h
f2698780c9e4a2405ffc438474971438527db569
[ "MIT" ]
permissive
naus3a/NauLibs
1350752954e42bbb0bcec7c7e449504d8b56598a
8598f160788fa8012e018b785f46bd085cb2d4f5
refs/heads/master
2020-03-28T00:56:03.538171
2014-10-09T15:06:56
2014-10-09T15:06:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
557
h
// // ofxUICustomDDL.h // MTSandbox // // Created by nausea on 8/1/14. // // #pragma once #include "ofxUIDropDownList.h" class ofxUICustomDDL : public ofxUIDropDownList{ public: ofxUICustomDDL(string _name, vector<string> items, float w = 0, float x = 0, float y = 0, int _size = OFX_UI_FONT_MEDIUM); void makeSingleFixed(); void customClear(); void customAddToggle(string fullName, int _idx, int _maxLen=10); void selectByRealIdx(int _idx); int getSelectedRealIdx(); vector<string>fullNames; vector<int>realIdx; };
[ "naus3a@gmail.com" ]
naus3a@gmail.com
936c596ab13cdd9f5d1c6b6b715f306d0cdb2527
dfdfbe15b54cc21207534de710cb1e54e66e8527
/Source/GridRuntime/Public/GridPainter/GridOutlinePainter.h
c7ea4dd6821b4f9d21fa3c858aef6316acaf9f3a
[ "MIT" ]
permissive
jinyuliao/Grid
37886c17c01995cbcb8672e45d04d50ec2f2d3dd
0b1b50eeb77007fad06bb398aab73f5297a0c4a4
refs/heads/master
2023-04-04T23:24:08.054103
2023-03-27T08:13:13
2023-03-27T08:13:13
108,792,150
232
64
MIT
2023-03-27T08:13:14
2017-10-30T02:30:22
C++
UTF-8
C++
false
false
1,507
h
#pragma once #include "CoreMinimal.h" #include "GridPainter/GridPainter.h" #include "Components/GridOutlineComponent.h" #include "GridOutlinePainter.generated.h" /** * */ UCLASS() class GRIDRUNTIME_API UGridOutlinePainter : public UGridPainter { GENERATED_BODY() public: UGridOutlinePainter(); virtual ~UGridOutlinePainter(); virtual void SetGridManager(AGridManager* NewGridManager) override; virtual void TickImpl_Implementation(float DeltaTime) override; /** * Descending order. * @note when different grid with different color share one edge, this array are used to determine the final color of the shared edge * @note you MUST implement this method if you override 'GetColors' */ UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "GridDecalPainter") void GetColorPriority(TArray<FLinearColor>& Colors); void GetColorPriority_Implementation(TArray<FLinearColor>& Colors); /** * @note a grid can have multi state(color), e.g: a grid is movable(white) and attackable(red) */ UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "GridDecalPainter") void GetColors(UGrid* Grid, TArray<FLinearColor>& Colors); virtual void GetColors_Implementation(UGrid* Grid, TArray<FLinearColor>& Colors); UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "GridOutlinePainter") float OutlineThickness; UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "GridOutlinePainter") float ZOffset; protected: UGridOutlineComponent* GridOutlineComp; };
[ "jinyuliao282@gmail.com" ]
jinyuliao282@gmail.com
3e1233ac72dbb6f9ceb8563e118de3230b3c057c
42c9b0ffa6c1a8225be32e2caf6cd238fe9a245b
/Client/ShopWnd.cpp
47b3a3d20de8514b6737e271932346b5ebc3b08b
[]
no_license
hjyu94/talesweaver
fd9f5fc5ff6a9a33cf445a0bb03dac63406c285d
71ee67ca9dfc663ccc8a79f1da039009530a8be7
refs/heads/master
2022-11-22T20:34:01.133203
2020-07-28T06:34:58
2020-07-28T06:34:58
283,120,242
0
2
null
null
null
null
UHC
C++
false
false
8,290
cpp
#include "stdafx.h" #include "ShopWnd.h" #include "ObjMgr.h" CShopWnd::CShopWnd() { } CShopWnd::~CShopWnd() { } HRESULT CShopWnd::Initialize(void) { m_tInfo.vPos = D3DXVECTOR3(50.f, 100.f, 0.f); m_vOriginalPos = m_tInfo.vPos; m_tFrame.wstrObjKey = L"ShopWnd"; m_bIsShow = false; m_pMenu = static_cast<CMenuUI*>(CObjMgr::Get_Instance()->Get_MenuUI()); return S_OK; } int CShopWnd::Progress(void) { CWndUI::Progress(); if (m_bIsShow) { // 인벤창 뜨게 하기 CMenuUI* pMenu = static_cast<CMenuUI*>(CObjMgr::Get_Instance()->Get_MenuUI()); for (int i = 0; i < CMenuUI::PT_END; ++i) { if (i == CMenuUI::PT_INVEN) { CWndUI* pPlayerInvenWnd = pMenu->Get_UI(CMenuUI::PT_INVEN); pPlayerInvenWnd->Show(true); pPlayerInvenWnd->Set_Pos(D3DXVECTOR3(400.f, 100.f, 0.f)); pPlayerInvenWnd->IsShopping(true); } else { CWndUI* pWnd = pMenu->Get_UI((CMenuUI::PART)i); pWnd->Show(false); } } // 위치, 렉트 for (int i = 0; i < 12; ++i) { float fY = 25.f * i + 54.f; m_vImgPos[i] = D3DXVECTOR3(23.f, fY, 0.f) + m_tInfo.vPos; fY = 25.f * i + 49.f; m_vNamePos[i] = D3DXVECTOR3(30.f, fY, 0.f) + m_tInfo.vPos; m_vCostPos[i] = D3DXVECTOR3(266.f, fY, 0.f) + m_tInfo.vPos; m_ImgRect[i] = Calculate_Rect(m_vImgPos[i], 24.f, 24.f); m_NameRect[i] = Calculate_Rect(m_vNamePos[i], 221.f, 15.f, false); m_CostRect[i] = Calculate_Rect(m_vCostPos[i], 52.f, 15.f, false); } m_vecScroll[S_UP] = D3DXVECTOR3{ 327.f, 60.f - 6.f, 0.f } +m_tInfo.vPos; m_vecScroll[S_SCROLL_MIN] = D3DXVECTOR3{ 327.f, 75.f, 0.f } +m_tInfo.vPos; m_vecScroll[S_SCROLL_MAX] = D3DXVECTOR3{ 327.f, 314.f, 0.f } +m_tInfo.vPos; m_vecScroll[S_DOWN] = D3DXVECTOR3{ 327.f, 327.f + 6.f, 0.f } +m_tInfo.vPos; m_rcScroll[S_UP] = Calculate_Rect(m_vecScroll[S_UP], 12.f, 13.f); m_rcScroll[S_DOWN] = Calculate_Rect(m_vecScroll[S_DOWN], 12.f, 13.f); // 스크롤 표시 여부 if (m_pShopInven->size() > 12) { m_bScrollNeed = true; } else { m_bScrollNeed = false; } // 스크롤 위 아래 버튼 클릭 시 POINT pt = GetMousePt(); if (m_bScrollNeed) { if (PtInRect(&m_rcScroll[S_UP], pt)) { if (CKeyMgr::Get_Instance()->KeyDown(KEY_LBUTTON, CKeyMgr::S_SHOP_WND)) { m_iScrollStart--; if (m_iScrollStart < 0) m_iScrollStart = 0; CSoundMgr::Get_Instance()->PlaySound(L"BtnOver.wav", CSoundMgr::CHANNELID::UI); } } if (PtInRect(&m_rcScroll[S_DOWN], pt)) { if (CKeyMgr::Get_Instance()->KeyDown(KEY_LBUTTON, CKeyMgr::S_SHOP_WND)) { m_iScrollStart++; if (m_iScrollStart > m_pShopInven->size() - 12) m_iScrollStart = m_pShopInven->size() - 12; CSoundMgr::Get_Instance()->PlaySound(L"BtnOver.wav", CSoundMgr::CHANNELID::UI); } } } // 물건 구매 for (int i = 0; i < 12; ++i) { // 아이템 사용하기 (마우스 좌 더블클릭) // 아이템 판매하기 if (PtInRect(&m_ImgRect[i], pt) || PtInRect(&m_NameRect[i], pt)) { if (CKeyMgr::Get_Instance()->KeyDown(KEY_LBUTTON, CKeyMgr::S_SHOP_WND)) { if (m_fClickTime <= 1.f) { CPlayer* pPlayer = static_cast<CPlayer*>(CObjMgr::Get_Instance()->Get_Player()); pPlayer->Buy_Item((*m_pShopInven)[i + m_iScrollStart]); } m_fClickTime = 0.f; } } } //for (int i = 0; i < 12; ++i) //{ // if (PtInRect(&m_ImgRect[i], pt) || PtInRect(&m_NameRect[i], pt)) // { // CPlayer* pPlayer = static_cast<CPlayer*>(CObjMgr::Get_Instance()->Get_Player()); // pPlayer->Buy_Item((*m_pShopInven)[i + m_iScrollStart]); // } //} } else { CMenuUI* pMenu = static_cast<CMenuUI*>(CObjMgr::Get_Instance()->Get_MenuUI()); for (int i = 0; i < CMenuUI::PT_END; ++i) { CWndUI* pWnd = pMenu->Get_UI((CMenuUI::PART)i); pWnd->IsShopping(false); } } return 0; } void CShopWnd::Render(void) { CWndUI::Render(); if (m_bIsShow) { for (size_t i = m_iScrollStart; i < m_iScrollStart + 12; ++i) { if (i < m_pShopInven->size()) { //1) 그림 wstring wstrObjKey = (*m_pShopInven)[i]->Get_ItemInfo().wstrObjKey; const TEXINFO* pTexture = CTextureMgr::Get_Instance()->GetTexture(wstrObjKey); if (nullptr == pTexture) return; float fX = float(pTexture->tImgInfo.Width) * 0.5f; float fY = float(pTexture->tImgInfo.Height) * 0.5f; D3DXMATRIX matTrans; D3DXMatrixTranslation(&matTrans , m_vImgPos[i - m_iScrollStart].x , m_vImgPos[i - m_iScrollStart].y , 0.f); CGraphicDev::Get_Instance()->GetSprite()->SetTransform(&matTrans); CGraphicDev::Get_Instance()->GetSprite()->Draw(pTexture->pTexture, NULL, &D3DXVECTOR3(fX, fY, 0.f), NULL, D3DCOLOR_ARGB(255, 255, 255, 255)); //2) 이름 D3DXMatrixTranslation(&matTrans, 0.f, 0.f, 0.f); wstring wstrName = (*m_pShopInven)[i]->Get_ItemInfo().wstrName; CGraphicDev::Get_Instance()->GetSprite()->SetTransform(&matTrans); CGraphicDev::Get_Instance()->GetFont_Normal12()->DrawTextW( CGraphicDev::Get_Instance()->GetSprite(), wstrName.c_str(), lstrlen(wstrName.c_str()), &m_NameRect[i - m_iScrollStart], DT_CENTER, D3DCOLOR_ARGB(255, 255, 255, 255)); //3) 가격 int iCost = (*m_pShopInven)[i]->Get_ItemInfo().iCost; TCHAR szBuf[MIN_STR] = L""; wsprintf(szBuf, L"%d", iCost); CGraphicDev::Get_Instance()->GetFont_Normal12()->DrawTextW( CGraphicDev::Get_Instance()->GetSprite(), szBuf, lstrlen(szBuf), &m_CostRect[i - m_iScrollStart], DT_CENTER, D3DCOLOR_ARGB(255, 255, 255, 255)); } } // 스크롤 if (m_bScrollNeed) { // Up { const TEXINFO* pTexture = CTextureMgr::Get_Instance()->GetTexture(L"UpScroll"); if (nullptr == pTexture) return; float fX = float(pTexture->tImgInfo.Width) * 0.5f; float fY = float(pTexture->tImgInfo.Height) * 0.5f; D3DXMATRIX matTrans; D3DXMatrixTranslation(&matTrans, m_vecScroll[S_UP].x, m_vecScroll[S_UP].y, 0.f); CGraphicDev::Get_Instance()->GetSprite()->SetTransform(&matTrans); CGraphicDev::Get_Instance()->GetSprite()->Draw(pTexture->pTexture, NULL, &D3DXVECTOR3(fX, fY, 0.f), NULL, D3DCOLOR_ARGB(255, 255, 255, 255)); } // Down { const TEXINFO* pTexture = CTextureMgr::Get_Instance()->GetTexture(L"DownScroll"); if (nullptr == pTexture) return; float fX = float(pTexture->tImgInfo.Width) * 0.5f; float fY = float(pTexture->tImgInfo.Height) * 0.5f; D3DXMATRIX matTrans; D3DXMatrixTranslation(&matTrans, m_vecScroll[S_DOWN].x, m_vecScroll[S_DOWN].y, 0.f); CGraphicDev::Get_Instance()->GetSprite()->SetTransform(&matTrans); CGraphicDev::Get_Instance()->GetSprite()->Draw(pTexture->pTexture, NULL, &D3DXVECTOR3(fX, fY, 0.f), NULL, D3DCOLOR_ARGB(255, 255, 255, 255)); } // Scroll { const TEXINFO* pTexture = CTextureMgr::Get_Instance()->GetTexture(L"Scroll"); if (nullptr == pTexture) return; float fCX = float(pTexture->tImgInfo.Width) * 0.5f; float fCY = float(pTexture->tImgInfo.Height) * 0.5f; float fIntervalY = m_vecScroll[S_SCROLL_MAX].y - m_vecScroll[S_SCROLL_MIN].y; int iIntervalCnt = m_pShopInven->size() - 12; fIntervalY = fIntervalY / iIntervalCnt; float fY = m_vecScroll[S_SCROLL_MIN].y + fIntervalY * m_iScrollStart; D3DXMATRIX matTrans; D3DXMatrixTranslation(&matTrans , m_vecScroll[S_SCROLL_MIN].x , fY , 0.f); CGraphicDev::Get_Instance()->GetSprite()->SetTransform(&matTrans); CGraphicDev::Get_Instance()->GetSprite()->Draw(pTexture->pTexture, NULL, &D3DXVECTOR3(fCX, fCY, 0.f), NULL, D3DCOLOR_ARGB(255, 255, 255, 255)); } } for (int i = 0; i < 12; ++i) { CGraphicDev::Get_Instance()->Draw_Rect(m_ImgRect[i]); CGraphicDev::Get_Instance()->Draw_Rect(m_NameRect[i]); CGraphicDev::Get_Instance()->Draw_Rect(m_CostRect[i]); } CGraphicDev::Get_Instance()->Draw_Rect(m_rcScroll[S_UP]); CGraphicDev::Get_Instance()->Draw_Rect(m_rcScroll[S_DOWN]); } } void CShopWnd::Update_World_Matrix(void) { } void CShopWnd::Update_State(void) { } void CShopWnd::Release(void) { } void CShopWnd::Set_Owner(CNpc * pNpc) { m_pShopInven = pNpc->Get_InvenPtr(); }
[ "hjeong.you@gmail.com" ]
hjeong.you@gmail.com
4b715425f1e48c56fdbc5d4bbc5c9a5f69fa4dcb
e06554696936fa87f2956b962e11437539b52460
/fboss/agent/state/RouteNextHopsMulti.h
f362ad8450fac1f89d333383b885a16d7a6fc21d
[ "BSD-3-Clause" ]
permissive
Opportunitylivetv/fboss
8fdf2f5dd79f7904dfc4022a6c892d92b65a016c
34eb8b42803122ca919c337c3fb13374016b377d
refs/heads/master
2021-01-24T19:38:44.745509
2018-02-28T00:11:52
2018-02-28T00:21:34
123,243,322
2
1
null
2018-02-28T06:57:03
2018-02-28T06:57:03
null
UTF-8
C++
false
false
2,627
h
/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #pragma once #include <folly/dynamic.h> #include <folly/FBString.h> #include <folly/IPAddress.h> #include <boost/container/flat_map.hpp> #include "fboss/agent/state/RouteNextHopEntry.h" #include "fboss/agent/if/gen-cpp2/ctrl_types.h" #include "fboss/agent/types.h" namespace facebook { namespace fboss { /** * Class relationship: * * RouteNextHopsMulti is a map from client ID to RouteNextHopEntry. * * There are two types of RouteNextHopEntry in general. * 1) An entry with multiple nexthop IPs (RouteNextHops), OR * 2) no nexthop IPs, but with pre-defined forwarding action * (i.e. ToCPU or DROP) * Each RouteNextHopEntry also has other common attribute, like admin distance. * * RouteNextHops is a set of RouteNextHop. * * RouteNextHop contains the nexthop IP address. In case of the v6 link-local * IP address, the interface ID is also included in this class. * * TODO: Rename RouteNextHops to RouteNextHopSet */ /** * Map form clientId -> RouteNextHopEntry */ class RouteNextHopsMulti { protected: ClientID findLowestAdminDistance(); boost::container::flat_map<ClientID, RouteNextHopEntry> map_; ClientID lowestAdminDistanceClientId_; public: folly::dynamic toFollyDynamicOld() const; static RouteNextHopsMulti fromFollyDynamicOld(const folly::dynamic& json); folly::dynamic toFollyDynamic() const; static RouteNextHopsMulti fromFollyDynamic(const folly::dynamic& json); std::vector<ClientAndNextHops> toThrift() const; std::string str() const; void update(ClientID clientid, RouteNextHopEntry nhe); void update(ClientID clientid, RouteNextHopEntry::NextHopSet nhs) { return update(clientid, RouteNextHopEntry(std::move(nhs))); } void clear() { map_.clear(); } bool operator==(const RouteNextHopsMulti& p2) const { return map_ == p2.map_; } bool isEmpty() const { // The code disallows adding/updating an empty nextHops list. So if the // map contains any entries, they are non-zero-length lists. return map_.empty(); } void delEntryForClient(ClientID clientId); const RouteNextHopEntry* FOLLY_NULLABLE getEntryForClient(ClientID clientId) const; std::pair<ClientID, const RouteNextHopEntry *> getBestEntry() const; bool isSame(ClientID clientId, const RouteNextHopEntry& nhe) const; }; }}
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
9eae35120af52b7316c07b2178dfe87bf1c897ce
73dfe43ddf9d5d7827991655ac7a2a28af4150a5
/signin.cpp
160fd3e0c7a32946b25ded74ae5297127cadd7c1
[]
no_license
himanshuhemu/Library-Management-System
902e9d43ca4f175a026599318c242ffe45291e42
6cc8c943d0012baf796435f52f20b6c00266d360
refs/heads/master
2020-03-23T16:33:11.966772
2018-07-21T14:14:39
2018-07-21T14:14:39
141,817,034
1
0
null
null
null
null
UTF-8
C++
false
false
699
cpp
#include"signin.h" int signin::login() { label: std::cout<<" -> Enter the username \t\n"; std::cout<<" :";std::cin>>username; std::cout<<" -> Enter the password \n"; std::cout<<" :";std::cin>>password; if( username=="admin" && password=="pass") { system("COLOR 7A"); std:: cout<<"Success!!!!!"; } else { system("CLS"); system("COLOR FC"); std::cout<<"ERROR ! Try Again :(\t\n"; goto label; } return 0; }
[ "himanshuk26698@gmail.com" ]
himanshuk26698@gmail.com
b596ccb262e1935fc8292ad0fa31821e8bb8215a
04b9894ec0b1dfab41df8b08e92db8344f4c6e15
/Sort.cpp
c92a03be2154b982bfef39f92d4f269cef38dad7
[]
no_license
Maulik-Khandelwal/Sorting-Visualizer
ddc622c7d9d355665dc60a24a60682b69440a462
c7f8178eca837b77bed82fe6c153db6c0a6f03d2
refs/heads/master
2023-04-10T00:43:00.084522
2021-04-21T05:22:58
2021-04-21T05:22:58
360,041,145
0
0
null
null
null
null
UTF-8
C++
false
false
141
cpp
#include "Sort.h" Animation::Animation(AnimationType type, int first, int second) : type(type), firstIndex(first), secondIndex(second) { }
[ "kmaulik07@gmail.com" ]
kmaulik07@gmail.com
e5c19ea3b58588706e90d1ee490ffd863847ea27
0ba1465b0499f4b5311bfdc73f30235553725f26
/src/Kernel/spot-on-starbeam-writer.cc
982f1c125d5f0e9ebc8e8eca0da05dca0f68b9ff
[]
no_license
berndhs/droidhola
cba52766df2364923449bc81cbc7bb509dc41cc1
ea60927783c1987f9046e33f20439537ed9c3022
refs/heads/master
2020-08-01T20:50:59.180605
2017-01-02T12:13:17
2017-01-02T12:13:17
73,574,391
0
0
null
null
null
null
UTF-8
C++
false
false
14,079
cc
/* ** Copyright (c) 2011 - 10^10^10, Alexis Megas. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions ** are met: ** 1. Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** 2. Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** 3. The name of the author may not be used to endorse or promote products ** derived from Spot-On without specific prior written permission. ** ** SPOT-ON IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 ** SPOT-ON, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <QDataStream> #include <QDir> #include <QSqlDatabase> #include <QSqlQuery> #include "Common/spot-on-crypt.h" #include "Common/spot-on-misc.h" #include "spot-on-kernel.h" #include "spot-on-starbeam-writer.h" #ifdef Q_OS_UNIX extern "C" { #include <unistd.h> } #endif spoton_starbeam_writer::spoton_starbeam_writer(QObject *parent): QThread(parent) { } spoton_starbeam_writer::~spoton_starbeam_writer() { quit(); wait(); } void spoton_starbeam_writer::run(void) { spoton_starbeam_writer_worker worker(this); connect(this, SIGNAL(newData(const QByteArray &, const QStringByteArrayHash &)), &worker, SLOT(slotNewData(const QByteArray &, const QStringByteArrayHash &))); exec(); } void spoton_starbeam_writer::processData (const QByteArray &dataIn, const QStringByteArrayHash &magnet) { if(dataIn.isEmpty() || magnet.isEmpty()) { if(dataIn.isEmpty()) spoton_misc::logError("spoton_starbeam_writer::processData(): " "dataIn is empty."); else spoton_misc::logError("spoton_starbeam_writer::processData(): " "magnet is empty."); return; } QByteArray data(dataIn.trimmed()); QList<QByteArray> list(data.split('\n')); if(list.size() != 3) return; for(int i = 0; i < list.size(); i++) list.replace(i, QByteArray::fromBase64(list.at(i))); bool ok = true; spoton_crypt crypt(magnet.value("ct").constData(), "", QByteArray(), magnet.value("ek"), 0, 0, ""); data = crypt.decrypted(list.value(0), &ok); if(!ok) return; QList<QByteArray> novas; QReadLocker locker(&m_keyMutex); novas = m_novas; locker.unlock(); QByteArray d (data.mid(0, data.length() - spoton_crypt::XYZ_DIGEST_OUTPUT_SIZE_IN_BYTES)); QByteArray messageCode(data.mid(d.length())); bool found = false; for(int i = 0; i < novas.size(); i++) { QByteArray bytes; QByteArray computedHash; bool ok = true; spoton_crypt crypt ("aes256", "sha512", QByteArray(), novas.at(i).mid(0, static_cast<int> (spoton_crypt:: cipherKeyLength("aes256"))), novas.at(i).mid(static_cast<int> (spoton_crypt:: cipherKeyLength("aes256"))), 0, 0, ""); computedHash = crypt.keyedHash(d, &ok); if(!ok) continue; if(!computedHash.isEmpty() && !messageCode.isEmpty() && spoton_crypt::memcmp(computedHash, messageCode)) { bytes = crypt.decrypted(d, &ok); if(ok) { found = true; list.clear(); QDataStream stream(&bytes, QIODevice::ReadOnly); for(int i = 0; i < 8; i++) { QByteArray a; stream >> a; if(stream.status() != QDataStream::Ok) { list.clear(); break; } else list << a; } break; } } } if(!found) { QDataStream stream(&data, QIODevice::ReadOnly); list.clear(); for(int i = 0; i < 8; i++) { QByteArray a; stream >> a; if(stream.status() != QDataStream::Ok) { list.clear(); break; } else list << a; } } if(list.value(0) != "0060") return; QString connectionName(""); QString fileName (spoton_kernel::setting("gui/etpDestinationPath", QDir::homePath()). toString() + QDir::separator() + QString::fromUtf8(list.value(1).constData(), list.value(1).length()).replace(" ", "-")); int locked = 0; spoton_crypt *s_crypt = spoton_kernel::s_crypts.value("chat", 0); if(s_crypt) { { QSqlDatabase db = spoton_misc::database(connectionName); db.setDatabaseName(spoton_misc::homePath() + QDir::separator() + "starbeam.db"); if(db.open()) { QSqlQuery query(db); bool ok = true; query.setForwardOnly(true); query.prepare("SELECT locked FROM received WHERE file_hash = ?"); query.bindValue (0, s_crypt->keyedHash(fileName.toUtf8(), &ok).toBase64()); if(ok) if(query.exec() && query.next()) locked = query.value(0).toInt(); } db.close(); } QSqlDatabase::removeDatabase(connectionName); if(locked) return; } QByteArray hash = list.value(7); int dataSize = qAbs(static_cast<int> (list.value(3).toLongLong())); int pulseSize = qAbs(static_cast<int> (list.value(6).toLongLong())); qint64 maximumSize = 1048576 * spoton_kernel::setting ("gui/maxMosaicSize", 512).toLongLong(); qint64 position = qAbs(list.value(2).toLongLong()); qint64 totalSize = qAbs(list.value(4).toLongLong()); if(dataSize != list.value(5).length()) // Data { spoton_misc::logError ("spoton_starbeam_writer::processData(): " "dataSize != list.value(5).length()."); return; } else if(dataSize > (pulseSize + pulseSize / 100 + 12)) { spoton_misc::logError ("spoton_starbeam_writer::processData(): " "dataSize > (pulseSize + pulseSize / 100 + 12)."); return; } else if(dataSize > maximumSize || totalSize > maximumSize) { spoton_misc::logError ("spoton_starbeam_writer::processData(): " "dataSize > maximumSize or totalSize > maximumSize."); return; } else if(dataSize > totalSize || position >= totalSize) { spoton_misc::logError ("spoton_starbeam_writer::processData(): " "dataSize > totalSize or position >= totalSize."); return; } else if(pulseSize > maximumSize || pulseSize > spoton_common::MAXIMUM_STARBEAM_PULSE_SIZE) { spoton_misc::logError ("spoton_starbeam_writer::processData(): " "pulseSize > maximumSize or pulseSize > " "spoton_common::MAXIMUM_STARBEAM_PULSE_SIZE."); return; } QFile file; file.setFileName(fileName); if(file.exists()) if(!(file.permissions() & QFile::WriteOwner)) { spoton_misc::logError ("spoton_starbeam_writer::processData(): " "file permissions error."); return; } if(file.open(QIODevice::ReadWrite | QIODevice::Unbuffered)) { if(position > file.size()) if(!file.resize(position)) { ok = false; spoton_misc::logError("spoton_starbeam_writer::processData(): " "resize() failure."); } if(file.seek(position)) { QByteArray data(list.value(5)); data = qUncompress(data); if(static_cast<int> (file.write(data.constData(), data.length())) != data.length()) { ok = false; spoton_misc::logError ("spoton_starbeam_writer::processData(): " "write() failure."); } file.flush(); } else { ok = false; spoton_misc::logError("spoton_starbeam_writer::processData(): " "seek() failure."); } } else spoton_misc::logError("spoton_starbeam_writer::processData(): " "QFile::open() failure."); #ifdef Q_OS_UNIX fsync(file.handle()); #endif file.close(); if(!ok) return; if(!s_crypt) { spoton_misc::logError("spoton_starbeam_writer::processData(): " "s_crypt is zero."); return; } { QSqlDatabase db = spoton_misc::database(connectionName); db.setDatabaseName(spoton_misc::homePath() + QDir::separator() + "starbeam.db"); if(db.open()) { QSqlQuery query(db); bool ok = true; query.prepare ("INSERT OR REPLACE INTO received " "(expected_file_hash, file, file_hash, hash, pulse_size, " "total_size) " "VALUES (?, ?, ?, " "(SELECT hash FROM received WHERE file_hash = ?), ?, ?)"); if(ok) { if(hash.isEmpty()) query.bindValue(0, QVariant::String); else query.bindValue (0, s_crypt-> encryptedThenHashed(hash, &ok).toBase64()); } if(ok) query.bindValue (1, s_crypt-> encryptedThenHashed(fileName.toUtf8(), &ok).toBase64()); if(ok) query.bindValue (2, s_crypt->keyedHash(fileName.toUtf8(), &ok).toBase64()); if(ok) query.bindValue (3, s_crypt->keyedHash(fileName.toUtf8(), &ok).toBase64()); if(ok) query.bindValue (4, s_crypt-> encryptedThenHashed(QByteArray::number(pulseSize), &ok). toBase64()); if(ok) query.bindValue (5, s_crypt-> encryptedThenHashed(QByteArray::number(totalSize), &ok). toBase64()); if(ok) query.exec(); } db.close(); } QSqlDatabase::removeDatabase(connectionName); } void spoton_starbeam_writer::start(void) { /* ** Magnets and nova updates from the user interface ** will trigger slotReadKeys(). */ slotReadKeys(); QThread::start(); } void spoton_starbeam_writer::stop(void) { quit(); wait(); QWriteLocker locker(&m_keyMutex); m_magnets.clear(); m_novas.clear(); locker.unlock(); } void spoton_starbeam_writer::slotReadKeys(void) { spoton_crypt *s_crypt = spoton_kernel::s_crypts.value("chat", 0); if(!s_crypt) { spoton_misc::logError("spoton_starbeam_writer::slotReadKeys(): " "s_crypt is zero."); return; } QString connectionName(""); { QSqlDatabase db = spoton_misc::database(connectionName); db.setDatabaseName (spoton_misc::homePath() + QDir::separator() + "starbeam.db"); if(db.open()) { QWriteLocker locker(&m_keyMutex); m_magnets.clear(); m_novas.clear(); locker.unlock(); QSqlQuery query(db); query.setForwardOnly(true); query.prepare("SELECT magnet FROM magnets"); if(query.exec()) while(query.next()) { QByteArray data (QByteArray::fromBase64(query.value(0).toByteArray())); bool ok = true; data = s_crypt->decryptedAfterAuthenticated(data, &ok); if(!ok) continue; QHash<QString, QByteArray> elements; QList<QByteArray> list (data.remove(0, static_cast<int> (qstrlen("magnet:?"))). split('&')); while(!list.isEmpty()) { QByteArray bytes(list.takeFirst()); if(bytes.startsWith("ct=")) // Cipher Type { bytes.remove(0, 3); elements.insert("ct", bytes); } else if(bytes.startsWith("ek=")) // Encryption Key { bytes.remove(0, 3); elements.insert("ek", bytes); } else if(bytes.startsWith("ht=")) // Hash Type { bytes.remove(0, 3); elements.insert("ht", bytes); } else if(bytes.startsWith("mk=")) // MAC Key { bytes.remove(0, 3); elements.insert("mk", bytes); } else if(bytes.startsWith("xt=")) { bytes.remove(0, 3); if(bytes == "urn:starbeam") elements.insert("xt", bytes); } } if(elements.contains("xt")) { QWriteLocker locker(&m_keyMutex); m_magnets.append(elements); } } query.prepare("SELECT nova FROM received_novas"); if(query.exec()) while(query.next()) { QByteArray data (QByteArray::fromBase64(query.value(0).toByteArray())); bool ok = true; data = s_crypt->decryptedAfterAuthenticated(data, &ok); if(!ok) continue; QWriteLocker locker(&m_keyMutex); m_novas.append(data); } } db.close(); } QSqlDatabase::removeDatabase(connectionName); } bool spoton_starbeam_writer::append (const QByteArray &data, QPair<QByteArray, QByteArray> &discoveredAdaptiveEchoPair) { if(data.isEmpty()) { spoton_misc::logError("spoton_starbeam_writer::append(): " "data is empty."); return false; } spoton_crypt *s_crypt = spoton_kernel::s_crypts.value("chat", 0); if(!s_crypt) { spoton_misc::logError("spoton_starbeam_writer::append(): " "s_crypt is zero."); return false; } spoton_kernel::discoverAdaptiveEchoPair (data.trimmed(), discoveredAdaptiveEchoPair); QReadLocker locker(&m_keyMutex); if(m_magnets.isEmpty()) return false; QHash<QString, QByteArray> magnet; QList<QByteArray> list(data.trimmed().split('\n')); for(int i = 0; i < list.size(); i++) list.replace(i, QByteArray::fromBase64(list.at(i))); for(int i = 0; i < m_magnets.size(); i++) { QByteArray messageCode; bool ok = true; messageCode = spoton_crypt::keyedHash (list.value(0), m_magnets.at(i).value("mk"), m_magnets.at(i).value("ht"), &ok); if(ok) if(!list.value(1).isEmpty() && !messageCode.isEmpty() && spoton_crypt::memcmp(list.value(1), messageCode)) { magnet = m_magnets.at(i); break; } } locker.unlock(); if(!magnet.isEmpty() && spoton_kernel::setting("gui/etpReceivers", false).toBool()) { /* ** If the thread is not active, it should be! */ if(!isRunning()) start(); emit newData(data, magnet); } return !magnet.isEmpty(); } bool spoton_starbeam_writer::isActive(void) const { return isRunning(); }
[ "bernd.stramm@gmail.com" ]
bernd.stramm@gmail.com
3faa83cada19da2a89f4db57196044b3a4987e78
b64bf08f99596f12b192eef2c844c65e9c723b6c
/1512418_tuan8/1512418/Source/1512418_BT1/main1.cpp
2a1e086783da944a64b22883a59302e2640874fa
[]
no_license
Duy-Phuong/CTDL
db536db059bee155f220fe546906840ef597ccb8
01784cdb92a0a104db53108bd7faea62e05c2ef0
refs/heads/master
2021-08-26T08:39:22.856672
2017-11-22T17:27:32
2017-11-22T17:27:32
111,713,202
0
0
null
null
null
null
UTF-8
C++
false
false
401
cpp
#include "thuvien1.h" int main() { AVLNODE *tree; tree = NULL;// khoi tao cay AVL = NULL int Data; do { cout << "Nhap vao du lieu, -1 de ket thuc: "; cin >> Data; if (Data == -1) break; InsertNode(tree, Data); } while (Data != -1); cout << "\nCay AVL vua tao: \n"; Traverse(tree); RemoveAll(tree); if (tree == NULL) cout << "xoa thanh cong\n"; system("pause"); return 0; }
[ "tranduyphuong20100@gmail.com" ]
tranduyphuong20100@gmail.com
9eb4f051f52a793cbc30f9b29d49e321e6aefadc
d1250816ef08e75669aa5c786684e94aa4f334fa
/experimental/sktext/tests/SelectableText.cpp
c6933697730e7ffd06300f1256fab164de0b3d8f
[ "BSD-3-Clause" ]
permissive
boundaryfree/skia
c5958e83defef659bfef6659db6095982be0a812
54a5744ac9d9530c79d42431dee7edf7678432b8
refs/heads/main
2023-08-22T18:21:17.618446
2021-10-11T07:42:35
2021-10-11T07:42:35
392,546,972
0
0
BSD-3-Clause
2021-08-04T04:25:38
2021-08-04T04:25:38
null
UTF-8
C++
false
false
15,922
cpp
// Copyright 2021 Google LLC. #include "include/core/SkBitmap.h" #include "include/core/SkCanvas.h" #include "include/core/SkColor.h" #include "include/core/SkEncodedImageFormat.h" #include "include/core/SkFontMgr.h" #include "include/core/SkFontStyle.h" #include "include/core/SkImageEncoder.h" #include "include/core/SkPaint.h" #include "include/core/SkPoint.h" #include "include/core/SkRect.h" #include "include/core/SkRefCnt.h" #include "include/core/SkScalar.h" #include "include/core/SkSpan.h" #include "include/core/SkStream.h" #include "include/core/SkString.h" #include "include/core/SkTypeface.h" #include "include/core/SkTypes.h" #include "tests/Test.h" #include "tools/Resources.h" #include "experimental/sktext/include/Text.h" #include "experimental/sktext/src/Paint.h" #include <string.h> #include <algorithm> #include <limits> #include <memory> #include <string> #include <utility> #include <vector> struct GrContextOptions; #define VeryLongCanvasWidth 1000000 #define TestCanvasWidth 1000 #define TestCanvasHeight 600 #if !defined(SK_BUILD_FOR_UNIX) #undef DEF_TEST #define DEF_TEST(name, reporter) \ static void test_##name(skiatest::Reporter* reporter, const GrContextOptions&); \ skiatest::TestRegistry name##TestRegistry(skiatest::Test(#name, false, test_##name)); \ void test_##name(skiatest::Reporter* reporter, const GrContextOptions&) { \ /* SkDebugf("Disabled:"#name "\n"); */ \ } \ void disabled_##name(skiatest::Reporter* reporter, const GrContextOptions&) #endif using namespace skia::text; struct TestLine { size_t index; TextRange lineText; bool hardBreak; SkRect bounds; GlyphRange trailingSpaces; Range<RunIndex> runRange; size_t glyphCount; }; struct TestRun { const SkFont& font; TextRange textRange; // Currently we make sure that the run edges are the grapheme cluster edges SkRect bounds; // bounds contains the physical boundaries of the run int trailingSpaces; // Depending of TextDirection it goes right to the end (LTR) or left to the start (RTL) SkSpan<const uint16_t> glyphs; SkSpan<const SkPoint> positions; SkSpan<const TextIndex> clusters; }; class TestVisitor : public Visitor { public: void onBeginLine(size_t index, TextRange lineText, bool hardBreak, SkRect bounds) override { SkASSERT(fTestLines.size() == index); fTestLines.push_back({ index, lineText, hardBreak, bounds, EMPTY_RANGE, Range<RunIndex>(fTestRuns.size(), fTestRuns.size()), 0 }); } void onEndLine(size_t index, TextRange lineText, GlyphRange trailingSpaces, size_t glyphCount) override { SkASSERT(fTestLines.size() == index + 1); fTestLines.back().trailingSpaces = trailingSpaces; fTestLines.back().runRange.fEnd = fTestRuns.size(); fTestLines.back().glyphCount = glyphCount; } void onGlyphRun(const SkFont& font, TextRange textRange, // Currently we make sure that the run edges are the grapheme cluster edges SkRect bounds, // bounds contains the physical boundaries of the run int trailingSpaces, // Depending of TextDirection it goes right to the end (LTR) or left to the start (RTL) int glyphCount, // Just the number of glyphs const uint16_t glyphs[], const SkPoint positions[], // Positions relative to the line const TextIndex clusters[]) override { fTestRuns.push_back({font, textRange, bounds, trailingSpaces, SkSpan<const uint16_t>(&glyphs[0], glyphCount), SkSpan<const SkPoint>(&positions[0], glyphCount + 1), SkSpan<const TextIndex>(&clusters[0], glyphCount + 1), }); } void onPlaceholder(TextRange, const SkRect& bounds) override { } std::vector<TestLine> fTestLines; std::vector<TestRun> fTestRuns; }; DEF_TEST(SkText_SelectableText_Bounds, reporter) { sk_sp<TrivialFontChain> fontChain = sk_make_sp<TrivialFontChain>("Roboto", 40.0f, SkFontStyle::Normal()); if (fontChain->empty()) return; std::u16string utf16(u" Leading spaces\nTrailing spaces \nLong text with collapsed spaces inside wrapped into few lines"); UnicodeText unicodeText(SkUnicode::Make(), SkSpan<uint16_t>((uint16_t*)utf16.data(), utf16.size())); if (!unicodeText.getUnicode()) return; FontBlock fontBlock(utf16.size(), fontChain); auto fontResolvedText = unicodeText.resolveFonts(SkSpan<FontBlock>(&fontBlock, 1)); auto shapedText = fontResolvedText->shape(&unicodeText, TextDirection::kLtr); auto wrappedText = shapedText->wrap(&unicodeText, 440.0f, 500.0f); auto selectableText = wrappedText->prepareToEdit(&unicodeText); TestVisitor testVisitor; wrappedText->visit(&testVisitor); REPORTER_ASSERT(reporter, selectableText->countLines() == 5); for (LineIndex lineIndex = 0; lineIndex < selectableText->countLines(); ++lineIndex) { auto& testLine = testVisitor.fTestLines[lineIndex]; auto boxLine = selectableText->getLine(lineIndex); SkScalar left = boxLine.fBounds.fLeft; for (auto& box : boxLine.fBoxGlyphs) { REPORTER_ASSERT(reporter, boxLine.fBounds.contains(box) || box.isEmpty()); REPORTER_ASSERT(reporter, left <= box.fLeft); left = box.fRight; } GlyphIndex trailingSpaces = boxLine.fBoxGlyphs.size() - 1; for (RunIndex runIndex = testLine.runRange.fEnd; runIndex > testLine.runRange.fStart; --runIndex) { auto& testRun = testVisitor.fTestRuns[runIndex - 1]; if (testRun.trailingSpaces == 0) { trailingSpaces -= testRun.glyphs.size(); } else { trailingSpaces -= (testRun.glyphs.size() - testRun.trailingSpaces); break; } } REPORTER_ASSERT(reporter, boxLine.fTrailingSpacesEnd == testLine.trailingSpaces.fEnd); REPORTER_ASSERT(reporter, boxLine.fTextEnd == trailingSpaces); REPORTER_ASSERT(reporter, boxLine.fTextRange == testLine.lineText); REPORTER_ASSERT(reporter, boxLine.fIndex == lineIndex); REPORTER_ASSERT(reporter, boxLine.fIsHardBreak == testLine.hardBreak); REPORTER_ASSERT(reporter, boxLine.fBounds == testLine.bounds); } } DEF_TEST(SkText_SelectableText_Navigation_FirstLast, reporter) { sk_sp<TrivialFontChain> fontChain = sk_make_sp<TrivialFontChain>("Roboto", 40.0f, SkFontStyle::Normal()); if (fontChain->empty()) return; std::u16string utf16(u" Leading spaces\nTrailing spaces \nLong text with collapsed spaces inside wrapped into few lines"); UnicodeText unicodeText(SkUnicode::Make(), SkSpan<uint16_t>((uint16_t*)utf16.data(), utf16.size())); if (!unicodeText.getUnicode()) return; FontBlock fontBlock(utf16.size(), fontChain); auto fontResolvedText = unicodeText.resolveFonts(SkSpan<FontBlock>(&fontBlock, 1)); auto shapedText = fontResolvedText->shape(&unicodeText, TextDirection::kLtr); auto wrappedText = shapedText->wrap(&unicodeText, 440.0f, 500.0f); auto selectableText = wrappedText->prepareToEdit(&unicodeText); TestVisitor testVisitor; wrappedText->visit(&testVisitor); // First position auto firstLine = testVisitor.fTestLines.front(); auto firstRun = testVisitor.fTestRuns.front(); auto firstPosition = selectableText->firstPosition(PositionType::kGraphemeCluster); REPORTER_ASSERT(reporter, firstPosition.fLineIndex == 0); REPORTER_ASSERT(reporter, firstPosition.fTextRange == TextRange(0, 0)); REPORTER_ASSERT(reporter, firstPosition.fGlyphRange == GlyphRange(0, 0)); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(firstPosition.fBoundaries.fLeft, 0.0f)); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(firstPosition.fBoundaries.fTop, 0.0f)); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(firstPosition.fBoundaries.width(), 0.0f)); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(firstPosition.fBoundaries.height(), firstLine.bounds.height())); // Last position auto lastLine = testVisitor.fTestLines.back(); auto lastRun = testVisitor.fTestRuns.back(); auto lastPosition = selectableText->lastPosition(PositionType::kGraphemeCluster); REPORTER_ASSERT(reporter, lastPosition.fLineIndex == testVisitor.fTestLines.size() - 1); REPORTER_ASSERT(reporter, lastPosition.fTextRange == TextRange(utf16.size(), utf16.size())); REPORTER_ASSERT(reporter, lastPosition.fGlyphRange == GlyphRange(lastRun.glyphs.size(), lastRun.glyphs.size())); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(lastPosition.fBoundaries.fLeft, lastRun.positions[lastRun.glyphs.size()].fX)); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(lastPosition.fBoundaries.fTop, lastLine.bounds.fTop)); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(lastPosition.fBoundaries.width(), 0.0f)); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(lastPosition.fBoundaries.height(), lastLine.bounds.height())); } DEF_TEST(SkText_SelectableText_ScanRightByGraphemeClusters, reporter) { sk_sp<TrivialFontChain> fontChain = sk_make_sp<TrivialFontChain>("Roboto", 40.0f, SkFontStyle::Normal()); if (fontChain->empty()) return; std::u16string utf16(u" Small Text \n"); UnicodeText unicodeText(SkUnicode::Make(), SkSpan<uint16_t>((uint16_t*)utf16.data(), utf16.size())); if (!unicodeText.getUnicode()) return; FontBlock fontBlock(utf16.size(), fontChain); auto fontResolvedText = unicodeText.resolveFonts(SkSpan<FontBlock>(&fontBlock, 1)); auto shapedText = fontResolvedText->shape(&unicodeText, TextDirection::kLtr); auto wrappedText = shapedText->wrap(&unicodeText, 440.0f, 500.0f); auto selectableText = wrappedText->prepareToEdit(&unicodeText); TestVisitor testVisitor; wrappedText->visit(&testVisitor); auto firstPosition = selectableText->firstPosition(PositionType::kGraphemeCluster); auto lastPosition = selectableText->lastPosition(PositionType::kGraphemeCluster); auto position = firstPosition; while (!(position.fGlyphRange == lastPosition.fGlyphRange)) { auto next = selectableText->nextPosition(position); REPORTER_ASSERT(reporter, position.fTextRange.fEnd == next.fTextRange.fStart); if (position.fLineIndex == next.fLineIndex - 1) { auto line = selectableText->getLine(next.fLineIndex); REPORTER_ASSERT(reporter, next.fGlyphRange.fStart == 0); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(next.fBoundaries.fLeft, 0.0f)); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(next.fBoundaries.fTop, line.fBounds.fTop)); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(next.fBoundaries.height(), line.fBounds.height())); } else { REPORTER_ASSERT(reporter, position.fLineIndex == next.fLineIndex); REPORTER_ASSERT(reporter, position.fGlyphRange.fEnd == next.fGlyphRange.fStart); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(position.fBoundaries.fRight, next.fBoundaries.fLeft)); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(position.fBoundaries.fTop, next.fBoundaries.fTop)); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(position.fBoundaries.height(), next.fBoundaries.height())); } position = next; } } DEF_TEST(SkText_SelectableText_ScanLeftByGraphemeClusters, reporter) { sk_sp<TrivialFontChain> fontChain = sk_make_sp<TrivialFontChain>("Roboto", 40.0f, SkFontStyle::Normal()); if (fontChain->empty()) return; std::u16string utf16(u" Small Text \n"); UnicodeText unicodeText(SkUnicode::Make(), SkSpan<uint16_t>((uint16_t*)utf16.data(), utf16.size())); if (!unicodeText.getUnicode()) return; FontBlock fontBlock(utf16.size(), fontChain); auto fontResolvedText = unicodeText.resolveFonts(SkSpan<FontBlock>(&fontBlock, 1)); auto shapedText = fontResolvedText->shape(&unicodeText, TextDirection::kLtr); auto wrappedText = shapedText->wrap(&unicodeText, 440.0f, 500.0f); auto selectableText = wrappedText->prepareToEdit(&unicodeText); TestVisitor testVisitor; wrappedText->visit(&testVisitor); auto firstPosition = selectableText->firstPosition(PositionType::kGraphemeCluster); auto lastPosition = selectableText->lastPosition(PositionType::kGraphemeCluster); auto position = lastPosition; while (!(position.fGlyphRange == firstPosition.fGlyphRange)) { auto prev = selectableText->previousPosition(position); REPORTER_ASSERT(reporter, position.fTextRange.fEnd == prev.fTextRange.fStart); if (position.fLineIndex == prev.fLineIndex + 1) { auto line = selectableText->getLine(prev.fLineIndex); REPORTER_ASSERT(reporter, prev.fGlyphRange.fEnd == line.fBoxGlyphs.size()); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(prev.fBoundaries.fRight, line.fBounds.fRight)); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(prev.fBoundaries.fTop, line.fBounds.fTop)); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(prev.fBoundaries.height(), line.fBounds.height())); } else { REPORTER_ASSERT(reporter, position.fLineIndex == prev.fLineIndex); REPORTER_ASSERT(reporter, position.fGlyphRange.fStart == prev.fGlyphRange.fEnd); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(position.fBoundaries.fLeft, prev.fBoundaries.fRight)); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(position.fBoundaries.fTop, prev.fBoundaries.fTop)); REPORTER_ASSERT(reporter, SkScalarNearlyEqual(position.fBoundaries.height(), prev.fBoundaries.height())); } position = prev; } } DEF_TEST(SkText_SelectableText_Navigation_UpDown, reporter) { sk_sp<TrivialFontChain> fontChain = sk_make_sp<TrivialFontChain>("Roboto", 40.0f, SkFontStyle::Normal()); if (fontChain->empty()) return; std::u16string utf16(u" Leading spaces\nTrailing spaces \nLong text with collapsed spaces inside wrapped into few lines"); UnicodeText unicodeText(SkUnicode::Make(), SkSpan<uint16_t>((uint16_t*)utf16.data(), utf16.size())); if (!unicodeText.getUnicode()) return; FontBlock fontBlock(utf16.size(), fontChain); auto fontResolvedText = unicodeText.resolveFonts(SkSpan<FontBlock>(&fontBlock, 1)); auto shapedText = fontResolvedText->shape(&unicodeText, TextDirection::kLtr); auto wrappedText = shapedText->wrap(&unicodeText, 440.0f, 500.0f); auto selectableText = wrappedText->prepareToEdit(&unicodeText); TestVisitor testVisitor; wrappedText->visit(&testVisitor); // Upper position auto position = selectableText->lastInLinePosition(PositionType::kGraphemeCluster, 0); while (position.fLineIndex > 0) { auto down = selectableText->downPosition(position); REPORTER_ASSERT(reporter, position.fLineIndex + 1 == down.fLineIndex); REPORTER_ASSERT(reporter, position.fBoundaries.centerX() >= down.fBoundaries.centerX()); position = down; } // Down position position = selectableText->lastInLinePosition(PositionType::kGraphemeCluster, selectableText->countLines() - 1); while (position.fLineIndex < selectableText->countLines() - 1) { auto down = selectableText->downPosition(position); REPORTER_ASSERT(reporter, position.fLineIndex - 1 == down.fLineIndex); REPORTER_ASSERT(reporter, position.fBoundaries.centerX() >= down.fBoundaries.centerX()); position = down; } }
[ "skcq-be@skia-corp.google.com.iam.gserviceaccount.com" ]
skcq-be@skia-corp.google.com.iam.gserviceaccount.com
b34339a8c0e119e60ebc9220d56ef55d55b23411
7fc6b6e9f32de081b2556650db418360b9e3085a
/sdk/main/SdkServer.cpp
aa118f22de8717d852d316173c13a20c894a2124
[ "MIT" ]
permissive
langxgm/xgs
932f4484a56b038bc5ec1bb0317a0fc5776c363a
d75f3f44ca7f9a5e633f5e14330e84a0fa2777ef
refs/heads/master
2021-06-28T15:29:55.975980
2020-10-28T07:38:58
2020-10-28T07:38:58
182,196,267
3
2
null
null
null
null
UTF-8
C++
false
false
1,450
cpp
 #include "SdkServer.h" #include "ResourceModule.h" #include "LogicModule.h" #include "DatabaseModule.h" #include "NetworkModule.h" #include "xbase/ModuleManager.h" #include <glog/logging.h> #include <list> #include <assert.h> SdkServer::SdkServer() { } SdkServer::~SdkServer() { } std::string SdkServer::GetName() { return "SdkServer"; } bool SdkServer::Init(int argc, char** argv) { if (!Application::Init(argc, argv)) return false; ModuleManager::InitInstance(); std::list<Module*> modules; // all module modules.push_back(new ResourceModule()); modules.push_back(new LogicModule()); modules.push_back(new DatabaseModule()); modules.push_back(new NetworkModule()); // register for (Module* m : modules) { ModuleManager::Me()->RegModule(m->GetName(), m); } // init for (Module* m : modules) { bool ret = m->Init(); assert(ret); if (!ret) { LOG(FATAL) << "Module:" << m->GetName() << " init failed"; } } return true; } void SdkServer::Exit() { // exit uint32_t nSize = ModuleManager::Me()->GetSize(); for (uint32_t i = nSize; i > 0; --i) { Module* m = ModuleManager::Me()->GetModuleByIndex(i - 1); m->Exit(); } // destroy ModuleManager::DestroyInstance(); // last Application::Exit(); } void SdkServer::RunOnce() { uint32_t nSize = ModuleManager::Me()->GetSize(); for (uint32_t i = 0; i < nSize; ++i) { Module* m = ModuleManager::Me()->GetModuleByIndex(i); m->RunOnce(); } }
[ "252040903@qq.com" ]
252040903@qq.com
5bc308cb7364dc1f878e0a785a4702c92f8d0030
ceaea7479c220436ebcc0e2fb89e8263deaebfb4
/codejam/taking_metro/tm.cpp
7f5ae64c91b8a1ab38a3faeef3cd3e5ef4486dd2
[]
no_license
ashishsonone/algo
dfb85367cc734b71413f5ae113be14b5b8b60fd4
a077877d630bfb972e8cd222569d55f8c363b13d
refs/heads/master
2016-09-03T07:08:20.180490
2015-07-25T15:50:27
2015-07-25T15:50:27
17,474,647
0
0
null
null
null
null
UTF-8
C++
false
false
4,728
cpp
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <vector> #define MAXDIST 1000000009 using namespace std; //utils int abs(int x){ return x < 0 ? (-x) : (x); } class edge_t; class station_t; //graph strutures class edge_t{ public: station_t * end; int cost; edge_t(int c, station_t* e){ cost = c; end = e; } }; class station_t{ public: bool visited; int distance; int snum; int lnum; vector<edge_t> adjacent; station_t(int l, int s){ visited = false; lnum = l; snum = s; distance = MAXDIST; } void print(){ printf("[%d, %d] ==> ", lnum, snum); for(int i=0; i<adjacent.size(); i++){ printf("{%d, %d, %d} ", adjacent[i].end->lnum, adjacent[i].end->snum, adjacent[i].cost); } printf("\n"); } }; //Aux structures storing direct mapping to station_t in graph struct point_t{ station_t * station; int time; //cum time point_t(int t, int l, int s){ station = new station_t(l, s); time = t; } void print(){ cout << "[" << station->lnum <<","<<station->snum << ","<< time << "]"; } }; class line_t{ public: int W; vector<point_t> points; void print(){ cout << "W=" << W << " : "; for(int i=1; i<points.size(); i++){ points[i].print(); } cout << endl; } void reset(){ for(int i=1; i<points.size(); i++){ points[i].station->visited = false; points[i].station->distance = MAXDIST; } } void make_links(){ for(int i=1; i<points.size(); i++){ for(int j=1; j<points.size(); j++){ //edge from i to j if(i==j) continue; edge_t edge(W + abs(points[i].time - points[j].time), points[j].station); //waiting time added points[i].station->adjacent.push_back(edge); } } } }; vector<line_t> network; //store time void print_network(){ for(int i=1; i<network.size(); i++){ network[i].print(); } } void reset_network(){//go to each station and reset visited bool for(int i=1; i<network.size(); i++){ network[i].reset(); } } void make_links(){ for(int i=1; i<network.size(); i++){ network[i].make_links(); } } station_t * find_min_non_visited(){ int min = MAXDIST+10; station_t * curr = NULL; for(int i=1; i<network.size(); i++){ for(int j=1; j<network[i].points.size(); j++){ //cout << network[i].points.size() << " "<< i << " " <<j << endl; station_t * station = network[i].points[j].station; if(station->visited == false && station->distance < min){ min = station->distance; curr = station; } } } return curr; } int dijkstra(station_t* source, station_t* dest){//return distance reset_network(); source->distance = 0; station_t * curr; while(true){ curr = find_min_non_visited(); //printf("curr [%d, %d] %d \n", curr->lnum, curr->snum, curr->distance); curr->visited = true; if(curr == dest) return curr->distance; for(int i=0; i<curr->adjacent.size(); i++){ edge_t edge = curr->adjacent[i]; station_t * neigh = edge.end; if(curr->distance + edge.cost < neigh->distance){//update neigh->distance = curr->distance + edge.cost; } } } return curr->distance; } int main(){ int T; cin >> T; for(int tc=1; tc<=T; tc++){ network.clear(); line_t linedummy; network.push_back(linedummy); int N; cin >> N; for(int l=1; l <= N; l++){ //l is line # line_t line; int S, W; cin >> S >> W; //waiting time line.W = W; //dummy point_t pdummy(-1,-1,-1); line.points.push_back(pdummy); int cumtime = 0; int s; //station # for(s=1; s<=S-1; s++){ //S-1 times int t; cin >> t; point_t point(cumtime, l, s); line.points.push_back(point); cumtime += t; } point_t point(cumtime, l, s); line.points.push_back(point); network.push_back(line); } //print_network(); make_links(); //make link(edges) from each station to every other station in each line //add tunnels int M; cin >> M; for(int i=0; i<M; i++){ int m1, s1, m2, s2, t; cin >> m1 >> s1 >> m2 >> s2 >> t; //cout << m1 << " " << s1 << endl; station_t * station1 = network[m1].points[s1].station; station_t * station2 = network[m2].points[s2].station; edge_t e12(t, station2); //no waiting time edge_t e21(t, station1); station1->adjacent.push_back(e12); station2->adjacent.push_back(e21); } //network[1].points[2].station->print(); //network[2].points[2].station->print(); int Q; cin >> Q; printf("Case #%d:\n", tc); for(int i=0; i<Q; i++){ int m1, s1, m2, s2; cin >> m1 >> s1 >> m2 >> s2; int dist = dijkstra(network[m1].points[s1].station, network[m2].points[s2].station); if(dist >= MAXDIST) dist = -1; //printf("[%d, %d] to [%d, %d] : %d\n", m1, s1, m2, s2, dist); printf("%d\n", dist); } } }
[ "ashson07@gmail.com" ]
ashson07@gmail.com
29e7191b5b3f9041b5464f291b8a34c471f94bc0
3371f703ad7dc22eaaea4fbec7f1644dc0ee2eac
/fastcp/qfilecopyimp.h
c02e411ba134517522a6fed068339d8670a26e7b
[]
no_license
holylong/crossbaseutils
632630f4c2a2149b0c29cdbffce1d89b7cc89dff
ebcac98a32f1b1cb67863e60106b885866cd2981
refs/heads/main
2023-08-25T05:46:59.756552
2021-10-16T03:59:35
2021-10-16T03:59:35
308,282,794
0
0
null
null
null
null
UTF-8
C++
false
false
518
h
#ifndef QFILECOPYIMP_H #define QFILECOPYIMP_H #include <QString> #include <vector> enum COPY_ERROR{ COPY_ok, COPY_error_last_is_file, COPY_error_unknow }; class QFileCopyImp { public: QFileCopyImp(); bool copyFileToPath(QString sourceDir ,QString toDir, bool coverFileIfExist); bool copyDirectoryFiles(const QString &fromDir, const QString &toDir, bool coverFileIfExist); COPY_ERROR copyMultiFile(std::vector<QString> arrFilesOrDir, bool coverFileIfExist); }; #endif // QFILECOPYIMP_H
[ "longlong921012@" ]
longlong921012@
2163e797cc12ccce7b914f1d0aeed2a03de4c01b
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/llvm/lib/Target/SystemZ/MCTargetDesc/SystemZMCAsmInfo.h
d440787de54805c26e478106367741bc40e70bda
[ "MIT", "NCSA", "BSD-3-Clause", "NTP", "LicenseRef-scancode-unknown-license-reference" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
757
h
//====-- SystemZMCAsmInfo.h - SystemZ asm properties -----------*- C++ -*--===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef SystemZTARGETASMINFO_H #define SystemZTARGETASMINFO_H #include "llvm/MC/MCAsmInfo.h" #include "llvm/Support/Compiler.h" namespace llvm { class StringRef; class SystemZMCAsmInfo : public MCAsmInfo { public: explicit SystemZMCAsmInfo(StringRef TT); // Override MCAsmInfo; virtual const MCSection *getNonexecutableStackSection(MCContext &Ctx) const LLVM_OVERRIDE; }; } // namespace llvm #endif
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
b04cd1941b51b83f87699b154b692b81d15faf48
786de89be635eb21295070a6a3452f3a7fe6712c
/psddl_pds2psana/tags/V00-07-00/src/epics.ddl.cpp
dc1abed9570dcd2450a645d20c0cea74fc9c1d4f
[]
no_license
connectthefuture/psdmrepo
85267cfe8d54564f99e17035efe931077c8f7a37
f32870a987a7493e7bf0f0a5c1712a5a030ef199
refs/heads/master
2021-01-13T03:26:35.494026
2015-09-03T22:22:11
2015-09-03T22:22:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
23,015
cpp
// *** Do not edit this file, it is auto-generated *** #include "psddl_pds2psana/epics.ddl.h" #include <cstddef> #include <stdexcept> namespace psddl_pds2psana { namespace Epics { Psana::Epics::DbrTypes pds_to_psana(PsddlPds::Epics::DbrTypes e) { return Psana::Epics::DbrTypes(e); } Psana::Epics::epicsTimeStamp pds_to_psana(PsddlPds::Epics::epicsTimeStamp pds) { return Psana::Epics::epicsTimeStamp(pds.sec(), pds.nsec()); } Psana::Epics::dbr_time_string pds_to_psana(PsddlPds::Epics::dbr_time_string pds) { return Psana::Epics::dbr_time_string(pds.status(), pds.severity(), pds_to_psana(pds.stamp())); } Psana::Epics::dbr_time_short pds_to_psana(PsddlPds::Epics::dbr_time_short pds) { return Psana::Epics::dbr_time_short(pds.status(), pds.severity(), pds_to_psana(pds.stamp())); } Psana::Epics::dbr_time_float pds_to_psana(PsddlPds::Epics::dbr_time_float pds) { return Psana::Epics::dbr_time_float(pds.status(), pds.severity(), pds_to_psana(pds.stamp())); } Psana::Epics::dbr_time_enum pds_to_psana(PsddlPds::Epics::dbr_time_enum pds) { return Psana::Epics::dbr_time_enum(pds.status(), pds.severity(), pds_to_psana(pds.stamp())); } Psana::Epics::dbr_time_char pds_to_psana(PsddlPds::Epics::dbr_time_char pds) { return Psana::Epics::dbr_time_char(pds.status(), pds.severity(), pds_to_psana(pds.stamp())); } Psana::Epics::dbr_time_long pds_to_psana(PsddlPds::Epics::dbr_time_long pds) { return Psana::Epics::dbr_time_long(pds.status(), pds.severity(), pds_to_psana(pds.stamp())); } Psana::Epics::dbr_time_double pds_to_psana(PsddlPds::Epics::dbr_time_double pds) { return Psana::Epics::dbr_time_double(pds.status(), pds.severity(), pds_to_psana(pds.stamp())); } Psana::Epics::dbr_sts_string pds_to_psana(PsddlPds::Epics::dbr_sts_string pds) { return Psana::Epics::dbr_sts_string(pds.status(), pds.severity()); } Psana::Epics::dbr_ctrl_short pds_to_psana(PsddlPds::Epics::dbr_ctrl_short pds) { return Psana::Epics::dbr_ctrl_short(pds.status(), pds.severity(), pds.units(), pds.upper_disp_limit(), pds.lower_disp_limit(), pds.upper_alarm_limit(), pds.upper_warning_limit(), pds.lower_warning_limit(), pds.lower_alarm_limit(), pds.upper_ctrl_limit(), pds.lower_ctrl_limit()); } Psana::Epics::dbr_ctrl_float pds_to_psana(PsddlPds::Epics::dbr_ctrl_float pds) { return Psana::Epics::dbr_ctrl_float(pds.status(), pds.severity(), pds.precision(), pds.units(), pds.upper_disp_limit(), pds.lower_disp_limit(), pds.upper_alarm_limit(), pds.upper_warning_limit(), pds.lower_warning_limit(), pds.lower_alarm_limit(), pds.upper_ctrl_limit(), pds.lower_ctrl_limit()); } Psana::Epics::dbr_ctrl_enum pds_to_psana(PsddlPds::Epics::dbr_ctrl_enum pds) { return Psana::Epics::dbr_ctrl_enum(pds.status(), pds.severity(), pds.no_str(), pds.strings(0)); } Psana::Epics::dbr_ctrl_char pds_to_psana(PsddlPds::Epics::dbr_ctrl_char pds) { return Psana::Epics::dbr_ctrl_char(pds.status(), pds.severity(), pds.units(), pds.upper_disp_limit(), pds.lower_disp_limit(), pds.upper_alarm_limit(), pds.upper_warning_limit(), pds.lower_warning_limit(), pds.lower_alarm_limit(), pds.upper_ctrl_limit(), pds.lower_ctrl_limit()); } Psana::Epics::dbr_ctrl_long pds_to_psana(PsddlPds::Epics::dbr_ctrl_long pds) { return Psana::Epics::dbr_ctrl_long(pds.status(), pds.severity(), pds.units(), pds.upper_disp_limit(), pds.lower_disp_limit(), pds.upper_alarm_limit(), pds.upper_warning_limit(), pds.lower_warning_limit(), pds.lower_alarm_limit(), pds.upper_ctrl_limit(), pds.lower_ctrl_limit()); } Psana::Epics::dbr_ctrl_double pds_to_psana(PsddlPds::Epics::dbr_ctrl_double pds) { return Psana::Epics::dbr_ctrl_double(pds.status(), pds.severity(), pds.precision(), pds.units(), pds.upper_disp_limit(), pds.lower_disp_limit(), pds.upper_alarm_limit(), pds.upper_warning_limit(), pds.lower_warning_limit(), pds.lower_alarm_limit(), pds.upper_ctrl_limit(), pds.lower_ctrl_limit()); } EpicsPvHeader::EpicsPvHeader(const boost::shared_ptr<const XtcType>& xtcPtr) : Psana::Epics::EpicsPvHeader() , m_xtcObj(xtcPtr) { } EpicsPvHeader::~EpicsPvHeader() { } int16_t EpicsPvHeader::pvId() const { return m_xtcObj->pvId(); } int16_t EpicsPvHeader::dbrType() const { return m_xtcObj->dbrType(); } int16_t EpicsPvHeader::numElements() const { return m_xtcObj->numElements(); } uint8_t EpicsPvHeader::isCtrl() const { return m_xtcObj->isCtrl(); } uint8_t EpicsPvHeader::isTime() const { return m_xtcObj->isTime(); } uint16_t EpicsPvHeader::status() const { return m_xtcObj->status(); } uint16_t EpicsPvHeader::severity() const { return m_xtcObj->severity(); } EpicsPvCtrlHeader::EpicsPvCtrlHeader(const boost::shared_ptr<const XtcType>& xtcPtr) : Psana::Epics::EpicsPvCtrlHeader() , m_xtcObj(xtcPtr) { } EpicsPvCtrlHeader::~EpicsPvCtrlHeader() { } int16_t EpicsPvCtrlHeader::pvId() const { return m_xtcObj->pvId(); } int16_t EpicsPvCtrlHeader::dbrType() const { return m_xtcObj->dbrType(); } int16_t EpicsPvCtrlHeader::numElements() const { return m_xtcObj->numElements(); } uint8_t EpicsPvCtrlHeader::isCtrl() const { return m_xtcObj->isCtrl(); } uint8_t EpicsPvCtrlHeader::isTime() const { return m_xtcObj->isTime(); } uint16_t EpicsPvCtrlHeader::status() const { return m_xtcObj->status(); } uint16_t EpicsPvCtrlHeader::severity() const { return m_xtcObj->severity(); } const char* EpicsPvCtrlHeader::pvName() const { return m_xtcObj->pvName(); } EpicsPvTimeHeader::EpicsPvTimeHeader(const boost::shared_ptr<const XtcType>& xtcPtr) : Psana::Epics::EpicsPvTimeHeader() , m_xtcObj(xtcPtr) { } EpicsPvTimeHeader::~EpicsPvTimeHeader() { } int16_t EpicsPvTimeHeader::pvId() const { return m_xtcObj->pvId(); } int16_t EpicsPvTimeHeader::dbrType() const { return m_xtcObj->dbrType(); } int16_t EpicsPvTimeHeader::numElements() const { return m_xtcObj->numElements(); } uint8_t EpicsPvTimeHeader::isCtrl() const { return m_xtcObj->isCtrl(); } uint8_t EpicsPvTimeHeader::isTime() const { return m_xtcObj->isTime(); } uint16_t EpicsPvTimeHeader::status() const { return m_xtcObj->status(); } uint16_t EpicsPvTimeHeader::severity() const { return m_xtcObj->severity(); } Psana::Epics::epicsTimeStamp EpicsPvTimeHeader::stamp() const { return pds_to_psana(m_xtcObj->stamp()); } EpicsPvCtrlString::EpicsPvCtrlString(const boost::shared_ptr<const XtcType>& xtcPtr) : Psana::Epics::EpicsPvCtrlString() , m_xtcObj(xtcPtr) , _dbr(psddl_pds2psana::Epics::pds_to_psana(xtcPtr->dbr())) { } EpicsPvCtrlString::~EpicsPvCtrlString() { } int16_t EpicsPvCtrlString::pvId() const { return m_xtcObj->pvId(); } int16_t EpicsPvCtrlString::dbrType() const { return m_xtcObj->dbrType(); } int16_t EpicsPvCtrlString::numElements() const { return m_xtcObj->numElements(); } uint8_t EpicsPvCtrlString::isCtrl() const { return m_xtcObj->isCtrl(); } uint8_t EpicsPvCtrlString::isTime() const { return m_xtcObj->isTime(); } uint16_t EpicsPvCtrlString::status() const { return m_xtcObj->status(); } uint16_t EpicsPvCtrlString::severity() const { return m_xtcObj->severity(); } const char* EpicsPvCtrlString::pvName() const { return m_xtcObj->pvName(); } const Psana::Epics::dbr_sts_string& EpicsPvCtrlString::dbr() const { return _dbr; } const char* EpicsPvCtrlString::data(uint32_t i0) const { return m_xtcObj->data(i0); } const char* EpicsPvCtrlString::value(uint32_t i) const { return m_xtcObj->value(i); } std::vector<int> EpicsPvCtrlString::data_shape() const { return m_xtcObj->data_shape(); } EpicsPvCtrlShort::EpicsPvCtrlShort(const boost::shared_ptr<const XtcType>& xtcPtr) : Psana::Epics::EpicsPvCtrlShort() , m_xtcObj(xtcPtr) , _dbr(psddl_pds2psana::Epics::pds_to_psana(xtcPtr->dbr())) { } EpicsPvCtrlShort::~EpicsPvCtrlShort() { } int16_t EpicsPvCtrlShort::pvId() const { return m_xtcObj->pvId(); } int16_t EpicsPvCtrlShort::dbrType() const { return m_xtcObj->dbrType(); } int16_t EpicsPvCtrlShort::numElements() const { return m_xtcObj->numElements(); } uint8_t EpicsPvCtrlShort::isCtrl() const { return m_xtcObj->isCtrl(); } uint8_t EpicsPvCtrlShort::isTime() const { return m_xtcObj->isTime(); } uint16_t EpicsPvCtrlShort::status() const { return m_xtcObj->status(); } uint16_t EpicsPvCtrlShort::severity() const { return m_xtcObj->severity(); } const char* EpicsPvCtrlShort::pvName() const { return m_xtcObj->pvName(); } const Psana::Epics::dbr_ctrl_short& EpicsPvCtrlShort::dbr() const { return _dbr; } ndarray<const int16_t, 1> EpicsPvCtrlShort::data() const { return m_xtcObj->data(); } int16_t EpicsPvCtrlShort::value(uint32_t i) const { return m_xtcObj->value(i); } EpicsPvCtrlFloat::EpicsPvCtrlFloat(const boost::shared_ptr<const XtcType>& xtcPtr) : Psana::Epics::EpicsPvCtrlFloat() , m_xtcObj(xtcPtr) , _dbr(psddl_pds2psana::Epics::pds_to_psana(xtcPtr->dbr())) { } EpicsPvCtrlFloat::~EpicsPvCtrlFloat() { } int16_t EpicsPvCtrlFloat::pvId() const { return m_xtcObj->pvId(); } int16_t EpicsPvCtrlFloat::dbrType() const { return m_xtcObj->dbrType(); } int16_t EpicsPvCtrlFloat::numElements() const { return m_xtcObj->numElements(); } uint8_t EpicsPvCtrlFloat::isCtrl() const { return m_xtcObj->isCtrl(); } uint8_t EpicsPvCtrlFloat::isTime() const { return m_xtcObj->isTime(); } uint16_t EpicsPvCtrlFloat::status() const { return m_xtcObj->status(); } uint16_t EpicsPvCtrlFloat::severity() const { return m_xtcObj->severity(); } const char* EpicsPvCtrlFloat::pvName() const { return m_xtcObj->pvName(); } const Psana::Epics::dbr_ctrl_float& EpicsPvCtrlFloat::dbr() const { return _dbr; } ndarray<const float, 1> EpicsPvCtrlFloat::data() const { return m_xtcObj->data(); } float EpicsPvCtrlFloat::value(uint32_t i) const { return m_xtcObj->value(i); } EpicsPvCtrlEnum::EpicsPvCtrlEnum(const boost::shared_ptr<const XtcType>& xtcPtr) : Psana::Epics::EpicsPvCtrlEnum() , m_xtcObj(xtcPtr) , _dbr(psddl_pds2psana::Epics::pds_to_psana(xtcPtr->dbr())) { } EpicsPvCtrlEnum::~EpicsPvCtrlEnum() { } int16_t EpicsPvCtrlEnum::pvId() const { return m_xtcObj->pvId(); } int16_t EpicsPvCtrlEnum::dbrType() const { return m_xtcObj->dbrType(); } int16_t EpicsPvCtrlEnum::numElements() const { return m_xtcObj->numElements(); } uint8_t EpicsPvCtrlEnum::isCtrl() const { return m_xtcObj->isCtrl(); } uint8_t EpicsPvCtrlEnum::isTime() const { return m_xtcObj->isTime(); } uint16_t EpicsPvCtrlEnum::status() const { return m_xtcObj->status(); } uint16_t EpicsPvCtrlEnum::severity() const { return m_xtcObj->severity(); } const char* EpicsPvCtrlEnum::pvName() const { return m_xtcObj->pvName(); } const Psana::Epics::dbr_ctrl_enum& EpicsPvCtrlEnum::dbr() const { return _dbr; } ndarray<const uint16_t, 1> EpicsPvCtrlEnum::data() const { return m_xtcObj->data(); } uint16_t EpicsPvCtrlEnum::value(uint32_t i) const { return m_xtcObj->value(i); } EpicsPvCtrlChar::EpicsPvCtrlChar(const boost::shared_ptr<const XtcType>& xtcPtr) : Psana::Epics::EpicsPvCtrlChar() , m_xtcObj(xtcPtr) , _dbr(psddl_pds2psana::Epics::pds_to_psana(xtcPtr->dbr())) { } EpicsPvCtrlChar::~EpicsPvCtrlChar() { } int16_t EpicsPvCtrlChar::pvId() const { return m_xtcObj->pvId(); } int16_t EpicsPvCtrlChar::dbrType() const { return m_xtcObj->dbrType(); } int16_t EpicsPvCtrlChar::numElements() const { return m_xtcObj->numElements(); } uint8_t EpicsPvCtrlChar::isCtrl() const { return m_xtcObj->isCtrl(); } uint8_t EpicsPvCtrlChar::isTime() const { return m_xtcObj->isTime(); } uint16_t EpicsPvCtrlChar::status() const { return m_xtcObj->status(); } uint16_t EpicsPvCtrlChar::severity() const { return m_xtcObj->severity(); } const char* EpicsPvCtrlChar::pvName() const { return m_xtcObj->pvName(); } const Psana::Epics::dbr_ctrl_char& EpicsPvCtrlChar::dbr() const { return _dbr; } ndarray<const uint8_t, 1> EpicsPvCtrlChar::data() const { return m_xtcObj->data(); } uint8_t EpicsPvCtrlChar::value(uint32_t i) const { return m_xtcObj->value(i); } EpicsPvCtrlLong::EpicsPvCtrlLong(const boost::shared_ptr<const XtcType>& xtcPtr) : Psana::Epics::EpicsPvCtrlLong() , m_xtcObj(xtcPtr) , _dbr(psddl_pds2psana::Epics::pds_to_psana(xtcPtr->dbr())) { } EpicsPvCtrlLong::~EpicsPvCtrlLong() { } int16_t EpicsPvCtrlLong::pvId() const { return m_xtcObj->pvId(); } int16_t EpicsPvCtrlLong::dbrType() const { return m_xtcObj->dbrType(); } int16_t EpicsPvCtrlLong::numElements() const { return m_xtcObj->numElements(); } uint8_t EpicsPvCtrlLong::isCtrl() const { return m_xtcObj->isCtrl(); } uint8_t EpicsPvCtrlLong::isTime() const { return m_xtcObj->isTime(); } uint16_t EpicsPvCtrlLong::status() const { return m_xtcObj->status(); } uint16_t EpicsPvCtrlLong::severity() const { return m_xtcObj->severity(); } const char* EpicsPvCtrlLong::pvName() const { return m_xtcObj->pvName(); } const Psana::Epics::dbr_ctrl_long& EpicsPvCtrlLong::dbr() const { return _dbr; } ndarray<const int32_t, 1> EpicsPvCtrlLong::data() const { return m_xtcObj->data(); } int32_t EpicsPvCtrlLong::value(uint32_t i) const { return m_xtcObj->value(i); } EpicsPvCtrlDouble::EpicsPvCtrlDouble(const boost::shared_ptr<const XtcType>& xtcPtr) : Psana::Epics::EpicsPvCtrlDouble() , m_xtcObj(xtcPtr) , _dbr(psddl_pds2psana::Epics::pds_to_psana(xtcPtr->dbr())) { } EpicsPvCtrlDouble::~EpicsPvCtrlDouble() { } int16_t EpicsPvCtrlDouble::pvId() const { return m_xtcObj->pvId(); } int16_t EpicsPvCtrlDouble::dbrType() const { return m_xtcObj->dbrType(); } int16_t EpicsPvCtrlDouble::numElements() const { return m_xtcObj->numElements(); } uint8_t EpicsPvCtrlDouble::isCtrl() const { return m_xtcObj->isCtrl(); } uint8_t EpicsPvCtrlDouble::isTime() const { return m_xtcObj->isTime(); } uint16_t EpicsPvCtrlDouble::status() const { return m_xtcObj->status(); } uint16_t EpicsPvCtrlDouble::severity() const { return m_xtcObj->severity(); } const char* EpicsPvCtrlDouble::pvName() const { return m_xtcObj->pvName(); } const Psana::Epics::dbr_ctrl_double& EpicsPvCtrlDouble::dbr() const { return _dbr; } ndarray<const double, 1> EpicsPvCtrlDouble::data() const { return m_xtcObj->data(); } double EpicsPvCtrlDouble::value(uint32_t i) const { return m_xtcObj->value(i); } EpicsPvTimeString::EpicsPvTimeString(const boost::shared_ptr<const XtcType>& xtcPtr) : Psana::Epics::EpicsPvTimeString() , m_xtcObj(xtcPtr) , _dbr(psddl_pds2psana::Epics::pds_to_psana(xtcPtr->dbr())) { } EpicsPvTimeString::~EpicsPvTimeString() { } int16_t EpicsPvTimeString::pvId() const { return m_xtcObj->pvId(); } int16_t EpicsPvTimeString::dbrType() const { return m_xtcObj->dbrType(); } int16_t EpicsPvTimeString::numElements() const { return m_xtcObj->numElements(); } uint8_t EpicsPvTimeString::isCtrl() const { return m_xtcObj->isCtrl(); } uint8_t EpicsPvTimeString::isTime() const { return m_xtcObj->isTime(); } uint16_t EpicsPvTimeString::status() const { return m_xtcObj->status(); } uint16_t EpicsPvTimeString::severity() const { return m_xtcObj->severity(); } Psana::Epics::epicsTimeStamp EpicsPvTimeString::stamp() const { return pds_to_psana(m_xtcObj->stamp()); } const Psana::Epics::dbr_time_string& EpicsPvTimeString::dbr() const { return _dbr; } const char* EpicsPvTimeString::data(uint32_t i0) const { return m_xtcObj->data(i0); } const char* EpicsPvTimeString::value(uint32_t i) const { return m_xtcObj->value(i); } std::vector<int> EpicsPvTimeString::data_shape() const { return m_xtcObj->data_shape(); } EpicsPvTimeShort::EpicsPvTimeShort(const boost::shared_ptr<const XtcType>& xtcPtr) : Psana::Epics::EpicsPvTimeShort() , m_xtcObj(xtcPtr) , _dbr(psddl_pds2psana::Epics::pds_to_psana(xtcPtr->dbr())) { } EpicsPvTimeShort::~EpicsPvTimeShort() { } int16_t EpicsPvTimeShort::pvId() const { return m_xtcObj->pvId(); } int16_t EpicsPvTimeShort::dbrType() const { return m_xtcObj->dbrType(); } int16_t EpicsPvTimeShort::numElements() const { return m_xtcObj->numElements(); } uint8_t EpicsPvTimeShort::isCtrl() const { return m_xtcObj->isCtrl(); } uint8_t EpicsPvTimeShort::isTime() const { return m_xtcObj->isTime(); } uint16_t EpicsPvTimeShort::status() const { return m_xtcObj->status(); } uint16_t EpicsPvTimeShort::severity() const { return m_xtcObj->severity(); } Psana::Epics::epicsTimeStamp EpicsPvTimeShort::stamp() const { return pds_to_psana(m_xtcObj->stamp()); } const Psana::Epics::dbr_time_short& EpicsPvTimeShort::dbr() const { return _dbr; } ndarray<const int16_t, 1> EpicsPvTimeShort::data() const { return m_xtcObj->data(); } int16_t EpicsPvTimeShort::value(uint32_t i) const { return m_xtcObj->value(i); } EpicsPvTimeFloat::EpicsPvTimeFloat(const boost::shared_ptr<const XtcType>& xtcPtr) : Psana::Epics::EpicsPvTimeFloat() , m_xtcObj(xtcPtr) , _dbr(psddl_pds2psana::Epics::pds_to_psana(xtcPtr->dbr())) { } EpicsPvTimeFloat::~EpicsPvTimeFloat() { } int16_t EpicsPvTimeFloat::pvId() const { return m_xtcObj->pvId(); } int16_t EpicsPvTimeFloat::dbrType() const { return m_xtcObj->dbrType(); } int16_t EpicsPvTimeFloat::numElements() const { return m_xtcObj->numElements(); } uint8_t EpicsPvTimeFloat::isCtrl() const { return m_xtcObj->isCtrl(); } uint8_t EpicsPvTimeFloat::isTime() const { return m_xtcObj->isTime(); } uint16_t EpicsPvTimeFloat::status() const { return m_xtcObj->status(); } uint16_t EpicsPvTimeFloat::severity() const { return m_xtcObj->severity(); } Psana::Epics::epicsTimeStamp EpicsPvTimeFloat::stamp() const { return pds_to_psana(m_xtcObj->stamp()); } const Psana::Epics::dbr_time_float& EpicsPvTimeFloat::dbr() const { return _dbr; } ndarray<const float, 1> EpicsPvTimeFloat::data() const { return m_xtcObj->data(); } float EpicsPvTimeFloat::value(uint32_t i) const { return m_xtcObj->value(i); } EpicsPvTimeEnum::EpicsPvTimeEnum(const boost::shared_ptr<const XtcType>& xtcPtr) : Psana::Epics::EpicsPvTimeEnum() , m_xtcObj(xtcPtr) , _dbr(psddl_pds2psana::Epics::pds_to_psana(xtcPtr->dbr())) { } EpicsPvTimeEnum::~EpicsPvTimeEnum() { } int16_t EpicsPvTimeEnum::pvId() const { return m_xtcObj->pvId(); } int16_t EpicsPvTimeEnum::dbrType() const { return m_xtcObj->dbrType(); } int16_t EpicsPvTimeEnum::numElements() const { return m_xtcObj->numElements(); } uint8_t EpicsPvTimeEnum::isCtrl() const { return m_xtcObj->isCtrl(); } uint8_t EpicsPvTimeEnum::isTime() const { return m_xtcObj->isTime(); } uint16_t EpicsPvTimeEnum::status() const { return m_xtcObj->status(); } uint16_t EpicsPvTimeEnum::severity() const { return m_xtcObj->severity(); } Psana::Epics::epicsTimeStamp EpicsPvTimeEnum::stamp() const { return pds_to_psana(m_xtcObj->stamp()); } const Psana::Epics::dbr_time_enum& EpicsPvTimeEnum::dbr() const { return _dbr; } ndarray<const uint16_t, 1> EpicsPvTimeEnum::data() const { return m_xtcObj->data(); } uint16_t EpicsPvTimeEnum::value(uint32_t i) const { return m_xtcObj->value(i); } EpicsPvTimeChar::EpicsPvTimeChar(const boost::shared_ptr<const XtcType>& xtcPtr) : Psana::Epics::EpicsPvTimeChar() , m_xtcObj(xtcPtr) , _dbr(psddl_pds2psana::Epics::pds_to_psana(xtcPtr->dbr())) { } EpicsPvTimeChar::~EpicsPvTimeChar() { } int16_t EpicsPvTimeChar::pvId() const { return m_xtcObj->pvId(); } int16_t EpicsPvTimeChar::dbrType() const { return m_xtcObj->dbrType(); } int16_t EpicsPvTimeChar::numElements() const { return m_xtcObj->numElements(); } uint8_t EpicsPvTimeChar::isCtrl() const { return m_xtcObj->isCtrl(); } uint8_t EpicsPvTimeChar::isTime() const { return m_xtcObj->isTime(); } uint16_t EpicsPvTimeChar::status() const { return m_xtcObj->status(); } uint16_t EpicsPvTimeChar::severity() const { return m_xtcObj->severity(); } Psana::Epics::epicsTimeStamp EpicsPvTimeChar::stamp() const { return pds_to_psana(m_xtcObj->stamp()); } const Psana::Epics::dbr_time_char& EpicsPvTimeChar::dbr() const { return _dbr; } ndarray<const uint8_t, 1> EpicsPvTimeChar::data() const { return m_xtcObj->data(); } uint8_t EpicsPvTimeChar::value(uint32_t i) const { return m_xtcObj->value(i); } EpicsPvTimeLong::EpicsPvTimeLong(const boost::shared_ptr<const XtcType>& xtcPtr) : Psana::Epics::EpicsPvTimeLong() , m_xtcObj(xtcPtr) , _dbr(psddl_pds2psana::Epics::pds_to_psana(xtcPtr->dbr())) { } EpicsPvTimeLong::~EpicsPvTimeLong() { } int16_t EpicsPvTimeLong::pvId() const { return m_xtcObj->pvId(); } int16_t EpicsPvTimeLong::dbrType() const { return m_xtcObj->dbrType(); } int16_t EpicsPvTimeLong::numElements() const { return m_xtcObj->numElements(); } uint8_t EpicsPvTimeLong::isCtrl() const { return m_xtcObj->isCtrl(); } uint8_t EpicsPvTimeLong::isTime() const { return m_xtcObj->isTime(); } uint16_t EpicsPvTimeLong::status() const { return m_xtcObj->status(); } uint16_t EpicsPvTimeLong::severity() const { return m_xtcObj->severity(); } Psana::Epics::epicsTimeStamp EpicsPvTimeLong::stamp() const { return pds_to_psana(m_xtcObj->stamp()); } const Psana::Epics::dbr_time_long& EpicsPvTimeLong::dbr() const { return _dbr; } ndarray<const int32_t, 1> EpicsPvTimeLong::data() const { return m_xtcObj->data(); } int32_t EpicsPvTimeLong::value(uint32_t i) const { return m_xtcObj->value(i); } EpicsPvTimeDouble::EpicsPvTimeDouble(const boost::shared_ptr<const XtcType>& xtcPtr) : Psana::Epics::EpicsPvTimeDouble() , m_xtcObj(xtcPtr) , _dbr(psddl_pds2psana::Epics::pds_to_psana(xtcPtr->dbr())) { } EpicsPvTimeDouble::~EpicsPvTimeDouble() { } int16_t EpicsPvTimeDouble::pvId() const { return m_xtcObj->pvId(); } int16_t EpicsPvTimeDouble::dbrType() const { return m_xtcObj->dbrType(); } int16_t EpicsPvTimeDouble::numElements() const { return m_xtcObj->numElements(); } uint8_t EpicsPvTimeDouble::isCtrl() const { return m_xtcObj->isCtrl(); } uint8_t EpicsPvTimeDouble::isTime() const { return m_xtcObj->isTime(); } uint16_t EpicsPvTimeDouble::status() const { return m_xtcObj->status(); } uint16_t EpicsPvTimeDouble::severity() const { return m_xtcObj->severity(); } Psana::Epics::epicsTimeStamp EpicsPvTimeDouble::stamp() const { return pds_to_psana(m_xtcObj->stamp()); } const Psana::Epics::dbr_time_double& EpicsPvTimeDouble::dbr() const { return _dbr; } ndarray<const double, 1> EpicsPvTimeDouble::data() const { return m_xtcObj->data(); } double EpicsPvTimeDouble::value(uint32_t i) const { return m_xtcObj->value(i); } Psana::Epics::PvConfigV1 pds_to_psana(PsddlPds::Epics::PvConfigV1 pds) { return Psana::Epics::PvConfigV1(pds.pvId(), pds.description(), pds.interval()); } ConfigV1::ConfigV1(const boost::shared_ptr<const XtcType>& xtcPtr) : Psana::Epics::ConfigV1() , m_xtcObj(xtcPtr) { { typedef ndarray<Psana::Epics::PvConfigV1, 1> NDArray; typedef ndarray<const PsddlPds::Epics::PvConfigV1, 1> XtcNDArray; const XtcNDArray& xtc_ndarr = xtcPtr->pvControls(); _pvControls_ndarray_storage_ = NDArray(xtc_ndarr.shape()); NDArray::iterator out = _pvControls_ndarray_storage_.begin(); for (XtcNDArray::iterator it = xtc_ndarr.begin(); it != xtc_ndarr.end(); ++ it, ++ out) { *out = psddl_pds2psana::Epics::pds_to_psana(*it); } } } ConfigV1::~ConfigV1() { } int32_t ConfigV1::numPv() const { return m_xtcObj->numPv(); } ndarray<const Psana::Epics::PvConfigV1, 1> ConfigV1::pvControls() const { return _pvControls_ndarray_storage_; } } // namespace Epics } // namespace psddl_pds2psana
[ "salnikov@SLAC.STANFORD.EDU@b967ad99-d558-0410-b138-e0f6c56caec7" ]
salnikov@SLAC.STANFORD.EDU@b967ad99-d558-0410-b138-e0f6c56caec7
2b6e34a7af0d9d9338247adb000db18b18d6461c
b5951ea6ab67afb8c4b78fadce6dfba319a1db97
/ADApp/pluginTests/AsynException.h
a0f0dda70e0fd9afd71edb456d913d2691f17818
[ "MIT" ]
permissive
areaDetector/ADCore
0ed64a8a1aac0b67b4294abf09abd74c74d3e54b
64b47e7895ba0f1e109c7edc5909cdd9ac9172a8
refs/heads/master
2023-09-04T10:58:49.419822
2023-08-21T13:36:37
2023-08-21T13:36:37
14,966,162
23
81
NOASSERTION
2023-08-02T14:53:18
2013-12-05T21:23:19
C++
UTF-8
C++
false
false
348
h
/* * AsynException.h * * Created on: 24 Jun 2015 * Author: gnx91527 */ #ifndef ADAPP_PLUGINTESTS_ASYNEXCEPTION_H_ #define ADAPP_PLUGINTESTS_ASYNEXCEPTION_H_ #include <exception> #include <string> class AsynException { public: AsynException(); virtual ~AsynException() throw (); }; #endif /* ADAPP_PLUGINTESTS_ASYNEXCEPTION_H_ */
[ "alan.greer@diamond.ac.uk" ]
alan.greer@diamond.ac.uk
21b68e20960a45f3109c6902bb9260e170d2aa63
965a4a3448a7a24b79bd26ce394399bdad365c72
/source/Game.Shared/InputAction.cpp
ecc05d5bf4c40c371db3afa52947ee7b594069b1
[]
no_license
lohithharesh/DataDrivenGameEngine
3a765099ba182bf1fc2915ad3f39ec6e765ec96e
d0afb3ee9684abb1f0c95df9022c8c7752ced83e
refs/heads/master
2020-03-17T12:00:40.843326
2019-01-03T19:35:30
2019-01-03T19:35:30
133,571,247
0
0
null
null
null
null
UTF-8
C++
false
false
4,872
cpp
#include "pch.h" #include "InputAction.h" #include "WorldState.h" #include "GameObject.h" #include "LevelManager.h" #include "AudioManager.h" namespace FieaGameEngine { RTTI_DEFINITIONS(InputAction) InputAction::InputAction() : Action(InputAction::TypeIdClass()) { } InputAction::~InputAction() { } void FieaGameEngine::InputAction::Update(WorldState & worldState) { Vector<GameObject*> players(0); auto& board = FieaGameEngine::LevelManager::mBoard; for (int i = 0; i < BoardSize; ++i) { for (int j = 0; j < BoardSize; ++j) { for (GameObject* gameObject : board[i][j]) { if (GameObject::mRelationships.At(gameObject->GetGameObjectType()).you) { players.PushBack(gameObject); } } } } for (auto& you : players) { int* youPos = you->GetGameObjectPosition(); std::pair<int, int> dir = InputDirectionHash.At(mInputDirection); std::pair<int, int> pos = { youPos[0] + dir.first, youPos[1] + dir.second }; if (pos.first < 0 || pos.first >= BoardSize || pos.second < 0 || pos.second >= BoardSize) { continue; } bool isThereStop = false; for (GameObject* gameObject : board[pos.first][pos.second]) { if (GameObject::mRelationships.At(gameObject->GetGameObjectType()).stop) { isThereStop = true; break; } } bool isTherePushable = false; bool didPush = false; if (!isThereStop) { for (GameObject* gameObject : board[pos.first][pos.second]) { if (GameObject::mRelationships.At(gameObject->GetGameObjectType()).push) { isTherePushable = true; int poses[2] = { pos.first + InputDirectionHash.At(mInputDirection).first, pos.second + InputDirectionHash.At(mInputDirection).second }; if (PushDirection({ poses[0], poses[1] }, worldState)) { didPush = true; LevelManager::mBoard[gameObject->GetGameObjectPosition()[0]][gameObject->GetGameObjectPosition()[1]].Remove(gameObject); gameObject->SetGameObjectPosition(poses); LevelManager::mBoard[gameObject->GetGameObjectPosition()[0]][gameObject->GetGameObjectPosition()[1]].PushBack(gameObject); break; } } } } if (didPush) { LevelManager::mBoard[you->GetGameObjectPosition()[0]][you->GetGameObjectPosition()[1]].Remove(you); int poses[2] = { youPos[0] + InputDirectionHash.At(mInputDirection).first, youPos[1] + InputDirectionHash.At(mInputDirection).second }; you->SetGameObjectPosition(poses); LevelManager::mBoard[you->GetGameObjectPosition()[0]][you->GetGameObjectPosition()[1]].PushBack(you); AudioManager::Instance()->Play("Move", false); } if (!isThereStop && !isTherePushable) { LevelManager::mBoard[you->GetGameObjectPosition()[0]][you->GetGameObjectPosition()[1]].Remove(you); int poses[2] = { youPos[0] + InputDirectionHash.At(mInputDirection).first, youPos[1] + InputDirectionHash.At(mInputDirection).second }; you->SetGameObjectPosition(poses); LevelManager::mBoard[you->GetGameObjectPosition()[0]][you->GetGameObjectPosition()[1]].PushBack(you); } } } bool FieaGameEngine::InputAction::PushDirection(std::pair<int, int> pos, WorldState & worldState) { if (pos.first < 0 || pos.first >= BoardSize || pos.second < 0 || pos.second >= BoardSize) { return false; } else { auto& board = FieaGameEngine::LevelManager::mBoard; for (GameObject* gameObject : board[pos.first][pos.second]) { if (GameObject::mRelationships.At(gameObject->GetGameObjectType()).stop) { return false; } } for (GameObject* gameObject : board[pos.first][pos.second]) { if (GameObject::mRelationships.At(gameObject->GetGameObjectType()).push) { bool canPush = PushDirection(std::make_pair(pos.first + InputDirectionHash.At(mInputDirection).first, pos.second + InputDirectionHash.At(mInputDirection).second), worldState); if (canPush) { int poses[2] = { pos.first + InputDirectionHash.At(mInputDirection).first, pos.second + InputDirectionHash.At(mInputDirection).second }; LevelManager::mBoard[gameObject->GetGameObjectPosition()[0]][gameObject->GetGameObjectPosition()[1]].Remove(gameObject); gameObject->SetGameObjectPosition(poses); LevelManager::mBoard[gameObject->GetGameObjectPosition()[0]][gameObject->GetGameObjectPosition()[1]].PushBack(gameObject); } return canPush; } } return true; } } void FieaGameEngine::InputAction::SetInputDirection(InputTypesEnum inputType) { mInputDirection = inputType; } const InputTypesEnum & FieaGameEngine::InputAction::SetInputDirection() { return mInputDirection; } Vector<Signature> InputAction::Signatures() { return Action::Signatures(); } Scope * FieaGameEngine::InputAction::Clone(const Scope & rhs) { return new InputAction(*(rhs.As<InputAction>())); } }
[ "lharesh@fiea.local" ]
lharesh@fiea.local
efa58c9a6d3ba174b41ce1427d4f3acd1ceb98e4
c5373d86ab38a3b63442960316e6347bbec8dfb9
/apps/c/shsgc/MPI_OpenMP/zerores_kernel_cpu_kernel.cpp
58c4537635058ec63be60347e49a4565c49bf9a0
[]
no_license
zbeekman/OPS
ab2d26511eec3e262093a566d6858fdc80543f45
54f5bea5d941e4308e1a21422838dceaea917d61
refs/heads/master
2020-12-23T00:59:20.018508
2019-11-08T20:37:34
2019-11-12T19:11:10
236,982,954
1
0
null
2020-01-29T13:01:01
2020-01-29T13:00:59
null
UTF-8
C++
false
false
4,016
cpp
// // auto-generated by ops.py // //user function // host stub function #ifndef OPS_LAZY void ops_par_loop_zerores_kernel(char const *name, ops_block block, int dim, int* range, ops_arg arg0, ops_arg arg1, ops_arg arg2) { #else void ops_par_loop_zerores_kernel_execute(ops_kernel_descriptor *desc) { ops_block block = desc->block; int dim = desc->dim; int *range = desc->range; ops_arg arg0 = desc->args[0]; ops_arg arg1 = desc->args[1]; ops_arg arg2 = desc->args[2]; #endif //Timing double __t1,__t2,__c1,__c2; ops_arg args[3] = { arg0, arg1, arg2}; #if defined(CHECKPOINTING) && !defined(OPS_LAZY) if (!ops_checkpointing_before(args,3,range,2)) return; #endif if (OPS_diags > 1) { ops_timing_realloc(2,"zerores_kernel"); OPS_kernels[2].count++; ops_timers_core(&__c2,&__t2); } #ifdef OPS_DEBUG ops_register_args(args, "zerores_kernel"); #endif //compute locally allocated range for the sub-block int start[1]; int end[1]; #ifdef OPS_MPI int arg_idx[1]; #endif #if defined(OPS_LAZY) || !defined(OPS_MPI) for ( int n=0; n<1; n++ ){ start[n] = range[2*n];end[n] = range[2*n+1]; } #else if (compute_ranges(args, 3,block, range, start, end, arg_idx) < 0) return; #endif //initialize global variable with the dimension of dats //set up initial pointers and exchange halos if necessary int base0 = args[0].dat->base_offset; double * __restrict__ rho_res_p = (double *)(args[0].data + base0); int base1 = args[1].dat->base_offset; double * __restrict__ rhou_res_p = (double *)(args[1].data + base1); int base2 = args[2].dat->base_offset; double * __restrict__ rhoE_res_p = (double *)(args[2].data + base2); #ifndef OPS_LAZY //Halo Exchanges ops_H_D_exchanges_host(args, 3); ops_halo_exchanges(args,3,range); ops_H_D_exchanges_host(args, 3); #endif if (OPS_diags > 1) { ops_timers_core(&__c1,&__t1); OPS_kernels[2].mpi_time += __t1 - __t2; } #pragma omp parallel for for ( int n_x=start[0]; n_x<end[0]; n_x++ ){ ACC<double> rho_res(rho_res_p + n_x*1); ACC<double> rhou_res(rhou_res_p + n_x*1); ACC<double> rhoE_res(rhoE_res_p + n_x*1); rho_res(0) = 0.0; rhou_res(0) = 0.0; rhoE_res(0) = 0.0; } if (OPS_diags > 1) { ops_timers_core(&__c2,&__t2); OPS_kernels[2].time += __t2 - __t1; } #ifndef OPS_LAZY ops_set_dirtybit_host(args, 3); ops_set_halo_dirtybit3(&args[0],range); ops_set_halo_dirtybit3(&args[1],range); ops_set_halo_dirtybit3(&args[2],range); #endif if (OPS_diags > 1) { //Update kernel record ops_timers_core(&__c1,&__t1); OPS_kernels[2].mpi_time += __t1 - __t2; OPS_kernels[2].transfer += ops_compute_transfer(dim, start, end, &arg0); OPS_kernels[2].transfer += ops_compute_transfer(dim, start, end, &arg1); OPS_kernels[2].transfer += ops_compute_transfer(dim, start, end, &arg2); } } #ifdef OPS_LAZY void ops_par_loop_zerores_kernel(char const *name, ops_block block, int dim, int* range, ops_arg arg0, ops_arg arg1, ops_arg arg2) { ops_kernel_descriptor *desc = (ops_kernel_descriptor *)malloc(sizeof(ops_kernel_descriptor)); desc->name = name; desc->block = block; desc->dim = dim; desc->device = 1; desc->index = 2; desc->hash = 5381; desc->hash = ((desc->hash << 5) + desc->hash) + 2; for ( int i=0; i<2; i++ ){ desc->range[i] = range[i]; desc->orig_range[i] = range[i]; desc->hash = ((desc->hash << 5) + desc->hash) + range[i]; } desc->nargs = 3; desc->args = (ops_arg*)malloc(3*sizeof(ops_arg)); desc->args[0] = arg0; desc->hash = ((desc->hash << 5) + desc->hash) + arg0.dat->index; desc->args[1] = arg1; desc->hash = ((desc->hash << 5) + desc->hash) + arg1.dat->index; desc->args[2] = arg2; desc->hash = ((desc->hash << 5) + desc->hash) + arg2.dat->index; desc->function = ops_par_loop_zerores_kernel_execute; if (OPS_diags > 1) { ops_timing_realloc(2,"zerores_kernel"); } ops_enqueue_kernel(desc); } #endif
[ "regulyistvan@gmail.com" ]
regulyistvan@gmail.com
f64d5745c911fc991c22ddbc4a510bbde24706c8
b7f3edb5b7c62174bed808079c3b21fb9ea51d52
/remoting/host/security_key/fake_security_key_message_writer.h
1922e56c00c45cefc72d2437bf06bcd666f316ce
[ "BSD-3-Clause" ]
permissive
otcshare/chromium-src
26a7372773b53b236784c51677c566dc0ad839e4
64bee65c921db7e78e25d08f1e98da2668b57be5
refs/heads/webml
2023-03-21T03:20:15.377034
2020-11-16T01:40:14
2020-11-16T01:40:14
209,262,645
18
21
BSD-3-Clause
2023-03-23T06:20:07
2019-09-18T08:52:07
null
UTF-8
C++
false
false
2,120
h
// 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. #ifndef REMOTING_HOST_SECURITY_KEY_FAKE_SECURITY_KEY_MESSAGE_WRITER_H_ #define REMOTING_HOST_SECURITY_KEY_FAKE_SECURITY_KEY_MESSAGE_WRITER_H_ #include <string> #include "base/callback.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "remoting/host/security_key/security_key_message.h" #include "remoting/host/security_key/security_key_message_writer.h" namespace remoting { // Simulates the SecurityKeyMessageWriter and provides access to data // members for testing. class FakeSecurityKeyMessageWriter : public SecurityKeyMessageWriter { public: explicit FakeSecurityKeyMessageWriter( const base::RepeatingClosure& write_callback); ~FakeSecurityKeyMessageWriter() override; // SecurityKeyMessageWriter interface. bool WriteMessage(SecurityKeyMessageType message_type) override; bool WriteMessageWithPayload(SecurityKeyMessageType message_type, const std::string& message_payload) override; base::WeakPtr<FakeSecurityKeyMessageWriter> AsWeakPtr(); SecurityKeyMessageType last_message_type() { return last_message_type_; } const std::string& last_message_payload() { return last_message_payload_; } void set_write_request_succeeded(bool should_succeed) { write_request_succeeded_ = should_succeed; } private: // Tracks the last message_type value written. SecurityKeyMessageType last_message_type_ = SecurityKeyMessageType::INVALID; // Tracks the last message_payload value written. std::string last_message_payload_; // This value is returned by the WriteMessage* functions above. bool write_request_succeeded_ = true; // Signaled whenever a write is requested. base::RepeatingClosure write_callback_; base::WeakPtrFactory<FakeSecurityKeyMessageWriter> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(FakeSecurityKeyMessageWriter); }; } // namespace remoting #endif // REMOTING_HOST_SECURITY_KEY_FAKE_SECURITY_KEY_MESSAGE_WRITER_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
2208ea695183d1e40e50e637deb8f94b5302b12f
44b6ac6d6709784f1bef2e5947ae01d0412797c4
/include/hdfs.hpp
3588ba62bbc8bd0c6b90a003bef56e03c9ed03c0
[ "Apache-2.0" ]
permissive
Yrp/mysql2hive
9967b8239b5f16924f5e8f553c8fe4d9633a105c
82f246e41458216e5d3215305b8c6d488eaf900b
refs/heads/master
2021-01-23T17:58:43.214006
2015-02-17T12:54:30
2015-02-17T12:54:30
30,831,621
0
0
null
null
null
null
UTF-8
C++
false
false
864
hpp
/* *author:yueruipeng@letv.com *date:2015/1/6 *file:hdfs.hpp * */ #ifndef COM_LETV_BIGDATA_MYSQL2HDFS_HDFS_HPP_ #define COM_LETV_BIGDATA_MYSQL2HDFS_HDFS_HPP_ #include "hdfs.h" #include <string> class Hdfs { public: Hdfs(); Hdfs(const std::string& _nn, tPort _port); ~Hdfs(); bool connect(const std::string& _nn="default", tPort _port=0); bool open(const std::string& _path, int _flags=O_WRONLY|O_CREAT, int _bufferSize=0, short _replication=0, tSize _blockSize=0); tSize write(const std::string& _buffer, tSize _length); tSize write(const std::string& _buffer); tSize write(const void* _buffer, tSize _length); bool exist(const std::string& _path); bool flush(); bool hflush(); bool hsync(); bool close(); private: static const unsigned int BUFFER_MAX_SIZE = 10 * 1024 * 1024; hdfsFS m_fs; hdfsFile m_write; }; #endif
[ "yueruipeng@YpproMacBook-Pro.local" ]
yueruipeng@YpproMacBook-Pro.local
f7b5e21038047060141d585613d2f5f0f3e67cf5
1153020dc34056d0445e1834d8b84cf2604a0637
/BookContainer.h
fa7a96c1d97268719b5a8d6b08cacd1e46569a53
[]
no_license
clementcole/Project
66d8f0f80351a0e993db24f7ee313206e3f70ff1
de8c9edadd4fd953801791e90b54e7ad9f630796
refs/heads/master
2016-09-09T19:50:25.163104
2015-01-27T18:46:06
2015-01-27T18:46:06
29,929,313
0
0
null
null
null
null
UTF-8
C++
false
false
402
h
#include <iostream> #include <string> #include <vector> #include <algorithm> #include "Book.h" using namespace std; #ifndef BookContainer_H #define BookContainer_H class BookContainer{ public: BookContainer(); void AddBook(const vector<Book>& new_Books); void PrintBooks(const vector<Book>&); void DeleteBook(); vector<Book*> m_Books; private: Book* m_bHead; }; #endif
[ "clementacole75@gmail.com" ]
clementacole75@gmail.com
cc42755e747b7ca2ef865da553a642e8e13ed850
51635684d03e47ebad12b8872ff469b83f36aa52
/external/gcc-12.1.0/libstdc++-v3/testsuite/25_algorithms/remove/moveable.cc
f57a9da9d84462cfa3d81e286a7f407c3b990941
[ "LGPL-2.1-only", "GPL-3.0-only", "GCC-exception-3.1", "GPL-2.0-only", "LGPL-3.0-only", "LGPL-2.0-or-later", "Zlib", "LicenseRef-scancode-public-domain" ]
permissive
zhmu/ananas
8fb48ddfe3582f85ff39184fc7a3c58725fe731a
30850c1639f03bccbfb2f2b03361792cc8fae52e
refs/heads/master
2022-06-25T10:44:46.256604
2022-06-12T17:04:40
2022-06-12T17:04:40
30,108,381
59
8
Zlib
2021-09-26T17:30:30
2015-01-31T09:44:33
C
UTF-8
C++
false
false
1,900
cc
// { dg-do run { target c++11 } } // Copyright (C) 2005-2022 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // 25.2.4 remove #undef _GLIBCXX_CONCEPT_CHECKS #include <algorithm> #include <testsuite_hooks.h> #include <testsuite_iterators.h> #include <testsuite_rvalref.h> using __gnu_test::test_container; using __gnu_test::forward_iterator_wrapper; using __gnu_test::rvalstruct; typedef test_container<rvalstruct, forward_iterator_wrapper> Container; void test1() { int intarray[] = {1}; rvalstruct array[1]; std::copy(intarray, intarray + 1, array); Container con(array, array + 1); rvalstruct remove_val0(0); rvalstruct remove_val1(1); VERIFY(std::remove(con.begin(), con.end(), remove_val0).ptr == array + 1); VERIFY(std::remove(con.begin(), con.end(), remove_val1).ptr == array); } void test2() { int intarray[] = {0, 1, 0, 1, 0, 0, 1, 1}; rvalstruct array[8]; std::copy(intarray, intarray + 8, array); Container con(array, array + 8); rvalstruct remove_val(1); VERIFY(std::remove(con.begin(), con.end(), remove_val).ptr == array + 4); VERIFY(array[0].val == 0 && array[1].val == 0 && array[2].val == 0 && array[3].val == 0); } int main() { test1(); test2(); }
[ "rink@rink.nu" ]
rink@rink.nu
25a1a679f6bbaaa907e9d0e9def35f3714b2d20e
081c091a9ab26c6a3f534e13b3d311d5c769b426
/leet143_reorderList.cpp
7c5186980abc33a46d6375c75e83134e378e4575
[]
no_license
jfan04/Leetcode-C--solution
d1d9681804fef6f19ee00175b6563994df93f129
cd58cb2d88a3936efc512b15a8f753800d459f0d
refs/heads/master
2016-09-13T12:06:59.237700
2016-04-16T22:33:02
2016-04-16T22:33:02
56,408,434
0
0
null
null
null
null
UTF-8
C++
false
false
1,136
cpp
//Definition for a singly-linked list. struct ListNode { int val; ListNode *next; ListNode(int x):val(x),next(NULL){} /* data */ }; class Solution{ public: ListNode *reverse(ListNode *head){ if(head==NULL||head->next==NULL) return head; ListNode *cur=head; ListNode *pNext=head->next; cur->next=NULL; while(pNext){ ListNode *tmp=pNext->next; pNext->next=cur; cur=pNext; pNext=tmp; } return cur; } void reorderList(ListNode *head){ if(head==NULL||head->next==NULL) return; ListNode *slow,*fast; slow=fast=head; while(fast){ fast=fast->next; if(fast){ fast=fast->next; } if(fast==NULL) break; slow=slow->next; } ListNode *head2=slow->next; slow->next=NULL; head2=reverse(head2); ListNode *p1=head; ListNode *p2=head2; ListNode *tmp; while(p1&&p2){ tmp=p1->next; p1->next=p2; p1=tmp; tmp=p2->next; p2->next=p1; p2=tmp; } } };
[ "fanjun19901225@gmail.com" ]
fanjun19901225@gmail.com
fcc85b1206b9c566e9b20ef2097717b33651a9c4
6d8f3149df4d81410243793d9ba946407beebc06
/src/frontend/Gui/Gui_sim.cpp
972b0320f052d4ab2c85b7f702cc5a7f4c41f5ab
[ "MIT" ]
permissive
bpapaspyros/RobSim
ed6f7e8ed739a3d813084fe4fe2733682ef6e14b
b126e892910085fde4d14f50380b8db44fa7cd24
refs/heads/master
2021-01-23T14:51:32.490531
2017-04-03T22:33:16
2017-04-03T22:33:16
21,862,493
0
0
null
null
null
null
UTF-8
C++
false
false
6,537
cpp
#include "frontend/Gui/Gui_sim.h" #include <iostream> #include <cmath> #include "frontend/Gui/Gui_print.h" #include "backend/SimulationStatus.h" Gui_sim::Gui_sim() : map_manip(0, 0), r(1, 1){} /*- -------------------------------------------------------------- -*/ void Gui_sim::init(Map &m){ map_manip = m; r = Robot_management(map_manip.get_width(), map_manip.get_height()); m_alpha = 0.3; selected = false; } /*- -------------------------------------------------------------- -*/ void Gui_sim::start_new_sim(){ // if the list has objects from a previous sim we delete them if ( !r.listEmpty() ) { r.emptyList(); } map_manip.reset(); // flags showing that the simulation ended failed = false; succeded = false; // we spawn 3 robots, one of each kind to begin with r.addRobot('A'); r.addRobot('R'); r.addRobot('S'); } /*- -------------------------------------------------------------- -*/ void Gui_sim::runSim(bool paused, int &vel, uint &iter) { if (!paused && !failed && !succeded) { // check if there is a simulation running if (vel < r.roblist[iter]->get_velocity()) { // check if this robot has to move multiple times cur_robot = iter; r.roblist[iter]->move(map_manip); // invoke move method // Handling damage int cur_x = r.roblist[iter]->get_pos_x(); // getting current x position int cur_y = r.roblist[iter]->get_pos_y(); // getting current y position // take damage int damage = pr.takeDamage(r.roblist[iter], map_manip.get_danger(cur_x, cur_y)); (void) damage; // Handling robot operation r.roblist[iter]->operate(map_manip); vel++; }else { vel = 0; iter++; if (iter == r.roblist.size()){ iter = 0; } }// velocity if SimulationStatus stat; failed = stat.fail(); succeded = stat.success(map_manip); }// active sim if } /*- -------------------------------------------------------------- -*/ void Gui_sim::end_sim(){ r.emptyList(); // emptying list map_manip.reset(); // resetting the map } /*- -------------------------------------------------------------- -*/ // draw a square customized so that its bind to our texture void Gui_sim::draw_custom_square(float side, float z, float hoff, float voff, vec3f colour, GLuint tex){ glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, tex); glColor3f(colour.x, colour.y, colour.z); shape.square(side, z, hoff, voff); glDisable(GL_TEXTURE_2D); } /*- -------------------------------------------------------------- -*/ void Gui_sim::draw_map() { float side = 0.4; float zfar = 6; float initX = -2.5; float initY = -6.5; vec3f baseC(1, 1, 1); vec3f backC(0, 0, 0); // robot characteristics int num; char type; selectedX = -1; selectedY = -1; // drawing the map square by square and draqing the robots/flags in the appropriate tile for (int i=0; i<map_manip.get_height(); i++) { for (int j=0; j<map_manip.get_width(); j++) { if (r.checkForRobots(j, i, num, type) ){ switch (type) { case 'R': draw_custom_square(side, zfar, initX, initY, baseC, tex_rescue); break; case 'A': draw_custom_square(side, zfar, initX, initY, baseC, tex_analysis); break; case 'S': draw_custom_square(side, zfar, initX, initY, baseC, tex_research); break; } }else { if (map_manip.flags[j][i]){ draw_custom_square(side, zfar-0.005, initX, initY, baseC, tex_flag); glColor4f(0, 0, 0, m_alpha); shape.square(side, zfar, initX, initY); } } // checkForRobots if-else if (selected && shape.chechInsideSq(side, initX, initY, mouseX, mouseY)){ glColor4f(1, 1, 1, m_alpha); shape.square(side, zfar-0.002, initX, initY); selectedX = j; selectedY = i; }else{ glColor4f(0, 0, 0, m_alpha); shape.square(side, zfar-0.002, initX, initY); }// selected tile if-else initX += 0.9; }// j loop initX = -2.5; initY += 0.9; }// i loop // printing info on the screen menu.round_info(cur_robot, map_manip.get_width(), map_manip.get_height()); menu.base_info(map_manip); } /*- -------------------------------------------------------------- -*/ // checks if a tile is selected void Gui_sim::set_tile_pressed(float world_x, float world_y, float world_z){ selected = true; if(world_z < 3|| world_z >7){ selected = false; } mouseX = world_x; mouseY = world_y; } /*- -------------------------------------------------------------- -*/ // setting the textures that we till use for the robots void Gui_sim::set_textures(GLuint tex[]){ tex_research = tex[0]; tex_rescue = tex[1]; tex_analysis = tex[2]; tex_flag = tex[3]; } /*- -------------------------------------------------------------- -*/ // tile alpha value void Gui_sim::set_alpha(float a){ m_alpha = a; } /*- -------------------------------------------------------------- -*/ float Gui_sim::get_alpha(){ return m_alpha; // returning alpha value } /*- -------------------------------------------------------------- -*/ // add robots void Gui_sim::addRobotPos(char type, int x, int y){ type = tolower(type); r.addRobot(type, x, y); } // remove robots void Gui_sim::removeRobotPos(int x, int y){ char type; int id; if (r.checkForRobots(x, y, id, type)){ r.delete_robot(id); } } // moving robots void Gui_sim::moveRobot(int curX, int curY, int targetX, int targetY){ char type; int id; if(targetX !=-1 && r.checkForRobots(curX, curY, id, type)){ r.roblist[id]->set_pos_x(targetX); r.roblist[id]->set_pos_y(targetY); } } /*- -------------------------------------------------------------- -*/ // returning the selected tile's coordinates void Gui_sim::get_selected_coord(int &sx, int &sy) { sx = selectedX; sy = selectedY; }
[ "b.papaspyros@gmail.com" ]
b.papaspyros@gmail.com
fed47b12caa6bdbc06c72c9c8d2ba7b5bd597a28
b6dc8b6d751bd764076f334521640ac383a14cea
/src/cpp/sortAlgorithm/quickSork.h
3b5e491b8854b9e5761522f8c288f8c327ab5d40
[]
no_license
hucaihui/hucaihui.github.io
9b72c3dd5e84fce49df16865e72ee51bfd4970b1
66870fe55d5c65aa83fab80864715fed08d2ee92
refs/heads/master
2020-05-02T20:08:26.546616
2020-02-07T09:49:56
2020-02-07T09:49:56
178,181,465
5
2
null
null
null
null
GB18030
C++
false
false
1,624
h
#pragma once #include "abstractSort.h" /* 快速排序 --冒泡排序的升级 平均情况 最好情况 最坏情况 辅助空间 稳定性 O(nlogn) O(nlogn) O(nlogn) O(1) 不稳定 */ class quickSort :public abstractSort { public: // void sort(std::vector<int> &nums) { int len = nums.size(); quick_sork(nums, 0, len - 1); } void quick_sork(vector<int> &nums, int low, int high) { if (low < high) { int pivot = partition(nums, low, high); quick_sork(nums, 0, pivot - 1); quick_sork(nums, pivot+1, high); } } void quick_sork_v2(vector<int> &nums, int low, int high) { //尾递归,减少递归深度 if (low < high) { int pivot = partition(nums, low, high); quick_sork(nums, low, pivot - 1); low = pivot + 1; } } int partition(vector<int> &nums, int low, int high) { if (high - low >= 2) { //三个数以上 getMidThreeNum(nums, low, high); } int pivot = nums[low]; //low high low while (low < high) { while (low < high&&pivot <= nums[high]) { //先高后低 high--; } nums[low] = nums[high]; //省略不必要的交换 //sw(nums[low], nums[high]); while (low < high&&nums[low] <= pivot) { low++; } nums[high] = nums[low]; //sw(nums[low], nums[high]); } nums[low] = pivot; return low; //while结束时low=high } void getMidThreeNum(vector<int> &nums, int low, int high) { //三数取中 int mid = low + (high - low) / 2; //结果与(low+high)/2一样,但可以防溢出 if (nums[low] > nums[mid]) sw(nums[low], nums[mid]); if (nums[low] > nums[high]) sw(nums[low], nums[high]); } };
[ "hucaihuime@foxmail.com" ]
hucaihuime@foxmail.com
84a3a39af647792627b9e4fe942b96ff472efba0
b6926a3e90d5f2322cf96e3819415d50a58097e2
/codeforces1408D.cpp
2c33330e8703c011596e5ee7ad80626b6a92c843
[]
no_license
AbhJ/some-cp-files-1
67c6814037e6cbc552119f3d2aa4077616b88667
04e7e62ac7d211bb38dd77dc44558a631805c501
refs/heads/master
2023-07-05T16:36:56.770787
2021-09-03T12:50:13
2021-09-03T12:50:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,866
cpp
//Coded by Abhijay Mitra #include <iostream> #include <stdlib.h> #include <algorithm> #include <cstdio> #include <numeric> #include <cstring> #include <numeric> #include <vector> #include <iterator> #include <map> #include <set> #include <climits> #include <queue> #include <cmath> #include <stack> #include <cctype> #include <bitset> // #include <bits/stdc++.h> #define double long double #define int long long int #define ll int #define ibs ios_base::sync_with_stdio(false) #define cti cin.tie(0) #define bp __builtin_popcount #define pb emplace_back #define koto_memory(a) cout<<(sizeof(a)/1048576.0)<<" MB"; #define res(v) sort(all(v)),v.erase(unique(all(v)), v.end()); #define timer cerr << "Time elapsed : " << 1.0 * clock() / CLOCKS_PER_SEC << " sec "<<endl; #define deb(x) cout<<endl<<"["<<#x<<" = "<<x<<"]"<<endl; using vi = std::vector<int>; using vvi = std::vector<vi>; using pii = std::pair<int,int>; using vpii = std::vector<pii>; using vvpii = std::vector<vpii>; #define mp make_pair #define rep(i,a,b) for (int i = a; i <= b; i++) #define per(i,b,a) for (int i = b; i >= a; i--) #define all(x) x.begin(), x.end() using namespace std; const int N=2e6+10; const int inf = /*0x3f3f3f3f*/1e18+10; // const ll M = 998244353 ; // Mulo // const int M = 1e9+7 ; // Mulo const double Pi = 3.14159265; #define F first #define S second int n,m;int a[N],b[N],c[N],d[N];int Y[N]; void solve(){ cin>>n>>m; rep(i,1,n)cin>>a[i]>>b[i]; rep(i,1,m)cin>>c[i]>>d[i]; rep(i,1,m){ rep(j,1,n)if(c[i]-a[j]>-1){ Y[c[i]-a[j]]=max(Y[c[i]-a[j]],d[i]-b[j]+1); } } per(i,N-2,0){ Y[i]=max(Y[i+1],Y[i]); } int ans=inf; rep(i,0,N-1){ ans=min(ans,i+Y[i]); } cout<<ans<<" "; } int32_t main() { ibs;cti; solve();return 0; int xx=0; int t;cin>>t;while(t--){/*xx++;cout<<"Case "<<xx<<": "*/;solve();cout<<endl;} return 0; }
[ "mitraabhijay@gmail.com" ]
mitraabhijay@gmail.com
b6ec275b3cffa7c048b19a8c1beada7664303f0d
0f5780cdf99c4b4568d8550f2bdfb3a1fa71126d
/src/DirWatcher.h
24d1e047aab9dc9a62c54443849158c91f3ef46f
[]
no_license
lenoval/e
3136e04e5cbfc140368f0ec32c6e500e9773d113
52f3c09282ddbf5c53fe75c1d4395a9bc134f52d
refs/heads/master
2021-01-18T03:51:50.353760
2009-05-08T21:57:49
2009-05-08T21:57:49
196,945
3
1
null
null
null
null
UTF-8
C++
false
false
5,574
h
/******************************************************************************* * * Copyright (C) 2009, Alexander Stigsen, e-texteditor.com * * This software is licensed under the Open Company License as described * in the file license.txt, which you should have received as part of this * distribution. The terms are also available at http://opencompany.org/license. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ******************************************************************************/ #ifndef __DIRWATCHER_H__ #define __DIRWATCHER_H__ #include "wx/wxprec.h" // For compilers that support precompilation, includes "wx/wx.h". #ifdef __WXGTK__ #include <wx/wx.h> #endif #include <wx/thread.h> #ifdef __WXMSW__ #pragma warning(push, 1) #endif #include <vector> #ifdef __WXMSW__ #pragma warning(pop) #endif using namespace std; #define READ_DIR_CHANGE_BUFFER_SIZE 4096 class DirWatcher : public wxThread { public: DirWatcher(); ~DirWatcher(); void* WatchDirectory(const wxString& path, wxEvtHandler& changeHandler, bool watchSubDirs); void UnwatchDirectory(void* handle); #ifdef __WXGTK__ void UnwatchDirByName(const wxString& path, bool unwatchSubDir = false); #endif void UnwatchAllDirectories(); virtual void* Entry(); private: #if defined(__WXGTK__) int m_fd; // file descriptor associated with inotify event class DirWatchInfo { public: DirWatchInfo(int desc, wxEvtHandler& hndl, const wxString& dir) : wd(desc), handler(hndl), path(dir) {}; int GetWD() {return wd;}; wxEvtHandler& GetHandler() {return handler;}; wxString GetPath() {return path;}; private: int wd; wxEvtHandler& handler; wxString path; }; wxEvtHandler* getEvtHandlerByWD(int desc); DirWatcher::DirWatchInfo* getDirWatchInfoByWD(int desc); #elif defined(__WXMSW__) class DirWatchInfo { public: DirWatchInfo(HANDLE hDir, const wxString& directoryName, wxEvtHandler& changeHandler, DWORD dwChangeFilter, bool watchSubDir, const wxString& includeFilter, const wxString& excludeFilter, DWORD dwFilterFlags); bool StartMonitor(HANDLE hCompPort); void UnwatchDirectory(HANDLE hCompPort); void SignalShutdown(HANDLE hCompPort); bool CloseDirectoryHandle(); void ProcessNotification(DWORD& ref_dwReadBuffer_Offset); void Lock() {m_cs.Enter();}; void UnLock() {m_cs.Leave();}; void SignalStartStop() {wxMutexLocker lock(m_sigMutex);m_startStopCond.Signal();}; private: HANDLE m_hDir; wxString m_dirName; wxEvtHandler& m_changeHandler; bool m_watchSubDir; wxString m_includeFilter; wxString m_excludeFilter; int m_changeFilter; int m_filterFlags; OVERLAPPED m_Overlapped; bool m_readDirSuccess; // indicates the success of the call to ReadDirectoryChanges() enum RunningState{ RUNNING_STATE_NOT_SET, RUNNING_STATE_START_MONITORING, RUNNING_STATE_STOP, RUNNING_STATE_STOP_STEP2, RUNNING_STATE_STOPPED, RUNNING_STATE_NORMAL }; RunningState m_runningState; wxCriticalSection m_cs; union { DWORD m_alignment; // buffer has to be DWORD aligned CHAR m_Buffer[ READ_DIR_CHANGE_BUFFER_SIZE ];//buffer for ReadDirectoryChangesW }; DWORD m_dwBufLength;//length or returned data from ReadDirectoryChangesW -- ignored?... wxMutex m_sigMutex; wxCondition m_startStopCond; friend class DirWatcher; }; // Member variables HANDLE m_hCompPort; //i/o completion port #endif //__WXMSW__ vector<DirWatchInfo*> m_dirsWatched; }; enum { DIRWATCHER_FILE_ADDED, DIRWATCHER_FILE_REMOVED, DIRWATCHER_FILE_MODIFIED, DIRWATCHER_FILE_RENAMED }; // Declare custom event BEGIN_DECLARE_EVENT_TYPES() DECLARE_EVENT_TYPE(wxEVT_DIRWATCHER, 801) END_DECLARE_EVENT_TYPES() class wxDirWatcherEvent : public wxEvent { public: wxDirWatcherEvent(int id = 0) : wxEvent(id, wxEVT_DIRWATCHER) {}; wxDirWatcherEvent(const wxDirWatcherEvent& event) : wxEvent(event) { m_changeType = event.m_changeType; m_changedFile = event.m_changedFile.c_str(); m_newFile = event.m_newFile.c_str(); #ifdef __WXGTK__ m_isDir = event.m_isDir; #endif }; virtual ~wxDirWatcherEvent() { // DEBUG: /*if (m_changeType == 0) OutputDebugString(wxT("~DWE: 0 ")); else if (m_changeType == 1) OutputDebugString(wxT("~DWE: 1 ")); else if (m_changeType == 2) OutputDebugString(wxT("~DWE: 2 ")); else { const wxString msg = wxString::Format(wxT("~DWE: %d "), m_changeType); OutputDebugString(msg); } OutputDebugString(m_changedFile); OutputDebugString(m_newFile); OutputDebugString(wxT("\n"));*/ }; virtual wxEvent* Clone() const { return new wxDirWatcherEvent(*this); }; int GetChangeType() const {return m_changeType;}; void SetChangeType(int type) {m_changeType = type;}; const wxString& GetChangedFile() const {return m_changedFile;}; const wxString& GetNewFile() const {return m_newFile;}; void SetChangedFile(const wxString& path) {m_changedFile = path;}; void SetNewFile(const wxString& path) {m_newFile = path;}; #ifdef __WXGTK__ void SetDirFlag(bool dir) {m_isDir = dir;}; bool IsDir() {return m_isDir;}; #endif private: int m_changeType; wxString m_changedFile; wxString m_newFile; #ifdef __WXGTK__ bool m_isDir; #endif }; typedef void (wxEvtHandler::*wxDirWatcherEventFunction) (wxDirWatcherEvent&); #define wxDirWatcherEventHandler(func) (wxObjectEventFunction)(wxEventFunction) (wxDirWatcherEventFunction) &func #define EVT_DIRWATCHER(func) wx__DECLARE_EVT0(wxEVT_DIRWATCHER, wxDirWatcherEventHandler(func)) #endif // __DIRWATCHER_H__
[ "stigsen@e-texteditor.com" ]
stigsen@e-texteditor.com
927e6084027c9c238be6adfbc0eaa4f9cc7e3dfe
0c24202e9e2ec494dd86f95c7eef6dbad10b938d
/source/chapter7/5/src/mytime0.cpp
8bccfa82f33341c1e665caf3b9fd0e72d8f34ef2
[]
no_license
AlexanderLukashuk/MyRepository
78aee7e8cb064211435cb35b8cf2d1ff95817c29
3e5070cd7c9beda6264b67b9f3c56a78b0fd35a9
refs/heads/master
2022-05-03T12:42:51.504274
2022-03-10T16:34:47
2022-03-10T16:34:47
220,230,823
0
0
null
null
null
null
UTF-8
C++
false
false
665
cpp
#include <iostream> #include "../include/mytime0.h" using namespace std; Time::Time() { hours = minutes = 0; } Time::Time(int h, int m) { hours = h; minutes = m; } void Time::addMin(int m) { minutes += m; hours += minutes / 60; minutes %= 60; } void Time::addHr(int h) { hours += h; } void Time::reset(int h, int m) { hours = h; minutes = m; } Time Time::sum(const Time & t) const { Time sum; sum.minutes = minutes + t.minutes; sum.hours = hours + t.hours + sum.minutes / 60; sum.minutes %= 60; return sum; } void Time::show() const { cout << hours << " hours, " << minutes << " minutes" << endl; }
[ "sanya@Sergejs-MacBook-Air.local" ]
sanya@Sergejs-MacBook-Air.local
2b3656747bdb44b7101c4207ea3428db07b7d2c1
4d5770353d96c43093d819552322c4c3e1391e61
/inc/server.hh
eb1c32143482edd2a42f496ca20a3f69c212dea4
[]
no_license
stlcours/ahttpd
509143fbc5d1e0efc37c15afe63227bcd726306d
6bc207a5e01a9a5333b8084be987f0d3a7121170
refs/heads/master
2021-01-21T11:31:05.675763
2016-07-05T06:11:28
2016-07-05T06:11:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,137
hh
#pragma once #include <string> #include <istream> #include "RequestHandler.hh" #include "request.hh" #include "response.hh" #include "ThreadPool.hh" #include "ptrs.hh" namespace ahttpd { class ServerImpl; /** * \brief * Server类,服务器主要类 */ class Server { public: /** 不允许复制 */ Server(const Server&) = delete; Server& operator=(const Server&) = delete; /** * \biref ctor * \param config流,内容为json格式的配置信息 * \param thread_pool_size Server内部的线程池大小 */ explicit Server(std::istream& config, size_t thread_pool_size = 10); /** * \biref ctor * \param service * io_service对象的引用,可由此让Server和其他代码共用一个service * \param config流,内容为json格式的配置信息 * \param thread_pool_size Server内部的线程池大小 */ explicit Server(boost::asio::io_service& service, std::istream& config, size_t thread_pool_size = 10); ~Server(); /** * \brief 启动Server * \param thread_number 分配给io_service的线程数 */ void run(size_t thread_number = 1); /** 停止Server */ void stop(); /** * \brief 对感兴趣的路径进行监听 * \param path 目标路径 * \param handler RequestHandler对象的指针 * \example * Server s(conofig); * s.addHandler("/", main_handler); */ void addHandler(const std::string& path, RequestHandler* handle) { request_handler_.addSubHandler(path, handle); } /** * \brief 转发请求到request handler. * \param req 解析完后的请求,其path指向请求路径 */ void deliverRequest(RequestPtr req) { auto res = std::make_shared<Response>(req->connection()); req->discardConnection(); request_handler_.handleRequest(req, res); if(req->keepAlive() && !res->getHeader("Connection")) res->addHeader("Connection", "keep-alive"); } /** * \brief 获取io_service引用(共享service给其他代码使用 * \example * Server s(config); * s.run(); * ---------另一处的代码---------- * Client c(s.service()); * c.request(...); */ boost::asio::io_service& service() { return service_; } /** * \brief 加入一个任务到线程池 * \param f 描述任务的函数 * \param args 任务函数的参数 * \return std::future */ template<typename _fCallable, typename... _tParams> auto enqueue(_fCallable&& f, _tParams&&... args) { return thread_pool_.enqueue(std::forward<_fCallable>(f), std::forward<_tParams>(args)...); } private: std::unique_ptr<ServerImpl> pimpl_; boost::asio::io_service& service_; RequestHandler request_handler_; size_t thread_pool_size_; ThreadPool thread_pool_; void startAccept(); void do_await_stop(); void handleRequest(ConnectionPtr req); }; } /**< namespace ahttpd */
[ "gnu.crazier@gmail.com" ]
gnu.crazier@gmail.com
6ba0ed4fc3e293b0def2b7059e5a5374edc8ffba
72bd070c76e23142233ff6852577027124658ebc
/SmackTown/Source/SmackTown/SmackTownGameMode.cpp
9113c021129a749ca38115aedc0422c0454dbc38
[]
no_license
jessepark123/MultiSmashGo
fe02802a3a8fb395c0db7a55a007517278bf9df8
b6d7b15d5536885c83ff0b599db3b3f86e2a9f43
refs/heads/master
2021-09-19T21:29:08.022178
2018-08-01T01:25:07
2018-08-01T01:25:07
143,080,682
1
0
null
null
null
null
UTF-8
C++
false
false
488
cpp
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. #include "SmackTownGameMode.h" #include "SmackTownCharacter.h" #include "UObject/ConstructorHelpers.h" ASmackTownGameMode::ASmackTownGameMode() { // set default pawn class to our Blueprinted character static ConstructorHelpers::FClassFinder<APawn> PlayerPawnBPClass(TEXT("/Game/SideScrollerCPP/Blueprints/SideScrollerCharacter")); if (PlayerPawnBPClass.Class != NULL) { DefaultPawnClass = PlayerPawnBPClass.Class; } }
[ "jessepark123@gmail.com" ]
jessepark123@gmail.com