blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
8b298c1663223fb30e2d27a7d3b72343056c6e70
70e9da06a454fc399eee5fb247ca8d362685d470
/Problems/0108_Convert_Sorted_Array_to_Binary_Search_Tree.h
ec01b0cd0b8b706b58d24e5a8ab541c8852a124e
[]
no_license
YejingWang/Leetcode
38499a5d5376e3f18ccece87f70722705771c9ee
b93e914e2acb418f9cdf84b3e6365db68a75e4b0
refs/heads/master
2023-08-05T04:43:45.596671
2021-08-31T09:30:53
2021-08-31T09:30:53
256,743,256
1
0
null
null
null
null
UTF-8
C++
false
false
1,790
h
#pragma once /* 108. Convert Sorted Array to Binary Search Tree https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree. A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one. Example 1: 0 / \ / \ -10 5 \ \ \ \ -3 9 Input: nums = [-10,-3,0,5,9] Output: [0,-3,9,-10,null,5] Explanation: [0,-10,5,null,-3,null,9] is also accepted: Example 2: 3 1 / \ / \ 1 3 Input: nums = [1,3] Output: [3,1] Explanation: [1,3] and [3,1] are both a height-balanced BSTs. Constraints: 1 <= nums.length <= 10^4 -10^4 <= nums[i] <= 10^4 nums is sorted in a strictly increasing order. */ #include <vector> // Definition for a binary tree node. struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; class Solution { public: TreeNode* convert(const std::vector<int>& nums, const int lo, const int hi) { if (lo >= hi) return nullptr; int mid = lo + (hi - lo) / 2; TreeNode* root = new TreeNode(nums[mid]); root->left = convert(nums, lo, mid); root->right = convert(nums, mid + 1, hi); return root; } TreeNode* sortedArrayToBST(std::vector<int>& nums) { // 1. Recursion // Time complexity: O(N) // Space complexity: O(lgN) return convert(nums, 0, nums.size()); } }; /* Tips: */
[ "yw687@cornell.edu" ]
yw687@cornell.edu
9fcda24bfd599aeb455b9171dc9abe59f6b95fce
47de9c88b957dc66c46769f40103d5147b00b7c9
/atcoder/abc187/A.cpp
eea2b88a94f9bed84c0768404a66655a56cbc7de
[]
no_license
autul2017831021/Codeforces_Atcoder_Solved_Problems
1027a606b3cb5be80e57fcfbcfa0327ebd47bd95
b95e432718c9393f8a781fa56c2ed65f082274f5
refs/heads/master
2023-07-02T02:23:58.307782
2021-03-01T13:00:00
2021-07-31T15:40:28
329,067,317
1
0
null
null
null
null
UTF-8
C++
false
false
1,756
cpp
#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef vector<pair<ll,ll> > vp; typedef vector<ll> vc; typedef map<ll,ll> ml; typedef ostringstream OS ; typedef stringstream SS ; typedef double dl; #define pb push_back #define bg begin() #define en end() #define rbg rbegin() #define ren rend() #define sz size() #define nl printf("\n") #define sp printf(" ") #define yes printf("YES\n") #define no printf("NO\n") #define mone printf("-1\n") #define ne cin>> #define de cout<< #define r0 return 0; #define F first #define S second #define its (*it).S #define itf (*it).F #define inf 1000000000000000000 #define ninf -1000000000 #define hoynai cout<<"hoynai"<<endl; #define mod 1000000007 #define pi acos(-1.0) #define FAST_FUCK ios::sync_with_stdio(0); cin.tie(0); cout.tie(0) /* priority_queue<ll,vector<ll>,greater<ll> > */ bool pusu(pair<int,int>a,pair<int,int>b) { if(a.F<b.F || (a.F==b.F && a.S>b.S))return true; return false; } string ntos(ll n) { OS str1 ; str1 << n ; return str1.str(); } ll ston(string s) { ll x ; SS str1(s); str1 >> x ; return x ; } ll bigmod(ll x, ll y) { ll res = 1; while(y>0) { if(y&1) res = (res*x)%mod; y=y>>1; x= (x*x)%mod; } return res; } ll Pow(ll x, ll y) { ll res = 1; while(y>0) { if(y&1) res = (res*x); y=y>>1; x= (x*x); } return res; } ll lcm(ll a,ll b) { return (a*b)/__gcd(a,b); } void A() { int n,m; cin>>n>>m; int a=0,b=0; while(n){ a=a+(n%10); n=n/10; } while(m){ b=b+(m%10); m=m/10; } de max(a,b); } void B() { } void C() { } void D() { } int main() { A(); }
[ "alexiautul@gmail.com" ]
alexiautul@gmail.com
877d5e02ac033664c5e90c2c2304b93d86d9d94e
bf426c05bbef45e9d169d6095e6b49bf66ff4b0c
/mini-common/XFileParser/nodeMesh.h
cf0ac47b610c9ab7c3db5025d3c734db20c718f5
[]
no_license
posejdon256/domek
1757598856ca88826721c432f3b50b65dc886fdd
ff857f17b9c86b682a0b52911e0af1ace63b2907
refs/heads/master
2020-03-19T09:47:22.107073
2018-06-17T22:00:50
2018-06-17T22:00:50
136,317,301
0
0
null
null
null
null
UTF-8
C++
false
false
1,276
h
#pragma once #include "mesh.h" namespace mini { class NodeMesh : public Mesh { public: NodeMesh() : m_materialIdx(UINT_MAX) { } NodeMesh(dx_ptr_vector<ID3D11Buffer>&& vbuffers, std::vector<unsigned int>&& vstrides, std::vector<unsigned int>&& voffsets, dx_ptr<ID3D11Buffer>&& indices, unsigned int indexCount, unsigned int materialIdx) : Mesh(std::move(vbuffers), std::move(vstrides), std::move(voffsets), std::move(indices), indexCount), m_materialIdx(materialIdx) { } NodeMesh(Mesh&& right, unsigned int materialIdx) : Mesh(std::move(right)), m_materialIdx(materialIdx) { } NodeMesh(NodeMesh&& right) : Mesh(std::move(right)), m_materialIdx(right.m_materialIdx), m_transform(right.m_transform) { } NodeMesh(const NodeMesh& right) = delete; NodeMesh& operator=(NodeMesh&& right); NodeMesh& operator= (const NodeMesh& right) = delete; unsigned int getMaterialIdx() const { return m_materialIdx; } void setMaterialIdx(unsigned int idx) { m_materialIdx = idx; } const DirectX::XMFLOAT4X4& getTransform() const { return m_transform; } void setTransform(const DirectX::XMFLOAT4X4& transform) { m_transform = transform; } private: unsigned int m_materialIdx; DirectX::XMFLOAT4X4 m_transform; }; }
[ "aniutka.pop@gmail.com" ]
aniutka.pop@gmail.com
8b1e3b406ead851986a37bcaeedc2a448a58f76b
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/inetsrv/iis/iisrearc/iisplus/w3cache/cachemanager.hxx
e6494cb2241340ceb9d894de04cf2bb19b836821
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
1,122
hxx
#ifndef _CACHEMANAGER_HXX_ #define _CACHEMANAGER_HXX_ #define MAX_CACHE_COUNT 10 class CACHE_MANAGER { public: CACHE_MANAGER(); ~CACHE_MANAGER(); HRESULT Initialize( IMSAdminBase * pAdminBase ); VOID Terminate( VOID ); HRESULT AddNewCache( OBJECT_CACHE * pCache ); HRESULT RemoveCache( OBJECT_CACHE * pCache ); VOID FlushAllCaches( VOID ); HRESULT MonitorDirectory( DIRMON_CONFIG * pDirmonConfig, CDirMonitorEntry ** ppDME ); HRESULT HandleDirMonitorInvalidation( WCHAR * pszFilePath, BOOL fFlushAll ); HRESULT HandleMetadataInvalidation( WCHAR * pszMetabasePath ); private: CDirMonitor * _pDirMonitor; IMSAdminBase * _pAdminBase; OBJECT_CACHE * _Caches[ 10 ]; }; extern CACHE_MANAGER * g_pCacheManager; #endif
[ "seta7D5@protonmail.com" ]
seta7D5@protonmail.com
585edd0a74bc5bc5c19859a40f8ebb9ced9bd03a
266a7683d692568e28f5f49090d2038fb27ff84f
/Arduino_AD9833_serial_controller/Arduino_AD9833_serial_controller.ino
dcc32f3ef16e66677f45150395ea4b176d6ca038
[]
no_license
TomHodson/AFM-zero-phase-detector
2013042631aaf0682ca3131215780771c87cbcb7
12b7234c000f15599b2ad7e06ca7d8ec2df86d15
refs/heads/master
2021-01-14T09:49:37.605251
2017-07-25T09:03:25
2017-07-25T09:03:25
68,515,290
1
0
null
null
null
null
UTF-8
C++
false
false
2,750
ino
#include <SPI.h> const float refFreq = 25000000.0; // On-board crystal reference frequency #define SPI_CLOCK_SPEED 12000000 const int SINE = 0x2003; // Define AD9833's waveform register value. const int SQUARE = 0x2020; // When we update the frequency, we need to const int TRIANGLE = 0x2002; // define the waveform when we end writing. const int FSYNC = 10; // Standard SPI pins for the AD9833 waveform generator. const int CLK = 13; // CLK and DATA pins are shared with the TFT display. const int DATA = 11; void setup() { Serial.begin(9600); Serial.setTimeout(5000); Serial.println("Send a value"); SPI.begin(); SPI.setDataMode(SPI_MODE2); delay(50); pinMode(FSYNC, OUTPUT); AD9833reset(); delay(1000); AD9833setFrequency(32000, SINE); AD9833setFrequency(32000, SINE); } long last_ping = 0; void loop() { long f = Serial.parseInt(); if(f) { //AD9833reset(); AD9833setFrequency(f, SINE); delay(50); Serial.print("F set to "); Serial.print(f); Serial.println("Hz"); } if(millis() - last_ping > 1000) { Serial.println("Ping!"); last_ping = millis(); } //long f = 32000.0 + 30000.0 * sin(millis() / 1000.0); //AD9833setFrequency(f, SINE); //delay(10); } // AD9833 documentation advises a 'Reset' on first applying power. void AD9833reset() { SPI.beginTransaction(SPISettings(SPI_CLOCK_SPEED, MSBFIRST, SPI_MODE2)); SPI.transfer16(0x0100); // Write '1' to AD9833 Control register bit D8. delay(10); SPI.endTransaction(); } // Set the frequency and waveform registers in the AD9833. void AD9833setFrequency(long frequency, int Waveform) { long FreqWord = (frequency * pow(2, 28)) / refFreq; int MSB = (int)((FreqWord & 0xFFFC000) >> 14); //Only lower 14 bits are used for data int LSB = (int)(FreqWord & 0x3FFF); //Set control bits 15 and 14 to 0 and 1, respectively, for frequency register 0 LSB |= 0x4000; MSB |= 0x4000; digitalWrite(FSYNC, LOW); // Set FSYNC low before writing to AD9833 registers delayMicroseconds(10); // Give AD9833 time to get ready to receive data. SPI.beginTransaction(SPISettings(SPI_CLOCK_SPEED, MSBFIRST, SPI_MODE2)); SPI.transfer16(0x2100); SPI.transfer16(LSB); // Write lower 16 bits to AD9833 registers SPI.transfer16(MSB); // Write upper 16 bits to AD9833 registers. SPI.transfer16(0xC000); // Phase register SPI.transfer16(Waveform); // Exit & Reset to SINE, SQUARE or TRIANGLE digitalWrite(FSYNC, HIGH); //Write done. Set FSYNC high SPI.endTransaction(); }
[ "thomas.c.hodson@gmail.com" ]
thomas.c.hodson@gmail.com
1093c784ff2e2ed0b830ac0892b04853eb0482a2
2e359b413caee4746e931e01807c279eeea18dca
/956. Tallest Billboard.cpp
614ef7021c36d01becc512ee3754e15d4cd1381e
[]
no_license
fsq/leetcode
3a8826a11df21f8675ad1df3632d74bbbd758b71
70ea4138caaa48cc99bb6e6436afa8bcce370db3
refs/heads/master
2023-09-01T20:30:51.433499
2023-08-31T03:12:30
2023-08-31T03:12:30
117,914,925
7
3
null
null
null
null
UTF-8
C++
false
false
687
cpp
class Solution { public: int tallestBillboard(vector<int>& a) { int n = a.size(); if (n==0) return 0; int s = accumulate(a.begin(), a.end(), 0) / 2; vector<vector<int>> f(n+1, vector<int>(s*2, -1)); f[0][0] = 0; a.insert(a.begin(), 0); for (int i=1; i<=n; ++i) for (int j=0; j<=s; ++j) { f[i][j] = f[i-1][j]; if (f[i-1][j+a[i]]!=-1) f[i][j] = max(f[i][j], f[i-1][j+a[i]]+a[i]); if (f[i-1][abs(a[i]-j)]!=-1) f[i][j] = max(f[i][j], f[i-1][abs(a[i]-j)]+max(a[i]-j, 0)); } return f[n][0]; } };
[ "fengsq@utexas.edu" ]
fengsq@utexas.edu
b9fd13b80d3aa8f5e639affe27d6141a87c34524
928b52d135a0a3be5c91a7e3a1e57395ff507542
/home/home/home.cpp
7976c2365b18581a327df78181b171e8f49978bf
[]
no_license
lepexys/projects
42a31340a75a87633f8a48fa591e44d92b9457c9
7b743a74ff4729eb06f81192e4bfd452bb35b620
refs/heads/master
2023-01-13T23:27:23.082545
2020-08-02T11:21:40
2020-08-02T11:21:40
284,444,894
0
0
null
null
null
null
UTF-8
C++
false
false
6,535
cpp
#include "pch.h" #include <cstdio> #include <iostream> #include <fstream> #include <clocale> #include <iomanip> using namespace std; struct Shower { bool* u,*s,*ls; int n; Shower(unsigned v,int num) { n = num; u = new bool[n]; for (int i = 0; i < n; i++) { u[i] = true; if (i == v) u[i] = false; } s = new bool[n]; ls = new bool[n]; for (int i = 0; i < n; i++) { ls[i] = false; s[i] = false; if (i == v) { s[i] = true; } } } bool Copy() { bool k = false; for (int i = 0; i < n; i++) { if (s[i]) k = true; ls[i] = s[i]; s[i] = false; } return k; } void Show(int **mat,int v) { for (int j = 0; j < n; j++) { if (mat[v][j] == 1) if (u[j]) { cout << j; u[j] = false; s[j] = true; } } } void Check(int **mat) { if(Copy()) { for (int i = 0; i < n; i++) { if (ls[i]) { Show(mat, i); } } Check(mat); } } void Show(int *mat, int v, int c) { for (int j = 0; j < c; j+=2) { if ((mat[j] == v)) if (u[mat[j + 1]]) { cout << mat[j+1]; u[mat[j+1]] = false; s[mat[j+1]] = true; } if (mat[j + 1] == v) if (u[mat[j]]) { cout << mat[j]; u[mat[j]] = false; s[mat[j]] = true; } } } void Check(int *mat, int c) { if (Copy()) { for (int i = 0; i < c; i+=2) { if (ls[mat[i]]) { Show(mat, mat[i], c); } } Check(mat,c); } } }; int main() { int **mat = nullptr, **ormat = nullptr, *list = nullptr; int n = 0; bool k = true; setlocale(LC_ALL, "rus"); while (k) { unsigned t = NULL; cout << "Матрица(\"1\") или список (\"2\")" << endl; cin >> t; if (!t) { cout << "Неправильное значение"; break; } if (t == 1) { k = false; cout << "Матрица задаётся следующим образом:" << endl; cout << "Сначале в файле пишется степень матрицы, затем через пробел её элементы" << endl; cout << "(Если элементов нехватает, матрица дополняется нулями, используются только 0 и 1)" << endl; ifstream file; char buff[20]; file.open("matrix.txt"); if (file.is_open()) cout << "file is open"<<endl; else { cout << "file is not open" << endl; break; } file >> n; mat = new int*[n]; ormat = new int*[n]; for (int i = 0; i < n; i++) { mat[i] = new int[n]; ormat[i] = new int[n]; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (!file.eof()) file >> ormat[i][j]; else ormat[i][j] = 0; if (mat[i][j] != 1) mat[i][j] = ormat[i][j]; if (mat[i][j] == 1) mat[j][i] = 1; } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout<<mat[i][j]; } cout << endl; } unsigned v; do { cout << "Введите номер вершины, из которой происходит обход..."; cin >> v; } while (v >= n); cout << "Очерёдность обхода :"; Shower* sh = new Shower(v,n); sh->Check(mat); cout << endl; int count = 0; cout << " "; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i != j) { if (ormat[i][j] == 1) { count++; cout << i << "->" << j << " "; } } } } cout << endl; int **incmat; incmat = new int*[n]; for (int i = 0; i < n; i++) { incmat[i] = new int[count]; for (int j = 0; j < count; j++) incmat[i][j] = 0; } int p = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i != j) { if (ormat[i][j] == 1) { incmat[i][p] = -1; incmat[j][p] = 1; p++; } } } } for (int i = 0; i < n; i++) { printf("%2d", i); for (int j = 0; j < count; j++) printf("%4d ", incmat[i][j]); cout << endl; } } else if (t == 2) { k = false; cout << "Матрица задаётся следующим образом:" << endl; cout << "Сначале в файле пишется степень матрицы, затем через пробел её элементы" << endl; cout << "(Если элементов нехватает, матрица дополняется нулями, используются только 0 и 1)" << endl; ifstream file; char buff[20]; file.open("matrix.txt", ifstream::in); if (file.is_open()) cout << "file is open" << endl; else { cout << "file is not open" << endl; break; } file >> n; int cnt = 0; mat = new int*[n]; ormat = new int*[n]; for (int i = 0; i < n; i++) { mat[i] = new int[n]; ormat[i] = new int[n]; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (!file.eof()) { file >> ormat[i][j]; if ((ormat[i][j] == 1) && (i != j)) cnt += 2; } else ormat[i][j] = 0; if (mat[i][j] != 1) mat[i][j] = ormat[i][j]; if (mat[i][j] == 1) mat[j][i] = 1; } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << mat[i][j]; } cout << endl; } list = new int[cnt]; int d = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if ((ormat[i][j] == 1) && (i != j)) { list[d] = i; list[d + 1] = j; d += 2; } } } unsigned v; do { cout << "Введите номер вершины, из которой происходит обход..."; cin >> v; } while (v >= n); cout << "Очерёдность обхода :"; Shower* sh = new Shower(v, n); sh->Check(list, cnt); cout << endl; cout << " "; for (int i = 0; i < cnt; i+=2) { cout << list[i] << "->" << list[i+1] << " "; } cout << endl; int **incmat; incmat = new int*[n]; for (int i = 0; i < n; i++) { incmat[i] = new int[cnt/2]; for (int j = 0; j < cnt/2; j++) incmat[i][j] = 0; } int p = 0; for (int i = 0; i < cnt; i+=2) { incmat[list[i]][p] = -1; incmat[list[i+1]][p] = 1; p++; } for (int i = 0; i < n; i++) { printf("%2d", i); for (int j = 0; j < cnt/2; j++) printf("%4d ", incmat[i][j]); cout << endl; } } } return NULL; }
[ "69108266+lepexys@users.noreply.github.com" ]
69108266+lepexys@users.noreply.github.com
dd8e1525639e6c2ed0b75977047906fb25e6165d
24208977b0a9169a416ddc442d333fd2e395869d
/include/paracooba/common/types.h
bc89541cf725c0d6d1b582c10514e9757c68dc98
[ "MIT" ]
permissive
wtmJepsen/Paracooba
def39bc0bfa3695e5b1228c3922071d6104990c4
4ccb4da1b5012cd73fe9081cdaef888d717076cf
refs/heads/master
2023-03-14T12:05:25.005079
2021-03-10T20:38:02
2021-03-10T20:38:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,242
h
#ifndef PARACOOBA_COMMON_TYPES_H #define PARACOOBA_COMMON_TYPES_H #ifdef __cplusplus extern "C" { #endif #include <stddef.h> #include <stdint.h> #include <stdbool.h> typedef uint64_t parac_id; typedef uint32_t parac_worker; typedef struct parac_string_vector { const char** strings; size_t size; } parac_string_vector; typedef enum parac_type { PARAC_TYPE_UINT64, PARAC_TYPE_INT64, PARAC_TYPE_UINT32, PARAC_TYPE_INT32, PARAC_TYPE_UINT16, PARAC_TYPE_INT16, PARAC_TYPE_UINT8, PARAC_TYPE_INT8, PARAC_TYPE_FLOAT, PARAC_TYPE_DOUBLE, PARAC_TYPE_SWITCH, PARAC_TYPE_STR, PARAC_TYPE_VECTOR_STR, } parac_type; typedef union parac_type_union { uint64_t uint64; int64_t int64; uint32_t uint32; int32_t int32; uint16_t uint16; int16_t int16; uint8_t uint8; int8_t int8; float f; double d; bool boolean_switch; const char* string; parac_string_vector string_vector; } parac_type_union; #define _PARAC_TYPE_GET_ASSERT_uint64(UNION, TYPE) \ assert(TYPE == PARAC_TYPE_UINT64); #define _PARAC_TYPE_GET_ASSERT_int64(UNION, TYPE) \ assert(TYPE == PARAC_TYPE_INT64); #define _PARAC_TYPE_GET_ASSERT_uint32(UNION, TYPE) \ assert(TYPE == PARAC_TYPE_UINT32); #define _PARAC_TYPE_GET_ASSERT_int32(UNION, TYPE) \ assert(TYPE == PARAC_TYPE_INT32); #define _PARAC_TYPE_GET_ASSERT_uint16(UNION, TYPE) \ assert(TYPE == PARAC_TYPE_UINT16); #define _PARAC_TYPE_GET_ASSERT_int16(UNION, TYPE) \ assert(TYPE == PARAC_TYPE_INT16); #define _PARAC_TYPE_GET_ASSERT_uint8(UNION, TYPE) \ assert(TYPE == PARAC_TYPE_UINT8); #define _PARAC_TYPE_GET_ASSERT_int8(UNION, TYPE) \ assert(TYPE == PARAC_TYPE_INT8); #define _PARAC_TYPE_GET_ASSERT_f(UNION, TYPE) assert(TYPE == PARAC_TYPE_FLOAT); #define _PARAC_TYPE_GET_ASSERT_d(UNION, TYPE) assert(TYPE == PARAC_TYPE_DOUBLE); #define _PARAC_TYPE_GET_ASSERT_string(UNION, TYPE) \ assert(TYPE == PARAC_TYPE_STRING); #define _PARAC_TYPE_GET_ASSERT_string_vector(UNION, TYPE) \ assert(TYPE == PARAC_TYPE_STRING_VECTOR); #define PARAC_TYPE_GET(UNION, TYPE, MEMBER) UNION.MEMBER #define PARAC_TYPE_ASSERT(UNION, TYPE, MEMBER) \ _PARAC_TYPE_GET_ASSERT_##MEMBER(UNION, TYPE) #ifdef __cplusplus } #include <iostream> inline std::ostream& operator<<(std::ostream& o, const parac_string_vector& v) { for(size_t i = 0; i < v.size; ++i) { o << v.strings[i]; if(i + 1 < v.size) { o << ", "; } } return o; } template<typename Functor> void ApplyFuncToParacTypeUnion(parac_type t, parac_type_union u, Functor f) { switch(t) { case PARAC_TYPE_UINT64: return f(u.uint64); case PARAC_TYPE_INT64: return f(u.int64); case PARAC_TYPE_UINT32: return f(u.uint32); case PARAC_TYPE_INT32: return f(u.int32); case PARAC_TYPE_UINT16: return f(u.uint16); case PARAC_TYPE_INT16: return f(u.int16); case PARAC_TYPE_UINT8: return f(u.uint8); case PARAC_TYPE_INT8: return f(u.int8); case PARAC_TYPE_FLOAT: return f(u.f); case PARAC_TYPE_DOUBLE: return f(u.d); case PARAC_TYPE_STR: return f(u.string); case PARAC_TYPE_SWITCH: return f(u.boolean_switch); case PARAC_TYPE_VECTOR_STR: return f(u.string_vector); } } #endif #endif
[ "mail@maximaximal.com" ]
mail@maximaximal.com
a0120d27632b242be0c157dc4a9a309b7a4f0695
07c856e147c6b3f0fa607ecb632a573c02165f4f
/Ch08_Algorithm/ex38_rotate.cpp
1129acbaa5c0eaa42a137b57dcbb2e4b37040e2f
[]
no_license
choisb/Study-Cpp-STL
46359db3783767b1ef6099761f67164ab637e579
e5b12b6da744f37713983ef6f61d4f0e10a4eb13
refs/heads/master
2023-06-25T04:13:40.960447
2021-07-19T01:38:59
2021-07-19T01:38:59
329,786,891
0
0
null
null
null
null
UHC
C++
false
false
830
cpp
// rotate() 알고리즘 예제 // 순차열을 회전시키려면 rotate()알고리즘 사용 // rotate(b,m,e) 알고리즘은 첫 원소와 마지막 원소가 연결된 것처럼 왼쪽으로 m-b만큼 회전 한다. #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<int> vec1; vec1.push_back(10); vec1.push_back(20); vec1.push_back(30); vec1.push_back(40); vec1.push_back(50); vec1.push_back(60); vec1.push_back(70); vec1.push_back(80); cout << "vec1: "; for (auto v : vec1) cout << v << " "; cout << endl; auto middle = vec1.begin() + 3; rotate(vec1.begin(), middle, vec1.end()); cout << "vec1: "; for (auto v : vec1) cout << v << " "; cout << endl; return 0; } // [출력 결과] // vec1: 10 20 30 40 50 60 70 80 // vec1: 40 50 60 70 80 10 20 30
[ "s004402@gmail.com" ]
s004402@gmail.com
e6d465f57b48e14466888a7c4f468d55f30f5993
2347e342d32b7ad50a27c91d43630cc928234363
/satlib/src/AcisPoint.cpp
c72f2959314284437e218001885ff22347d51847
[ "MIT" ]
permissive
humkyung/app.framework
112ea8269971b990ec0c5a26fca1d14525635d6f
6a709c0ccc6a78e66ad8638b2db9d560da5ee77a
refs/heads/master
2021-01-20T18:33:23.668384
2017-04-04T20:23:57
2017-04-04T20:23:57
63,311,572
0
1
null
null
null
null
UTF-8
C++
false
false
1,504
cpp
// AcisPoint.cpp: implementation of the AcisPoint class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include <tokenizer.h> #include <AcisLib.h> #include <AcisPoint.h> ACISLIB_IMPLEMENT_FUNC(AcisPoint , AcisEntity , TYPELIST({_T("point") , NULL})) ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// AcisPoint::AcisPoint(const TCHAR* pType,const long& nIndex) : AcisEntity(pType,nIndex) { } AcisPoint::~AcisPoint() { } /** @brief The AcisPoint::Parse function @author humkyung @param psz a parameter of type const char* @return bool */ bool AcisPoint::Parse(AcisDoc* pDoc,const TCHAR* psz) { assert(pDoc && psz && "pDoc or psz is NULL"); bool bRet=false; if((NULL != pDoc) && (NULL != psz)) { vector<STRING_T> oResult; CTokenizer<CIsFromString>::Tokenize(oResult,psz,CIsFromString(_T(" \t"))); if(700 == pDoc->GetVer()) { /// ACAD 2004 , ACAD 2005 m_pt.Set(ATOF_T(oResult[4].c_str()) , ATOF_T(oResult[5].c_str()) , ATOF_T(oResult[6].c_str())); } else { m_pt.Set(ATOF_T(oResult[2].c_str()) , ATOF_T(oResult[3].c_str()) , ATOF_T(oResult[4].c_str())); } bRet = true; } return bRet; } /** @brief The AcisPoint::GetPoint function @author humkyung @date @return POINT_T */ CPoint3d AcisPoint::GetPoint() const { return m_pt; }
[ "zbaekhk@gmail.com" ]
zbaekhk@gmail.com
84bb3c7b4f364c8f4f378c8ea4e90dc490edc46f
dffbfae4b192072483996806e3f9dd96cc483c52
/C++/Plazza/Kitchen/ScopedLock.hpp
9cb4676a169a681ad0ae079464bfb3dc2bb121cd
[]
no_license
Zippee0709/Tek2-Project
b14b5c0629d96a5cb6760a2326e84d8d3d1703f6
4aaf18bdbbaabda079e10f8ac128c737caf5337f
refs/heads/master
2023-03-21T02:55:49.585534
2021-03-17T20:03:53
2021-03-17T20:03:53
348,810,770
0
0
null
null
null
null
UTF-8
C++
false
false
350
hpp
/* ** EPITECH PROJECT, 2020 ** bootstrap_plaza ** File description: ** ScopedLock */ #ifndef SCOPEDLOCK_HPP_ #define SCOPEDLOCK_HPP_ #include <iostream> #include "Mutex.hpp" class ScopedLock { public: ScopedLock(Mutex &mutex); ~ScopedLock(); protected: Mutex &_mutex; private: }; #endif /* !SCOPEDLOCK_HPP_ */
[ "zhiwen.wang@epitech.eu" ]
zhiwen.wang@epitech.eu
5cfb27b9d92b072a03c2718a95dbf629852155e6
31ddd3bcf02f103481280b2bee7a9771f5c33c45
/Code/src/system.cpp
fe622ffb80ee1d5d5c37645e84ab45a62f3af3e1
[]
no_license
madhur08/Starling_Murmurations
e5cc667464175ac8cb59f85ebc1857591f29267e
a7989e425de4220f6767a142c298b5b000993518
refs/heads/master
2020-04-01T00:37:48.130047
2018-10-13T15:55:41
2018-10-13T15:55:41
152,705,400
0
0
null
null
null
null
UTF-8
C++
false
false
7,169
cpp
#include "system.h" #include "boid.h" #include "predator.h" #include <bits/stdc++.h> using namespace std; bool printEnergy; void system::toggleEnergyOutput() { printEnergy=1-printEnergy; } float distance(vec3 a,vec3 b) { return length(a-b); } system::system() { setNumBoids(0); printEnergy =false; } void system::addBoid(boid b) { boids.push_back(b); setNumBoids(getNumBoids()+1); } void system::addBoid(vec3 pos) { boids.push_back(boid(pos,this)); setNumBoids(getNumBoids()+1); } void system::addBoid(vec3 pos,vec3 vel) { boids.push_back(boid(pos,vel,this)); setNumBoids(getNumBoids()+1); } void system::addPredator(predator p) { predators.push_back(p); setNumPredators(getNumPredators()+1); } void system::addPredator(vec3 pos) { predators.push_back(predator(pos,this)); setNumPredators(getNumPredators()+1); } void system::addPredator(vec3 pos, vec3 vel) { predators.push_back(predator(pos,vel,this)); setNumPredators(getNumPredators()+1); } void system::addObstacle(vec3 o) { obstacles.push_back(o); setNumObstacles(getNumObstacles()+1); } vector<pair<vec3,vec3>> system::findNeighbouringBoids(vec3 b) { long beg=chrono::duration_cast<chrono::microseconds>(chrono::steady_clock::now().time_since_epoch()).count(); vector<pair<vec3,vec3>> neighbours; vector<float> dist; for(int i=0;i<boids.size();++i) { dist.push_back(distance(b,boids[i].getPosition())); } for(int i=0;i<7;++i) { float minimum=dist[i]; int minindex=i; for(int j=i+1;j<boids.size();++j) { if(dist[j]<minimum) { minimum=dist[j]; minindex=j; } } if(minimum>maxDistForRule1) break; boid temp=boids[minindex]; float temp1=dist[minindex]; boids[minindex]=boids[i]; dist[minindex]=dist[i]; boids[i]=temp; dist[i]=temp1; neighbours.push_back(make_pair(boids[i].getPosition(),boids[i].getVelocity())); } long end=chrono::duration_cast<chrono::microseconds>(chrono::steady_clock::now().time_since_epoch()).count(); return neighbours; } pair<vector<pair<vec3,vec3>>,vector<pair<vec3,vec3>>> system::findVeryCloseObjects(vec3 b) { long beg= chrono::duration_cast<chrono::microseconds>(chrono::steady_clock::now().time_since_epoch()).count(); vector<pair<vec3,vec3>> closeObjects1,closeObjects2; for(int i=0;i<boids.size();++i) { float dist=distance(b,boids[i].getPosition()); if(dist<=(0.5*minDistance)) { closeObjects1.push_back(make_pair(boids[i].getPosition(),boids[i].getVelocity())); } else if(dist<=minDistance) { closeObjects2.push_back(make_pair(boids[i].getPosition(),boids[i].getVelocity())); } } for(int i=0;i<predators.size();++i) { float dist=distance(b,predators[i].getPosition()); if(dist<=(0.5*minDistanceForPredators)) closeObjects1.push_back(make_pair(predators[i].getPosition(),predators[i].getVelocity())); else if(dist<=minDistanceForPredators) closeObjects2.push_back(make_pair(predators[i].getPosition(),predators[i].getVelocity())); } for(int i=0;i<obstacles.size();++i) { float dist=distance(b,obstacles[i]); if(dist<=(0.5*minDistanceForObstacles)) closeObjects1.push_back(make_pair(obstacles[i],obstacles[i])); else if(dist<=minDistanceForObstacles) closeObjects2.push_back(make_pair(obstacles[i],obstacles[i])); } pair<vector<pair<vec3,vec3>>,vector<pair<vec3,vec3>>> closeObjects=make_pair(closeObjects1,closeObjects2); long end= chrono::duration_cast<chrono::microseconds>(chrono::steady_clock::now().time_since_epoch()).count(); return closeObjects; } pair<vector<pair<vec3,vec3>>,vector<pair<vec3,vec3>>> system::findObstaclesForPredator(vec3 b) { vector<pair<vec3,vec3>> closeObjects1,closeObjects2; for(int i=0;i<predators.size();++i) { if(distance(b,predators[i].getPosition())<=(0.7*minDistanceForPredators)) closeObjects1.push_back(make_pair(predators[i].getPosition(),predators[i].getVelocity())); else if(distance(b,predators[i].getPosition())<=(1.4*minDistanceForPredators)) closeObjects2.push_back(make_pair(predators[i].getPosition(),predators[i].getVelocity())); } for(int i=0;i<obstacles.size();++i) { if(distance(b,obstacles[i])<=(0.7*minDistanceForObstacles)) closeObjects1.push_back(make_pair(obstacles[i],obstacles[i])); else if(distance(b,obstacles[i])<=(1.4*minDistanceForObstacles)) closeObjects2.push_back(make_pair(obstacles[i],obstacles[i])); } pair<vector<pair<vec3,vec3>>,vector<pair<vec3,vec3>>> closeObjects=make_pair(closeObjects1,closeObjects2); return closeObjects; } pair<vec3,vec3> system::findNearestBoid(vec3 p) { float mini=0; for(int i=1;i<boids.size();++i) { if(distance(p,boids[i].getPosition())<distance(p,boids[mini].getPosition())) { mini=i; } } return make_pair(boids[mini].getPosition(),boids[mini].getVelocity()); } void system::startWithBoids(int n) { if(n>400) n=400+(n-400)*0.7; int maxSize=2000; int arr1[2000],arr2[2000],arr3[2000]; for(int i=0;i<maxSize;++i) { arr1[i]=i; arr2[i]=i; arr3[i]=i; } int max=maxSize-1; for(int i=max;i>max-n;--i) { int r; bool newFound=false; do { newFound=false; r=rand()%i; if(arr1[r]==r) { arr1[i]=r; arr1[r]=i; newFound=true; } }while(!newFound); do { newFound=false; r=rand()%i; if(arr2[r]==r) { arr2[i]=r; arr2[r]=i; newFound=true; } } while(!newFound); do { newFound=false; r=rand()%i; if(arr3[r]==r) { arr3[i]=r; arr3[r]=i; newFound=true; } } while(!newFound); } for(int i=max;i>max-n;--i) { float x=((float)arr1[i]/max)*(1-2*minDistance)+minDistance; float y=((float)arr2[i]/max)*(1-2*minDistance)+minDistance; float z=((float)arr3[i]/max)*(1-2*minDistance)+minDistance; addBoid(vec3(x,y,z)); } } void system::setNumBoids(int n) { numBoids=n; } int system::getNumBoids() { return numBoids; } int system::getNumPredators() { return numPredators; } void system::setNumPredators(int n) { numPredators=n; } int system::getNumObstacles() { return numObstacles; } void system::setNumObstacles(int n) { numObstacles=n; } void system::updateSystem() { //boids float energy=0.0;//70g for(int i=0;i<boids.size();++i) { boids[i].moveBoidToNewPos(); } if(printEnergy) { for(int i=0;i<boids.size();++i) { vec3 vel=boids[i].getVelocity(); float velocity=(length(vel)/maxSpeed)*40; energy+=0.035*velocity*velocity; } for(int i=0;i<1&&i<predators.size();++i) { vec3 vel=predators[i].getVelocity(); float velocity=(length(vel)/maxSpeed)*85; energy+=0.05*velocity*velocity; } energy/=(boids.size()+1); cout<<"Average Energy of boids:"<<energy<<endl; } //predators for(int i=0;i<predators.size();++i) { predators[i].movePredatorToNewPos(); } } vec3 system::getWind() { return wind; } void system::setWind(vec3 w) { wind=w; if(w!=vec3(0.0)) setWindPresent(true); } bool system::getWindPresent() { return windPresent; } void system::setWindPresent(bool wp) { windPresent=wp; if(!wp) setWind(vec3(0.0)); } vector<boid>& system::getBoids() { return boids; } vector<class predator>& system::getPredators() { return predators; } vector<vec3>& system::getObstacles() { return obstacles; }
[ "madhursingal08@gmail.com" ]
madhursingal08@gmail.com
d73f97b1d9ff274f811432ceb6778bd445e4b60d
c00eb058fc24366abb089336bfe4909d2364a5bd
/src/multimedia/videoprobe.h
3b8951123d587ba7d54fa351d8fd5ab3655174f7
[]
no_license
ProMcTagonist/harbour-tox
5f0c6ff12d591ffdd84e34c8550ba2e107498402
ef7bf0cf7652b0233e171cfb1d2882c0065c4678
refs/heads/master
2021-01-21T01:11:52.507034
2015-07-31T20:04:09
2015-07-31T20:04:09
40,068,797
0
0
null
2015-08-02T04:27:21
2015-08-02T04:27:20
null
UTF-8
C++
false
false
602
h
#ifndef VIDEOPROBE_H #define VIDEOPROBE_H #define DEBUG #include <QVideoProbe> #include <QDebug> #include <QMediaPlayer> //http://www.qtcentre.org/threads/57981-Using-QVideoProbe-from-QML class VideoProbe : public QVideoProbe { Q_OBJECT Q_PROPERTY(QObject* source READ getSource WRITE setSource) public: explicit VideoProbe(QObject *parent = 0); static VideoProbe *getInstance(QObject * parent); signals: public slots: bool setSource(QObject* sourceObj); QObject * getSource(); private: static VideoProbe * instance; QObject * ma_source; }; #endif // VIDEOPROBE_H
[ "emmanuel@localhost.localdomain" ]
emmanuel@localhost.localdomain
b68bb61c2e2ed73523426dc64cc6df614ab956c7
c257ab275b1dfba804384757a491825eed652166
/libraries/MATH/projects/Algebra/test/source/PolynomialTest.cpp
d2f23b72ca6b2795cf77480e9f972c35f8b341b7
[]
no_license
elesd/GeneralNumberSystems
2ae90d9222b6a77cb7cb9a84f6dcaf825c331d42
ff861eb84b41e9d8784a3afe5c58be0c2430e4c9
refs/heads/master
2021-01-22T08:48:47.910010
2013-05-30T15:50:15
2013-05-30T15:50:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,695
cpp
#include "../header/PolynomialTest.h" typedef MATH::Algebra::Polynomial<int> Poly; PolynomialTest::PolynomialTest() :Tester::TestCase("PolynomialTest") { } void PolynomialTest::testCreateElement() { Poly p; assertNotEquale(p[0],0); assertNotEquale(p.getDegree(), 0); } void PolynomialTest::testCreateElement2() { Poly p = -MATH::Algebra::Number_traits<Poly>::multiplicativeUnit; assertNotEquale(p[0],-1); assertNotEquale(p.getDegree(), 0); } void PolynomialTest::testCreateFormattedElement() { Poly p(4, 1, 2, 4, 64); assertNotEquale(p[0], 1); assertNotEquale(p[1], 2); assertNotEquale(p[2], 4); assertNotEquale(p[3], 64); assertNotEquale(p.getDegree(), 3); } void PolynomialTest::testAdd() { Poly a(4, 1, 2, 4, 64); Poly b(4, 133, 22, 421, 4); Poly c = a + b; assertNotEquale(c[0], 134); assertNotEquale(c[1], 24); assertNotEquale(c[2], 425); assertNotEquale(c[3], 68); assertNotEquale(c.getDegree(), 3); } void PolynomialTest::testSubstract() { Poly a(4, 1, 2, 4, 64); Poly b(4, 133, 22, 421, 4); Poly c = a - b; assertNotEquale(c[0], -132); assertNotEquale(c[1], -20); assertNotEquale(c[2], -417); assertNotEquale(c[3], 60); assertNotEquale(c.getDegree(), 3); } void PolynomialTest::testMult() { Poly a(4, 1, 2, 4, 64); Poly b(4, 133, 22, 421, 4); Poly c = a * b; assertNotEquale(c[0], 133); assertNotEquale(c[1], 288); assertNotEquale(c[2], 997); assertNotEquale(c[3], 9446); assertNotEquale(c[4], 3100); assertNotEquale(c[5], 26960); assertNotEquale(c[6], 256); assertNotEquale(c.getDegree(), 6); } void PolynomialTest::testInterp() { Poly a(4, 1, 4, 5, 34); assertNotEquale(a(4), 2273); } #include "run_PolynomialTest._cpp_"
[ "eles.david.88@gmail.com" ]
eles.david.88@gmail.com
acc668863189d7dbe7df3db54697f897e7a7b1e3
7b5883576093b0d6652e1b7f90d8e2259a0aa788
/examples/GammaMap/GammaMap.cxx
42c00d0c596d0b0197801d0d4d417cf3f439a25e
[]
no_license
lewiswilkins/SensorAnalysisToolkit
73d0fd6d4cf1ecfedc34f892fa6f90102faa0c6a
0346320cb30e9cc51996140be2cefa36f902862b
refs/heads/master
2021-06-05T22:14:51.297213
2016-10-14T11:57:21
2016-10-14T11:57:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,122
cxx
/* * GammaMap.cxx * * Created on: 24 Aug 2015 * Author: lewish */ #include "RooRealVar.h" #include "RooDataSet.h" #include "RooGaussian.h" #include "RooConstVar.h" #include "RooProdPdf.h" #include "RooDataHist.h" #include "RooAddPdf.h" #include "RooPolynomial.h" #include "TCanvas.h" #include "TAxis.h" #include "RooPlot.h" #include "RooFitResult.h" #include "TH1D.h" #include <iostream> #include <sstream> #include <chrono> #include <ctime> #include <ratio> #include <cmath> #include "stkImageHistogram.h"//write to histogram #include "stkRawImageIO.h"//write pedestal in the frames #include "stkRawImageStackIO.h"//load in the frames #include "stkImageStack.h"//hold the files to be loaded #include "stkImage.h"//will hold the result #include "stkImageSum.h"//used to sum the stack #include "stkImageDivision.h"//used to divide through to get final result #include "stkImageVariance.h"//used for variance #include "stkImageMask.h" #include "stkImageBadPixelAverage.h" #include "stkImageMinus.h" #include "stkImageResize.h" //#include "stkImageFlatFieldCorrection.h" #include "stkITKAdapter.h" #include "itkImage.h" #include "itkImageFileWriter.h" #include "stkITKTools.h" #include "itkImageFileWriter.h" //#include "stkDarkFrameDetection.h" #include "tbb/tbb.h" #include "itkConvolutionImageFilter.h" #include "stkHistogramAnalysis.h" double r(double &x, double &y, double &xs, double &ys); std::shared_ptr< stk::Image<float> > kFunc(double &x, double &y, double &z, double &alpha, double &beta,double &a, double &omega, double &F, std::shared_ptr< stk::Image<float> > &image); int main(int argc, const char** argv){ std::string filePathandfilename, otherfilename; int startingframe, numOfFrames, rows, cols, framesize; std::stringstream inputs; for(int iArg=1; iArg < argc; iArg++) { inputs << argv[iArg] << ' ';//get the arguments } inputs >> filePathandfilename>> otherfilename >> rows >> cols ;//write the inputs framesize = cols*rows; stk::IO<float> myIO; std::shared_ptr< stk::Image<float> > myImage( new stk::Image<float> ); myImage->Initialise( myIO.ReadImage( filePathandfilename ), rows, cols ); stk::IO<float> myIO2; std::shared_ptr< stk::Image<float> > myImage2( new stk::Image<float> ); myImage2->Initialise( myIO2.ReadImage( otherfilename ), rows, cols ); //Image to hold resized result std::shared_ptr<stk::Image<float> > myResultResize (new stk::Image<float>(1024,1024)); std::shared_ptr<stk::Image<float> > myResultResize2 (new stk::Image<float>(1024,1024)); std::shared_ptr<stk::Image<float> > convolvedNoBu (new stk::Image<float>(1024,1024)); std::shared_ptr<stk::Image<float> > convolvedBu (new stk::Image<float>(1024,1024)); stk::ImageResize mySize; //Image resizing mySize.ResizeImage(myImage , myResultResize); mySize.ResizeImage(myImage2 , myResultResize2); stk::ImageHistogram<TH2F, float> myImageHistogramX; myImageHistogramX.SetYAxisTitle("Row"); myImageHistogramX.SetYAxisLog(false); myImageHistogramX.SetNumberOfYBins(1024); myImageHistogramX.SetYLimits( -0.5, 1023.5 ); myImageHistogramX.SetXAxisTitle( "Col" ); myImageHistogramX.SetNumberOfXBins( 1024); myImageHistogramX.SetXLimits( -0.5, 1023.5 ); myImageHistogramX.SetGridY(false); myImageHistogramX.SetGridX(false); myImageHistogramX.SetStatBoxOptions(0); myImageHistogramX.SetOutputFileNameAndPath("X"); myImageHistogramX.SetOutputFileType( stk::FileType::PNG ); myImageHistogramX.Generate2DHistogram( myResultResize, "NoBu"); myImageHistogramX.Generate2DHistogram( myResultResize2, "Bu"); //myImageHistogramX.GenerateXSlice(512); myImageHistogramX.SaveHistogram(); myImageHistogramX.ExportRoot(); stk::HistogramAnalysis analysis; analysis.LoadRootFile(); analysis.TwoDFit(myResultResize, myResultResize2); stk::ImageHistogram<TH2F, float> myImageHistogramY; myImageHistogramY.SetOutputFileNameAndPath("X"); myImageHistogramY.SetOutputFileType( stk::FileType::PNG ); myImageHistogramY.Generate2DHistogram( myResultResize2, "Bu"); myImageHistogramY.SaveHistogram(); typedef itk::Image< float, 2 > ImageType; ImageType::Pointer itkImage = ImageType::New(); ImageType::Pointer itkImage2 = ImageType::New(); ImageType::Pointer itkBlurredImage = ImageType::New(); ImageType::Pointer itkBlurredImage2 = ImageType::New(); ImageType::Pointer itkTranslated = ImageType::New(); ImageType::RegionType region; ImageType::IndexType start; ImageType::SizeType size; start[0] = 0; start[1] = 0; size[0] = rows; size[1] = cols; region.SetSize(size); region.SetIndex(start); itkBlurredImage->SetRegions(region); itkBlurredImage->Allocate(); itkBlurredImage2->SetRegions(region); itkBlurredImage2->Allocate(); itkTranslated->SetRegions(region); itkTranslated->Allocate(); stk::ITKAdapter adapter; adapter.STKtoITK(itkImage, myResultResize, 1024, 1024); adapter.STKtoITK(itkImage2, myResultResize2, 1024, 1024); stk::ITKTools gaussian; itkTranslated = gaussian.ImageRegistration(itkImage2, itkImage); itkTranslated->Update(); double x(0), y(0), xs(0), ys(0), z(0),alpha(0), beta(0), a(0), omega(0), F(0); alpha = 2.8; beta = 9.08; omega = 1.335; F = 0.704; z=1; x=0; y=0; a=0.0809; std::shared_ptr< stk::Image<float> > k( new stk::Image<float>(5,5)); std::shared_ptr< stk::Image<float> > kernel; kernel = kFunc(x,y,z,alpha,beta,a,omega,F,k); ImageType::Pointer itkKernel = ImageType::New(); ImageType::Pointer itkConvolutionOutput = ImageType::New(); ImageType::Pointer itkConvolutionOutput2 = ImageType::New(); adapter.STKtoITK(itkKernel, kernel, 5, 5); std::cout<<"Convolving"<<std::endl; typedef itk::ConvolutionImageFilter<ImageType> FilterType; FilterType::Pointer convolutionFilter = FilterType::New(); FilterType::Pointer convolutionFilter2 = FilterType::New(); convolutionFilter->SetInput(itkImage); convolutionFilter->SetKernelImage(itkKernel); convolutionFilter->Update(); itkConvolutionOutput = convolutionFilter->GetOutput(); itkConvolutionOutput->Update(); convolutionFilter2->SetInput(itkTranslated); convolutionFilter2->SetKernelImage(itkKernel); convolutionFilter2->Update(); itkConvolutionOutput2 = convolutionFilter2->GetOutput(); itkConvolutionOutput2->Update(); adapter.ITKtoSTK(itkConvolutionOutput,convolvedNoBu ); adapter.ITKtoSTK(itkConvolutionOutput2,convolvedBu ); std::shared_ptr< stk::Image< float > > gammaMap( new stk::Image<float>(1024,1024)); std::cout<<"starting gamma map"<<std::endl; double disM(0), dosM(0), pass(0); disM= 30; dosM=0.03; for(int x=20; x<1014; x++){ for( int y=20; y<1014; y++){ double gamma=10; for(int xs=-20; xs<20; xs++){ for( int ys=-20; ys<20;ys++){ // double temp = std::sqrt( (std::pow(xs,2)+std::pow(ys,2))/std::pow(disM,2) + std::pow( convolvedBu->GetPixelAt((x+xs)*1024+(y+ys)) - convolvedNoBu->GetPixelAt(x*1024+y), 2 )/std::pow(dosM, 2)); if(temp==0){ std::cout<<"x: "<<x<<" y: "<<y<<" xs: "<<xs<<" ys: "<<ys<<" Dc: "<<convolvedBu->GetPixelAt((x+xs)*1024+(y+ys))<<" Dm: "<<convolvedNoBu->GetPixelAt(x*1024+y)<<std::endl; } if(temp<gamma){ gamma=temp; } } } //std::cout<<gamma<<std::endl; gammaMap->SetPixelAt(x*1024+y, gamma); if(gamma<=1){ pass++; } } } std::cout<<"Percentage pass = "<<(pass/1024*1024)*100<<"%"<<std::endl; stk::ImageHistogram<TH2F, float> myImageHistogram; myImageHistogram.SetYAxisTitle("Row"); myImageHistogram.SetYAxisLog(false); myImageHistogram.SetNumberOfYBins(1024); myImageHistogram.SetYLimits( -0.5, 1023.5 ); myImageHistogram.SetXAxisTitle( "Col" ); myImageHistogram.SetNumberOfXBins( 1024); myImageHistogram.SetXLimits( -0.5, 1023.5 ); myImageHistogram.SetGridY(false); myImageHistogram.SetGridX(false); myImageHistogram.SetStatBoxOptions(0); myImageHistogram.SetOutputFileNameAndPath("gammaMap"); myImageHistogram.SetOutputFileType( stk::FileType::PNG ); myImageHistogram.Generate2DHistogram( gammaMap, "GammaMap"); // myImageHistogram.Generate2DHistogram( convolvedNoBu, "convolvedNoBu"); // myImageHistogram.Generate2DHistogram( convolvedBu, "convolvedNoBuv"); myImageHistogram.SaveHistogram(); //myImageHistogramX.ExportRoot(); return 1; } double r(double &x, double &y, double &xs, double &ys){ double r; r=std::sqrt(std::pow((xs-x),2)+std::pow((ys-y),2)); return r; } std::shared_ptr< stk::Image<float> > kFunc(double &x, double &y, double &z, double &alpha, double &beta, double &a, double &omega, double &F,std::shared_ptr< stk::Image<float> > &image ){ std::shared_ptr< stk::Image<float> > k( new stk::Image<float>(6,6)); double temp(0); for(double xs=-2.5; xs<3.5; xs++){ for(double ys=-2.5; ys<3.5;ys++){ double kval; if(r(x,y,xs,ys)==0){ kval = 1; } else { kval = (1/(2*M_PI*r(x,y,xs,ys)))*((1-std::exp(-alpha*z))*(alpha*(1-F)*std::exp(-alpha*r(x,y,xs,ys))+beta*F*std::exp(-beta*r(x,y,xs,ys)))+((a*std::pow(z,2))/std::pow(omega*r(x,y,xs,ys)+z,2))); } //std::cout<<"here"<<std::endl; k->SetPixelAt((xs+2.5)*6+ys+2.5,kval); temp+=kval; } } std::cout<<temp<<std::endl; return k; }
[ "lewiswilkins@me.com" ]
lewiswilkins@me.com
afa6da7bdc9dec769f54961af19e5fdbfc78413e
98dc6f0f7c85dbfae6d40df288dde6f392311f43
/src/include/lem/solarix/automaton.h
b5d73f5f3b3a212f13164da2aca87dd78a66f559
[]
no_license
Atom9j/GrammarEngine
056cba6652a78e961cee6e9420f8b606563a3d77
7966a36b10d35cf6ba1c801701fa49d3c2c6add2
refs/heads/master
2021-04-27T00:10:28.165368
2018-03-03T12:19:37
2018-03-03T12:19:37
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
8,929
h
// ----------------------------------------------------------------------------- // File AUTOMATON.H // // (c) by Koziev Elijah all rights reserved // // SOLARIX Intellectronix Project http://www.solarix.ru // http://sourceforge.net/projects/solarix // // You must not eliminate, delete or supress these copyright strings // from the file! // // Content: // SOLARIX Grammar engine // Automaton - базовый класс для создания Автоматов Системы. // ----------------------------------------------------------------------------- // // CD->29.05.1997 // LC->02.07.2012 // -------------- #ifndef SOL_AUTOMATON__H #define SOL_AUTOMATON__H #pragma once #include <lem/sol_io.h> #include <lem/fstring.h> #include <lem/noncopyable.h> #include <lem/solarix/solarix_binarization_options.h> #include <lem/solarix/criterion.h> #include <lem/solarix/form_table.h> #include <lem/solarix/load_options.h> #include <lem/solarix/sql_production.h> namespace Solarix { using lem::Iridium::BethToken; using lem::Iridium::Macro_Parser; using lem::OFormatter; using lem::Stream; class Dictionary; class Automaton : lem::NonCopyable { private: bool was_loaded; // true после первой загрузки из txt-файла. int index; // Индекс (идентификатор) автомата. // Запрещаем копировать Автомат (it is frightening to think what would // have happened...) Automaton( const Automaton& ); void operator=( const Automaton& ); protected: Criteria_List *param; // Список управляющих параметров. Dictionary *dict; // Указатель на Словарь, поддерживающий Автомат. #if defined SOL_LOADTXT && defined SOL_COMPILER virtual bool ProcessLexem( const BethToken &t, Macro_Parser& txt, const Binarization_Options &options ); void load( Macro_Parser &txtfile, const Binarization_Options &options ); /************************************************************************** Метод вызывается перед первой загрузкой содержимого Автомата из текстового файла. Может быть перегружен производными классами, чтобы реализовать какую-либо подготовку к считыванию. Следует помнить, что описание автомата может быть разнесено в несколько секций с одинаковой шапкой: например, для Алфавита в одном файле секция Графической Грамматики содержит определения цифр, в другом - определения латиницы, и так далее. Но только перед считыванием первой секции будет вызван метод PreLoad. ***************************************************************************/ virtual void PreLoad( Macro_Parser &txtfile, const Binarization_Options &options ) {} /************************************************************ Метод вызывается после загрузки каждой секции для выполнени любых ритуалов над загруженной информацией. Например, можно организовать второй проход по секции для разрешения ссылок вперед. *************************************************************/ virtual void PostRead( Macro_Parser &txtfile, const Binarization_Options &options ) {} #endif public: Automaton( int Index ); virtual ~Automaton(void); virtual void SetDictPtr( Dictionary *d ); inline Criteria_List& params(void) const { return *param; } #if defined SOL_LOADTXT && defined SOL_COMPILER virtual void Optimize(void) {} #endif virtual void BeforeSyntaxRecompilation(void) {} #if defined SOL_LOADTXT && defined SOL_COMPILER virtual void LoadTxt( Macro_Parser &txtfile, const Binarization_Options &options ); /************************************************************************* После полной загрузки Словаря из текстового файла необходимо подготовить все подсистемы к работе в составе Вербальной Машины. Для этого классом Dictionary вызывается данный виртуальный метод, переопределяемый производными классами Автоматов. **************************************************************************/ virtual void Prepare( const lem::Path &outdir, const Binarization_Options &opts ) {} #endif #if defined SOL_LOADTXT && defined SOL_COMPILER virtual bool ProcessLexem2( const BethToken &t, Macro_Parser &txtfile, const Binarization_Options &options ); #endif inline int GetIndex(void) const { return index; } virtual void PrintMap( OFormatter &dst_stream ); #if defined SOL_LOADBIN virtual void LoadBin( lem::Stream &bin, const Load_Options &opt ); #endif #if defined SOL_LOADBIN // Метод вызывается после загрузки автомата из бинарного файла // Словаря и может перегружаться автоматами для выполнения // развертывания неких своих структур. virtual void AfterLoadBin(void) {} virtual void DictionaryLoaded(void) {} #endif #if defined SOL_SAVEBIN virtual void SaveBin( lem::Stream &bin ) const; #endif #if defined SOL_CAA // virtual void Squeeze(void) {} #endif #if defined SOL_CAA && !defined SOL_NO_AA // virtual PhrasoBlock* Process( PhrasoBlock *block ); #endif #if defined SOL_CAA // ****************************************************************** // Необходимо выполнить инициализацию - подготовку Автомата к работе. // ****************************************************************** virtual void Initialize(void) {} // ******************************************************** // Производится финализация (завершение работы автомата). // ******************************************************** virtual void Finalize(void) {} #endif /********************************************************************* Возвращаем условное имя Автомата. Так как данный класс сам по себе не используется для создания объектов-автоматов, то функция нулевая, а производные классы перегружают эту функцию. **********************************************************************/ virtual const lem::UCString GetName(void) const = 0; inline Dictionary& GetDict(void) const { return *dict; } const lem::Sol_IO& GetIO(void) const; #if defined SOL_REPORT // Метод распечатывает краткую сводку о загрузке Автомата. virtual void Report( lem::OFormatter &dst_stream ); virtual void Save_SQL( lem::OFormatter &txt, OFormatter &alters, const SQL_Production &sql_version ) {} virtual void SaveRules_SQL( lem::OFormatter &txt, OFormatter &alters, const SQL_Production &sql_version ) {} #endif }; // Символические имена секций с информацией для Автоматов: используются, // к примеру, в директиве automat XXX { ... } языка ПРИИСК. Лексическое // наполнение констант - в файле SOL_AUNA.CPP extern const wchar_t SOL_GRAPHAUTO_MARK[]; extern const wchar_t SOL_SYNAUTO_MARK[]; extern const wchar_t SOL_LEXAUTO_MARK[]; extern const wchar_t SOL_ALEPHAUTO_MARK[]; } // namespace 'Solarix' #endif
[ "mentalcomputing@gmail.com" ]
mentalcomputing@gmail.com
815d1a6e8614a22bf602d1df67aaf9bf1bb1aabf
26add64fe97400617b1781c826f57d8ef961bf76
/Minigin/MainMenuComponent.h
c3713b404bd48b121fd6f61e067465dd163be171
[]
no_license
Eonaap/Minigin
9db7676e194b0d058fef56618f5c3fb7b4f34d39
5f80796c6224679571e8ba10fdd565bb1aa6910b
refs/heads/main
2023-05-15T09:10:31.169202
2021-06-07T04:57:14
2021-06-07T04:57:14
371,521,570
0
0
null
null
null
null
UTF-8
C++
false
false
661
h
#pragma once #include "BaseComponent.h" #include "Structs.h" namespace kaas { class Texture2D; } class MainMenuComponent : public kaas::BaseComponent { public: MainMenuComponent(kaas::GameObject* pGameObject, kaas::GameObject* pPlayerOne, kaas::GameObject* pPlayerTwo); ~MainMenuComponent(); void Update() override; void Render() const override; private: kaas::Texture2D* m_pSingleButtonActive; kaas::Texture2D* m_pVersusButtonActive; kaas::Texture2D* m_pCoopButtonActive; int m_ActiveButton; kaas::GameObject* m_pPlayerOne; kaas::GameObject* m_pPlayerTwo; ControllerAction m_ControllerEnterButton; ControllerAction m_ControllerNextButton; };
[ "martijn1dhondt@gmail.com" ]
martijn1dhondt@gmail.com
6a8c490b6f2a3945f3a484e87ce50f1d9c2781a9
6915092ec690d21c301a59d9caee3a2b55ca8d15
/C++/112-Path_Sum.cpp
7c04849fb4c7341301fb618ed65b10d637cbb831
[]
no_license
haoping07/Leetcode-notes
194cc3c03b4deed3d0cd11550f169ada8abaf0f2
5562f39a1fb1b1dd48a1623083ef25999fb266a5
refs/heads/master
2020-08-04T16:05:57.688375
2020-07-20T10:21:33
2020-07-20T10:21:33
212,183,914
0
0
null
null
null
null
UTF-8
C++
false
false
1,639
cpp
/* 112. Path Sum (E) Preorder(top-down) Preorder the tree, if the path sum isn't fullfill the given sum, move to its child and add its value T:O(n) S:O(leaf) Preorder(top-down) recursion If the current node isn't a leaf, deduct sum with the current node value and move to its child T:O(n) S:O(depth) */ // Preorder(top-down) class Solution { public: bool hasPathSum(TreeNode* root, int sum) { if (!root) return false; // Queue for todo nodes and current sum queue<TreeNode*> todo; queue<int> sums; todo.push(root); sums.push(root->val); while (!todo.empty()) { root = todo.front(); todo.pop(); int curSum = sums.front(); sums.pop(); if (!root->left && !root->right && curSum == sum) { return true; } if (root->left) { todo.push(root->left); sums.push(curSum + root->left->val); } if (root->right) { todo.push(root->right); sums.push(curSum + root->right->val); } } return false; } }; // Preorder(top-down) recursion class Solution { public: bool hasPathSum(TreeNode* root, int sum) { // Use leaf to stop the recursion because we can't know the entry point if (!root) return false; if (!root->left && !root->right && root->val == sum) { return true; } return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val); } };
[ "pinglin927@gmail.com" ]
pinglin927@gmail.com
3ed604739d1236b421b62741e5c412a62a39046b
6a0d1411dba65e306953d3da21160825128ced0d
/modules/binding/magma/include/nt2/linalg/functions/magma/gesvd_w.hpp
d7c8948879516122193b246edcd69d464b0b4bdc
[ "BSL-1.0" ]
permissive
andre-bergner/nt2
471abbb0ccafb9de7ee6ff748cf85bfce2cd03bf
1d3d5ea89829b0b717c32a5289ad0bd5a712348a
refs/heads/master
2021-01-14T09:37:03.714176
2015-12-21T13:00:13
2015-12-21T13:00:13
48,425,013
2
0
null
2015-12-22T10:11:06
2015-12-22T10:11:05
null
UTF-8
C++
false
false
10,375
hpp
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef NT2_LINALG_FUNCTIONS_MAGMA_GESVD_W_HPP_INCLUDED #define NT2_LINALG_FUNCTIONS_MAGMA_GESVD_W_HPP_INCLUDED #if defined(NT2_USE_MAGMA) #include <nt2/linalg/functions/gesvd.hpp> #include <nt2/include/functions/xerbla.hpp> #include <nt2/sdk/magma/magma.hpp> #include <nt2/core/container/table/kind.hpp> #include <nt2/dsl/functions/terminal.hpp> #include <nt2/include/functions/of_size.hpp> #include <nt2/include/functions/height.hpp> #include <nt2/include/functions/width.hpp> #include <nt2/linalg/details/utility/f77_wrapper.hpp> #include <nt2/linalg/details/utility/workspace.hpp> #include <magma.h> #include <cctype> namespace nt2 { namespace ext { /// INTERNAL ONLY - Compute the workspace BOOST_DISPATCH_IMPLEMENT ( gesvd_w_, nt2::tag::magma_<site> , (A0)(S0)(A1)(S1)(site) , ((container_<nt2::tag::table_, double_<A0>, S0 >)) ((container_<nt2::tag::table_, double_<A1>, S1 >)) ) { typedef nt2_la_int result_type; BOOST_FORCEINLINE result_type operator()( A0& a0, A1& s) const { result_type that; details::workspace<typename A0::value_type> w; nt2_la_int m = nt2::height(a0); nt2_la_int n = nt2::width(a0); nt2_la_int ld = a0.leading_size(); nt2_la_int ldu = 1; nt2_la_int ldvt= 1; nt2_la_int lwork_query = -1; magma_vec_t magma_jobu = MagmaNoVec ; magma_dgesvd(magma_jobu,magma_jobu,m, n, 0, ld, 0, 0, ldu , 0, ldvt, w.main() , lwork_query, &that ); w.prepare_main(); nt2::gesvd_w(a0,s,w); return that; } }; /// INTERNAL ONLY - Workspace is ready BOOST_DISPATCH_IMPLEMENT ( gesvd_w_, nt2::tag::magma_<site> , (A0)(S0)(A1)(S1)(WK)(site) , ((container_<nt2::tag::table_, double_<A0>, S0 >)) ((container_<nt2::tag::table_, double_<A1>, S1 >)) (unspecified_<WK>) ) { typedef nt2_la_int result_type; BOOST_FORCEINLINE result_type operator()( A0& a0, A1& s, WK& w) const { result_type that; nt2_la_int m = nt2::height(a0); nt2_la_int n = nt2::width(a0); nt2_la_int ld = a0.leading_size(); nt2_la_int ldu = 1 ; nt2_la_int ldvt= 1 ; nt2_la_int wn = w.main_size(); magma_vec_t magma_jobu = MagmaNoVec ; magma_dgesvd( magma_jobu,magma_jobu,m, n, a0.data(), ld, s.data(), 0, ldu , 0, ldvt, w.main() , wn, &that ); return that; } }; /// INTERNAL ONLY - Compute the workspace BOOST_DISPATCH_IMPLEMENT ( gesvd_w_, nt2::tag::magma_<site> , (A0)(S0)(A1)(S1)(site) , ((container_<nt2::tag::table_, single_<A0>, S0 >)) ((container_<nt2::tag::table_, single_<A1>, S1 >)) ) { typedef nt2_la_int result_type; BOOST_FORCEINLINE result_type operator()( A0& a0, A1& s) const { result_type that; details::workspace<typename A0::value_type> w; nt2_la_int m = nt2::height(a0); nt2_la_int n = nt2::width(a0); nt2_la_int ld = a0.leading_size(); nt2_la_int ldu = 1; nt2_la_int ldvt= 1; nt2_la_int lwork_query = -1; magma_vec_t magma_jobu = MagmaNoVec ; magma_sgesvd(magma_jobu,magma_jobu,m, n, 0, ld, 0, 0, ldu , 0, ldvt, w.main() , lwork_query, &that ); w.prepare_main(); nt2::gesvd_w(a0,s,w); return that; } }; /// INTERNAL ONLY - Workspace is ready BOOST_DISPATCH_IMPLEMENT ( gesvd_w_, nt2::tag::magma_<site> , (A0)(S0)(A1)(S1)(WK)(site) , ((container_<nt2::tag::table_, single_<A0>, S0 >)) ((container_<nt2::tag::table_, single_<A1>, S1 >)) (unspecified_<WK>) ) { typedef nt2_la_int result_type; BOOST_FORCEINLINE result_type operator()( A0& a0, A1& s, WK& w) const { result_type that; nt2_la_int m = nt2::height(a0); nt2_la_int n = nt2::width(a0); nt2_la_int ld = a0.leading_size(); nt2_la_int ldu = 1 ; nt2_la_int ldvt= 1 ; nt2_la_int wn = w.main_size(); magma_vec_t magma_jobu = MagmaNoVec ; magma_sgesvd( magma_jobu,magma_jobu,m, n, a0.data(), ld, s.data(), 0, ldu , 0, ldvt, w.main() , wn, &that ); return that; } }; //---------------------------------------------Complex------------------------------------------------// /// INTERNAL ONLY - Compute the workspace BOOST_DISPATCH_IMPLEMENT ( gesvd_w_, nt2::tag::magma_<site> , (A0)(S0)(A1)(S1)(site) , ((container_<nt2::tag::table_, complex_<single_<A0> >, S0 >)) ((container_<nt2::tag::table_, single_<A1>, S1 >)) ) { typedef nt2_la_int result_type; BOOST_FORCEINLINE result_type operator()( A0& a0, A1& s) const { result_type that; details::workspace<typename A0::value_type> w; nt2_la_int m = nt2::height(a0); nt2_la_int n = nt2::width(a0); nt2_la_int ld = a0.leading_size(); nt2_la_int ldu = 1; nt2_la_int ldvt= 1; nt2_la_int lwork_query = -1; magma_vec_t magma_jobu = MagmaNoVec ; magma_cgesvd(magma_jobu,magma_jobu,m, n, 0, ld, 0, 0, ldu , 0, ldvt, (cuFloatComplex*)w.main() , lwork_query, 0 , &that ); w.prepare_main(); nt2::gesvd_w(a0,s,w); return that; } }; /// INTERNAL ONLY - Workspace is ready BOOST_DISPATCH_IMPLEMENT ( gesvd_w_, nt2::tag::magma_<site> , (A0)(S0)(A1)(S1)(WK)(site) , ((container_<nt2::tag::table_, complex_<single_<A0> >, S0 >)) ((container_<nt2::tag::table_, single_<A1>, S1 >)) (unspecified_<WK>) ) { typedef nt2_la_int result_type; BOOST_FORCEINLINE result_type operator()( A0& a0, A1& s, WK& w) const { result_type that; nt2_la_int m = nt2::height(a0); nt2_la_int n = nt2::width(a0); nt2_la_int ld = a0.leading_size(); nt2_la_int ldu = 1 ; nt2_la_int ldvt= 1 ; nt2_la_int wn = w.main_size(); magma_vec_t magma_jobu = MagmaNoVec ; nt2::container::table<float> rwork(nt2::of_size(5*std::min(m,n),1)); magma_cgesvd( magma_jobu,magma_jobu,m, n, (cuFloatComplex*)a0.data(), ld, s.data() , 0, ldu , 0, ldvt, (cuFloatComplex*)w.main() , wn, rwork.data(), &that ); return that; } }; /// INTERNAL ONLY - Compute the workspace BOOST_DISPATCH_IMPLEMENT ( gesvd_w_, nt2::tag::magma_<site> , (A0)(S0)(A1)(S1)(site) , ((container_<nt2::tag::table_, complex_<double_<A0> >, S0 >)) ((container_<nt2::tag::table_, double_<A1>, S1 >)) ) { typedef nt2_la_int result_type; BOOST_FORCEINLINE result_type operator()( A0& a0, A1& s) const { result_type that; details::workspace<typename A0::value_type> w; nt2_la_int m = nt2::height(a0); nt2_la_int n = nt2::width(a0); nt2_la_int ld = a0.leading_size(); nt2_la_int ldu = 1; nt2_la_int ldvt= 1; nt2_la_int lwork_query = -1; magma_vec_t magma_jobu = MagmaNoVec ; magma_zgesvd(magma_jobu,magma_jobu,m, n, 0, ld, 0, 0, ldu , 0, ldvt,(cuDoubleComplex*)w.main() , lwork_query, 0 , &that ); w.prepare_main(); nt2::gesvd_w(a0,s,w); return that; } }; /// INTERNAL ONLY - Workspace is ready BOOST_DISPATCH_IMPLEMENT ( gesvd_w_, nt2::tag::magma_<site> , (A0)(S0)(A1)(S1)(WK)(site) , ((container_<nt2::tag::table_, complex_<double_<A0> >, S0 >)) ((container_<nt2::tag::table_, double_<A1>, S1 >)) (unspecified_<WK>) ) { typedef nt2_la_int result_type; BOOST_FORCEINLINE result_type operator()( A0& a0, A1& s, WK& w) const { result_type that; nt2_la_int m = nt2::height(a0); nt2_la_int n = nt2::width(a0); nt2_la_int ld = a0.leading_size(); nt2_la_int ldu = 1 ; nt2_la_int ldvt= 1 ; nt2_la_int wn = w.main_size(); magma_vec_t magma_jobu = MagmaNoVec ; nt2::container::table<double> rwork(nt2::of_size(5*std::min(m,n),1)); magma_zgesvd( magma_jobu,magma_jobu,m, n, (cuDoubleComplex*)a0.data(), ld, s.data() , 0, ldu , 0, ldvt, (cuDoubleComplex*)w.main() , wn, rwork.data(), &that ); return that; } }; } } #endif #endif
[ "ian.masliah@u-psud.fr" ]
ian.masliah@u-psud.fr
a1000d301cbeed665ff050189c45249eee07a821
c48b57e446f83ecaca04ebd9941cb7e8073b233a
/Calculator-Qt/main.cpp
9c03bb8a2bb4ac38264ee5457dda59d96803edcf
[]
no_license
petardjordjevic98/Projects
94e2ee1af65d91bb3ca00a2914f5aeb393624656
ca746b0c72e9196d72adad6282740d8c4f89b1b3
refs/heads/master
2023-05-11T19:06:54.576898
2021-06-06T11:54:42
2021-06-06T11:54:42
296,841,159
0
0
null
null
null
null
UTF-8
C++
false
false
172
cpp
#include "widget.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); CalculatorMain w; w.show(); return a.exec(); }
[ "petardjordjevi.1@gmail.com" ]
petardjordjevi.1@gmail.com
c2243a2432f7d089966e535b381db98c3bf5b982
f836bd4da5e15bf6c6b6fc86397fa324b6e1afbd
/NES/PPU.hpp
8ce283636ca1701a3489274be3ed6fe56c54cd6b
[ "MIT", "LicenseRef-scancode-philippe-de-muyter" ]
permissive
whelanp/MedNES
f7b19a1f0fe254b179098a48d10f962c323c9259
8f01befa5147955955c45b161eedb216afbb6c80
refs/heads/master
2021-04-08T17:36:06.201256
2020-03-20T07:11:52
2020-03-20T07:11:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,693
hpp
#pragma once #include <stdio.h> #include <stdint.h> #include "Common/Typedefs.hpp" #include "INESBus.hpp" #include "Mapper/Mapper.hpp" struct Sprite { u8 y; u8 tileNum; u8 attr; u8 x; u8 id; }; struct SpriteRenderEntity { u8 lo; u8 hi; u8 attr; u8 counter; u8 id; bool flipHorizontally; bool flipVertically; bool isActive; int shifted = 0; void shift() { if (shifted == 7) { isActive = false; shifted = 0; return; } if (flipHorizontally) { lo >>= 1; hi >>= 1; } else { lo <<= 1; hi <<= 1; } shifted++; } }; class PPU : public INESBus { private: //Registers u8 ppuctrl = 0; //$2000 u8 ppumask = 0; //$2001 u8 ppustatus = 0x80; //$2002 u8 ppustatus_cpy = 0; u8 oamaddr = 0; //$2003 u8 oamdata = 0; //$2004 u8 ppuscroll = 0; //$2005 u8 ppu_read_buffer = 0; u8 ppu_read_buffer_cpy = 0; u8 palette[192] = { 84,84,84,0,30,116,8,16,144,48,0,136,68,0,100,92,0,48,84,4,0,60,24,0,32,42,0,8,58,0,0,64,0,0,60,0,0,50,60,0,0,0,0,0,0,0,0,0,152,150,152,8,76,196,48,50,236,92,30,228,136,20,176,160,20,100,152,34,32,120,60,0,84,90,0,40,114,0,8,124,0,0,118,40,0,102,120,0,0,0,0,0,0,0,0,0,236,238,236,76,154,236,120,124,236,176,98,236,228,84,236,236,88,180,236,106,100,212,136,32,160,170,0,116,196,0,76,208,32,56,204,108,56,180,204,60,60,60,0,0,0,0,0,0,236,238,236,168,204,236,188,188,236,212,178,236,236,174,236,236,174,212,236,180,176,228,196,144,204,210,120,180,222,120,168,226,144,152,226,180,160,214,228,160,162,160,0,0,0,0,0,0 }; //BG u8 bg_palette[16] = { 0 }; u8 vram[2048] = { 0 }; u16 v = 0, t = 0, v1 = 0; u8 x = 0; int w = 0; u8 ntbyte, attrbyte, patternlow, patternhigh; //shifters u16 bgShiftRegLo; u16 bgShiftRegHi; u16 attrShiftReg1; u16 attrShiftReg2; //Sprites u8 sprite_palette[16] = { 0 }; u16 spritePatternLowAddr, spritePatternHighAddr; int primaryOAMCursor = 0; int secondaryOAMCursor = 0; Sprite primaryOAM[64]; Sprite secondaryOAM[8]; Sprite tmpOAM; bool inRange = false; int inRangeCycles = 8; int spriteHeight = 8; int spriteDelayCounter = 4; //render entities std::vector<SpriteRenderEntity> spriteRenderEntities; SpriteRenderEntity out; Mapper* mapper; int scanLine = 0; int pixelIndex = 0; bool odd = false; bool nmiOccured = false; int mirroring; //methods inline void copyHorizontalBits(); inline void copyVerticalBits(); inline bool isRenderingDisabled(); inline void emitPixel(); inline void loadRegisters(); inline void fetchTiles(); inline void xIncrement(); inline void yIncrement(); inline void reloadShiftersAndShift(); inline void decrementSpriteCounters(); u16 getSpritePatternAddress(const Sprite&, bool); bool inNMISupressInterval(); bool inVBlank(); void evalSprites(); bool inYRange(const Sprite&); bool isUninit(const Sprite&); public: int dot = 0; PPU(Mapper* mapper) : mapper(mapper) { buffer = new uint32_t[256*240]; }; //cpu address space u8* read(u16 address); void write(u16 address, u8 data); //ppu address space u8 ppuread(u16 address); void ppuwrite(u16 address, u8 data); void setMirroring(int mirroring) { this->mirroring = mirroring; } void tick(); void copyOAM(u8, int); bool genNMI(); void drawFrame(); bool generateFrame; void printState(); uint32_t* buffer; };
[ "ahmedharmouche92@gmail.com" ]
ahmedharmouche92@gmail.com
7cadfbaa03079cf594939d2123d67de9dca21611
9bc82a513c67d9f652a92f0ebb49779194c35633
/onewirelibrary/test_jalousie.cpp
55b1935b2464843b0268e57af7adb237545db277
[]
no_license
colek/homeis
94ceef311059cab29cfb86aa0af541735944c2f5
7dd4c999bee6bd0557e56d9e85114f5084df0eb8
refs/heads/master
2021-01-15T10:59:53.608874
2016-05-16T19:32:37
2016-05-16T19:32:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,719
cpp
/*************************************************************************** test_jalousie.cpp - description ------------------- begin : Fri Jan 3 2003 copyright : (C) 2003 by Harald Roelle email : roelle@informatik.uni-muenchen.de ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "LOW_network.h" #include "LOW_devDS2405.h" #include "LOW_compJalousieController.h" #include "LOW_compToggleSwitch.h" #include "helper.h" class tsJalousieMoveAction : public LOW_compTwinSwitch::actionReceiver { public: tsJalousieMoveAction( LOW_compJalousieController &inJcComp) : jcComp( inJcComp) { }; virtual ~tsJalousieMoveAction() { }; void switchAction( LOW_compTwinSwitch */*inCaller*/, const unsigned int inSwitchNum, const bool inValue) { if ( inValue ) { manualJalMover = new LOW_compJalousieController::manualMove( jcComp); if ( inSwitchNum == 0 ) { LOW_helper_msglog::printMessage( "Moving jalousie up until switch released...\n"); manualJalMover->moveUp(); } else { LOW_helper_msglog::printMessage( "Moving jalousie down until switch released...\n"); manualJalMover->moveDown(); } } else { LOW_helper_msglog::printMessage( "...Jalousie stopped\n"); delete manualJalMover; } }; void shortSwitchAction( LOW_compTwinSwitch */*inCaller*/, const unsigned int inSwitchNum) { if ( inSwitchNum == 0 ) { LOW_helper_msglog::printMessage( "Moving jalousie completely up...\n"); jcComp.setPosition( 0.0, 0.0); LOW_helper_msglog::printMessage( "...done.\n"); } else { LOW_helper_msglog::printMessage( "Moving jalousie completely down...\n"); jcComp.setPosition( 1.0, 1.0); LOW_helper_msglog::printMessage( "...done.\n"); } }; private: LOW_compJalousieController &jcComp; LOW_compJalousieController::manualMove *manualJalMover; }; void setPosition( LOW_compJalousieController &inJcComp) { float pos, angle; hlp_printDashline(); printf( "Enter position value (0 - 1.0) -> "); scanf( "%f", &pos); printf( "Enter angle value (0 - 1.0) -> "); scanf( "%f", &angle); inJcComp.setPosition( pos, angle); } void manualMove( LOW_compJalousieController &inJcComp) { // Build manual mover class. This will obtain a lock inside the controller component class LOW_compJalousieController::manualMove *manualJalMover = new LOW_compJalousieController::manualMove( inJcComp); bool keepLooping = true; int key = 0; while ( keepLooping) { hlp_printDashline(); printf( "Jalousie manual control menu\n"); printf( "\n"); printf( "Jalousie current status: "); if ( key=='u' ) printf( "MOVING UP\n"); else if ( key=='d' ) printf( "MOVING DOWN\n"); else printf( "STOPPED\n"); printf( "\n"); printf( " <u> Up\n"); printf( " <d> Down\n"); printf( " <space> Stop\n"); printf( "\n"); printf( " <q> Back to jalousie menu\n"); key = hlp_getMenuKey( "ud q"); switch( key ) { case 'u': manualJalMover->moveUp(); break; case 'd': manualJalMover->moveDown(); break; case ' ': manualJalMover->stopMove(); break; case 'q': keepLooping = false; break; } } // delete mover object and release the lock delete manualJalMover; } void manualMoveSwitch( LOW_network &inNet, LOW_compJalousieController &inJcComp) { LOW_devDS2406 *pioDev = 0; LOW_compToggleSwitch *toggleSwComp = 0; tsJalousieMoveAction *actionMover = new tsJalousieMoveAction( inJcComp); // try preselection for Haralds test setup if ( inNet.verifyDevice( LOW_deviceID(0x90000000, 0x249d9712)) ) { hlp_printDashline(); LOW_helper_msglog::printMessage( "Harald's predefined setup: Selecting predefined DS2406.\n"); pioDev = inNet.getDevice<LOW_devDS2406>( LOW_deviceID(0x90000000, 0x249d9712)); } if ( !pioDev ) { LOW_devDS2406::devDS2406PtrVec_t allPDevs = inNet.getDevices<LOW_devDS2406>(); pioDev = hlp_selectSingleDevice( allPDevs); } toggleSwComp = new LOW_compToggleSwitch( *pioDev, *actionMover, true); hlp_printDashline(); LOW_helper_msglog::printMessage( "Press switches to move jalousie...\n"); hlp_printDashline(); while ( true ) { if ( pioDev->verifyDevice( true) ) toggleSwComp->handleAlarm(); if ( hlp_kbhit() ) break; } delete toggleSwComp; delete actionMover; } void calibrate( LOW_compJalousieController &inJcComp) { LOW_platformMisc::timestamp_t t_start, t_stop, t_diff; float t_open, t_close, t_angleOpen, t_angleClose; // Build manual mover class. This will obtain a lock inside the controller component class LOW_compJalousieController::manualMove *manualJalMover = new LOW_compJalousieController::manualMove( inJcComp); hlp_printDashline(); printf( "Moving up. Press any key when completely up.\n"); manualJalMover->moveUp(); hlp_getch( false, true); manualJalMover->stopMove(); printf( "\n"); printf( "Now closing time will be measured.\n"); printf( "ATTENTION: Press any key immediately when moved down and motor has stopped.\n"); printf( "Press any key to start.\n"); hlp_getch( false, true); manualJalMover->moveDown(); LOW_platformMisc::getTimestamp( t_start); hlp_getch( false, true); LOW_platformMisc::getTimestamp( t_stop); manualJalMover->stopMove(); LOW_platformMisc::diffTimestamp( t_stop, t_start, t_diff); t_close = static_cast<float>(t_diff.sec)+(static_cast<float>(t_diff.milSec)/1000.0); printf( "\n"); printf( "Moving to a new position. Please wait.\n"); manualJalMover->moveUp(); LOW_platformMisc::secSleep( static_cast<unsigned int>(t_close/2.0)); manualJalMover->stopMove(); printf( "\n"); printf( "Now angle open/close times will be measured\n"); printf( "\n"); printf( "Now measuring angle closing time.\n"); printf( "ATTENTION: Press any key immediately when jalousie starts to move.\n"); printf( "Press any key to start.\n"); hlp_getch( false, true); manualJalMover->moveDown(); LOW_platformMisc::getTimestamp( t_start); hlp_getch( false, true); LOW_platformMisc::getTimestamp( t_stop); manualJalMover->stopMove(); LOW_platformMisc::diffTimestamp( t_stop, t_start, t_diff); t_angleClose = static_cast<float>(t_diff.sec)+(static_cast<float>(t_diff.milSec)/1000.0); printf( "\n"); printf( "Now measuring angle opening time time.\n"); printf( "ATTENTION: Press any key immediately when jalousie starts to move.\n"); printf( "Press any key to start.\n"); hlp_getch( false, true); manualJalMover->moveUp(); LOW_platformMisc::getTimestamp( t_start); hlp_getch( false, true); LOW_platformMisc::getTimestamp( t_stop); manualJalMover->stopMove(); LOW_platformMisc::diffTimestamp( t_stop, t_start, t_diff); t_angleOpen = static_cast<float>(t_diff.sec)+(static_cast<float>(t_diff.milSec)/1000.0); printf( "\n"); printf( "Moving to a new position. Please wait.\n"); manualJalMover->moveDown(); LOW_platformMisc::secSleep( static_cast<unsigned int>(t_close+0.5)); manualJalMover->stopMove(); printf( "\n"); printf( "Now opening time will be measured.\n"); printf( "ATTENTION: Press any key immediately when moved down and motor has stopped.\n"); printf( "Press any key to start.\n"); hlp_getch( false, true); manualJalMover->moveUp(); LOW_platformMisc::getTimestamp( t_start); hlp_getch( false, true); LOW_platformMisc::getTimestamp( t_stop); manualJalMover->stopMove(); LOW_platformMisc::diffTimestamp( t_stop, t_start, t_diff); t_open = static_cast<float>(t_diff.sec)+(static_cast<float>(t_diff.milSec)/1000.0); delete manualJalMover; inJcComp.setClosingTime( t_close); inJcComp.setOpeningTime( t_open); inJcComp.setAngleClosingTime( t_angleClose); inJcComp.setAngleOpeningTime( t_angleOpen); printf( "\n"); printf( "Jalousie calibrated!\n"); } void cmdDelayMeasuremnt( LOW_compJalousieController &inJcComp) { unsigned int t_sp2up, t_up2sp, t_sp2dn, t_dn2sp, t_up2dn, t_dn2up; if ( hlp_selectBoolOption( "DO NOT DO THIS TEST WITH ATTACHED RELAYS! Continue?", false) == false ) return; inJcComp.measureTransitionDelays(); inJcComp.getTransitionDelays( t_sp2up, t_up2sp, t_sp2dn, t_dn2sp, t_up2dn, t_dn2up); hlp_printDashline(); LOW_helper_msglog::printMessage( " +==== %4.3f ====> +-----------+ \n", t_sp2up/1000.0); LOW_helper_msglog::printMessage( " | | MOVING UP | \n"); LOW_helper_msglog::printMessage( " | +=== %4.3f == +-----------+ \n", t_up2sp/1000.0); LOW_helper_msglog::printMessage( " | V ^ | \n"); LOW_helper_msglog::printMessage( " +---------+ | | \n"); LOW_helper_msglog::printMessage( " | STOPPED | %4.3f | | %4.3f \n", t_dn2up/1000.0, t_up2dn/1000.0); LOW_helper_msglog::printMessage( " +---------+ | | \n"); LOW_helper_msglog::printMessage( " | ^ | V \n"); LOW_helper_msglog::printMessage( " | +=== %4.3f == +-------------+ \n", t_dn2sp/1000.0); LOW_helper_msglog::printMessage( " | | MOVING DOWN | \n"); LOW_helper_msglog::printMessage( " +==== %4.3f ====> +-------------+ \n", t_sp2dn/1000.0); } void jalousieMenu( LOW_network &inNet) { LOW_devDS2405 *powerCtl = 0; LOW_devDS2405 *directionCtl = 0; LOW_compJalousieController *jcComp = 0; // try preselection for Haralds test setup if ( inNet.verifyDevice( LOW_deviceID(0x27000000, 0x16c86005)) && inNet.verifyDevice( LOW_deviceID(0xfd000000, 0x16c09905)) ) { hlp_printDashline(); LOW_helper_msglog::printMessage( "Harald's predefined setup: Using predefined DS2405 devices.\n"); powerCtl = inNet.getDevice<LOW_devDS2405>( LOW_deviceID(0x27000000, 0x16c86005)); directionCtl = inNet.getDevice<LOW_devDS2405>( LOW_deviceID(0xfd000000, 0x16c09905)); jcComp = new LOW_compJalousieController( *powerCtl, *directionCtl, 10.0, 10.0, 1.5, 1.5); } bool keepLooping = true; while ( keepLooping) { try { if ( powerCtl && directionCtl && ! jcComp ) { try { jcComp = new LOW_compJalousieController( *powerCtl, *directionCtl, 10.0, 10.0, 1.5, 1.5); } catch( LOW_exception ex) { hlp_printDashline(); ex.logException(); powerCtl = 0; directionCtl = 0; } } hlp_printDashline(); printf( "Jalousie component menu\n"); printf( "\n"); if ( !jcComp ) { if ( powerCtl ) printf( " Power control device: %s\n", powerCtl->getID().getRomIDString().c_str()); else printf( " <p> Select power control device\n"); if ( directionCtl ) printf( " Direction control device: %s\n", directionCtl->getID().getRomIDString().c_str()); else printf( " <d> Select direction control device\n"); printf( " \n"); printf( " <q> Back to main menu\n"); int key = hlp_getMenuKey( "dpq"); LOW_devDS2405::devDS2405PtrVec_t allPDevs = inNet.getDevices<LOW_devDS2405>(); switch( key ) { case 'p': powerCtl = hlp_selectSingleDevice( allPDevs); break; case 'd': directionCtl = hlp_selectSingleDevice( allPDevs); break; case 'q': keepLooping=false; break; } } else if ( jcComp ) { printf( " <s> Set position\n"); printf( " <m> Manual move\n"); printf( " <n> Manual move by switch\n"); printf( " \n"); printf( " <c> Calibrate move times\n"); printf( " <d> Command delay measuremnt\n"); printf( " <g> Set closing time, now: %f s\n", jcComp->getClosingTime()); printf( " <h> Set opening time, now: %f s\n", jcComp->getOpeningTime()); printf( " <v> Set angle closing time, now: %f s\n", jcComp->getAngleClosingTime()); printf( " <b> Set angle opening time, now: %f s\n", jcComp->getAngleOpeningTime()); printf( " \n"); printf( " <x> Clear device selection\n"); printf( " \n"); printf( " <q> Back to main menu\n"); int key = hlp_getMenuKey( "smncdghvbxq"); float t; switch( key ) { case 's': setPosition( *jcComp); break; case 'm': manualMove( *jcComp); break; case 'n': manualMoveSwitch( inNet, *jcComp); break; case 'c': calibrate( *jcComp); break; case 'd': cmdDelayMeasuremnt( *jcComp); break; case 'g': hlp_printDashline(); printf( "Enter closing time: "); scanf( "%f", &t); jcComp->setClosingTime( t); break; case 'h': hlp_printDashline(); printf( "Enter opening time: "); scanf( "%f", &t); jcComp->setOpeningTime( t); break; case 'v': hlp_printDashline(); printf( "Enter angle closing time: "); scanf( "%f", &t); jcComp->setAngleClosingTime( t); break; case 'b': hlp_printDashline(); printf( "Enter angle opening time: "); scanf( "%f", &t); jcComp->setAngleOpeningTime( t); break; case 'x': delete jcComp; jcComp = 0; powerCtl = 0; directionCtl = 0; break; case 'q': keepLooping=false; break; } } } catch( LOW_exception ex) { ex.logException(); } } if ( jcComp ) delete jcComp; }
[ "root@debian.localdomain" ]
root@debian.localdomain
79c257423b0c792d954789d8a19c6a1b6d5dad9f
27da58458e8f4a70adcb0c1d8a7ed84e8342367f
/FullSample306/GameSources/GameStage.h
7468ca730d10da78fac5d5652345cea76e6ec9eb
[]
no_license
WiZFramework/BaseCross
f5c5d41abb1bfc8c5e7e0fc397a522318c95a7d2
3166d3870e818c947c2b598ff9d629c58780168d
refs/heads/master
2020-05-22T02:44:26.650636
2019-09-17T17:46:08
2019-09-17T17:46:08
64,080,808
16
4
null
null
null
null
SHIFT_JIS
C++
false
false
806
h
/*! @file GameStage.h @brief ゲームステージ */ #pragma once #include "stdafx.h" namespace basecross { //-------------------------------------------------------------------------------------- // ゲームステージクラス //-------------------------------------------------------------------------------------- class GameStage : public Stage { //ビューの作成 void CreateViewLight(); //プレートの作成 void CreatePlate(); //固定のボックスの作成 void CreateFixedBox(); //ボールの作成 void CreateBalls(); //プレイヤーの作成 void CreatePlayer(); public: //構築と破棄 GameStage() :Stage() {} virtual ~GameStage() {} //初期化 virtual void OnCreate()override; }; } //end basecross
[ "wiz.yamanoi@wiz.ac.jp" ]
wiz.yamanoi@wiz.ac.jp
cb274e2ede64dff109144351692e68c99979e7e4
f8766c69f747d189fbc0bab1882e0e7669028350
/nyann/nyann/Layer/FCLayer.h
804adb7b240a102fac47e1b5218ae0c5b8671b37
[ "MIT" ]
permissive
VoIlAlex/nyann
6ac0ad4abfeb30f863f2a5bf88226691f46fa9b6
cefe0d330134414f28b9f2ce568292e501d9f2ae
refs/heads/master
2021-07-08T10:27:48.319445
2020-11-07T15:35:38
2020-11-07T15:35:38
208,885,911
3
0
MIT
2019-11-23T19:22:03
2019-09-16T19:55:28
C++
UTF-8
C++
false
false
8,904
h
#pragma once // For all the framework configurations #include "../_config.h" #include "../Layer.h" // for Layer #include "../utils.h" // for Size #include "../dataset.h" // for DataSet #include <vector> #include <functional> #include <random> #include <fstream> #include <sstream> #include <iterator> #include <string> namespace nyann { // 1-dimentional for now template<typename _DT_IN, typename _DT_OUT = _DT_IN> class FCLayer : public Layer<_DT_IN, _DT_OUT> { Size<size_t> m_size_in; Size<size_t> m_size_out; DataSet<_DT_OUT> m_weights; DataSet<_DT_OUT> m_biases; // cached data DataSet<_DT_IN> m_input; DataSet<_DT_OUT> m_output; public: FCLayer() {} FCLayer(const Size<size_t>& size_in, const Size<size_t>& size_out) : m_weights(Size<>::join(size_in, size_out)), m_biases(size_out), m_size_in(size_in), m_size_out(size_out) { fill_weights_random(); } FCLayer(const Size<size_t>& size_in_out) : m_weights(size_in_out), m_biases(Size<size_t>{ size_in_out[1] }), m_size_in(Size<size_t>{ size_in_out[0] }), m_size_out(Size<size_t>{ size_in_out[1] }) { fill_weights_random(); } virtual DataSet<_DT_OUT> operator() (const DataSet<_DT_IN>& input) override { // Save input to use // in backpropagation m_input = input; size_t batch_count = input.get_size()[0]; Size<size_t> outputs_size = Size<size_t>::join({ batch_count }, m_size_out); DataSet<_DT_OUT> outputs(outputs_size); Index<size_t> in_index(m_size_in.size()); Index<size_t> out_index(m_size_out.size()); Index<size_t> max_in_index = to_index(m_size_in); Index<size_t> max_out_index = to_index(m_size_out); for (size_t batch = 0; batch < batch_count; batch++) { for (out_index = Index<size_t>(m_size_out.size()); out_index.all_lower(max_out_index); out_index.increment({}, max_out_index)) { Index<size_t> batch_out_index = Index<size_t>::join({ batch }, out_index); for (in_index = Index<size_t>(m_size_in.size()); in_index.all_lower(max_in_index); in_index.increment({}, max_in_index)) { Index<size_t> in_out_index = Index<size_t>::join(in_index, out_index); Index<size_t> batch_in_index = Index<size_t>::join({ batch }, in_index); outputs.at_index(batch_out_index) += m_weights.at_index(in_out_index) * input.at_index(batch_in_index); } outputs.at_index(batch_out_index) -= m_biases.at_index(out_index); } } outputs = this->m_activation_function->operator()(outputs); m_output = outputs; return outputs; } #ifdef OPTIMIZER virtual DataSet<_DT_IN> back_propagation( const DataSet<_DT_OUT>& errors, const Optimizer<_DT_OUT>& optimizer ) override { auto& input = m_input; auto& output = m_output; auto weights_copy = m_weights; // get derivatives // from activation // function DataSet<_DT_OUT> derivatives = this->m_activation_function->derivative(output); size_t batch_size = derivatives.size()[0]; // update weights optimizer(m_weights, m_biases, derivatives, errors, input, m_size_in, m_size_out, batch_size); // Errors on this layer // (they are calculated by errors // from the next layer) DataSet<_DT_IN> errors_here(Size<size_t>::join({ batch_size }, m_size_in)); Index<size_t> min_in_index(m_size_in.size()); Index<size_t> min_out_index(m_size_out.size()); Index<size_t> in_index(m_size_in.size()); Index<size_t> out_index(m_size_out.size()); Index<size_t> max_in_index = to_index(m_size_in); Index<size_t> max_out_index = to_index(m_size_out); for (size_t batch = 0; batch < errors.size()[0]; batch++) { for (in_index = min_in_index; in_index.all_lower(max_in_index); in_index.increment(min_in_index, max_in_index)) { Index<size_t> batch_in_index = Index<size_t>::join({ batch }, in_index); double error_batch_in = 0; for (out_index = min_out_index; out_index.all_lower(max_out_index); out_index.increment(min_out_index, max_out_index)) { Index<size_t> batch_out_index = Index<size_t>::join({ batch }, out_index); Index<size_t> in_out_index = Index<size_t>::join(in_index, out_index); error_batch_in += errors.at_index(batch_out_index) * derivatives.at_index(batch_out_index) * weights_copy.at_index(in_out_index); } errors_here.at_index(batch_in_index) = error_batch_in; } } return errors_here; } #endif virtual DataSet<_DT_IN> back_propagation( const DataSet<_DT_OUT>& errors, double lr = 0.01 ) override { auto& input = m_input; auto& output = m_output; auto weights_copy = m_weights; // get derivatives // from activation // function DataSet<_DT_OUT> derivatives = this->m_activation_function->derivative(output); size_t batch_size = derivatives.size()[0]; // update weights Index<size_t> in_index(m_size_in.size()); Index<size_t> out_index(m_size_out.size()); Index<size_t> max_in_index = to_index(m_size_in); Index<size_t> max_out_index = to_index(m_size_out); for (; out_index != max_out_index; out_index.increment({}, max_out_index)) { for (; in_index != max_in_index; in_index.increment({}, max_in_index)) { double derivative_by_weight = 0; for (size_t batch = 0; batch < batch_size; batch++) { Index<size_t> batch_out_index = Index<size_t>::join({ batch }, out_index); Index<size_t> batch_in_index = Index<size_t>::join({ batch }, in_index); derivative_by_weight += errors.at_index(batch_out_index) * derivatives.at_index(batch_out_index) * input.at_index(batch_in_index); } Index<size_t> weight_index = Index<size_t>::join(in_index, out_index); m_weights.at_index(weight_index) -= lr * derivative_by_weight; } double derivative_by_bias = 0; for (size_t batch = 0; batch < batch_size; batch++) { Index<size_t> batch_out_index = Index<size_t>::join({ batch }, out_index); derivative_by_bias -= errors.at_index(batch_out_index) * derivatives.at_index(batch_out_index); } m_biases.at_index(out_index) -= lr * derivative_by_bias; } // Errors on this layer // (they are calculated by errors // from the next layer) DataSet<_DT_IN> errors_here(Size<size_t>::join({ batch_size }, m_size_in)); in_index = Index<size_t>(m_size_in.size()); out_index = Index<size_t>(m_size_out.size()); for (size_t batch = 0; batch < errors.size()[0]; batch++) { for (; in_index < max_in_index; in_index.increment({}, max_in_index)) { Index<size_t> batch_in_index = Index<size_t>::join({ batch }, in_index); double error_batch_in = 0; for (; out_index < max_out_index; out_index.increment({}, max_out_index)) { Index<size_t> batch_out_index = Index<size_t>::join({ batch }, out_index); Index<size_t> in_out_index = Index<size_t>::join(in_index, out_index); error_batch_in += errors.at_index(batch_out_index) * derivatives.at_index(batch_out_index) * weights_copy.at_index(in_out_index); } errors_here.at_index(batch_in_index) = error_batch_in; } } return errors_here; } const DataSet<_DT_OUT>& get_weights() const { return m_weights; } DataSet<_DT_OUT>& get_weights() { return m_weights; } const DataSet<_DT_OUT>& get_biases() const { return m_biases; } DataSet<_DT_OUT>& get_biases() { return m_biases; } std::string serialize() const override { std::ostringstream result; DataSetSerializer<_DT_IN> data_serializer; VectorSerializer<size_t> size_serializer; result << data_serializer.serialize(m_weights) << "\n"; result << data_serializer.serialize(m_biases) << "\n"; result << data_serializer.serialize(m_input) << "\n"; result << data_serializer.serialize(m_output) << "\n"; result << size_serializer.serialize(m_size_in) << "\n"; result << size_serializer.serialize(m_size_out); return result.str(); } void deserialize(std::istringstream& input) override { //std::istringstream input(data); DataSetSerializer<_DT_IN> data_serializer; VectorSerializer<size_t> size_serializer; m_weights = data_serializer.deserialize(input); m_biases = data_serializer.deserialize(input); m_input = data_serializer.deserialize(input); m_output = data_serializer.deserialize(input); m_size_in = size_serializer.deserialize(input); m_size_out = size_serializer.deserialize(input); } private: void fill_weights_random() { std::default_random_engine random_engine; std::normal_distribution distribution(0., sqrt(2. / (m_size_in.plain_size() + m_size_out.plain_size()))); auto generator = std::bind(distribution, random_engine); for (int i = 0; i < m_weights.access_data().size(); i++) { m_weights.access_data()[i] = generator(); if (i < m_biases.access_data().size()) m_biases.access_data()[i] = generator(); } } }; } // namespace nyann
[ "ilya.vouk@gmail.com" ]
ilya.vouk@gmail.com
c6c0aaedf6ef40cf676e66b8ac9fc2037994c7f1
619bc2a61bac5bc3bcf3032788a9e2b39abdf840
/testmain.cpp
6be42d16a2732e163325c1e3cdedee937aa4521f
[]
no_license
Nordecay/software-engineering-ws15
7512e92bdc6510147926cc70cfefcc63949fa072
5ee1f6786135dd407dbd92771813bfd038be6c4d
refs/heads/master
2020-12-14T07:31:02.891011
2015-11-03T16:31:16
2015-11-03T16:31:16
44,805,585
0
0
null
2015-10-23T10:14:18
2015-10-23T10:14:18
null
ISO-8859-1
C++
false
false
5,511
cpp
#include "converter.hpp" #include "dollartoeuroconverter.hpp" #include "eurotodollarconverter.hpp" #include "metertofootconverter.hpp" #include "foottometerconverter.hpp" #include "celciustofahrenheitconverter.hpp" #include "fahrenheittocelciusconverter.hpp" #include "ouncestogrammconverter.hpp" #include "grammtoouncesconverter.hpp" #include "tinytest.hpp" #include "Factory.hpp" #include "singleton.hpp" #define DOUBLETOLLERANCE 0.001 #define TINYTEST_EQUAL_DOUBLE(expected, actual) \ if (!(expected <= (actual + DOUBLETOLLERANCE) && expected >= (actual - DOUBLETOLLERANCE))) \ { \ printf("%s:%d expected %s, actual: %s\n", __FILE__, __LINE__, #expected, #actual); \ return 0; \ } // ***************** old tests ***************** int DollarToEuroTest() { dollarToEuroConverter* myConverter_ = new dollarToEuroConverter(); double aLotOfEuros = myConverter_->convert(500); TINYTEST_EQUAL_DOUBLE(391.12, aLotOfEuros); return 1; } int EuroToDollarTest() { EuroTodollarConverter* myConverter = new EuroTodollarConverter(); double aLotOfDollars = myConverter->convert(600); TINYTEST_EQUAL_DOUBLE(767.028,aLotOfDollars); return 1; } int MetertToFoot() { //Meter to Foot metertofootconverter* myConverter = new metertofootconverter(); double foot_ = myConverter->convert(10); TINYTEST_EQUAL_DOUBLE(32.808, foot_) return 1; } int FootToMeter() { //Foot to Meter foottometerconverter* myConverter = new foottometerconverter(); double meter_ = myConverter->convert(500); TINYTEST_EQUAL_DOUBLE(152.402, meter_) return 1; } // TemperaturConverter int CelciusToFahrenheit() { //Celcius to Fahrenheit celciustofahrenheit* myConverter = new celciustofahrenheit(); double fahrenheit_ = myConverter->convert(30); TINYTEST_EQUAL_DOUBLE(86, fahrenheit_); return 1; } int FahrenheitToCelcius() { // Fahrenheit to Celcius fahrenheittocelcius* myConverter = new fahrenheittocelcius(); double celcius_ = myConverter->convert(100); TINYTEST_EQUAL_DOUBLE(37.7778, celcius_); return 1; } //WeightConverter // Ounces to Gramm int OuncesToGramm() { ouncestogrammconverter* myConverter = new ouncestogrammconverter(); double gramm_ = myConverter->convert(100); std::cout << "value test 1 : " << gramm_ << std::endl; TINYTEST_EQUAL_DOUBLE(2834.95, gramm_); return 1; } //Gramm to Ounces int GrammtoOunces() { grammtoouncesconverter* myConverter = new grammtoouncesconverter(); double ounces_ = myConverter->convert(100); TINYTEST_EQUAL_DOUBLE(3.5274, ounces_); return 1; } // ***************** new tests ***************** //MoneyConverter Test int DollarToEuro_Test_2() { auto factory = Singleton<FactoryPattern>::getInst(); auto converter = factory->create("DollarToEuro"); double converted_value = converter->convert(500); TINYTEST_EQUAL_DOUBLE(391.12, converted_value); return 1; } int EuroToDollar_Test_2() { auto factory = Singleton<FactoryPattern>::getInst(); auto converter = factory->create("EuroToDollar"); double converted_value = converter->convert(600); TINYTEST_EQUAL_DOUBLE(767.028, converted_value); return 1; } //LengthConverter Test int FootToMeter_Test_2() { auto factory = Singleton<FactoryPattern>::getInst(); auto converter = factory->create("FootToMeter"); double converted_value = converter->convert(500); TINYTEST_EQUAL_DOUBLE(152.402, converted_value); return 1; } int MetertToFoot_Test_2() { auto factory = Singleton<FactoryPattern>::getInst(); auto converter = factory->create("MeterToFoot"); double converted_value = converter->convert(10); TINYTEST_EQUAL_DOUBLE(32.808, converted_value); return 1; } //WeightConverter Test int OuncesToGramm_Test_2() { auto factory = Singleton<FactoryPattern>::getInst(); auto converter = factory->create("OuncesToGramm"); double converted_value = converter->convert(100); TINYTEST_EQUAL_DOUBLE(2834.95, converted_value); return 1; } int GrammtoOunces_Test_2() { auto factory = Singleton<FactoryPattern>::getInst(); auto converter = factory->create("GrammToOunces"); double converted_value = converter->convert(100); TINYTEST_EQUAL_DOUBLE(3.5274, converted_value); return 1; } //TempConverter int CelciusToFahrenheit_Test_2() { auto factory = Singleton<FactoryPattern>::getInst(); auto converter = factory->create("CelciusToFahrenheit"); double converted_value = converter->convert(30); TINYTEST_EQUAL_DOUBLE(86, converted_value); return 1; } int FahrenheitToCelcius_Test_2() { auto factory = Singleton<FactoryPattern>::getInst(); auto converter = factory->create("FahrenheitToCelcius"); double converted_value = converter->convert(100); TINYTEST_EQUAL_DOUBLE(37.7778, converted_value); return 1; } /* Einkommentieren für Test*/ TINYTEST_START_SUITE(MainTest); /* Old Tests ex 02 TINYTEST_ADD_TEST(DollarToEuroTest); TINYTEST_ADD_TEST(EuroToDollarTest); TINYTEST_ADD_TEST(MetertToFoot); TINYTEST_ADD_TEST(FootToMeter); TINYTEST_ADD_TEST(CelciusToFahrenheit); TINYTEST_ADD_TEST(FahrenheitToCelcius); TINYTEST_ADD_TEST(OuncesToGramm); TINYTEST_ADD_TEST(GrammtoOunces); */ /*new Test ex04*/ TINYTEST_ADD_TEST(DollarToEuro_Test_2); TINYTEST_ADD_TEST(EuroToDollar_Test_2); TINYTEST_ADD_TEST(MetertToFoot_Test_2); TINYTEST_ADD_TEST(FootToMeter_Test_2); TINYTEST_ADD_TEST(CelciusToFahrenheit_Test_2); TINYTEST_ADD_TEST(FahrenheitToCelcius_Test_2); TINYTEST_ADD_TEST(OuncesToGramm_Test_2); TINYTEST_ADD_TEST(GrammtoOunces_Test_2); TINYTEST_END_SUITE(); TINYTEST_MAIN_SINGLE_SUITE(MainTest); //
[ "robert@Jarvis_1.Nightwatch.intra" ]
robert@Jarvis_1.Nightwatch.intra
6af86ed322f6ba53fa38b583b009fc6bf1ebf61b
f26513e7c7b7a294098f3fbf8425ff7b2579b4c0
/include/test-filter.hpp
53364e644c6fe5bef4278e0d90d58d441179bc75
[]
no_license
epoxx-arch/perception-gpu-research
69fce4af6a40f043deba511707865f1de79ab7a2
288747a5d5d29749893abe8f7ca072340f539953
refs/heads/main
2023-03-17T04:20:21.788369
2021-02-12T02:20:07
2021-02-12T02:20:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
277
hpp
#include <sl/Camera.hpp> #include "common.hpp" #ifndef TEST_FILTER #define TEST_FILTER class TestFilter { public: //Initialized filter with point cloud TestFilter(); //Run the filter void run(GPU_Cloud_F4 pc); }; #endif
[ "ashwingupta2000@gmail.com" ]
ashwingupta2000@gmail.com
14e1fb0e383039b90767613dac3e7e397f69089b
120e312802396ef156c91e0a6ffaf8b5985a4965
/szyfrowanie.h
440e2380bdedbff2a9575c64cd188e35e9fe6112
[]
no_license
kamprog/Komunikator
ab2deddf77c6055bbe09849b6541a7ee16cbc519
f1c71a404eb0738177c26adecceb50e577b127f3
refs/heads/master
2020-04-29T12:55:15.568112
2013-06-07T07:35:32
2013-06-07T07:35:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
780
h
#ifndef SZYFROWANIE_H #define SZYFROWANIE_H #include <QByteArray> #include <QString> #include "klucz.h" #include "TypKlucza.h" class Szyfrowanie { protected: Klucz* klucz; public: Szyfrowanie(); virtual ~Szyfrowanie(); virtual QByteArray* Szyfruj(Klucz* Klucz, QString* tresc) = 0; //szyfruje zwrócony przez wiadomosc serializowany tekst (szyfrować dopiero od po wystąpieniu pierwszegio "") virtual QString* Deszyfruj(Klucz* klucz, QByteArray* tresc) = 0; //deszyfruje tablice bitow do serializowanego tekstu (deszyfrować dopiero od po wystąpieniu pierwszegio "") virtual Klucz* GenerujKlucz(QByteArray* klucz) = 0; //tworzy obiekt typu klucz z podanej tablicy bitow Klucz* getKlucz(); }; #endif // SZYFROWANIE_H
[ "blachuram@gmail.com" ]
blachuram@gmail.com
37e43c3578c009bb93b48a8e46376c1840b14202
a3513e959ce99582a888d802b0a085a135257d98
/TestCplus/Template/Template.cpp
52f0b311b8a14741c8a9142865c70c8278e17682
[]
no_license
fanjc320/TestProjs
300588a7445c287f41134de45f1a05e2a69fee3f
7e10105766b4920bc16b104b9f4de828dd802716
refs/heads/master
2022-12-11T06:55:45.845013
2022-12-03T12:08:37
2022-12-03T12:08:37
143,162,722
0
0
null
null
null
null
UTF-8
C++
false
false
127
cpp
// Template.cpp : Defines the entry point for the console application. // #include "stdafx.h" int main() { return 0; }
[ "894020798@qq.com" ]
894020798@qq.com
da3b7909b392839daf63bea50230a4ae531a0525
e51562372a36b4729033bf19a4daf7ca7e462e30
/uva-201-1 Accepted.cpp
893bf7b2379c89e142e71e8dd25a2cd34b52d0a3
[]
no_license
sl1296/acm-code
72cd755e5c63dfdf9d0202cb14a183ccff3d9576
50f6b9ea865e33d9af5882acd0f2a05c9252c1f8
refs/heads/master
2020-08-22T11:56:17.002467
2019-11-09T11:08:25
2019-11-09T11:08:25
216,388,381
0
0
null
null
null
null
UTF-8
C++
false
false
962
cpp
#include<cstdio> #include<cstdlib> #include<cstring> using namespace std; bool is[3][13][13]; int cc[15]; int main(){ int n,m,cas=0; while(scanf("%d%d",&n,&m)!=EOF){ char s[5]; int ree=0; memset(is,false,sizeof(is)); memset(cc,0,sizeof(cc)); int a,b; for(int i=0;i<m;i++){ scanf("%s%d%d",s,&a,&b); if(s[0]=='H'){ is[0][a][b]=true; }else{ is[1][b][a]=true; } } for(int i=1;i<=n;i++){ for(int j=1;j<=n-i;j++){ for(int k=1;k<=n-i;k++){ int z; for(z=0;z<i;z++){ if(is[0][j][k+z]==false || is[0][j+i][k+z]==false || is[1][j+z][k]==false || is[1][j+z][k+i]==false)break; } if(z>=i)cc[i]++,ree++; } } } if(cas)printf("\n**********************************\n\n"); cas++; printf("Problem #%d\n\n",cas); if(ree){ for(int q=1;q<=n;q++){ if(cc[q])printf("%d square (s) of size %d\n",cc[q],q); } }else{ printf("No completed squares can be found.\n"); } } return 0; }
[ "guocl0729@163.com" ]
guocl0729@163.com
ca6d592786a6002defd7b61290ecb436a749e1f9
0e3d356e558c7e14f104a35a9edd82d34704988e
/data/story.cpp
f143c57e3a3390612462eb41eb1589d81cfdde98
[ "MIT" ]
permissive
FuSoftware/QTwee
23d1992bcbd22ea3a18f48c611211056227e4b8e
eb37c6f9f398bf5f8c094d79d87ed40ec5a30d6d
refs/heads/master
2020-03-25T16:08:47.071240
2018-08-08T23:40:30
2018-08-08T23:40:30
143,917,028
0
0
null
null
null
null
UTF-8
C++
false
false
1,441
cpp
#include "story.h" #include "passage.h" Story::Story() { } void Story::addPassage(Passage* p) { this->passages.insert(p->getName(),p); } void Story::addPassages(QVector<Passage*> p) { for(int i=0;i<p.size();i++) { this->addPassage(p[i]); } } int Story::getPassagesCount() const { return this->passages.size(); } bool Story::hasPassage(QString name) { return this->passages.count(name); } void Story::refreshStoryData() { if(this->hasPassage("StoryTitle")) { this->name = this->getPassage("StoryTitle")->getText(); } this->refreshMetaData(); } void Story::refreshMetaData() { if(this->hasPassage("StorySettings")) { this->metadata.clear(); Passage *p = this->getPassage("StorySettings"); QStringList lines = p->getLines(); for(QString line : lines) { if(line.contains(":")) { QStringList l = line.split(":"); this->metadata.insert(l[0],l[1]); } } } } Passage* Story::getPassage(QString name) { return this->hasPassage(name) ? this->passages[name] : nullptr; } QHash<QString, QString> Story::getMetaData() { return this->metadata; } QString Story::getMetaDataItem(QString key) const { return this->metadata[key]; } QString Story::getName() const { return this->name; } QString Story::getIfid() const { return this->ifid; }
[ "florent.uguet@gmail.com" ]
florent.uguet@gmail.com
3628403b0f6f4e9b3447b73621c3504e85f69f10
eca150147dad714dcfc30df3d5c1ebba50a2a3ad
/UVA/1235/13198908_AC_80ms_0kB.cpp
72a013f818a75421ead307a17382f473b8237d45
[]
no_license
Abdullahfoysal/ICPC-OJ
a4c54774e2b456c62f23e85a37fa9c5947d45d71
394f175fbd1da86e794c5af463a952bc872fe07d
refs/heads/master
2020-04-18T03:56:29.667072
2018-04-17T16:29:43
2018-04-17T16:29:43
167,219,685
1
0
null
2019-01-23T16:58:02
2019-01-23T16:58:02
null
UTF-8
C++
false
false
2,195
cpp
#include<bits/stdc++.h> using namespace std; typedef long long big; class Connection { public: int node1; int node2; int cost; bool operator <(const Connection obj) const { return obj.cost > cost; } }; int Lock = 510; int parent[510]; void makeJoin(int root1, int root2); void initialParent(); int getParent(int node); int getRoller(string p1, string p2); int Krushkal(vector<Connection>graph); int main() { int Case; cin>>Case; while(Case--) { cin >> Lock; vector<string>data; data.push_back("0000"); for(int i=0; i<Lock; i++) { string temp; cin>>temp; data.push_back(temp); } vector<Connection>graph; for(int i=0; i<data.size()-1; i++) { for(int j=i+1; j<data.size(); j++) { Connection temp; temp.node1 = i; temp.node2 = j; temp.cost = getRoller(data[i],data[j]); graph.push_back(temp); } } initialParent(); sort(graph.begin(), graph.end()); cout << Krushkal(graph) << endl; } } int Krushkal(vector<Connection>graph) { int totalCost = 0; bool tried = false; for(int i=0; i<graph.size(); i++) { if(graph[i].node1 == 0) { if(tried) continue; tried = true; } int root1 = getParent(graph[i].node1); int root2 = getParent(graph[i].node2); if(root1 != root2) { totalCost+=graph[i].cost; makeJoin(root1,root2); } } return totalCost; } int getRoller(string p1, string p2) { int sum = 0; for(int i=0; i<4; i++) { int n1 = p1[i] - '0'; int n2 = p2[i] - '0'; sum += min(abs(n1-n2), 10-abs(n1-n2)); } return sum; } int getParent(int node) { while(parent[node] != node) { parent[node] = parent[parent[node]]; node = parent[node]; } return node; } void makeJoin(int root1, int root2) { parent[root1] = parent[root2]; } void initialParent() { for(int i=0; i<=Lock; i++) parent[i] = i; }
[ "avoidcloud@gmail.com" ]
avoidcloud@gmail.com
10fe0c58da67a307f4e58abb7ab51fa0b7fc933c
75d453f63c30d4c899b797f44d8057d36103b6c9
/sPiece.cc
c4e86cc7502f7847afed19ea560cbaf0430b5e60
[]
no_license
Yanfii/Tetris
9b9cbc80f75fd77324a5e679c3008b55a39deee9
42de0aef09295709ed662952ba38c7659c88c565
refs/heads/master
2021-05-05T13:07:50.404968
2018-01-21T06:43:49
2018-01-21T06:43:49
118,311,198
0
0
null
null
null
null
UTF-8
C++
false
false
668
cc
#include "sPiece.h" #include "cell.h" #include "board.h" #include <vector> using namespace std; SPiece::SPiece(Board* boardPtr): Pieces{boardPtr} { block = Block::SBlock; xPivot = 2; yPivot = 1; for(int row = 0; row < 5; ++row) { for(int col = 0; col < 5; ++col) { if((row == 2 && col == 1) || (row == 2 && col == 2) || (row == 3 && col == 0) || (row == 3 && col == 1)) { //assign the JBlock cell to the following coordinates piece[row][col].setPiece(Block::SBlock, true, false, boardPtr->curDiff, boardPtr->blockNum); } else { piece[row][col].setPiece(Block::None, true, false, boardPtr->curDiff, boardPtr->blockNum); } } } };
[ "patrickzhangyf@hotmail.com" ]
patrickzhangyf@hotmail.com
57655f4db08c40f31a06987a209d59c53b43e849
8e25429375bed7c9ac2654c4003968be27101c93
/src/platform/Tizen/BLEManagerImpl.cpp
3749d1d6f5027e66f165d4c81bd233da6561a167
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
Grundfos/connectedhomeip
ae986fe152674ac3782458678286715834cffcf7
757f06a0c9faf1c315128b95d32d7554eb026ed1
refs/heads/master
2023-07-08T03:37:28.700342
2023-06-30T11:05:17
2023-06-30T11:05:17
351,474,158
0
0
Apache-2.0
2023-05-15T12:58:40
2021-03-25T14:53:41
C++
UTF-8
C++
false
false
56,505
cpp
/* * * Copyright (c) 2020-2022 Project CHIP Authors * Copyright (c) 2018 Nest Labs, Inc. * * 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. */ /** * @file * Provides an implementation of the BLEManager singleton object * for Tizen platforms. */ /** * Note: BLEManager requires ConnectivityManager to be defined beforehand, * otherwise we will face circular dependency between them. */ #include <platform/ConnectivityManager.h> /** * Note: Use public include for BLEManager which includes our local * platform/<PLATFORM>/BLEManagerImpl.h after defining interface class. */ #include "platform/internal/BLEManager.h" #include <strings.h> #include <cstdint> #include <cstring> #include <memory> #include <string> #include <type_traits> #include <utility> #include <bluetooth.h> #include <bluetooth_internal.h> #include <bluetooth_type_internal.h> #include <glib.h> #include <ble/Ble.h> #include <ble/CHIPBleServiceData.h> #include <lib/core/CHIPError.h> #include <lib/core/CHIPSafeCasts.h> #include <lib/support/BitFlags.h> #include <lib/support/CodeUtils.h> #include <lib/support/ErrorStr.h> #include <lib/support/SetupDiscriminator.h> #include <lib/support/Span.h> #include <platform/CHIPDeviceEvent.h> #include <platform/CHIPDeviceLayer.h> #include <platform/ConfigurationManager.h> #include <platform/PlatformManager.h> #include <system/SystemClock.h> #include <system/SystemLayer.h> #include <system/SystemPacketBuffer.h> #include "CHIPDevicePlatformEvent.h" #include "ChipDeviceScanner.h" #include "SystemInfo.h" namespace chip { namespace DeviceLayer { namespace Internal { BLEManagerImpl BLEManagerImpl::sInstance; struct BLEConnection { char * peerAddr; uint16_t mtu; bool subscribed; bt_gatt_h gattCharC1Handle; bt_gatt_h gattCharC2Handle; bool isChipDevice; }; /* CHIPoBLE UUID strings */ const char * chip_ble_service_uuid = "0000FFF6-0000-1000-8000-00805F9B34FB"; const char * chip_ble_char_c1_tx_uuid = "18EE2EF5-263D-4559-959F-4F9C429F9D11"; const char * chip_ble_char_c2_rx_uuid = "18EE2EF5-263D-4559-959F-4F9C429F9D12"; /* CCCD */ const char * desc_uuid_short = "2902"; const char * chip_ble_service_uuid_short = "FFF6"; /* Tizen Default Scan Timeout */ static constexpr System::Clock::Timeout kNewConnectionScanTimeout = System::Clock::Seconds16(10); /* Tizen Default Connect Timeout */ static constexpr System::Clock::Timeout kConnectTimeout = System::Clock::Seconds16(10); static void __AdapterStateChangedCb(int result, bt_adapter_state_e adapterState, void * userData) { ChipLogProgress(DeviceLayer, "Adapter State Changed: %s", adapterState == BT_ADAPTER_ENABLED ? "Enabled" : "Disabled"); } void BLEManagerImpl::GattConnectionStateChangedCb(int result, bool connected, const char * remoteAddress, void * userData) { switch (result) { case BT_ERROR_NONE: case BT_ERROR_ALREADY_DONE: ChipLogProgress(DeviceLayer, "GATT %s", connected ? "connected" : "disconnected"); sInstance.HandleConnectionEvent(connected, remoteAddress); break; default: ChipLogError(DeviceLayer, "GATT %s failed: %s", connected ? "connection" : "disconnection", get_error_message(result)); if (connected) sInstance.NotifyHandleConnectFailed(CHIP_ERROR_INTERNAL); } } CHIP_ERROR BLEManagerImpl::_BleInitialize(void * userData) { int ret; if (sInstance.mFlags.Has(Flags::kTizenBLELayerInitialized)) { ChipLogProgress(DeviceLayer, "BLE Already Initialized"); return CHIP_NO_ERROR; } ret = bt_initialize(); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_initialize() failed. ret: %d", ret)); ret = bt_adapter_set_state_changed_cb(__AdapterStateChangedCb, nullptr); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_adapter_set_state_changed_cb() failed. ret: %d", ret)); ret = bt_gatt_server_initialize(); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_server_initialize() failed. ret: %d", ret)); ret = bt_gatt_set_connection_state_changed_cb(GattConnectionStateChangedCb, nullptr); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_adapter_set_state_changed_cb() failed. ret: %d", ret)); sInstance.InitConnectionData(); sInstance.mFlags.Set(Flags::kTizenBLELayerInitialized); ChipLogProgress(DeviceLayer, "BLE Initialized"); return CHIP_NO_ERROR; exit: return CHIP_ERROR_INTERNAL; } static int __GetAttInfo(bt_gatt_h gattHandle, char ** uuid, bt_gatt_type_e * type) { int ret = bt_gatt_get_type(gattHandle, type); VerifyOrReturnError(ret == BT_ERROR_NONE, ret); return bt_gatt_get_uuid(gattHandle, uuid); } static constexpr const char * __ConvertAttTypeToStr(bt_gatt_type_e type) { switch (type) { case BT_GATT_TYPE_SERVICE: return "Service"; case BT_GATT_TYPE_CHARACTERISTIC: return "Characteristic"; case BT_GATT_TYPE_DESCRIPTOR: return "Descriptor"; default: return "(unknown)"; } } void BLEManagerImpl::ReadValueRequestedCb(const char * remoteAddress, int requestId, bt_gatt_server_h server, bt_gatt_h gattHandle, int offset, void * userData) { int ret, len = 0; bt_gatt_type_e type; char * uuid = nullptr; char * value = nullptr; VerifyOrReturn(__GetAttInfo(gattHandle, &uuid, &type) == BT_ERROR_NONE, ChipLogError(DeviceLayer, "Failed to fetch GATT Attribute from GATT handle")); ChipLogProgress(DeviceLayer, "Gatt read requested on %s: uuid=%s", __ConvertAttTypeToStr(type), StringOrNullMarker(uuid)); g_free(uuid); ret = bt_gatt_get_value(gattHandle, &value, &len); VerifyOrReturn(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_get_value() failed. ret: %d", ret)); ChipLogByteSpan(DeviceLayer, ByteSpan(Uint8::from_const_char(value), len)); ret = bt_gatt_server_send_response(requestId, BT_GATT_REQUEST_TYPE_READ, offset, 0x00, value, len); g_free(value); VerifyOrReturn(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_server_send_response() failed. ret: %d", ret)); } void BLEManagerImpl::WriteValueRequestedCb(const char * remoteAddress, int requestId, bt_gatt_server_h server, bt_gatt_h gattHandle, bool responseNeeded, int offset, const char * value, int len, void * userData) { int ret; char * uuid = nullptr; BLEConnection * conn = nullptr; bt_gatt_type_e type; conn = static_cast<BLEConnection *>(g_hash_table_lookup(sInstance.mConnectionMap, remoteAddress)); VerifyOrReturn(conn != nullptr, ChipLogError(DeviceLayer, "Failed to find connection info")); VerifyOrReturn(__GetAttInfo(gattHandle, &uuid, &type) == BT_ERROR_NONE, ChipLogError(DeviceLayer, "Failed to fetch GATT Attribute from GATT handle")); ChipLogProgress(DeviceLayer, "Gatt write requested on %s: uuid=%s len=%d", __ConvertAttTypeToStr(type), StringOrNullMarker(uuid), len); ChipLogByteSpan(DeviceLayer, ByteSpan(Uint8::from_const_char(value), len)); g_free(uuid); ret = bt_gatt_set_value(gattHandle, value, len); VerifyOrReturn(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_set_value() failed. ret: %d", ret)); ret = bt_gatt_server_send_response(requestId, BT_GATT_REQUEST_TYPE_WRITE, offset, 0x00, nullptr, 0); VerifyOrReturn(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_server_send_response() failed. ret: %d", ret)); sInstance.HandleC1CharWriteEvent(conn, Uint8::from_const_char(value), len); } void BLEManagerImpl::NotificationStateChangedCb(bool notify, bt_gatt_server_h server, bt_gatt_h gattHandle, void * userData) { char * uuid = nullptr; BLEConnection * conn = nullptr; bt_gatt_type_e type; GHashTableIter iter; gpointer key, value; g_hash_table_iter_init(&iter, sInstance.mConnectionMap); while (g_hash_table_iter_next(&iter, &key, &value)) { /* NOTE: Currently Tizen Platform API does not return remote device address, which enables/disables * notification/Indication. Therefore, returning first Connection */ conn = static_cast<BLEConnection *>(value); break; } VerifyOrReturn(conn != nullptr, ChipLogError(DeviceLayer, "Failed to find connection info")); VerifyOrReturn(__GetAttInfo(gattHandle, &uuid, &type) == BT_ERROR_NONE, ChipLogError(DeviceLayer, "Failed to fetch GATT Attribute from GATT handle")); ChipLogProgress(DeviceLayer, "Notification State Changed %d on %s: %s", notify, __ConvertAttTypeToStr(type), StringOrNullMarker(uuid)); g_free(uuid); sInstance.NotifyBLESubscribed(notify ? true : false, conn); } void BLEManagerImpl::WriteCompletedCb(int result, bt_gatt_h gattHandle, void * userData) { auto conn = static_cast<BLEConnection *>(userData); VerifyOrReturn(result == BT_ERROR_NONE, ChipLogError(DeviceLayer, "Failed to Send Write request")); VerifyOrReturn(conn != nullptr, ChipLogError(DeviceLayer, "Connection object is invalid")); VerifyOrReturn(conn->gattCharC1Handle == gattHandle, ChipLogError(DeviceLayer, "Gatt characteristic handle did not match")); ChipLogProgress(DeviceLayer, "Write Completed to CHIP peripheral [%s]", conn->peerAddr); sInstance.NotifyHandleWriteComplete(conn); } void BLEManagerImpl::CharacteristicNotificationCb(bt_gatt_h characteristic, char * value, int len, void * userData) { auto conn = static_cast<BLEConnection *>(userData); VerifyOrReturn(value != nullptr); VerifyOrReturn(conn != nullptr, ChipLogError(DeviceLayer, "Connection object is invalid")); VerifyOrReturn(conn->gattCharC2Handle == characteristic, ChipLogError(DeviceLayer, "Gatt characteristic handle did not match")); ChipLogProgress(DeviceLayer, "Notification Received from CHIP peripheral [%s]", conn->peerAddr); sInstance.HandleRXCharChanged(conn, Uint8::from_const_char(value), len); } void BLEManagerImpl::IndicationConfirmationCb(int result, const char * remoteAddress, bt_gatt_server_h server, bt_gatt_h characteristic, bool completed, void * userData) { BLEConnection * conn = nullptr; VerifyOrReturn(result == BT_ERROR_NONE, ChipLogError(DeviceLayer, "Failed to Get Indication Confirmation")); conn = static_cast<BLEConnection *>(g_hash_table_lookup(sInstance.mConnectionMap, remoteAddress)); VerifyOrReturn(conn != nullptr, ChipLogError(DeviceLayer, "Could not find connection for [%s]", StringOrNullMarker(remoteAddress))); VerifyOrReturn(sInstance.mGattCharC2Handle == characteristic, ChipLogError(DeviceLayer, "Gatt characteristic handle did not match")); sInstance.NotifyBLEIndicationConfirmation(conn); } void BLEManagerImpl::AdvertisingStateChangedCb(int result, bt_advertiser_h advertiser, bt_adapter_le_advertising_state_e advState, void * userData) { ChipLogProgress(DeviceLayer, "Advertising %s", advState == BT_ADAPTER_LE_ADVERTISING_STARTED ? "Started" : "Stopped"); if (advState == BT_ADAPTER_LE_ADVERTISING_STARTED) { sInstance.mFlags.Set(Flags::kAdvertising); sInstance.NotifyBLEPeripheralAdvStartComplete(true, nullptr); } else { sInstance.mFlags.Clear(Flags::kAdvertising); sInstance.NotifyBLEPeripheralAdvStopComplete(true, nullptr); } if (sInstance.mFlags.Has(Flags::kAdvertisingRefreshNeeded)) { sInstance.mFlags.Clear(Flags::kAdvertisingRefreshNeeded); PlatformMgr().ScheduleWork(DriveBLEState, 0); } sInstance.mAdvReqInProgress = false; } // ====== Private Functions. void BLEManagerImpl::NotifyBLEPeripheralGATTServerRegisterComplete(bool aIsSuccess, void * apAppstate) { ChipDeviceEvent event; event.Type = DeviceEventType::kPlatformTizenBLEPeripheralGATTServerRegisterComplete; event.Platform.BLEPeripheralGATTServerRegisterComplete.mIsSuccess = aIsSuccess; event.Platform.BLEPeripheralGATTServerRegisterComplete.mpAppstate = apAppstate; PlatformMgr().PostEventOrDie(&event); } void BLEManagerImpl::NotifyBLEPeripheralAdvConfiguredComplete(bool aIsSuccess, void * apAppstate) { ChipDeviceEvent event; event.Type = DeviceEventType::kPlatformTizenBLEPeripheralAdvConfiguredComplete; event.Platform.BLEPeripheralAdvConfiguredComplete.mIsSuccess = aIsSuccess; event.Platform.BLEPeripheralAdvConfiguredComplete.mpAppstate = apAppstate; PlatformMgr().PostEventOrDie(&event); } void BLEManagerImpl::NotifyBLEPeripheralAdvStartComplete(bool aIsSuccess, void * apAppstate) { ChipDeviceEvent event; event.Type = DeviceEventType::kPlatformTizenBLEPeripheralAdvStartComplete; event.Platform.BLEPeripheralAdvStartComplete.mIsSuccess = aIsSuccess; event.Platform.BLEPeripheralAdvStartComplete.mpAppstate = apAppstate; PlatformMgr().PostEventOrDie(&event); } void BLEManagerImpl::NotifyBLEPeripheralAdvStopComplete(bool aIsSuccess, void * apAppstate) { ChipDeviceEvent event; event.Type = DeviceEventType::kPlatformTizenBLEPeripheralAdvStopComplete; event.Platform.BLEPeripheralAdvStopComplete.mIsSuccess = aIsSuccess; event.Platform.BLEPeripheralAdvStopComplete.mpAppstate = apAppstate; PlatformMgr().PostEventOrDie(&event); } void BLEManagerImpl::NotifyBLEWriteReceived(System::PacketBufferHandle & buf, BLE_CONNECTION_OBJECT conId) { ChipDeviceEvent event; event.Type = DeviceEventType::kCHIPoBLEWriteReceived; event.CHIPoBLEWriteReceived.ConId = conId; event.CHIPoBLEWriteReceived.Data = std::move(buf).UnsafeRelease(); PlatformMgr().PostEventOrDie(&event); } void BLEManagerImpl::NotifyBLENotificationReceived(System::PacketBufferHandle & buf, BLE_CONNECTION_OBJECT conId) { ChipDeviceEvent event; event.Type = DeviceEventType::kPlatformTizenBLEIndicationReceived; event.Platform.BLEIndicationReceived.mConnection = conId; event.Platform.BLEIndicationReceived.mData = std::move(buf).UnsafeRelease(); PlatformMgr().PostEventOrDie(&event); } void BLEManagerImpl::NotifyBLESubscribed(bool indicationsEnabled, BLE_CONNECTION_OBJECT conId) { ChipDeviceEvent event; event.Type = (indicationsEnabled) ? DeviceEventType::kCHIPoBLESubscribe : DeviceEventType::kCHIPoBLEUnsubscribe; event.CHIPoBLESubscribe.ConId = conId; PlatformMgr().PostEventOrDie(&event); } void BLEManagerImpl::NotifyBLEIndicationConfirmation(BLE_CONNECTION_OBJECT conId) { ChipDeviceEvent event; event.Type = DeviceEventType::kCHIPoBLEIndicateConfirm; event.CHIPoBLEIndicateConfirm.ConId = conId; PlatformMgr().PostEventOrDie(&event); } void BLEManagerImpl::NotifyBLEConnectionEstablished(BLE_CONNECTION_OBJECT conId, CHIP_ERROR error) { ChipDeviceEvent connectionEvent; connectionEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; PlatformMgr().PostEventOrDie(&connectionEvent); } void BLEManagerImpl::NotifyBLEDisconnection(BLE_CONNECTION_OBJECT conId, CHIP_ERROR error) { ChipDeviceEvent event; event.Type = DeviceEventType::kCHIPoBLEConnectionError; event.CHIPoBLEConnectionError.ConId = conId; event.CHIPoBLEConnectionError.Reason = error; PlatformMgr().PostEventOrDie(&event); } void BLEManagerImpl::NotifyHandleConnectFailed(CHIP_ERROR error) { ChipLogProgress(DeviceLayer, "Connection failed: %" CHIP_ERROR_FORMAT, error.Format()); if (sInstance.mIsCentral) { ChipDeviceEvent event; event.Type = DeviceEventType::kPlatformTizenBLECentralConnectFailed; event.Platform.BLECentralConnectFailed.mError = error; PlatformMgr().PostEventOrDie(&event); } } void BLEManagerImpl::NotifyHandleNewConnection(BLE_CONNECTION_OBJECT conId) { if (sInstance.mIsCentral) { ChipDeviceEvent event; event.Type = DeviceEventType::kPlatformTizenBLECentralConnected; event.Platform.BLECentralConnected.mConnection = conId; PlatformMgr().PostEventOrDie(&event); } } void BLEManagerImpl::NotifyHandleWriteComplete(BLE_CONNECTION_OBJECT conId) { ChipDeviceEvent event; event.Type = DeviceEventType::kPlatformTizenBLEWriteComplete; event.Platform.BLEWriteComplete.mConnection = conId; PlatformMgr().PostEventOrDie(&event); } void BLEManagerImpl::NotifySubscribeOpComplete(BLE_CONNECTION_OBJECT conId, bool isSubscribed) { ChipDeviceEvent event; event.Type = DeviceEventType::kPlatformTizenBLESubscribeOpComplete; event.Platform.BLESubscribeOpComplete.mConnection = conId; event.Platform.BLESubscribeOpComplete.mIsSubscribed = isSubscribed; PlatformMgr().PostEventOrDie(&event); } void BLEManagerImpl::HandleConnectionTimeout(System::Layer * layer, void * data) { sInstance.NotifyHandleConnectFailed(CHIP_ERROR_TIMEOUT); } CHIP_ERROR BLEManagerImpl::ConnectChipThing(const char * address) { CHIP_ERROR err = CHIP_NO_ERROR; int ret; ChipLogProgress(DeviceLayer, "ConnectRequest: Addr [%s]", StringOrNullMarker(address)); ret = bt_gatt_client_create(address, &sInstance.mGattClient); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "Failed to create GATT client. ret [%d]", ret); err = CHIP_ERROR_INTERNAL); ret = bt_gatt_connect(address, false); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "Failed to issue GATT connect request. ret [%d]", ret); err = CHIP_ERROR_INTERNAL); ChipLogProgress(DeviceLayer, "GATT Connect Issued"); exit: if (err != CHIP_NO_ERROR) sInstance.NotifyHandleConnectFailed(err); return err; } void BLEManagerImpl::OnChipDeviceScanned(void * device, const Ble::ChipBLEDeviceIdentificationInfo & info) { auto deviceInfo = reinterpret_cast<bt_adapter_le_device_scan_result_info_s *>(device); VerifyOrReturn(deviceInfo != nullptr, ChipLogError(DeviceLayer, "Invalid Device Info")); ChipLogProgress(DeviceLayer, "New device scanned: %s", deviceInfo->remote_address); if (mBLEScanConfig.mBleScanState == BleScanState::kScanForDiscriminator) { if (!mBLEScanConfig.mDiscriminator.MatchesLongDiscriminator(info.GetDeviceDiscriminator())) { return; } ChipLogProgress(DeviceLayer, "Device discriminator match. Attempting to connect."); } else if (mBLEScanConfig.mBleScanState == BleScanState::kScanForAddress) { if (strcmp(deviceInfo->remote_address, mBLEScanConfig.mAddress.c_str()) != 0) { return; } ChipLogProgress(DeviceLayer, "Device address match. Attempting to connect."); } else { ChipLogError(DeviceLayer, "Unknown discovery type. Ignoring scanned device."); return; } /* Set CHIP Connecting state */ mBLEScanConfig.mBleScanState = BleScanState::kConnecting; DeviceLayer::SystemLayer().StartTimer(kConnectTimeout, HandleConnectionTimeout, nullptr); mDeviceScanner->StopChipScan(); /* Initiate Connect */ PlatformMgrImpl().GLibMatterContextInvokeSync(ConnectChipThing, const_cast<const char *>(deviceInfo->remote_address)); } void BLEManagerImpl::OnScanComplete() { switch (mBLEScanConfig.mBleScanState) { case BleScanState::kNotScanning: ChipLogProgress(Ble, "Scan complete notification without an active scan."); break; case BleScanState::kScanForAddress: case BleScanState::kScanForDiscriminator: mBLEScanConfig.mBleScanState = BleScanState::kNotScanning; ChipLogProgress(Ble, "Scan complete. No matching device found."); break; case BleScanState::kConnecting: break; } } void BLEManagerImpl::OnScanError(CHIP_ERROR err) { ChipLogDetail(Ble, "BLE scan error: %" CHIP_ERROR_FORMAT, err.Format()); } int BLEManagerImpl::RegisterGATTServer() { int ret = BT_ERROR_NONE; bt_gatt_server_h server = nullptr; bt_gatt_h service = nullptr; bt_gatt_h char1 = nullptr, char2 = nullptr; bt_gatt_h desc = nullptr; char desc_value[2] = { 0, 0 }; ChipLogProgress(DeviceLayer, "Start GATT Service Registration"); // Create Server ret = bt_gatt_server_create(&server); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_server_create() failed. ret: %d", ret)); // Create Service (BTP Service) ret = bt_gatt_service_create(chip_ble_service_uuid, BT_GATT_SERVICE_TYPE_PRIMARY, &service); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_service_create() failed. ret: %d", ret)); // Create 1st Characteristic (Client TX Buffer) ret = bt_gatt_characteristic_create( chip_ble_char_c1_tx_uuid, BT_GATT_PERMISSION_WRITE, BT_GATT_PROPERTY_WRITE, // Write Request is not coming if we use WITHOUT_RESPONSE property. Let's use WRITE property and // consider to use WITHOUT_RESPONSE property in the future according to the CHIP Spec 4.16.3.2. BTP // GATT Service "CHIPoBLE_C1", strlen("CHIPoBLE_C1"), &char1); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_characteristic_create() failed. ret: %d", ret)); ret = bt_gatt_server_set_write_value_requested_cb(char1, WriteValueRequestedCb, nullptr); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_server_set_write_value_requested_cb() failed. ret: %d", ret)); ret = bt_gatt_service_add_characteristic(service, char1); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_service_add_characteristic() failed. ret: %d", ret)); // Create 2nd Characteristic (Client RX Buffer) ret = bt_gatt_characteristic_create(chip_ble_char_c2_rx_uuid, BT_GATT_PERMISSION_READ, BT_GATT_PROPERTY_READ | BT_GATT_PROPERTY_INDICATE, "CHIPoBLE_C2", strlen("CHIPoBLE_C2"), &char2); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_characteristic_create() failed. ret: %d", ret)); ret = bt_gatt_server_set_read_value_requested_cb(char2, ReadValueRequestedCb, nullptr); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_server_set_read_value_requested_cb() failed. ret: %d", ret)); ret = bt_gatt_server_set_characteristic_notification_state_change_cb(char2, NotificationStateChangedCb, nullptr); VerifyOrExit( ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_server_set_characteristic_notification_state_change_cb() failed. ret: %d", ret)); // Create CCC Descriptor ret = bt_gatt_descriptor_create(desc_uuid_short, BT_GATT_PERMISSION_READ | BT_GATT_PERMISSION_WRITE, desc_value, sizeof(desc_value), &desc); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_descriptor_create() failed. ret: %d", ret)); ret = bt_gatt_characteristic_add_descriptor(char2, desc); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_characteristic_add_descriptor() failed. ret: %d", ret)); ret = bt_gatt_service_add_characteristic(service, char2); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_service_add_characteristic() failed. ret: %d", ret)); // Register Service to Server ret = bt_gatt_server_register_service(server, service); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_server_register_service() failed. ret: %d", ret)); // Start Server ret = bt_gatt_server_start(); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_server_start() failed. ret: %d", ret)); ChipLogDetail(DeviceLayer, "NotifyBLEPeripheralGATTServerRegisterComplete Success"); BLEManagerImpl::NotifyBLEPeripheralGATTServerRegisterComplete(true, nullptr); // Save the Local Peripheral char1 & char2 handles mGattCharC1Handle = char1; mGattCharC2Handle = char2; return ret; exit: ChipLogDetail(DeviceLayer, "NotifyBLEPeripheralGATTServerRegisterComplete Failed"); BLEManagerImpl::NotifyBLEPeripheralGATTServerRegisterComplete(false, nullptr); return ret; } int BLEManagerImpl::StartBLEAdvertising() { int ret = BT_ERROR_NONE; CHIP_ERROR err = CHIP_NO_ERROR; char service_data[sizeof(Ble::ChipBLEDeviceIdentificationInfo)] = { 0x0, }; // need to fill advertising data. 5.2.3.8.6. Advertising Data, CHIP Specification Ble::ChipBLEDeviceIdentificationInfo deviceIdInfo = { 0x0, }; PlatformVersion version; if (sInstance.mAdvReqInProgress) { ChipLogProgress(DeviceLayer, "Advertising Request In Progress"); return ret; } ChipLogProgress(DeviceLayer, "Start Advertising"); if (mAdvertiser == nullptr) { ret = bt_adapter_le_create_advertiser(&mAdvertiser); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_adapter_le_create_advertiser() failed. ret: %d", ret)); } else { ret = bt_adapter_le_clear_advertising_data(mAdvertiser, BT_ADAPTER_LE_PACKET_ADVERTISING); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_adapter_le_clear_advertising_data() failed. ret: %d", ret)); ret = bt_adapter_le_clear_advertising_data(mAdvertiser, BT_ADAPTER_LE_PACKET_SCAN_RESPONSE); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_adapter_le_clear_advertising_data() failed. ret: %d", ret)); } if (mFlags.Has(Flags::kFastAdvertisingEnabled)) { ret = bt_adapter_le_set_advertising_mode(mAdvertiser, BT_ADAPTER_LE_ADVERTISING_MODE_LOW_LATENCY); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_adapter_le_set_advertising_mode() failed. ret: %d", ret)); // NOTE: Check specification for recommended Advertising Interval range for Fast Advertising // ret = bt_adapter_le_set_advertising_interval(mAdvertiser, BT_LE_ADV_INTERVAL_MIN, BT_LE_ADV_INTERVAL_MIN); } else { // NOTE: Check specification for recommended Advertising Interval range for Slow Advertising // ret = bt_adapter_le_set_advertising_interval(mAdvertiser, BT_LE_ADV_INTERVAL_MAX, BT_LE_ADV_INTERVAL_MAX); } err = ConfigurationMgr().GetBLEDeviceIdentificationInfo(deviceIdInfo); VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(DeviceLayer, "GetBLEDeviceIdentificationInfo() failed. %s", ErrorStr(err))); memcpy(service_data, &deviceIdInfo, sizeof(service_data)); ret = bt_adapter_le_add_advertising_service_data(mAdvertiser, BT_ADAPTER_LE_PACKET_ADVERTISING, chip_ble_service_uuid_short, service_data, sizeof(service_data)); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_adapter_le_add_advertising_service_data() failed. ret: %d", ret)); err = SystemInfo::GetPlatformVersion(version); VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(DeviceLayer, "GetPlatformVersion() failed. %s", ErrorStr(err))); if (version.mMajor >= 8) { ret = bt_adapter_le_set_advertising_flags( mAdvertiser, BT_ADAPTER_LE_ADVERTISING_FLAGS_GEN_DISC | BT_ADAPTER_LE_ADVERTISING_FLAGS_BREDR_UNSUP); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_adapter_le_set_advertising_flags() failed. ret: %d", ret)); } else { ChipLogProgress(DeviceLayer, "setting function of advertising flags is available from tizen 7.5 or later"); } ret = bt_adapter_le_set_advertising_device_name(mAdvertiser, BT_ADAPTER_LE_PACKET_ADVERTISING, true); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_adapter_le_set_advertising_device_name() failed. ret: %d", ret)); BLEManagerImpl::NotifyBLEPeripheralAdvConfiguredComplete(true, nullptr); ret = bt_adapter_le_start_advertising_new(mAdvertiser, AdvertisingStateChangedCb, nullptr); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_adapter_le_start_advertising_new() failed. ret: %d", ret)); sInstance.mAdvReqInProgress = true; return ret; exit: BLEManagerImpl::NotifyBLEPeripheralAdvStartComplete(false, nullptr); return ret; } int BLEManagerImpl::StopBLEAdvertising() { int ret = BT_ERROR_NONE; ChipLogProgress(DeviceLayer, "Stop Advertising"); ret = bt_adapter_le_stop_advertising(mAdvertiser); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_adapter_le_stop_advertising() failed. ret: %d", ret)); sInstance.mAdvReqInProgress = true; return ret; exit: BLEManagerImpl::NotifyBLEPeripheralAdvStopComplete(false, nullptr); return ret; } void BLEManagerImpl::InitConnectionData() { /* Initialize Hashmap */ if (!mConnectionMap) { mConnectionMap = g_hash_table_new(g_str_hash, g_str_equal); ChipLogProgress(DeviceLayer, "GATT Connection HashMap created"); } } static bool __GattClientForeachCharCb(int total, int index, bt_gatt_h charHandle, void * data) { bt_gatt_type_e type; char * uuid = nullptr; auto conn = static_cast<BLEConnection *>(data); VerifyOrExit(__GetAttInfo(charHandle, &uuid, &type) == BT_ERROR_NONE, ChipLogError(DeviceLayer, "Failed to fetch GATT Attribute from CHAR handle")); if (strcasecmp(uuid, chip_ble_char_c1_tx_uuid) == 0) { ChipLogProgress(DeviceLayer, "CHIP Char C1 TX Found [%s]", StringOrNullMarker(uuid)); conn->gattCharC1Handle = charHandle; } else if (strcasecmp(uuid, chip_ble_char_c2_rx_uuid) == 0) { ChipLogProgress(DeviceLayer, "CHIP Char C2 RX Found [%s]", StringOrNullMarker(uuid)); conn->gattCharC2Handle = charHandle; } g_free(uuid); exit: /* Try next Char UUID */ return true; } static bool __GattClientForeachServiceCb(int total, int index, bt_gatt_h svcHandle, void * data) { bt_gatt_type_e type; char * uuid = nullptr; auto conn = static_cast<BLEConnection *>(data); ChipLogProgress(DeviceLayer, "__GattClientForeachServiceCb"); VerifyOrExit(__GetAttInfo(svcHandle, &uuid, &type) == BT_ERROR_NONE, ChipLogError(DeviceLayer, "Failed to fetch GATT Attribute from SVC handle")); if (strcasecmp(uuid, chip_ble_service_uuid) == 0) { ChipLogProgress(DeviceLayer, "CHIP Service UUID Found [%s]", StringOrNullMarker(uuid)); if (bt_gatt_service_foreach_characteristics(svcHandle, __GattClientForeachCharCb, conn) == BT_ERROR_NONE) conn->isChipDevice = true; /* Got CHIP Device, no need to process further service */ g_free(uuid); return false; } g_free(uuid); exit: /* Try next Service UUID */ return true; } bool BLEManagerImpl::IsDeviceChipPeripheral(BLE_CONNECTION_OBJECT conId) { auto conn = static_cast<BLEConnection *>(conId); if (bt_gatt_client_foreach_services(sInstance.mGattClient, __GattClientForeachServiceCb, conn) != BT_ERROR_NONE) ChipLogError(DeviceLayer, "Error Browsing GATT services"); return (conn->isChipDevice ? true : false); } void BLEManagerImpl::AddConnectionData(const char * remoteAddr) { BLEConnection * conn; ChipLogProgress(DeviceLayer, "AddConnectionData for [%s]", StringOrNullMarker(remoteAddr)); if (!g_hash_table_lookup(mConnectionMap, remoteAddr)) { ChipLogProgress(DeviceLayer, "Connection not found in map [%s]", StringOrNullMarker(remoteAddr)); conn = static_cast<BLEConnection *>(g_malloc0(sizeof(BLEConnection))); conn->peerAddr = g_strdup(remoteAddr); if (sInstance.mIsCentral) { /* Local Device is BLE Central Role */ if (IsDeviceChipPeripheral(conn)) { g_hash_table_insert(mConnectionMap, (gpointer) conn->peerAddr, conn); ChipLogProgress(DeviceLayer, "New Connection Added for [%s]", StringOrNullMarker(remoteAddr)); NotifyHandleNewConnection(conn); } else { g_free(conn->peerAddr); g_free(conn); } } else { /* Local Device is BLE Peripheral Role, assume remote is CHIP Central */ conn->isChipDevice = true; /* Save own gatt handles */ conn->gattCharC1Handle = mGattCharC1Handle; conn->gattCharC2Handle = mGattCharC2Handle; g_hash_table_insert(mConnectionMap, (gpointer) conn->peerAddr, conn); ChipLogProgress(DeviceLayer, "New Connection Added for [%s]", StringOrNullMarker(remoteAddr)); } } } void BLEManagerImpl::RemoveConnectionData(const char * remoteAddr) { BLEConnection * conn = nullptr; ChipLogProgress(DeviceLayer, "Connection Remove Request for [%s]", StringOrNullMarker(remoteAddr)); VerifyOrReturn(mConnectionMap != nullptr, ChipLogError(DeviceLayer, "Connection map does not exist")); conn = static_cast<BLEConnection *>(g_hash_table_lookup(mConnectionMap, remoteAddr)); VerifyOrReturn(conn != nullptr, ChipLogError(DeviceLayer, "Connection does not exist for [%s]", StringOrNullMarker(remoteAddr))); g_hash_table_remove(mConnectionMap, conn->peerAddr); g_free(conn->peerAddr); g_free(conn); if (!g_hash_table_size(mConnectionMap)) mConnectionMap = nullptr; ChipLogProgress(DeviceLayer, "Connection Removed"); } void BLEManagerImpl::HandleC1CharWriteEvent(BLE_CONNECTION_OBJECT conId, const uint8_t * value, size_t len) { CHIP_ERROR err = CHIP_NO_ERROR; System::PacketBufferHandle buf; ChipLogProgress(DeviceLayer, "Write request received for CHIPoBLE Client TX characteristic (data len %u)", static_cast<unsigned int>(len)); // Copy the data to a packet buffer. buf = System::PacketBufferHandle::NewWithData(value, len); VerifyOrExit(!buf.IsNull(), err = CHIP_ERROR_NO_MEMORY); NotifyBLEWriteReceived(buf, conId); return; exit: if (err != CHIP_NO_ERROR) { ChipLogError(DeviceLayer, "HandleC1CharWriteEvent() failed: %s", ErrorStr(err)); } } void BLEManagerImpl::HandleRXCharChanged(BLE_CONNECTION_OBJECT conId, const uint8_t * value, size_t len) { CHIP_ERROR err = CHIP_NO_ERROR; System::PacketBufferHandle buf; ChipLogProgress(DeviceLayer, "Notification received on CHIPoBLE Client RX characteristic (data len %u)", static_cast<unsigned int>(len)); // Copy the data to a packet buffer. buf = System::PacketBufferHandle::NewWithData(value, len); VerifyOrExit(!buf.IsNull(), err = CHIP_ERROR_NO_MEMORY); NotifyBLENotificationReceived(buf, conId); return; exit: if (err != CHIP_NO_ERROR) { ChipLogError(DeviceLayer, "HandleRXCharChanged() failed: %s", ErrorStr(err)); } } void BLEManagerImpl::HandleConnectionEvent(bool connected, const char * remoteAddress) { if (connected) { ChipLogProgress(DeviceLayer, "Device Connected [%s]", StringOrNullMarker(remoteAddress)); AddConnectionData(remoteAddress); } else { ChipLogProgress(DeviceLayer, "Device DisConnected [%s]", StringOrNullMarker(remoteAddress)); RemoveConnectionData(remoteAddress); } } void BLEManagerImpl::DriveBLEState() { int ret = BT_ERROR_NONE; ChipLogProgress(DeviceLayer, "Enter DriveBLEState"); if (!mIsCentral && mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && !mFlags.Has(Flags::kAppRegistered)) { ret = RegisterGATTServer(); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "Register GATT Server Failed. ret: %d", ret)); ChipLogProgress(DeviceLayer, "GATT Service Registered"); mFlags.Set(Flags::kAppRegistered); ExitNow(); } if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && mFlags.Has(Flags::kAdvertisingEnabled)) { if (!mFlags.Has(Flags::kAdvertising)) { ret = StartBLEAdvertising(); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "Start Advertising Failed. ret: %d", ret)); } else if (mFlags.Has(Flags::kAdvertisingRefreshNeeded)) { ChipLogProgress(DeviceLayer, "Advertising Refreshed Needed. Stop Advertising"); ret = StopBLEAdvertising(); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "Stop Advertising Failed. ret: %d", ret)); } } else if (mFlags.Has(Flags::kAdvertising)) { ChipLogProgress(DeviceLayer, "Stop Advertising"); ret = StopBLEAdvertising(); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "Stop Advertising Failed. ret: %d", ret)); ret = bt_adapter_le_destroy_advertiser(mAdvertiser); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_adapter_le_destroy_advertiser() failed. ret: %d", ret)); mAdvertiser = nullptr; } exit: if (ret != BT_ERROR_NONE) { mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Disabled; } } void BLEManagerImpl::DriveBLEState(intptr_t arg) { sInstance.DriveBLEState(); } CHIP_ERROR BLEManagerImpl::_Init() { CHIP_ERROR err; err = BleLayer::Init(this, this, this, &DeviceLayer::SystemLayer()); SuccessOrExit(err); mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Enabled; ChipLogProgress(DeviceLayer, "Initialize BLE"); err = PlatformMgrImpl().GLibMatterContextInvokeSync(_BleInitialize, static_cast<void *>(nullptr)); SuccessOrExit(err); PlatformMgr().ScheduleWork(DriveBLEState, 0); exit: return err; } void BLEManagerImpl::_Shutdown() { int ret = bt_deinitialize(); VerifyOrReturn(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_deinitialize() failed. ret: %d", ret)); } CHIP_ERROR BLEManagerImpl::_SetAdvertisingEnabled(bool val) { mFlags.Set(Flags::kAdvertisingEnabled, val); PlatformMgr().ScheduleWork(DriveBLEState, 0); return CHIP_NO_ERROR; } CHIP_ERROR BLEManagerImpl::_SetAdvertisingMode(BLEAdvertisingMode mode) { switch (mode) { case BLEAdvertisingMode::kFastAdvertising: mFlags.Set(Flags::kFastAdvertisingEnabled, true); break; case BLEAdvertisingMode::kSlowAdvertising: mFlags.Set(Flags::kFastAdvertisingEnabled, false); break; default: return CHIP_ERROR_INVALID_ARGUMENT; } mFlags.Set(Flags::kAdvertisingRefreshNeeded); PlatformMgr().ScheduleWork(DriveBLEState, 0); return CHIP_NO_ERROR; } CHIP_ERROR BLEManagerImpl::_GetDeviceName(char * buf, size_t bufSize) { CHIP_ERROR err = CHIP_NO_ERROR; int ret; char * deviceName = nullptr; VerifyOrExit(buf != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT); ret = bt_adapter_get_name(&deviceName); if (ret != BT_ERROR_NONE) { ChipLogError(DeviceLayer, "bt_adapter_get_name() failed. ret: %d", ret); return CHIP_ERROR_INTERNAL; } VerifyOrExit(deviceName != nullptr, err = CHIP_ERROR_INTERNAL); VerifyOrExit(strlen(deviceName) >= bufSize, err = CHIP_ERROR_BUFFER_TOO_SMALL); g_strlcpy(buf, deviceName, bufSize); ChipLogProgress(DeviceLayer, "DeviceName: %s", buf); exit: return err; } CHIP_ERROR BLEManagerImpl::_SetDeviceName(const char * deviceName) { CHIP_ERROR err = CHIP_NO_ERROR; int ret; VerifyOrExit(deviceName != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT); ret = bt_adapter_set_name(deviceName); if (ret != BT_ERROR_NONE) { ChipLogError(DeviceLayer, "bt_adapter_set_name() failed. ret: %d", ret); return CHIP_ERROR_INTERNAL; } exit: return err; } uint16_t BLEManagerImpl::_NumConnections() { return 0; } CHIP_ERROR BLEManagerImpl::ConfigureBle(uint32_t aAdapterId, bool aIsCentral) { mAdapterId = aAdapterId; mIsCentral = aIsCentral; return CHIP_NO_ERROR; } void BLEManagerImpl::CleanScanConfig() { if (mBLEScanConfig.mBleScanState == BleScanState::kConnecting) DeviceLayer::SystemLayer().CancelTimer(HandleConnectionTimeout, nullptr); mBLEScanConfig.mBleScanState = BleScanState::kNotScanning; } void BLEManagerImpl::HandlePlatformSpecificBLEEvent(const ChipDeviceEvent * apEvent) { ChipLogDetail(DeviceLayer, "HandlePlatformSpecificBLEEvent %d", apEvent->Type); switch (apEvent->Type) { case DeviceEventType::kPlatformTizenBLECentralConnected: if (mBLEScanConfig.mBleScanState == BleScanState::kConnecting) { BleConnectionDelegate::OnConnectionComplete(mBLEScanConfig.mAppState, apEvent->Platform.BLECentralConnected.mConnection); CleanScanConfig(); } break; case DeviceEventType::kPlatformTizenBLECentralConnectFailed: if (mBLEScanConfig.mBleScanState == BleScanState::kConnecting) { BleConnectionDelegate::OnConnectionError(mBLEScanConfig.mAppState, apEvent->Platform.BLECentralConnectFailed.mError); CleanScanConfig(); } break; case DeviceEventType::kPlatformTizenBLEWriteComplete: { Ble::ChipBleUUID service_uuid; Ble::ChipBleUUID char_write_uuid; StringToUUID(chip_ble_service_uuid, service_uuid); StringToUUID(chip_ble_char_c1_tx_uuid, char_write_uuid); HandleWriteConfirmation(apEvent->Platform.BLEWriteComplete.mConnection, &service_uuid, &char_write_uuid); break; } case DeviceEventType::kPlatformTizenBLESubscribeOpComplete: { Ble::ChipBleUUID service_uuid; Ble::ChipBleUUID char_notif_uuid; StringToUUID(chip_ble_service_uuid, service_uuid); StringToUUID(chip_ble_char_c2_rx_uuid, char_notif_uuid); if (apEvent->Platform.BLESubscribeOpComplete.mIsSubscribed) HandleSubscribeComplete(apEvent->Platform.BLESubscribeOpComplete.mConnection, &service_uuid, &char_notif_uuid); else HandleUnsubscribeComplete(apEvent->Platform.BLESubscribeOpComplete.mConnection, &service_uuid, &char_notif_uuid); break; } case DeviceEventType::kPlatformTizenBLEIndicationReceived: { Ble::ChipBleUUID service_uuid; Ble::ChipBleUUID char_notif_uuid; StringToUUID(chip_ble_service_uuid, service_uuid); StringToUUID(chip_ble_char_c2_rx_uuid, char_notif_uuid); HandleIndicationReceived(apEvent->Platform.BLEIndicationReceived.mConnection, &service_uuid, &char_notif_uuid, System::PacketBufferHandle::Adopt(apEvent->Platform.BLEIndicationReceived.mData)); break; } default: break; } } void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) { Ble::ChipBleUUID service_uuid; Ble::ChipBleUUID char_notification_uuid; Ble::ChipBleUUID char_write_uuid; switch (event->Type) { case DeviceEventType::kCHIPoBLESubscribe: ChipLogProgress(DeviceLayer, "CHIPoBLESubscribe"); StringToUUID(chip_ble_service_uuid, service_uuid); StringToUUID(chip_ble_char_c2_rx_uuid, char_notification_uuid); HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &service_uuid, &char_notification_uuid); NotifyBLEConnectionEstablished(event->CHIPoBLESubscribe.ConId, CHIP_NO_ERROR); break; case DeviceEventType::kCHIPoBLEUnsubscribe: ChipLogProgress(DeviceLayer, "CHIPoBLEUnsubscribe"); StringToUUID(chip_ble_service_uuid, service_uuid); StringToUUID(chip_ble_char_c2_rx_uuid, char_notification_uuid); HandleUnsubscribeReceived(event->CHIPoBLESubscribe.ConId, &service_uuid, &char_notification_uuid); break; case DeviceEventType::kCHIPoBLEWriteReceived: ChipLogProgress(DeviceLayer, "CHIPoBLEWriteReceived"); StringToUUID(chip_ble_service_uuid, service_uuid); StringToUUID(chip_ble_char_c1_tx_uuid, char_write_uuid); HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &service_uuid, &char_write_uuid, System::PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data)); break; case DeviceEventType::kCHIPoBLEIndicateConfirm: ChipLogProgress(DeviceLayer, "CHIPoBLEIndicateConfirm"); StringToUUID(chip_ble_service_uuid, service_uuid); StringToUUID(chip_ble_char_c2_rx_uuid, char_notification_uuid); HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &service_uuid, &char_notification_uuid); break; case DeviceEventType::kCHIPoBLEConnectionError: ChipLogProgress(DeviceLayer, "CHIPoBLEConnectionError"); HandleConnectionError(event->CHIPoBLEConnectionError.ConId, event->CHIPoBLEConnectionError.Reason); break; case DeviceEventType::kServiceProvisioningChange: break; default: HandlePlatformSpecificBLEEvent(event); break; } } uint16_t BLEManagerImpl::GetMTU(BLE_CONNECTION_OBJECT conId) const { auto conn = static_cast<BLEConnection *>(conId); return (conn != nullptr) ? conn->mtu : 0; } bool BLEManagerImpl::SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, const Ble::ChipBleUUID * charId) { Ble::ChipBleUUID service_uuid; Ble::ChipBleUUID char_notif_uuid; auto conn = static_cast<BLEConnection *>(conId); int ret = BT_ERROR_NONE; ChipLogProgress(DeviceLayer, "SubscribeCharacteristic"); StringToUUID(chip_ble_service_uuid, service_uuid); StringToUUID(chip_ble_char_c2_rx_uuid, char_notif_uuid); VerifyOrExit(conn != nullptr, ChipLogError(DeviceLayer, "Invalid Connection")); VerifyOrExit(Ble::UUIDsMatch(svcId, &service_uuid), ChipLogError(DeviceLayer, "SubscribeCharacteristic() called with invalid service ID")); VerifyOrExit(Ble::UUIDsMatch(charId, &char_notif_uuid), ChipLogError(DeviceLayer, "SubscribeCharacteristic() called with invalid characteristic ID")); VerifyOrExit(conn->gattCharC2Handle != nullptr, ChipLogError(DeviceLayer, "Char C2 is null")); ChipLogProgress(DeviceLayer, "Sending Notification Enable Request to CHIP Peripheral(con %s)", conn->peerAddr); ret = bt_gatt_client_set_characteristic_value_changed_cb(conn->gattCharC2Handle, CharacteristicNotificationCb, conn); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_client_set_characteristic_value_changed_cb() failed. ret: %d", ret)); sInstance.NotifySubscribeOpComplete(conn, true); return true; exit: return false; } bool BLEManagerImpl::UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, const Ble::ChipBleUUID * charId) { Ble::ChipBleUUID service_uuid; Ble::ChipBleUUID char_notif_uuid; auto conn = static_cast<BLEConnection *>(conId); int ret = BT_ERROR_NONE; ChipLogProgress(DeviceLayer, "UnSubscribeCharacteristic"); StringToUUID(chip_ble_service_uuid, service_uuid); StringToUUID(chip_ble_char_c2_rx_uuid, char_notif_uuid); VerifyOrExit(conn != nullptr, ChipLogError(DeviceLayer, "Invalid Connection")); VerifyOrExit(Ble::UUIDsMatch(svcId, &service_uuid), ChipLogError(DeviceLayer, "UnSubscribeCharacteristic() called with invalid service ID")); VerifyOrExit(Ble::UUIDsMatch(charId, &char_notif_uuid), ChipLogError(DeviceLayer, "UnSubscribeCharacteristic() called with invalid characteristic ID")); VerifyOrExit(conn->gattCharC2Handle != nullptr, ChipLogError(DeviceLayer, "Char C2 is null")); ChipLogProgress(DeviceLayer, "Disable Notification Request to CHIP Peripheral(con %s)", conn->peerAddr); ret = bt_gatt_client_unset_characteristic_value_changed_cb(conn->gattCharC2Handle); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_client_unset_characteristic_value_changed_cb() failed. ret: %d", ret)); sInstance.NotifySubscribeOpComplete(conn, false); return true; exit: return false; } bool BLEManagerImpl::CloseConnection(BLE_CONNECTION_OBJECT conId) { auto conn = static_cast<BLEConnection *>(conId); int ret = BT_ERROR_NONE; ChipLogProgress(DeviceLayer, "Close BLE Connection"); conn = static_cast<BLEConnection *>(g_hash_table_lookup(sInstance.mConnectionMap, conn->peerAddr)); VerifyOrExit(conn != nullptr, ChipLogError(DeviceLayer, "Failed to find connection info")); ChipLogProgress(DeviceLayer, "Send GATT disconnect to [%s]", conn->peerAddr); ret = bt_gatt_disconnect(conn->peerAddr); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_disconnect() failed. ret: %d", ret)); RemoveConnectionData(conn->peerAddr); return true; exit: return false; } bool BLEManagerImpl::SendIndication(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, const Ble::ChipBleUUID * charId, System::PacketBufferHandle pBuf) { auto conn = static_cast<BLEConnection *>(conId); int ret = BT_ERROR_NONE; ChipLogProgress(DeviceLayer, "SendIndication"); conn = static_cast<BLEConnection *>(g_hash_table_lookup(sInstance.mConnectionMap, conn->peerAddr)); VerifyOrExit(conn != nullptr, ChipLogError(DeviceLayer, "Failed to find connection info")); ret = bt_gatt_set_value(mGattCharC2Handle, Uint8::to_const_char(pBuf->Start()), pBuf->DataLength()); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_set_value() failed. ret: %d", ret)); ChipLogProgress(DeviceLayer, "Sending indication for CHIPoBLE RX characteristic (con %s, len %u)", conn->peerAddr, pBuf->DataLength()); ret = bt_gatt_server_notify_characteristic_changed_value(mGattCharC2Handle, IndicationConfirmationCb, conn->peerAddr, nullptr); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_server_notify_characteristic_changed_value() failed. ret: %d", ret)); return true; exit: return false; } bool BLEManagerImpl::SendWriteRequest(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, const Ble::ChipBleUUID * charId, System::PacketBufferHandle pBuf) { Ble::ChipBleUUID service_uuid; Ble::ChipBleUUID char_write_uuid; auto conn = static_cast<BLEConnection *>(conId); int ret = BT_ERROR_NONE; ChipLogProgress(DeviceLayer, "SendWriteRequest"); StringToUUID(chip_ble_service_uuid, service_uuid); StringToUUID(chip_ble_char_c1_tx_uuid, char_write_uuid); VerifyOrExit(conn != nullptr, ChipLogError(DeviceLayer, "Invalid Connection")); VerifyOrExit(Ble::UUIDsMatch(svcId, &service_uuid), ChipLogError(DeviceLayer, "SendWriteRequest() called with invalid service ID")); VerifyOrExit(Ble::UUIDsMatch(charId, &char_write_uuid), ChipLogError(DeviceLayer, "SendWriteRequest() called with invalid characteristic ID")); VerifyOrExit(conn->gattCharC1Handle != nullptr, ChipLogError(DeviceLayer, "Char C1 is null")); ret = bt_gatt_set_value(conn->gattCharC1Handle, Uint8::to_const_char(pBuf->Start()), pBuf->DataLength()); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_set_value() failed. ret: %d", ret)); ChipLogProgress(DeviceLayer, "Sending Write Request for CHIPoBLE TX characteristic (con %s, len %u)", conn->peerAddr, pBuf->DataLength()); ret = bt_gatt_client_write_value(conn->gattCharC1Handle, WriteCompletedCb, conn); VerifyOrExit(ret == BT_ERROR_NONE, ChipLogError(DeviceLayer, "bt_gatt_client_write_value() failed. ret: %d", ret)); return true; exit: return false; } bool BLEManagerImpl::SendReadRequest(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, const Ble::ChipBleUUID * charId, System::PacketBufferHandle pBuf) { return false; } bool BLEManagerImpl::SendReadResponse(BLE_CONNECTION_OBJECT conId, BLE_READ_REQUEST_CONTEXT requestContext, const Ble::ChipBleUUID * svcId, const Ble::ChipBleUUID * charId) { return false; } void BLEManagerImpl::NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId) {} void BLEManagerImpl::NewConnection(BleLayer * bleLayer, void * appState, const SetupDiscriminator & connDiscriminator) { mBLEScanConfig.mDiscriminator = connDiscriminator; mBLEScanConfig.mAppState = appState; if (connDiscriminator.IsShortDiscriminator()) { ChipLogProgress(DeviceLayer, "NewConnection: short discriminator value [%u]", connDiscriminator.GetShortValue()); } else { ChipLogProgress(DeviceLayer, "NewConnection: long discriminator value [%u]", connDiscriminator.GetLongValue()); } // Initiate Scan. PlatformMgr().ScheduleWork(InitiateScan, static_cast<intptr_t>(BleScanState::kScanForDiscriminator)); } void BLEManagerImpl::InitiateScan(BleScanState scanType) { CHIP_ERROR err = CHIP_NO_ERROR; ScanFilterData data = { { 0x0 }, }; ChipLogProgress(DeviceLayer, "Initiate Scan"); /* Check Scanning state */ if (scanType == BleScanState::kNotScanning) { err = CHIP_ERROR_INCORRECT_STATE; ChipLogError(DeviceLayer, "Invalid scan type requested"); goto exit; } /* Check Tizen BLE layer is initialized or not */ if (!mFlags.Has(Flags::kTizenBLELayerInitialized)) { err = CHIP_ERROR_INCORRECT_STATE; ChipLogError(DeviceLayer, "Tizen BLE Layer is not yet initialized"); goto exit; } /* Setup ScanFilter */ memset(&data.service_data, 0x00, sizeof(data.service_data)); data.service_data_len = 0; strcpy(data.service_uuid, chip_ble_service_uuid_short); /* Acquire Chip Device Scanner */ if (!mDeviceScanner) mDeviceScanner = Internal::ChipDeviceScanner::Create(this); if (!mDeviceScanner) { err = CHIP_ERROR_INTERNAL; ChipLogError(DeviceLayer, "Failed to create a BLE device scanner"); goto exit; } /* Send StartChipScan Request to Scanner Class */ err = mDeviceScanner->StartChipScan(kNewConnectionScanTimeout, ScanFilterType::kServiceData, data); VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(DeviceLayer, "Failed to start a BLE scan")); ChipLogProgress(DeviceLayer, "BLE scan initiation successful"); mBLEScanConfig.mBleScanState = scanType; return; exit: ChipLogError(DeviceLayer, "BLE scan initiation failed: %" CHIP_ERROR_FORMAT, err.Format()); mBLEScanConfig.mBleScanState = BleScanState::kNotScanning; BleConnectionDelegate::OnConnectionError(mBLEScanConfig.mAppState, err); } void BLEManagerImpl::InitiateScan(intptr_t arg) { sInstance.InitiateScan(static_cast<BleScanState>(arg)); } CHIP_ERROR BLEManagerImpl::CancelConnection() { return CHIP_ERROR_NOT_IMPLEMENTED; } } // namespace Internal } // namespace DeviceLayer } // namespace chip
[ "noreply@github.com" ]
noreply@github.com
49ca18a1d0a44146f7d3dd8880c11c99ff42372a
3d6f999526ac252f5d68d564c553391c1c219825
/srcs/client_src/SoundArranger/SoundArrangerView.cpp
48bfaf088c9fc799e421ddb69be22f4f802896f9
[ "Unlicense" ]
permissive
kdoggdev/cncn_m2
e77354257de654f6507bcd14f0589311318bcbc0
149087e114be2b35c3e1548f4d37d6618ae27442
refs/heads/main
2023-02-02T09:56:37.306125
2020-12-23T09:52:14
2020-12-23T09:52:14
337,634,606
0
1
Unlicense
2021-02-10T06:13:27
2021-02-10T06:13:27
null
UTF-8
C++
false
false
2,289
cpp
// SoundArrangerView.cpp : implementation of the CSoundArrangerView class // #include "stdafx.h" #include "SoundArranger.h" #include "SoundArrangerDoc.h" #include "SoundArrangerView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CSoundArrangerView IMPLEMENT_DYNCREATE(CSoundArrangerView, CView) BEGIN_MESSAGE_MAP(CSoundArrangerView, CView) //{{AFX_MSG_MAP(CSoundArrangerView) //}}AFX_MSG_MAP // Standard printing commands ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CSoundArrangerView construction/destruction CSoundArrangerView::CSoundArrangerView() { } CSoundArrangerView::~CSoundArrangerView() { } BOOL CSoundArrangerView::PreCreateWindow(CREATESTRUCT& cs) { return CView::PreCreateWindow(cs); } ///////////////////////////////////////////////////////////////////////////// // CSoundArrangerView drawing void CSoundArrangerView::OnDraw(CDC* pDC) { CSoundArrangerDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); } ///////////////////////////////////////////////////////////////////////////// // CSoundArrangerView printing BOOL CSoundArrangerView::OnPreparePrinting(CPrintInfo* pInfo) { // default preparation return DoPreparePrinting(pInfo); } void CSoundArrangerView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { } void CSoundArrangerView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { } ///////////////////////////////////////////////////////////////////////////// // CSoundArrangerView diagnostics #ifdef _DEBUG void CSoundArrangerView::AssertValid() const { CView::AssertValid(); } void CSoundArrangerView::Dump(CDumpContext& dc) const { CView::Dump(dc); } CSoundArrangerDoc* CSoundArrangerView::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CSoundArrangerDoc))); return (CSoundArrangerDoc*)m_pDocument; } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CSoundArrangerView message handlers
[ "uchregdefault@gmail.com" ]
uchregdefault@gmail.com
57bc5dd71f956d9fb118983d5c36c046765eedfc
a138033ace80cce59fdf721c1c0950b7d3e1d21a
/libSomeVM/VM.cpp
f9973f16321a1dee5387544ccba3c60f1b8b1666
[ "MIT" ]
permissive
fengjixuchui/SomeVM
2e5940ed178304bb653d0a66764f0577763b2396
99ea638431665069b6b69836f66b81a7da65add3
refs/heads/master
2020-05-09T18:11:44.995614
2018-03-12T16:51:44
2018-03-12T16:51:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,101
cpp
#include "VM.hpp" #include <iterator> #include <cmath> #include "Program.hpp" #include "SysCall.hpp" namespace { using namespace svm; int64_t getInteger(Float f) { constexpr uint64_t VALUE_MASK = 0x000fffffffffffffu; constexpr uint64_t SIGN_BIT = 1ull << 63; auto& ir = reinterpret_cast<int64_t&>(f); bool sign = (ir & SIGN_BIT) != 0; // assume exponent is +1 return (ir & VALUE_MASK) * (sign ? -1 : 1); } } namespace svm { VM::VM(std::uint64_t initialRegistrySize) : registry(initialRegistrySize), nextFree(registry.begin()) {} void VM::load(const Program& program) { // make sure we only need to do 1 allocation while inserting constants.reserve(constants.size() + program.constants.size()); std::copy(program.constants.begin(), program.constants.end(), std::back_inserter(constants)); // make sure we only need to do 1 allocation while inserting functions.reserve(functions.size() + program.functions.size()); std::copy(program.functions.begin(), program.functions.end(), std::back_inserter(functions)); } void VM::run() { callStack.emplace(functions.front(), 0, 0); while (!callStack.empty()) { Frame& frame = callStack.top(); if (!frame.complete()) interpret(*frame.next(), frame); else callStack.pop(); } } std::uint64_t VM::callStackSize() const { return callStack.size(); } std::uint64_t VM::registrySize() const { return registry.size(); } void VM::write(Value val) { if (nextFree != registry.end()) { *nextFree++ = val; } else { registry.push_back(val); nextFree = registry.end(); } } void VM::write(std::uint64_t idx, Value val) { registry.at(idx) = val; } Value VM::read(std::uint64_t idx) const { return registry.at(idx); } void VM::interpret(Instruction instr, Frame& frame) { switch (instr.type()) { /* memory ops */ case Instruction::Type::Load: { auto dest = instr.arg1_24(); auto src = instr.arg2_32(); registry.at(dest) = registry.at(src); break; } case Instruction::Type::LoadC: { auto dest = instr.arg1_24(); auto src = instr.arg2_32(); registry.at(dest) = constants.at(src); break; } /* math ops */ case Instruction::Type::Add: { Float one = registry.at(instr.arg2_16()); Float two = registry.at(instr.arg3_16()); registry.at(instr.arg1_16()) = { one + two }; break; } case Instruction::Type::Sub: { Float one = registry.at(instr.arg2_16()); Float two = registry.at(instr.arg3_16()); registry.at(instr.arg1_16()) = { one - two }; break; } case Instruction::Type::Mult: { Float one = registry.at(instr.arg2_16()); Float two = registry.at(instr.arg3_16()); registry.at(instr.arg1_16()) = { one * two }; break; } case Instruction::Type::Div: { Float one = registry.at(instr.arg2_16()); Float two = registry.at(instr.arg3_16()); registry.at(instr.arg1_16()) = { one / two }; break; } case Instruction::Type::Mod: { Float one = registry.at(instr.arg2_16()); Float two = registry.at(instr.arg3_16()); registry.at(instr.arg1_16()) = std::fmod(one, two); break; } case Instruction::Type::Neg: { Float one = registry.at(instr.arg2_16()); registry.at(instr.arg1_16()) = { -one }; break; } /* comparison ops */ case Instruction::Type::Lt: { Float one = registry.at(instr.arg2_16()); Float two = registry.at(instr.arg3_16()); registry.at(instr.arg1_16()) = { one < two }; break; } case Instruction::Type::LtEq: { Float one = registry.at(instr.arg2_16()); Float two = registry.at(instr.arg3_16()); registry.at(instr.arg1_16()) = { one <= two }; break; } case Instruction::Type::Gt: { Float one = registry.at(instr.arg2_16()); Float two = registry.at(instr.arg3_16()); registry.at(instr.arg1_16()) = { one > two }; break; } case Instruction::Type::GtEq: { Float one = registry.at(instr.arg2_16()); Float two = registry.at(instr.arg3_16()); registry.at(instr.arg1_16()) = { one >= two }; break; } case Instruction::Type::Eq: { Float one = registry.at(instr.arg2_16()); Float two = registry.at(instr.arg3_16()); registry.at(instr.arg1_16()) = { one == two }; break; } case Instruction::Type::Neq: { Float one = registry.at(instr.arg2_16()); Float two = registry.at(instr.arg3_16()); registry.at(instr.arg1_16()) = { one != two }; break; } /* logical ops */ case Instruction::Type::Not: { Bool one = registry.at(instr.arg2_32()); registry.at(instr.arg1_24()) = { !one }; break; } case Instruction::Type::And: { Bool one = registry.at(instr.arg2_16()); Bool two = registry.at(instr.arg3_16()); registry.at(instr.arg1_16()) = { one && two }; break; } case Instruction::Type::Or: { Bool one = registry.at(instr.arg2_16()); Bool two = registry.at(instr.arg3_16()); registry.at(instr.arg1_16()) = { one || two }; break; } case Instruction::Type::Xor: { Bool one = registry.at(instr.arg2_16()); Bool two = registry.at(instr.arg3_16()); registry.at(instr.arg1_16()) = { one != two }; break; } /* conditional branching */ case Instruction::Type::JmpT: { Bool b = registry.at(instr.arg1_24()); auto idx = getInteger(constants.at(instr.arg2_32())); // if true, skip the next instruction (the jump to the "else") if (b) frame.jump(idx); break; } case Instruction::Type::JmpF: { Bool b = registry.at(instr.arg1_24()); auto idx = getInteger(constants.at(instr.arg2_32())); // if false, skip the next instruction (the jump to the "else") if (!b) frame.jump(idx); break; } case Instruction::Type::JmpTC: { Bool b = registry.at(instr.arg1_24()); auto idx = getInteger(constants.at(instr.arg2_32())); // if true, skip the next instruction (the jump to the "else") if (b) frame.jump(idx); break; } case Instruction::Type::JmpFC: { Bool b = registry.at(instr.arg1_24()); auto idx = getInteger(constants.at(instr.arg2_32())); // if false, skip the next instruction (the jump to the "else") if (!b) frame.jump(idx); break; } case Instruction::Type::RJmpT: { Bool b = registry.at(instr.arg1_24()); auto off = getInteger(constants.at(instr.arg2_32())); // if true, skip the next instruction (the jump to the "else") if (b) frame.rjump(off); break; } case Instruction::Type::RJmpF: { Bool b = registry.at(instr.arg1_24()); auto off = getInteger(constants.at(instr.arg2_32())); // if false, skip the next instruction (the jump to the "else") if (!b) frame.rjump(off); break; } case Instruction::Type::RJmpTC: { Bool b = registry.at(instr.arg1_24()); auto off = getInteger(constants.at(instr.arg2_32())); // if true, skip the next instruction (the jump to the "else") if (b) frame.rjump(off); break; } case Instruction::Type::RJmpFC: { Bool b = registry.at(instr.arg1_24()); auto off = getInteger(constants.at(instr.arg2_32())); // if false, skip the next instruction (the jump to the "else") if (!b) frame.rjump(off); break; } /* branching */ case Instruction::Type::Call: { auto nargs = getInteger(registry.at(instr.arg1_16())); auto argIdx = getInteger(registry.at(instr.arg2_16())); auto funcIdx = getInteger(registry.at(instr.arg3_16())); const Function& callee = functions[funcIdx]; if (nargs != callee.args()) throw std::logic_error("Invalid number of arguments!"); callStack.emplace(callee, funcIdx, argIdx); break; } case Instruction::Type::Ret: { // TODO: make work like it should // auto nrets = getInteger(registry.at(instr.arg1_24())); // auto retIdx = getInteger(registry.at(instr.arg2_32())); callStack.pop(); break; } case Instruction::Type::Jmp: { auto idx = getInteger(registry.at(instr.arg1_56())); frame.jump(idx); break; } case Instruction::Type::RJmp: { auto off = getInteger(registry.at(instr.arg1_56())); frame.rjump(off); break; } case Instruction::Type::JmpC: { auto idx = getInteger(constants.at(instr.arg1_56())); frame.jump(idx); break; } case Instruction::Type::RJmpC: { auto off = getInteger(constants.at(instr.arg1_56())); frame.rjump(off); break; } case Instruction::Type::SysCall: { auto nargs = getInteger(registry.at(instr.arg1_16())); auto argIdx = getInteger(registry.at(instr.arg2_16())); auto funcIdx = static_cast<SysCall>(getInteger(registry.at(instr.arg3_16()))); switch (funcIdx) { case SysCall::Print: for (; argIdx < argIdx + nargs; ++argIdx) { //auto& s = registry.at(argIdx); //auto& v = registry.at(++argIdx); //std::printf(s, v); } break; default: // ignore unknown syscall ids for now break; } break; } case Instruction::Type::Nop: { break; } } } }
[ "adiverso93@gmail.com" ]
adiverso93@gmail.com
adcdba673af435d742a932239d69172351285238
ef2bbb47747036829c6aa1ef712fe75ea13fd0a0
/3.Lab3/Code@testing/Lab3_2/MyStack.cpp
4fd919baba0f1bb348ab2ca98b4154f5a2e32f64
[]
no_license
Sciencethebird/CS_OOP
ce1c24ffe251ccc726ead9c888e798dded4e4fe6
939c1d227daebb4f136c994026fe57b1cc2eef89
refs/heads/master
2020-04-01T20:48:39.884046
2019-02-04T09:33:45
2019-02-04T09:33:45
153,621,632
1
0
null
null
null
null
UTF-8
C++
false
false
739
cpp
#include <iostream> #include<iomanip> using namespace std; #include "MyStack.h" MyStack :: MyStack() { cap = 5; len = 0; arr= new int[cap]; } MyStack :: MyStack(int c) { cap = c; len = 0; arr= new int[cap]; } MyStack :: MyStack(const MyStack & s) { int *temp; temp = new int[cap]; for(int i=0; i<len; i++) { temp[i]=arr[i]; } arr = temp; } MyStack:: ~MyStack() { delete []arr; } void MyStack:: push(int n) { if(len < cap) { arr[len] = n; len++; } } void MyStack:: pop() { if(len > 0) { arr[len] = '\0'; len--; } } int getAvailCap(MyStack & s){ return s.cap - s.len; }
[ "sciencethebird@gmail.com" ]
sciencethebird@gmail.com
814f0038f169c68b538053c30ba3317cb166c8a9
0d23c7faa7f8556815402c7b14cebf1d1de6bc4c
/src/ProtoSegment.cxx
12232bdea3185e950bb7117ecc519f1aaf31eca2
[]
no_license
BNLIF/wire-cell-pid
cfa027f25ffe275f55332bc9d32c98789fa0c441
290f24197788e80ab4e1127d7b562911c15ecf81
refs/heads/master
2022-07-05T06:25:27.115571
2022-06-30T22:44:53
2022-06-30T22:44:53
179,381,058
0
0
null
null
null
null
UTF-8
C++
false
false
76,701
cxx
#include "WCPPID/ProtoSegment.h" #include "WCPData/TPCParams.h" #include "WCPData/Singleton.h" #include "WCPData/Line.h" #include "TH1F.h" using namespace WCP; int WCPPID::ProtoSegment::get_particle_type(){ if (get_flag_shower()){ particle_type = 11; // shower are all treated as electron } return particle_type; } WCPPID::ProtoSegment::ProtoSegment(int id, std::list<WCP::WCPointCloud<double>::WCPoint >& path_wcps, int cluster_id ) : id(id) , cluster_id(cluster_id) , flag_fit(false) , pcloud_fit(0) , pcloud_associated(0) , pcloud_associated_steiner(0) , flag_shower_trajectory(false) , flag_shower_topology(false) , flag_avoid_muon_check(false) , flag_dir(0) , dir_weak(false) , particle_type(0) , particle_score(100) , particle_mass(0) , kenergy_charge(0) , kenergy_best(0) { for (int i=0;i!=4;i++){ particle_4mom[i] = 0; } for (auto it = path_wcps.begin(); it!=path_wcps.end(); it++){ wcpt_vec.push_back(*it); Point p; p.x = wcpt_vec.back().x; p.y = wcpt_vec.back().y; p.z = wcpt_vec.back().z; fit_pt_vec.push_back(p); } if (pcloud_fit != (ToyPointCloud*)0) delete pcloud_fit; pcloud_fit = new ToyPointCloud(); pcloud_fit->AddPoints(fit_pt_vec); pcloud_fit->build_kdtree_index(); } void WCPPID::ProtoSegment::build_pcloud_fit(){ if (pcloud_fit != (ToyPointCloud*)0) delete pcloud_fit; pcloud_fit = new ToyPointCloud(); pcloud_fit->AddPoints(fit_pt_vec); pcloud_fit->build_kdtree_index(); } WCPPID::ProtoSegment::~ProtoSegment(){ if (pcloud_fit != (ToyPointCloud*)0) delete pcloud_fit; if (pcloud_associated != (ToyPointCloud*)0) delete pcloud_associated; if (pcloud_associated_steiner != (ToyPointCloud*)0) delete pcloud_associated_steiner; } bool WCPPID::ProtoSegment::determine_shower_direction(){ flag_dir = 0; // look at the points ... std::vector<PointVector > local_points_vec(fit_pt_vec.size()); std::vector<std::tuple<double, double, double> > vec_rms_vals(fit_pt_vec.size(), std::make_tuple(0,0,0)); std::vector<double> vec_dQ_dx(fit_pt_vec.size(), 0); std::vector<TVector3> vec_dir(fit_pt_vec.size()); if (pcloud_associated == 0 ) return false; WCP::WCPointCloud<double>& cloud = pcloud_associated->get_cloud(); for (size_t i = 0; i!= cloud.pts.size(); i++){ Point test_p(cloud.pts.at(i).x, cloud.pts.at(i).y, cloud.pts.at(i).z); std::vector<std::pair<size_t,double>> results = pcloud_fit->get_closest_index(test_p,1); local_points_vec.at(results.front().first).push_back(test_p); } TVector3 drift_dir(1,0,0); // drift direction for (size_t i=0;i!=local_points_vec.size();i++){ TVector3 dir_1, dir_2, dir_3; Point v1(0,0,0); for (size_t j=1;j!=3;j++){ if (i+j<local_points_vec.size()){ v1.x += fit_pt_vec.at(i+j).x - fit_pt_vec.at(i).x; v1.y += fit_pt_vec.at(i+j).y - fit_pt_vec.at(i).y; v1.z += fit_pt_vec.at(i+j).z - fit_pt_vec.at(i).z; } if (i>=j){ v1.x += fit_pt_vec.at(i).x - fit_pt_vec.at(i-j).x; v1.y += fit_pt_vec.at(i).y - fit_pt_vec.at(i-j).y; v1.z += fit_pt_vec.at(i).z - fit_pt_vec.at(i-j).z; } } dir_1.SetXYZ(v1.x, v1.y, v1.z); dir_1 = dir_1.Unit(); vec_dir.at(i) = dir_1; if (dir_1.Angle(drift_dir)/3.1415926*180. < 7.5){ dir_1.SetXYZ(1,0,0); dir_2.SetXYZ(0,1,0); dir_3.SetXYZ(0,0,1); }else{ dir_2 = drift_dir.Cross(dir_1); dir_2 = dir_2.Unit(); dir_3 = dir_1.Cross(dir_2); } std::vector<std::tuple<double, double, double> > vec_projs; for (size_t j=0;j!=local_points_vec.at(i).size();j++){ double proj_1 = dir_1.X() * local_points_vec.at(i).at(j).x + dir_1.Y() * local_points_vec.at(i).at(j).y + dir_1.Z() * local_points_vec.at(i).at(j).z; double proj_2 = dir_2.X() * local_points_vec.at(i).at(j).x + dir_2.Y() * local_points_vec.at(i).at(j).y + dir_2.Z() * local_points_vec.at(i).at(j).z; double proj_3 = dir_3.X() * local_points_vec.at(i).at(j).x + dir_3.Y() * local_points_vec.at(i).at(j).y + dir_3.Z() * local_points_vec.at(i).at(j).z; vec_projs.push_back(std::make_tuple(proj_1, proj_2, proj_3)); } std::tuple<double, double, double> means = std::make_tuple(0,0,0); int ncount = local_points_vec.at(i).size(); if (ncount >1){ std::get<0>(means) = dir_1.X() * fit_pt_vec.at(i).x + dir_1.Y() * fit_pt_vec.at(i).y + dir_1.Z() * fit_pt_vec.at(i).z; std::get<1>(means) = dir_2.X() * fit_pt_vec.at(i).x + dir_2.Y() * fit_pt_vec.at(i).y + dir_2.Z() * fit_pt_vec.at(i).z; std::get<2>(means) = dir_3.X() * fit_pt_vec.at(i).x + dir_3.Y() * fit_pt_vec.at(i).y + dir_3.Z() * fit_pt_vec.at(i).z; for (size_t j=0;j!=local_points_vec.at(i).size();j++){ std::get<0>(vec_rms_vals.at(i)) += pow(std::get<0>(vec_projs.at(j)) - std::get<0>(means),2); std::get<1>(vec_rms_vals.at(i)) += pow(std::get<1>(vec_projs.at(j)) - std::get<1>(means),2); std::get<2>(vec_rms_vals.at(i)) += pow(std::get<2>(vec_projs.at(j)) - std::get<2>(means),2); } std::get<0>(vec_rms_vals.at(i)) = sqrt(std::get<0>(vec_rms_vals.at(i))*1./(ncount)); std::get<1>(vec_rms_vals.at(i)) = sqrt(std::get<1>(vec_rms_vals.at(i))*1./(ncount)); std::get<2>(vec_rms_vals.at(i)) = sqrt(std::get<2>(vec_rms_vals.at(i))*1./(ncount)); } vec_dQ_dx.at(i) = dQ_vec.at(i)/(dx_vec.at(i)+1e-9)/43e3*units::cm; } double max_spread = 0; double large_spread_length = 0; double total_effective_length = 0; double max_cont_length = 0; double max_cont_weighted_length = 0; double cont_length = 0; double cont_weighted_length = 0; bool flag_prev = false; double total_length; for (size_t i=0;i+1<local_points_vec.size();i++){ double length = sqrt(pow(fit_pt_vec.at(i+1).x - fit_pt_vec.at(i).x,2) + pow(fit_pt_vec.at(i+1).y - fit_pt_vec.at(i).y,2) + pow(fit_pt_vec.at(i+1).z - fit_pt_vec.at(i).z,2)); //std::cout << i << " " << std::get<2>(vec_rms_vals.at(i))/units::cm << std::endl; total_length += length; if (std::get<2>(vec_rms_vals.at(i))!=0){ total_effective_length += length; if (std::get<2>(vec_rms_vals.at(i)) > 0.4*units::cm) { large_spread_length += length; cont_length += length; cont_weighted_length += length * std::get<2>(vec_rms_vals.at(i)); flag_prev = true; }else{ if (flag_prev && cont_length > max_cont_length){ max_cont_length = cont_length; max_cont_weighted_length = cont_weighted_length; } cont_length = 0; cont_weighted_length = 0; flag_prev = false; } if (std::get<2>(vec_rms_vals.at(i)) > max_spread) max_spread = std::get<2>(vec_rms_vals.at(i)); } } if (max_spread > 0.7*units::cm && large_spread_length > 0.2 * total_effective_length && total_effective_length > 3*units::cm && total_effective_length < 15*units::cm && ( large_spread_length > 2.7*units::cm || large_spread_length > 0.35 * total_effective_length) || max_spread > 0.8*units::cm && large_spread_length > 0.3 * total_effective_length && total_effective_length >= 15*units::cm || max_spread > 1.0*units::cm && large_spread_length > 0.4 * total_effective_length) { TVector3 drift_dir(1,0,0); TVector3 main_dir1, main_dir2; bool flag_skip_angle1 = false; bool flag_skip_angle2 = false; if (fit_pt_vec.front().z < fit_pt_vec.back().z){ main_dir1 = cal_dir_3vector(fit_pt_vec.front(), 15*units::cm); main_dir2 = cal_dir_3vector(fit_pt_vec.back(), 6*units::cm); if (fabs(main_dir1.Angle(drift_dir)/3.1415926*180.-90)<10) flag_skip_angle1 = true; }else{ main_dir1 = cal_dir_3vector(fit_pt_vec.front(), 6*units::cm); main_dir2 = cal_dir_3vector(fit_pt_vec.back(), 15*units::cm); if (fabs(main_dir2.Angle(drift_dir)/3.1415926*180.-90)<10) flag_skip_angle2 = true; } // std::cout << main_dir.Angle(drift_dir)/3.1415926*180. << std::endl; std::vector<std::tuple<int, int, double> > threshold_segs; for(size_t i=0;i!=vec_dQ_dx.size(); i++){ // std::cout << i << " A: " << main_dir.Angle(vec_dir.at(i))/3.1415926*180. << " " <<vec_dir.at(i).Angle(drift_dir)/3.1415926*180. << " " << vec_dQ_dx.at(i) << " " << std::get<2>(vec_rms_vals.at(i))/units::cm << std::endl; double angle = main_dir1.Angle(vec_dir.at(i))/3.1415926*180.; if (threshold_segs.size()==0 && (angle < 30 || flag_skip_angle1 && angle < 60) && (std::get<2>(vec_rms_vals.at(i))/units::cm> 0.4 || vec_dQ_dx.at(i) > 1.6)){ threshold_segs.push_back(std::make_tuple(i,i,std::get<2>(vec_rms_vals.at(i)))); }else if ((angle < 30 || flag_skip_angle1 && angle < 60) && (std::get<2>(vec_rms_vals.at(i))/units::cm> 0.4 || vec_dQ_dx.at(i) > 1.6)){ if (i == std::get<1>(threshold_segs.back())+1 && std::get<2>(threshold_segs.back()) < std::get<2>(vec_rms_vals.at(i)) ){ std::get<1>(threshold_segs.back()) = i; std::get<2>(threshold_segs.back()) = std::get<2>(vec_rms_vals.at(i)); }else{ if (i!=std::get<1>(threshold_segs.back())+1) threshold_segs.push_back(std::make_tuple(i,i,std::get<2>(vec_rms_vals.at(i)))); } } // loop ... } double total_length1 = 0, max_length1 = 0; for (auto it = threshold_segs.begin(); it!= threshold_segs.end(); it++){ int start_n = std::get<0>(*it); if (start_n >0) start_n --; int end_n = std::get<1>(*it); double tmp_length = 0; for (int i=start_n; i!=end_n;i++){ tmp_length += sqrt(pow(fit_pt_vec.at(i+1).x - fit_pt_vec.at(i).x,2)+pow(fit_pt_vec.at(i+1).y - fit_pt_vec.at(i).y,2)+pow(fit_pt_vec.at(i+1).z - fit_pt_vec.at(i).z,2)); } total_length1 += tmp_length; if (tmp_length > max_length1) max_length1 = tmp_length; // std::cout << id << " A: " << start_n << " " << end_n << " " << tmp_length/units::cm << std::endl; } threshold_segs.clear(); for(int i=vec_dQ_dx.size()-1;i>=0; i--){ // std::cout << "B: " << 180-main_dir.Angle(vec_dir.at(i))/3.1415926*180. << std::endl; double angle = 180-main_dir2.Angle(vec_dir.at(i))/3.1415926*180.; if (threshold_segs.size()==0 && (angle < 30 || flag_skip_angle2 && angle < 60) && (std::get<2>(vec_rms_vals.at(i))/units::cm> 0.4 || vec_dQ_dx.at(i) > 1.6)){ threshold_segs.push_back(std::make_tuple(i,i,std::get<2>(vec_rms_vals.at(i)))); }else if ( (angle < 30 || flag_skip_angle2 && angle < 60) && (std::get<2>(vec_rms_vals.at(i))/units::cm> 0.4 || vec_dQ_dx.at(i) > 1.6)){ if (i == std::get<1>(threshold_segs.back())-1 && std::get<2>(threshold_segs.back()) < std::get<2>(vec_rms_vals.at(i)) ){ std::get<1>(threshold_segs.back()) = i; std::get<2>(threshold_segs.back()) = std::get<2>(vec_rms_vals.at(i)); }else{ if (i!=std::get<1>(threshold_segs.back())-1) threshold_segs.push_back(std::make_tuple(i,i,std::get<2>(vec_rms_vals.at(i)))); } } // loop ... } double total_length2 = 0, max_length2 = 0; for (auto it = threshold_segs.begin(); it!= threshold_segs.end(); it++){ int start_n = std::get<0>(*it); if (start_n <fit_pt_vec.size()-1) start_n ++; int end_n = std::get<1>(*it); double tmp_length = 0; for (int i=start_n; i!=end_n;i--){ tmp_length+= sqrt(pow(fit_pt_vec.at(i-1).x - fit_pt_vec.at(i).x,2)+pow(fit_pt_vec.at(i-1).y - fit_pt_vec.at(i).y,2)+pow(fit_pt_vec.at(i-1).z - fit_pt_vec.at(i).z,2)); } total_length2 += tmp_length; if (tmp_length > max_length2) max_length2 = tmp_length; // std::cout << id << " B: " << start_n << " " << end_n << " " << tmp_length/units::cm << std::endl; } if (total_length1 + max_length1 > 1.1*(total_length2 + max_length2)){ flag_dir = 1; }else if (1.1*(total_length1 + max_length1) < total_length2 + max_length2){ flag_dir = -1; } // std::cout << cluster_id << " " << id << " " << total_length1/units::cm << " " << total_length2/units::cm << " " << max_length1/units::cm << " " << max_length2/units::cm << " " << flag_dir << std::endl; }else{ if (total_length < 5*units::cm){ if (!is_shower_trajectory()) determine_dir_track(0, fit_pt_vec.size()); }else{ TVector3 main_dir = cal_dir_3vector(fit_pt_vec.front(),6*units::cm); Int_t ncount_front = 0, ncount_back = 0; for(size_t i=0;i!=vec_dQ_dx.size(); i++){ if (main_dir.Angle(vec_dir.at(i))/3.1415926*180. < 30) ncount_front ++; // std::cout << i << " A: " << main_dir.Angle(vec_dir.at(i))/3.1415926*180. << std::endl; } main_dir = cal_dir_3vector(fit_pt_vec.back(),6*units::cm); for(int i=vec_dQ_dx.size()-1;i>=0; i--){ if (180-main_dir.Angle(vec_dir.at(i))/3.1415926*180. < 30) ncount_back++; // std::cout << "B: " << 180-main_dir.Angle(vec_dir.at(i))/3.1415926*180. << std::endl; } if (1.2 * ncount_front < ncount_back){ flag_dir = -1; }else if (ncount_front > 1.2 * ncount_back){ flag_dir = 1; } // std::cout << id << " " << ncount_front << " " << ncount_back << std::endl; } } if (flag_dir !=0) return true; else return false; } bool WCPPID::ProtoSegment::is_shower_topology(bool tmp_val){ flag_shower_topology = tmp_val; flag_dir = 0; // look at the points ... std::vector<PointVector > local_points_vec(fit_pt_vec.size()); std::vector<std::tuple<double, double, double> > vec_rms_vals(fit_pt_vec.size(), std::make_tuple(0,0,0)); std::vector<double> vec_dQ_dx(fit_pt_vec.size(), 0); // std::cout << fit_pt_vec.size() << " " << pcloud_associated << " " << std::endl; if (pcloud_associated == 0 ) return false; WCP::WCPointCloud<double>& cloud = pcloud_associated->get_cloud(); for (size_t i = 0; i!= cloud.pts.size(); i++){ Point test_p(cloud.pts.at(i).x, cloud.pts.at(i).y, cloud.pts.at(i).z); std::vector<std::pair<size_t,double>> results = pcloud_fit->get_closest_index(test_p,1); local_points_vec.at(results.front().first).push_back(test_p); } TVector3 drift_dir(1,0,0); // drift direction for (size_t i=0;i!=local_points_vec.size();i++){ TVector3 dir_1, dir_2, dir_3; Point v1(0,0,0); for (size_t j=1;j!=3;j++){ if (i+j<local_points_vec.size()){ v1.x += fit_pt_vec.at(i+j).x - fit_pt_vec.at(i).x; v1.y += fit_pt_vec.at(i+j).y - fit_pt_vec.at(i).y; v1.z += fit_pt_vec.at(i+j).z - fit_pt_vec.at(i).z; } if (i>=j){ v1.x += fit_pt_vec.at(i).x - fit_pt_vec.at(i-j).x; v1.y += fit_pt_vec.at(i).y - fit_pt_vec.at(i-j).y; v1.z += fit_pt_vec.at(i).z - fit_pt_vec.at(i-j).z; } } dir_1.SetXYZ(v1.x, v1.y, v1.z); dir_1 = dir_1.Unit(); if (dir_1.Angle(drift_dir)/3.1415926*180. < 7.5){ dir_1.SetXYZ(1,0,0); dir_2.SetXYZ(0,1,0); dir_3.SetXYZ(0,0,1); }else{ dir_2 = drift_dir.Cross(dir_1); dir_2 = dir_2.Unit(); dir_3 = dir_1.Cross(dir_2); } std::vector<std::tuple<double, double, double> > vec_projs; for (size_t j=0;j!=local_points_vec.at(i).size();j++){ double proj_1 = dir_1.X() * local_points_vec.at(i).at(j).x + dir_1.Y() * local_points_vec.at(i).at(j).y + dir_1.Z() * local_points_vec.at(i).at(j).z; double proj_2 = dir_2.X() * local_points_vec.at(i).at(j).x + dir_2.Y() * local_points_vec.at(i).at(j).y + dir_2.Z() * local_points_vec.at(i).at(j).z; double proj_3 = dir_3.X() * local_points_vec.at(i).at(j).x + dir_3.Y() * local_points_vec.at(i).at(j).y + dir_3.Z() * local_points_vec.at(i).at(j).z; vec_projs.push_back(std::make_tuple(proj_1, proj_2, proj_3)); } std::tuple<double, double, double> means = std::make_tuple(0,0,0); int ncount = local_points_vec.at(i).size(); //for (size_t j=0;j!=local_points_vec.at(i).size();j++){ // std::get<0>(means) += std::get<0>(vec_projs.at(j)); // std::get<1>(means) += std::get<1>(vec_projs.at(j)); // std::get<2>(means) += std::get<2>(vec_projs.at(j)); // ncount ++; //} if (ncount >1){ //std::get<0>(means) /= 1.*ncount; //std::get<1>(means) /= 1.*ncount; //std::get<2>(means) /= 1.*ncount; std::get<0>(means) = dir_1.X() * fit_pt_vec.at(i).x + dir_1.Y() * fit_pt_vec.at(i).y + dir_1.Z() * fit_pt_vec.at(i).z; std::get<1>(means) = dir_2.X() * fit_pt_vec.at(i).x + dir_2.Y() * fit_pt_vec.at(i).y + dir_2.Z() * fit_pt_vec.at(i).z; std::get<2>(means) = dir_3.X() * fit_pt_vec.at(i).x + dir_3.Y() * fit_pt_vec.at(i).y + dir_3.Z() * fit_pt_vec.at(i).z; for (size_t j=0;j!=local_points_vec.at(i).size();j++){ std::get<0>(vec_rms_vals.at(i)) += pow(std::get<0>(vec_projs.at(j)) - std::get<0>(means),2); std::get<1>(vec_rms_vals.at(i)) += pow(std::get<1>(vec_projs.at(j)) - std::get<1>(means),2); std::get<2>(vec_rms_vals.at(i)) += pow(std::get<2>(vec_projs.at(j)) - std::get<2>(means),2); } std::get<0>(vec_rms_vals.at(i)) = sqrt(std::get<0>(vec_rms_vals.at(i))*1./(ncount)); std::get<1>(vec_rms_vals.at(i)) = sqrt(std::get<1>(vec_rms_vals.at(i))*1./(ncount)); std::get<2>(vec_rms_vals.at(i)) = sqrt(std::get<2>(vec_rms_vals.at(i))*1./(ncount)); } vec_dQ_dx.at(i) = dQ_vec.at(i)/(dx_vec.at(i)+1e-9)/43e3*units::cm; //std::cout << dir_1.Angle(drift_dir)/3.1415926*180. << " " << dir_1.Mag() << " " << v1 << std::endl; // std::cout << i << " " << dQ_vec.at(i)/(dx_vec.at(i)+1e-9)/43e3*units::cm << " " << std::get<0>(vec_rms_vals.at(i))/units::cm << " " << std::get<1>(vec_rms_vals.at(i))/units::cm << " " << std::get<2>(vec_rms_vals.at(i))/units::cm << std::endl; } double max_spread = 0; double large_spread_length = 0; double total_effective_length = 0; double max_cont_length = 0; double max_cont_weighted_length = 0; double cont_length = 0; double cont_weighted_length = 0; bool flag_prev = false; for (size_t i=0;i+1<local_points_vec.size();i++){ double length = sqrt(pow(fit_pt_vec.at(i+1).x - fit_pt_vec.at(i).x,2) + pow(fit_pt_vec.at(i+1).y - fit_pt_vec.at(i).y,2) + pow(fit_pt_vec.at(i+1).z - fit_pt_vec.at(i).z,2)); if (std::get<2>(vec_rms_vals.at(i))!=0){ total_effective_length += length; if (std::get<2>(vec_rms_vals.at(i)) > 0.4*units::cm) { large_spread_length += length; cont_length += length; cont_weighted_length += length * std::get<2>(vec_rms_vals.at(i)); flag_prev = true; }else{ if (flag_prev && cont_length > max_cont_length){ max_cont_length = cont_length; max_cont_weighted_length = cont_weighted_length; } cont_length = 0; cont_weighted_length = 0; flag_prev = false; } if (std::get<2>(vec_rms_vals.at(i)) > max_spread) max_spread = std::get<2>(vec_rms_vals.at(i)); } } if (max_spread > 0.7*units::cm && large_spread_length > 0.2 * total_effective_length && total_effective_length > 3*units::cm && total_effective_length < 15*units::cm && ( large_spread_length > 2.7*units::cm || large_spread_length > 0.35 * total_effective_length) || max_spread > 0.8*units::cm && large_spread_length > 0.3 * total_effective_length && total_effective_length >= 15*units::cm || max_spread > 0.8*units::cm && large_spread_length > 8*units::cm && large_spread_length > 0.18 * total_effective_length || max_spread > 1.0*units::cm && large_spread_length > 0.4 * total_effective_length || max_spread > 1.0*units::cm && large_spread_length > 5*units::cm && large_spread_length > 0.23 * total_effective_length ){ flag_shower_topology = true; } // std::cout << cluster_id << " " << id << " " << max_spread/units::cm << " " << large_spread_length/units::cm << " " << total_effective_length/units::cm << std::endl; if (flag_shower_topology){ std::vector<std::tuple<int, int, double> > threshold_segs; for(size_t i=0;i!=vec_dQ_dx.size(); i++){ if (threshold_segs.size()==0 && std::get<2>(vec_rms_vals.at(i))/units::cm> 0.4){ threshold_segs.push_back(std::make_tuple(i,i,std::get<2>(vec_rms_vals.at(i)))); }else if (std::get<2>(vec_rms_vals.at(i))/units::cm> 0.4){ if (i == std::get<1>(threshold_segs.back())+1 && std::get<2>(threshold_segs.back()) < std::get<2>(vec_rms_vals.at(i)) ){ std::get<1>(threshold_segs.back()) = i; std::get<2>(threshold_segs.back()) = std::get<2>(vec_rms_vals.at(i)); }else{ if (i!=std::get<1>(threshold_segs.back())+1) threshold_segs.push_back(std::make_tuple(i,i,std::get<2>(vec_rms_vals.at(i)))); } } // loop ... } double total_length1 = 0, max_length1 = 0; for (auto it = threshold_segs.begin(); it!= threshold_segs.end(); it++){ int start_n = std::get<0>(*it); if (start_n >0) start_n --; int end_n = std::get<1>(*it); double tmp_length = 0; for (int i=start_n; i!=end_n;i++){ tmp_length += sqrt(pow(fit_pt_vec.at(i+1).x - fit_pt_vec.at(i).x,2)+pow(fit_pt_vec.at(i+1).y - fit_pt_vec.at(i).y,2)+pow(fit_pt_vec.at(i+1).z - fit_pt_vec.at(i).z,2)); } total_length1 += tmp_length; if (tmp_length > max_length1) max_length1 = tmp_length; // std::cout << id << " A: " << start_n << " " << end_n << " " << tmp_length/units::cm << std::endl; } threshold_segs.clear(); for(int i=vec_dQ_dx.size()-1;i>=0; i--){ if (threshold_segs.size()==0 && std::get<2>(vec_rms_vals.at(i))/units::cm> 0.4){ threshold_segs.push_back(std::make_tuple(i,i,std::get<2>(vec_rms_vals.at(i)))); }else if (std::get<2>(vec_rms_vals.at(i))/units::cm> 0.4){ if (i == std::get<1>(threshold_segs.back())-1 && std::get<2>(threshold_segs.back()) < std::get<2>(vec_rms_vals.at(i)) ){ std::get<1>(threshold_segs.back()) = i; std::get<2>(threshold_segs.back()) = std::get<2>(vec_rms_vals.at(i)); }else{ if (i!=std::get<1>(threshold_segs.back())-1) threshold_segs.push_back(std::make_tuple(i,i,std::get<2>(vec_rms_vals.at(i)))); } } // loop ... } double total_length2 = 0, max_length2 = 0; for (auto it = threshold_segs.begin(); it!= threshold_segs.end(); it++){ int start_n = std::get<0>(*it); if (start_n <fit_pt_vec.size()-1) start_n ++; int end_n = std::get<1>(*it); double tmp_length = 0; for (int i=start_n; i!=end_n;i--){ tmp_length+= sqrt(pow(fit_pt_vec.at(i-1).x - fit_pt_vec.at(i).x,2)+pow(fit_pt_vec.at(i-1).y - fit_pt_vec.at(i).y,2)+pow(fit_pt_vec.at(i-1).z - fit_pt_vec.at(i).z,2)); } total_length2 += tmp_length; if (tmp_length > max_length2) max_length2 = tmp_length; // std::cout << id << " B: " << start_n << " " << end_n << " " << tmp_length/units::cm << std::endl; } if (total_length1 + max_length1 > 1.1*(total_length2 + max_length2)){ flag_dir = 1; }else if (1.1*(total_length1 + max_length1) < total_length2 + max_length2){ flag_dir = -1; } double tmp_total_length = get_length(); if (tmp_total_length > 50*units::cm && total_length1 < 0.25* tmp_total_length && total_length2 < 0.25* tmp_total_length ){ flag_dir = 0; flag_shower_topology = false; } // std::cout << cluster_id << " " << id << " " << total_length1/units::cm << " " << total_length2/units::cm << " " << max_length1/units::cm << " " << max_length2/units::cm << " " << flag_dir << " " << get_length()/units::cm << std::endl; } // std::cout << cluster_id << " " << id << " " << max_spread/units::cm << " " << large_spread_length/total_effective_length << " " << max_cont_length/units::cm << " " << total_effective_length/units::cm << " " << flag_shower_trajectory << " " << flag_shower_topology << std::endl; return flag_shower_topology; } bool WCPPID::ProtoSegment::is_shower_trajectory(double step_size){ flag_shower_trajectory = false; double length = get_length(); // too long if (length > 50*units::cm) return flag_shower_trajectory; int ncount = std::round(length/step_size); if (ncount ==0 ) ncount = 1; std::vector<std::pair<int,int> > sections(ncount); for (size_t i=0;i!=ncount;i++){ sections.at(i)=std::make_pair(std::round(fit_pt_vec.size()/ncount*i),std::round(fit_pt_vec.size()/ncount*(i+1))); } sections.back().second = fit_pt_vec.size()-1; int n_shower_like = 0; TVector3 drift_dir(1,0,0); // for (size_t j=0;j!=ncount;j++){ TVector3 dir_1(fit_pt_vec.at(sections.at(j).first).x - fit_pt_vec.at(sections.at(j).second).x, fit_pt_vec.at(sections.at(j).first).y - fit_pt_vec.at(sections.at(j).second).y, fit_pt_vec.at(sections.at(j).first).z - fit_pt_vec.at(sections.at(j).second).z); dir_1 = dir_1.Unit(); double tmp_dQ_dx = get_medium_dQ_dx(sections.at(j).first, sections.at(j).second)/(50000/units::cm); // std::cout << fabs(drift_dir.Angle(dir_1)/3.1415926*180.-90.) << std::endl; double angle_diff = fabs(drift_dir.Angle(dir_1)/3.1415926*180.-90.); if (angle_diff>10 ){ // not parallel case ... double direct_length = get_direct_length(sections.at(j).first, sections.at(j).second); double integrated_length = get_length(sections.at(j).first, sections.at(j).second); double max_dev = get_max_deviation(sections.at(j).first, sections.at(j).second); // std::cout << max_dev/units::cm << " " << fabs(drift_dir.Angle(dir_1)/3.1415926*180.-90.) << std::endl; double length_ratio; if (direct_length == 0 ) length_ratio = 1; else length_ratio = direct_length / integrated_length; if (tmp_dQ_dx*0.11 + 2*length_ratio < 2.03 && tmp_dQ_dx < 2 && length_ratio < 0.95 && (angle_diff < 60 || integrated_length < 10*units::cm || integrated_length >= 10*units::cm && max_dev > 0.75*units::cm) ) n_shower_like ++; // std::cout << "Xin: " << id << " " << j << " " << sections.at(j).first << " " << sections.at(j).second << " " << length_ratio << " " << tmp_dQ_dx << " " << direct_length << " " << drift_dir.Angle(dir_1)/3.1415926*180. << std::endl; }else{ TVector3 dir_2 = drift_dir.Cross(dir_1); dir_2 = dir_2.Unit(); TVector3 dir_3 = dir_1.Cross(dir_2); double direct_length = get_direct_length(sections.at(j).first, sections.at(j).second, dir_2); double integrated_length = get_length(sections.at(j).first, sections.at(j).second, dir_2); double max_dev = get_max_deviation(sections.at(j).first, sections.at(j).second); double length_ratio; if (direct_length == 0 ) length_ratio = 1; else length_ratio = direct_length / integrated_length; if (tmp_dQ_dx*0.11 + 2*length_ratio < 2.06 && tmp_dQ_dx < 2 && length_ratio < 0.97 && (integrated_length < 10*units::cm || integrated_length >= 10*units::cm && max_dev > 0.75*units::cm) ) n_shower_like ++; // std::cout << "Xin: " << j << " " << sections.at(j).first << " " << sections.at(j).second << " " << length_ratio << " " << tmp_dQ_dx << " " << direct_length << " " << drift_dir.Angle(dir_1)/3.1415926*180. << " " << tmp_dQ_dx*0.11 + 2*length_ratio - 2 << std::endl; } } //std::cout << "BB " << id << " " << sections.size() << " " << get_length()/units::cm << " " << n_shower_like << std::endl; //std::cout << id << " " << get_medium_dQ_dx()/(43e3/units::cm) << std::endl; // double medium_dQ_dx = get_medium_dQ_dx()/(43e3/units::cm); // not a good idea to require dQ/dx ... if (n_shower_like >=0.5*sections.size() //&& medium_dQ_dx < 1.1 ) flag_shower_trajectory = true; // calculate direct length, accumulated length, medium dQ/dx in each section ... // std::cout << length/units::cm << " " << ncount << std::endl; return flag_shower_trajectory; } double WCPPID::ProtoSegment::get_max_deviation(int n1, int n2){ if (n1 < 0) n1 = 0; if (n1+1 > fit_pt_vec.size()) n1 = int(fit_pt_vec.size())-1; if (n2 < 0) n2 = 0; if (n2+1 > fit_pt_vec.size()) n2 = int(fit_pt_vec.size())-1; double max_dev = 0; if (n1 != n2){ WCP::Line l(fit_pt_vec.at(n1), fit_pt_vec.at(n2)); for (size_t i=n1; i<=n2;i++){ double dis = l.closest_dis(fit_pt_vec.at(i)); if (dis > max_dev) max_dev = dis; } } return max_dev; } double WCPPID::ProtoSegment::get_direct_length(int n1, int n2){ if (n1 < 0) n1 = 0; if (n1+1 > fit_pt_vec.size()) n1 = int(fit_pt_vec.size())-1; if (n2 < 0) n2 = 0; if (n2+1 > fit_pt_vec.size()) n2 = int(fit_pt_vec.size())-1; double length = sqrt(pow(fit_pt_vec.at(n1).x - fit_pt_vec.at(n2).x,2)+pow(fit_pt_vec.at(n1).y - fit_pt_vec.at(n2).y,2)+pow(fit_pt_vec.at(n1).z - fit_pt_vec.at(n2).z,2)); return length; } double WCPPID::ProtoSegment::get_length(int n1, int n2){ if (n1 < 0) n1 = 0; if (n1+1 > fit_pt_vec.size()) n1 = int(fit_pt_vec.size())-1; if (n2 < 0) n2 = 0; if (n2+1 > fit_pt_vec.size()) n2 = int(fit_pt_vec.size())-1; double length = 0; for (int i=n1;i+1<=n2;i++){ length += sqrt(pow(fit_pt_vec.at(i+1).x - fit_pt_vec.at(i).x,2)+pow(fit_pt_vec.at(i+1).y - fit_pt_vec.at(i).y,2)+pow(fit_pt_vec.at(i+1).z - fit_pt_vec.at(i).z,2)); } return length; } double WCPPID::ProtoSegment::get_direct_length(int n1, int n2, TVector3 dir_perp){ if (n1 < 0) n1 = 0; if (n1+1 > fit_pt_vec.size()) n1 = int(fit_pt_vec.size())-1; if (n2 < 0) n2 = 0; if (n2+1 > fit_pt_vec.size()) n2 = int(fit_pt_vec.size())-1; TVector3 temp_dir(fit_pt_vec.at(n1).x - fit_pt_vec.at(n2).x, fit_pt_vec.at(n1).y - fit_pt_vec.at(n2).y, fit_pt_vec.at(n1).z - fit_pt_vec.at(n2).z); double length = sqrt(pow(temp_dir.Mag(),2) - pow(temp_dir.Dot(dir_perp.Unit()),2)); return length; } double WCPPID::ProtoSegment::get_length(int n1, int n2, TVector3 dir_perp){ if (n1 < 0) n1 = 0; if (n1+1 > fit_pt_vec.size()) n1 = int(fit_pt_vec.size())-1; if (n2 < 0) n2 = 0; if (n2+1 > fit_pt_vec.size()) n2 = int(fit_pt_vec.size())-1; double length = 0; for (int i=n1;i+1<=n2;i++){ TVector3 temp_dir(fit_pt_vec.at(i+1).x - fit_pt_vec.at(i).x, fit_pt_vec.at(i+1).y - fit_pt_vec.at(i).y, fit_pt_vec.at(i+1).z - fit_pt_vec.at(i).z); length += sqrt(pow(temp_dir.Mag(),2)-pow(temp_dir.Dot(dir_perp.Unit()),2)); } return length; } double WCPPID::ProtoSegment::get_rms_dQ_dx(){ std::vector<double> vec_dQ_dx; double sum[3]={0,0,0}; if (dQ_vec.size()<=1) return 0; for (int i = 0 ; i< dQ_vec.size(); i++){ vec_dQ_dx.push_back(dQ_vec.at(i)/(dx_vec.at(i)+1e-9)); sum[0] += pow(vec_dQ_dx.back(),2); sum[1] += vec_dQ_dx.back(); sum[2] += 1; } return sqrt((sum[0] - pow(sum[1],2)/sum[2])/(sum[2]-1.)); } double WCPPID::ProtoSegment::get_medium_dQ_dx(){ return get_medium_dQ_dx(0, fit_pt_vec.size()); } double WCPPID::ProtoSegment::get_medium_dQ_dx(int n1, int n2){ if (n1 < 0) n1 = 0; if (n1+1 > fit_pt_vec.size()) n1 = int(fit_pt_vec.size())-1; if (n2 < 0) n2 = 0; if (n2+1 > fit_pt_vec.size()) n2 = int(fit_pt_vec.size())-1; std::vector<double> vec_dQ_dx; for (int i = n1 ; i<=n2; i++){ vec_dQ_dx.push_back(dQ_vec.at(i)/(dx_vec.at(i)+1e-9)); } std::nth_element(vec_dQ_dx.begin(), vec_dQ_dx.begin() + vec_dQ_dx.size()/2, vec_dQ_dx.end()); return *std::next(vec_dQ_dx.begin(), vec_dQ_dx.size()/2); } double WCPPID::ProtoSegment::get_direct_length(){ double length =sqrt(pow(fit_pt_vec.front().x - fit_pt_vec.back().x ,2) + pow(fit_pt_vec.front().y - fit_pt_vec.back().y,2) + pow(fit_pt_vec.front().z - fit_pt_vec.back().z,2)); return length; } double WCPPID::ProtoSegment::get_length(){ double length = 0; for (size_t i=0;i+1<fit_pt_vec.size();i++){ length += sqrt(pow(fit_pt_vec.at(i+1).x - fit_pt_vec.at(i).x ,2) + pow(fit_pt_vec.at(i+1).y - fit_pt_vec.at(i).y,2) + pow(fit_pt_vec.at(i+1).z - fit_pt_vec.at(i).z,2)); } return length; } std::tuple<WCP::Point, TVector3, TVector3, bool> WCPPID::ProtoSegment::search_kink(Point& start_p){ // find the first point ... // Point start_p = fit_pt_vec.front(); std::pair<double, WCP::Point> tmp_results = get_closest_point(start_p); Point test_p = tmp_results.second; TVector3 drift_dir(1,0,0); std::vector<double> refl_angles(fit_pt_vec.size(),0); std::vector<double> para_angles(fit_pt_vec.size(),0); // start the angle search for (int i=0;i!=fit_pt_vec.size(); i++){ double angle1 = 0; double angle2 = 0; for (int j=0;j!=6;j++){ TVector3 v10(0,0,0); TVector3 v20(0,0,0); // std::cout << i << " " << j << std::endl; if (i >= (j+1)*2){ v10.SetXYZ(fit_pt_vec.at(i).x - fit_pt_vec.at(i-(j+1)*2).x, fit_pt_vec.at(i).y - fit_pt_vec.at(i-(j+1)*2).y, fit_pt_vec.at(i).z - fit_pt_vec.at(i-(j+1)*2).z); }else{ v10.SetXYZ(fit_pt_vec.at(i).x - fit_pt_vec.front().x, fit_pt_vec.at(i).y - fit_pt_vec.front().y, fit_pt_vec.at(i).z - fit_pt_vec.front().z); } if (i+(j+1)*2<fit_pt_vec.size()){ v20.SetXYZ(fit_pt_vec.at(i+(j+1)*2).x - fit_pt_vec.at(i).x, fit_pt_vec.at(i+(j+1)*2).y - fit_pt_vec.at(i).y, fit_pt_vec.at(i+(j+1)*2).z - fit_pt_vec.at(i).z); }else{ v20.SetXYZ(fit_pt_vec.back().x - fit_pt_vec.at(i).x, fit_pt_vec.back().y - fit_pt_vec.at(i).y, fit_pt_vec.back().z - fit_pt_vec.at(i).z); } if (j==0){ angle1 = v10.Angle(v20)/3.1415926*180.; angle2 = std::max(fabs(v10.Angle(drift_dir)/3.1415926*180.-90.), fabs(v20.Angle(drift_dir)/3.1415926*180.-90.)); }else{ if (v10.Mag()!=0 && v20.Mag()!=0){ // std::cout << i << " " << j << " " << angle1 << " " << angle2 << std::endl; angle1 = std::min(v10.Angle(v20)/3.1415926*180., angle1); angle2 = std::min(std::max(fabs(v10.Angle(drift_dir)/3.1415926*180.-90.), fabs(v20.Angle(drift_dir)/3.1415926*180.-90.)),angle2); } } } refl_angles.at(i) = angle1; para_angles.at(i) = angle2; } bool flag_check = false; int save_i = -1; bool flag_switch = false; bool flag_search = false; for (int i=0;i!=fit_pt_vec.size();i++){ if (sqrt(pow(test_p.x - fit_pt_vec.at(i).x,2) + pow(test_p.y - fit_pt_vec.at(i).y,2) + pow(test_p.z - fit_pt_vec.at(i).z,2) ) < 0.1*units::cm) flag_check = true; // not too close and not too far to the begin and end ... if (sqrt(pow(fit_pt_vec.at(i).x - fit_pt_vec.front().x,2) + pow(fit_pt_vec.at(i).y - fit_pt_vec.front().y,2) + pow(fit_pt_vec.at(i).z - fit_pt_vec.front().z,2) ) < 1*units::cm || sqrt(pow(fit_pt_vec.at(i).x - fit_pt_vec.back().x,2) + pow(fit_pt_vec.at(i).y - fit_pt_vec.back().y,2) + pow(fit_pt_vec.at(i).z - fit_pt_vec.back().z,2) ) < 1*units::cm || sqrt(pow(fit_pt_vec.at(i).x - start_p.x,2) + pow(fit_pt_vec.at(i).y - start_p.y,2) + pow(fit_pt_vec.at(i).z - start_p.z,2) ) < 1*units::cm ) continue; // std::cout << sqrt(pow(fit_pt_vec.at(i).x - fit_pt_vec.front().x,2) + // pow(fit_pt_vec.at(i).y - fit_pt_vec.front().y,2) + // pow(fit_pt_vec.at(i).z - fit_pt_vec.front().z,2) )/units::cm << std::endl; if (flag_check){ double ave_dQ_dx = 0; int ave_count = 0; double max_dQ_dx = dQ_vec.at(i)/dx_vec.at(i); for (size_t j = -2;j!=3;j++){ if (i+j<fit_pt_vec.size() && i+j>=0){ ave_dQ_dx += dQ_vec.at(i+j)/dx_vec.at(i+j); ave_count ++; if (dQ_vec.at(i+j)/dx_vec.at(i+j) > max_dQ_dx) max_dQ_dx = dQ_vec.at(i+j)/dx_vec.at(i+j); } } if (ave_count!=0) ave_dQ_dx /= ave_count; double sum_angles = 0; double nsum = 0; double sum_angles1 = 0; double nsum1 = 0; for (int j = -2; j!=3;j++){ if (i+j>=0 && i+j<fit_pt_vec.size()){ if (para_angles.at(i+j)>10){ sum_angles += pow(refl_angles.at(i+j),2); nsum ++; } if (para_angles.at(i+j)>7.5){ sum_angles1 += pow(refl_angles.at(i+j),2); nsum1 ++; } } } if (nsum!=0) sum_angles=sqrt(sum_angles/nsum); if (nsum1!=0) sum_angles1 = sqrt(sum_angles1/nsum1); //if (wcpt_vec.front().index >940 && wcpt_vec.front().index < 1200) // if (fabs(fit_pt_vec.at(i).x-2121.19)<30 && fabs(fit_pt_vec.at(i).y-218.775) < 30 && fabs(fit_pt_vec.at(i).z-715.347)<30) // std::cout << i << " " << max_dQ_dx << " " << para_angles.at(i) << " " << refl_angles.at(i) << " " << sum_angles << " " << sum_angles1<< " " << sqrt(pow(fit_pt_vec.at(i).x - fit_pt_vec.front().x,2) + pow(fit_pt_vec.at(i).y - fit_pt_vec.front().y,2) + pow(fit_pt_vec.at(i).z - fit_pt_vec.front().z,2) ) /units::cm << " " << sqrt(pow(fit_pt_vec.at(i).x - fit_pt_vec.back().x,2) + pow(fit_pt_vec.at(i).y - fit_pt_vec.back().y,2) + pow(fit_pt_vec.at(i).z - fit_pt_vec.back().z,2) )/units::cm << " " << fit_pt_vec.at(i) << std::endl; if (para_angles.at(i) > 10 && refl_angles.at(i) > 30 && sum_angles > 15 ){ save_i = i; break; }else if (para_angles.at(i) > 7.5 && refl_angles.at(i) > 45 && sum_angles1 > 25){ save_i = i; break; }else if (para_angles.at(i) > 15 && refl_angles.at(i) > 27 && sum_angles > 12.5){ //std::cout << i << " " << ave_dQ_dx << " " <<max_dQ_dx << " " << para_angles.at(i) << " " << refl_angles.at(i) << " " << sum_angles << " " << sqrt(pow(fit_pt_vec.at(i).x - fit_pt_vec.front().x,2) + pow(fit_pt_vec.at(i).y - fit_pt_vec.front().y,2) + pow(fit_pt_vec.at(i).z - fit_pt_vec.front().z,2) ) /units::cm << " " << sqrt(pow(fit_pt_vec.at(i).x - fit_pt_vec.back().x,2) + pow(fit_pt_vec.at(i).y - fit_pt_vec.back().y,2) + pow(fit_pt_vec.at(i).z - fit_pt_vec.back().z,2) )/units::cm << " " << fit_pt_vec.at(i) << std::endl; save_i = i; break; }else if(para_angles.at(i) > 15 && refl_angles.at(i) > 22 && sum_angles > 19 && max_dQ_dx > 43e3/units::cm*1.5 && ave_dQ_dx > 43e3/units::cm){ // std::cout << i << " " << ave_dQ_dx << " " << max_dQ_dx << " " << para_angles.at(i) << " " << refl_angles.at(i) << " " << sum_angles << " " << sqrt(pow(fit_pt_vec.at(i).x - fit_pt_vec.front().x,2) + pow(fit_pt_vec.at(i).y - fit_pt_vec.front().y,2) + pow(fit_pt_vec.at(i).z - fit_pt_vec.front().z,2) ) /units::cm << " " << sqrt(pow(fit_pt_vec.at(i).x - fit_pt_vec.back().x,2) + pow(fit_pt_vec.at(i).y - fit_pt_vec.back().y,2) + pow(fit_pt_vec.at(i).z - fit_pt_vec.back().z,2) )/units::cm << " " << fit_pt_vec.at(i) << std::endl; save_i = i; flag_search = true; break; } } } // return the results ... if (save_i>0 && save_i+1 < fit_pt_vec.size() ){ Point p = fit_pt_vec.at(save_i); Point prev_p(0,0,0); Point next_p(0,0,0); int num_p = 0; int num_p1 = 0; double length1 = 0; double length2 = 0; Point last_p1, last_p2; for (size_t i=1;i!=10;i++){ if (save_i>=i){ length1 += sqrt(pow(fit_pt_vec.at(save_i-i).x -fit_pt_vec.at(save_i-i+1).x,2) + pow(fit_pt_vec.at(save_i-i).y -fit_pt_vec.at(save_i-i+1).y,2) + pow(fit_pt_vec.at(save_i-i).z -fit_pt_vec.at(save_i-i+1).z,2)); prev_p.x += fit_pt_vec.at(save_i-i).x; prev_p.y += fit_pt_vec.at(save_i-i).y; prev_p.z += fit_pt_vec.at(save_i-i).z; last_p1 = fit_pt_vec.at(save_i-i); num_p ++; } if (save_i+i<fit_pt_vec.size()){ length2 += sqrt(pow(fit_pt_vec.at(save_i+i).x - fit_pt_vec.at(save_i+i-1).x,2)+pow(fit_pt_vec.at(save_i+i).y - fit_pt_vec.at(save_i+i-1).y,2)+pow(fit_pt_vec.at(save_i+i).z - fit_pt_vec.at(save_i+i-1).z,2)); next_p.x += fit_pt_vec.at(save_i+i).x; next_p.y += fit_pt_vec.at(save_i+i).y; next_p.z += fit_pt_vec.at(save_i+i).z; last_p2 = fit_pt_vec.at(save_i+i); num_p1 ++; } } double length1_1 = sqrt(pow(last_p1.x - fit_pt_vec.at(save_i).x,2) + pow(last_p1.y - fit_pt_vec.at(save_i).y,2) + pow(last_p1.z - fit_pt_vec.at(save_i).z,2)); double length2_1 = sqrt(pow(last_p2.x - fit_pt_vec.at(save_i).x,2) + pow(last_p2.y - fit_pt_vec.at(save_i).y,2) + pow(last_p2.z - fit_pt_vec.at(save_i).z,2)); if (fabs(length2 - length2_1)< 0.03 * length2_1 && length1 * length2_1 > 1.06 * length2 * length1_1){ flag_switch = true; flag_search = true; }else if (fabs(length1 - length1_1)< 0.03 * length1_1 && length2 * length1_1 > 1.06 * length1 * length2_1){ flag_search = true; } // std::cout << length1/length1_1 << " " << length2/length2_1 << " " << flag_switch << std::endl; prev_p.x /= num_p; prev_p.y /= num_p; prev_p.z /= num_p; next_p.x /= num_p1; next_p.y /= num_p1; next_p.z /= num_p1; TVector3 dir(p.x - prev_p.x, p.y - prev_p.y, p.z - prev_p.z); dir = dir.Unit(); TVector3 dir1(p.x - next_p.x, p.y - next_p.y, p.z - next_p.z); dir1 = dir1.Unit(); double sum_dQ = 0, sum_dx = 0; for (int i=-2;i!=3;i++){ if (save_i+i>=0&&save_i+i<fit_pt_vec.size()){ sum_dQ += dQ_vec.at(save_i+i); sum_dx += dx_vec.at(save_i+i); } } // std::cout << sqrt(pow(p.x-start_p.x,2) + pow(p.y-start_p.y,2) + pow(p.z-start_p.z,2))/units::cm << std::endl; // std::cout << sum_dQ/(sum_dx) << " " << flag_search << std::endl; if (flag_search){ if (flag_switch){ std::cout << "Cluster: " << cluster_id << " Continue Search True Kink in Backward" << std::endl; return std::make_tuple(p, dir1, dir, true); }else{ std::cout << "Cluster: " << cluster_id<< " Continue Search True Kink in Forward" << std::endl; return std::make_tuple(p, dir, dir1, true); } }else if (sum_dQ/(sum_dx+1e-9) > 2500 ){ if (flag_switch){ return std::make_tuple(p, dir1, dir, false); }else{ return std::make_tuple(p, dir, dir1, false); } }else{ if (flag_switch){ std::cout << "Cluster: " << cluster_id<< " Continue Search True Kink in Backward" << std::endl; return std::make_tuple(p, dir1, dir, true); }else{ std::cout << "Cluster: " << cluster_id << " Continue Search True Kink in Forward" << std::endl; return std::make_tuple(p, dir, dir1, true); } } }else{ Point p1 = fit_pt_vec.back(); TVector3 dir(0,0,0); return std::make_tuple(p1,dir, dir,false); } // std::cout << save_i << std::endl; } void WCPPID::ProtoSegment::set_point_vec(std::vector<WCP::Point >& tmp_pt_vec){ fit_pt_vec = tmp_pt_vec; if (pcloud_fit != (ToyPointCloud*)0) delete pcloud_fit; pcloud_fit = new ToyPointCloud(); pcloud_fit->AddPoints(fit_pt_vec); pcloud_fit->build_kdtree_index(); } void WCPPID::ProtoSegment::set_fit_vec(std::vector<WCP::Point >& tmp_fit_pt_vec, std::vector<double>& tmp_dQ_vec, std::vector<double>& tmp_dx_vec, std::vector<double>& tmp_pu_vec, std::vector<double>& tmp_pv_vec, std::vector<double>& tmp_pw_vec, std::vector<double>& tmp_pt_vec, std::vector<double>& tmp_reduced_chi2_vec){ flag_fit = true; fit_pt_vec = tmp_fit_pt_vec; dQ_vec = tmp_dQ_vec; dx_vec = tmp_dx_vec; dQ_dx_vec.resize(dQ_vec.size(),0); for (size_t i=0;i!=dQ_vec.size();i++){ dQ_dx_vec.at(i) = dQ_vec.at(i)/(dx_vec.at(i)+1e-9); } pu_vec = tmp_pu_vec; pv_vec = tmp_pv_vec; pw_vec = tmp_pw_vec; pt_vec = tmp_pt_vec; reduced_chi2_vec = tmp_reduced_chi2_vec; if (pcloud_fit != (ToyPointCloud*)0) delete pcloud_fit; pcloud_fit = new ToyPointCloud(); pcloud_fit->AddPoints(fit_pt_vec); pcloud_fit->build_kdtree_index(); } void WCPPID::ProtoSegment::set_fit_associate_vec(std::vector<WCP::Point >& tmp_fit_pt_vec, std::vector<int>& tmp_fit_index, std::vector<bool>& tmp_fit_skip){ fit_pt_vec = tmp_fit_pt_vec; fit_index_vec = tmp_fit_index; fit_flag_skip = tmp_fit_skip; if (pcloud_fit != (ToyPointCloud*)0) delete pcloud_fit; pcloud_fit = new ToyPointCloud(); pcloud_fit->AddPoints(fit_pt_vec); pcloud_fit->build_kdtree_index(); } void WCPPID::ProtoSegment::reset_fit_prop(){ fit_index_vec.resize(fit_pt_vec.size(),-1); fit_flag_skip.resize(fit_pt_vec.size(),false); } void WCPPID::ProtoSegment::clear_fit(){ flag_fit = false; fit_pt_vec.clear(); fit_pt_vec.resize(wcpt_vec.size()); for (size_t i=0;i!=wcpt_vec.size();i++){ fit_pt_vec.at(i).x = wcpt_vec.at(i).x; fit_pt_vec.at(i).y = wcpt_vec.at(i).y; fit_pt_vec.at(i).z = wcpt_vec.at(i).z; } if (pcloud_fit != (ToyPointCloud*)0) delete pcloud_fit; pcloud_fit = new ToyPointCloud(); pcloud_fit->AddPoints(fit_pt_vec); pcloud_fit->build_kdtree_index(); dQ_vec.clear(); dx_vec.clear(); dQ_dx_vec.clear(); pu_vec.clear(); pv_vec.clear(); pw_vec.clear(); pt_vec.clear(); reduced_chi2_vec.clear(); fit_index_vec.clear(); fit_flag_skip.clear(); } void WCPPID::ProtoSegment::reset_associate_points(){ if (pcloud_associated != (ToyPointCloud*)0){ delete pcloud_associated; // flag_good_associated.clear(); } pcloud_associated = 0; if (pcloud_associated_steiner != (ToyPointCloud*)0){ delete pcloud_associated_steiner; // flag_good_associated_steiner.clear(); } pcloud_associated_steiner = 0; } void WCPPID::ProtoSegment::add_associate_point_steiner(WCP::WCPointCloud<double>::WCPoint& wcp){ if (pcloud_associated_steiner == (ToyPointCloud*)0) pcloud_associated_steiner = new ToyPointCloud(); pcloud_associated_steiner->AddPoint(wcp); // flag_good_associated_steiner.push_back(true); } void WCPPID::ProtoSegment::add_associate_point(WCPointCloud<double>::WCPoint& wcp, WC2DPointCloud<double>::WC2DPoint& wcp_u, WC2DPointCloud<double>::WC2DPoint& wcp_v, WC2DPointCloud<double>::WC2DPoint& wcp_w){ // std::cout << pcloud_associated << std::endl; if (pcloud_associated == (ToyPointCloud*)0) pcloud_associated = new ToyPointCloud(); pcloud_associated->AddPoint(wcp, wcp_u, wcp_v, wcp_w); // flag_good_associated.push_back(true); } void WCPPID::ProtoSegment::print_dis(){ for (size_t i=0;i!=wcpt_vec.size(); i++){ Point p(wcpt_vec.at(i).x, wcpt_vec.at(i).y, wcpt_vec.at(i).z); std::pair<double, WCP::Point> results = get_closest_point(p); if (results.first > 0.6*units::cm) std::cout << i << " " << results.first/units::cm << std::endl; } } std::pair<double, WCP::Point> WCPPID::ProtoSegment::get_closest_point(WCP::Point &p){ if (pcloud_fit != (ToyPointCloud*)0) return pcloud_fit->get_closest_point(p); else{ WCP::Point p1(0,0,0); return std::make_pair(-1,p1); } } double WCPPID::ProtoSegment::get_closest_2d_dis(double x, double y, int plane){ return pcloud_fit->get_closest_2d_dis(x, y, plane); } std::tuple<double, double, double> WCPPID::ProtoSegment::get_closest_2d_dis(WCP::Point &p){ if (pcloud_fit != (ToyPointCloud*)0) { std::pair<int, double> results_u = pcloud_fit->get_closest_2d_dis(p, 0); std::pair<int, double> results_v = pcloud_fit->get_closest_2d_dis(p, 1); std::pair<int, double> results_w = pcloud_fit->get_closest_2d_dis(p, 2); return std::make_tuple(results_u.second, results_v.second, results_w.second); }else{ return std::make_tuple(-1,-1,-1); } } WCP::WCPointCloud<double>::WCPoint WCPPID::ProtoSegment::get_closest_wcpt(WCP::Point& test_p){ double min_dis = 1e9; WCP::WCPointCloud<double>::WCPoint min_wcpt = wcpt_vec.front(); for (auto it = wcpt_vec.begin(); it!=wcpt_vec.end(); it++){ double dis = sqrt(pow(test_p.x - (*it).x,2) + pow(test_p.y - (*it).y,2) + pow(test_p.z - (*it).z,2)); if (dis < min_dis){ min_dis = dis; min_wcpt = *it; } } return min_wcpt; } std::vector<double> WCPPID::ProtoSegment::do_track_comp(std::vector<double>& L , std::vector<double>& dQ_dx, double compare_range, double offset_length){ TPCParams& mp = Singleton<TPCParams>::Instance(); TGraph *g_muon = mp.get_muon_dq_dx(); TGraph *g_proton = mp.get_proton_dq_dx(); TGraph *g_electron = mp.get_electron_dq_dx(); double end_L = L.back() + 0.15*units::cm-offset_length; int ncount = 0; std::vector<double> vec_x; std::vector<double> vec_y; for (size_t i=0;i!=L.size(); i++){ if (end_L - L.at(i) < compare_range && end_L - L.at(i) > 0){ // check up to compared range ... vec_x.push_back(end_L-L.at(i)); vec_y.push_back(dQ_dx.at(i)); ncount ++; } } TH1F *h1 = new TH1F("h1","h1",ncount,0,ncount); TH1F *h2 = new TH1F("h2","h2",ncount,0,ncount); TH1F *h3 = new TH1F("h3","h3",ncount,0,ncount); TH1F *h4 = new TH1F("h4","h4",ncount,0,ncount); TH1F *h5 = new TH1F("h5","h5",ncount,0,ncount); for (size_t i=0;i!=ncount;i++){ // std::cout << i << " " << vec_y.at(i) << std::endl; h1->SetBinContent(i+1,vec_y.at(i)); h2->SetBinContent(i+1,g_muon->Eval((vec_x.at(i))/units::cm)); //muon h3->SetBinContent(i+1,50e3); //MIP like ... h4->SetBinContent(i+1,g_proton->Eval(vec_x.at(i)/units::cm)); //proton h5->SetBinContent(i+1,g_electron->Eval(vec_x.at(i)/units::cm)); // electron } double ks1 = h2->KolmogorovTest(h1,"M"); double ratio1 = h2->GetSum()/(h1->GetSum()+1e-9); double ks2 = h3->KolmogorovTest(h1,"M"); double ratio2 = h3->GetSum()/(h1->GetSum()+1e-9); double ks3 = h4->KolmogorovTest(h1,"M"); double ratio3 = h4->GetSum()/(h1->GetSum()+1e-9); double ks4 = h5->KolmogorovTest(h1,"M"); double ratio4 = h5->GetSum()/(h1->GetSum()+1e-9); delete h1; delete h2; delete h3; delete h4; delete h5; // std::cout << id << " " << get_length()/units::cm << " " << ks1 << " " << ratio1 << " " << ks2 << " " << ratio2 << " " << ks3 << " " << ratio3 << " " << ks4 << " " << ratio4 << " " << ks1-ks2 + (fabs(ratio1-1)-fabs(ratio2-1))/1.5*0.3 << std::endl; std::vector<double> results; results.push_back(eval_ks_ratio(ks1, ks2, ratio1, ratio2)); // direction metric results.push_back(sqrt(pow(ks1,2) + pow(ratio1-1,2))); // muon information // results.push_back(ratio1); results.push_back(sqrt(pow(ks3,2) + pow(ratio3-1,2))); // proton information //results.push_back(ratio3); results.push_back(sqrt(pow(ks4,2) + pow(ratio4-1,2))); // electron information // results.push_back(ratio4); return results; } bool WCPPID::ProtoSegment::eval_ks_ratio(double ks1, double ks2, double ratio1, double ratio2){ // std::cout << ks1 << " " << ks2 << " " << ratio1 << " " << ratio2 << " " << sqrt(pow(ks2/0.06,2)+pow((ratio2-1)/0.06,2)) << " " << ks1-ks2 + (fabs(ratio1-1)-fabs(ratio2-1))/1.5*0.3 << " " << ks1-ks2 + (fabs(ratio1-1)-fabs(ratio2-1))/1.5*0.3 << " " << std::endl; if (ks1-ks2 >= 0.0) return false; if (sqrt(pow(ks2/0.06,2)+pow((ratio2-1)/0.06,2))< 1.4 && ks1-ks2 + (fabs(ratio1-1)-fabs(ratio2-1))/1.5*0.3 > -0.02) return false; if (ks1 - ks2 < -0.02 && (ks2 > 0.09 && fabs(ratio2-1) >0.1 || ratio2 > 1.5 || ks2 > 0.2)) return true; if ( ks1-ks2 + (fabs(ratio1-1)-fabs(ratio2-1))/1.5*0.3 < 0) return true; return false; } bool WCPPID::ProtoSegment::do_track_pid(std::vector<double>& L , std::vector<double>& dQ_dx, double compare_range , double offset_length, bool flag_force ){ std::vector<double> rL(L.size(),0); std::vector<double> rdQ_dx(L.size(),0); // get reverse vectors ... for (size_t i=0;i!=L.size();i++){ rL.at(i) = L.back() - L.at(L.size()-1-i); rdQ_dx.at(i) = dQ_dx.at(L.size()-1-i); } std::vector<double> result_forward = do_track_comp(L, dQ_dx, compare_range, offset_length); std::vector<double> result_backward = do_track_comp(rL, rdQ_dx, compare_range, offset_length); // direction determination bool flag_forward = std::round(result_forward.at(0)); bool flag_backward = std::round(result_backward.at(0)); double length = get_length(); double length1 = sqrt(pow(fit_pt_vec.front().x - fit_pt_vec.back().x,2) + pow(fit_pt_vec.front().y - fit_pt_vec.back().y,2) + pow(fit_pt_vec.front().z - fit_pt_vec.back().z,2)); int forward_particle_type = 13; // default muon double min_forward_val = result_forward.at(1) ; if (result_forward.at(2) < min_forward_val){ min_forward_val = result_forward.at(2); forward_particle_type = 2212; } if (result_forward.at(3) < min_forward_val && length < 20*units::cm){ min_forward_val = result_forward.at(3); forward_particle_type = 11; } // std::cout << length/units::cm << " " << length1/units::cm << std::endl; int backward_particle_type =13; // default muon double min_backward_val = result_backward.at(1); if (result_backward.at(2) < min_backward_val){ min_backward_val = result_backward.at(2); backward_particle_type = 2212; } if (result_backward.at(3) < min_backward_val && length < 20*units::cm){ min_backward_val = result_backward.at(3); backward_particle_type = 11; } // std::cout << id << " " << get_length()/units::cm << " " << flag_forward << " " << result_forward.at(0) << " m: " << result_forward.at(1) << " p: " << result_forward.at(2) << " e: " << result_forward.at(3) << std::endl; // std::cout << id << " " << get_length()/units::cm << " " << flag_backward << " " << result_backward.at(0) << " m: " << result_backward.at(1) << " p: " << result_backward.at(2) << " e: " << result_backward.at(3) << std::endl; if (flag_forward == 1 && flag_backward == 0){ flag_dir = 1; particle_type = forward_particle_type; particle_score = min_forward_val; return true; }else if (flag_forward == 0 && flag_backward == 1){ flag_dir = -1; particle_type = backward_particle_type; particle_score = min_backward_val; return true; }else if (flag_forward == 1 && flag_backward == 1){ if (min_forward_val < min_backward_val){ flag_dir = 1; particle_type = forward_particle_type; particle_score = min_forward_val; }else{ flag_dir = -1; particle_type = backward_particle_type; particle_score = min_backward_val; } return true; }else if (flag_forward ==0 && flag_backward == 0 && flag_force){ if (min_forward_val < min_backward_val){ particle_score = min_forward_val; particle_type = forward_particle_type; flag_dir = 1; }else{ particle_score = min_backward_val; particle_type = backward_particle_type; flag_dir = -1; } return true; } // reset before return ... flag_dir = 0; particle_type = 0; return false; } bool WCPPID::ProtoSegment::is_dir_weak(){ double length = get_length(); if (fabs(particle_type)==13 && particle_score > 0.07 && length >= 5*units::cm || fabs(particle_type)==13 && particle_score > 0.15 && length < 5*units::cm || fabs(particle_type)==2212 && particle_score > 0.13 && length >=5*units::cm || fabs(particle_type)==2212 && particle_score > 0.27 && length < 5*units::cm || dir_weak ) return true; return false; } bool WCPPID::ProtoSegment::get_flag_shower(){ return flag_shower_trajectory || flag_shower_topology || get_flag_shower_dQdx(); } bool WCPPID::ProtoSegment::get_flag_shower_dQdx(){ if (fabs(particle_type)==11) return true; return false; } double WCPPID::ProtoSegment::cal_kine_dQdx(std::vector<double>& vec_dQ, std::vector<double>& vec_dx){ double kine_energy =0; Double_t alpha = 1.0; Double_t beta = 0.255; for (size_t i=0;i!=vec_dQ.size();i++){ Double_t dQdx = vec_dQ.at(i)/(vec_dx.at(i) + 1e-9) * units::cm; if (dQdx/43e3 > 1000) dQdx = 0; //std::cout << id << " " << i << " " << dQdx/43e3 << std::endl; Double_t dEdx = (exp(dQdx * 23.6e-6*beta/1.38/0.273) - alpha)/(beta/1.38/0.273) * units::MeV/units::cm; if (dEdx < 0) dEdx = 0; if (dEdx > 50*units::MeV/units::cm ) dEdx = 50*units::MeV/units::cm; kine_energy += dEdx * vec_dx.at(i); } return kine_energy; } double WCPPID::ProtoSegment::cal_kine_dQdx(){ double kine_energy =0; Double_t alpha = 1.0; Double_t beta = 0.255; for (size_t i=0;i!=fit_pt_vec.size();i++){ Double_t dQdx = dQ_vec.at(i)/(dx_vec.at(i) + 1e-9) * units::cm; if (dQdx/43e3 > 1000) dQdx = 0; Double_t dEdx = (exp(dQdx * 23.6e-6*beta/1.38/0.273) - alpha)/(beta/1.38/0.273) * units::MeV/units::cm; if (dEdx < 0) dEdx = 0; if (dEdx > 50*units::MeV/units::cm ) dEdx = 50*units::MeV/units::cm; // std::cout << id << " " << i << " " << dQdx/(43e3) << " " << dEdx/(units::MeV/units::cm) << " " << dx_vec.at(i)/units::cm << " " << kine_energy << std::endl; if (i==0){ double dis = sqrt(pow(fit_pt_vec.at(1).x - fit_pt_vec.at(0).x,2) + pow(fit_pt_vec.at(1).y - fit_pt_vec.at(0).y,2) + pow(fit_pt_vec.at(1).z - fit_pt_vec.at(0).z,2)); if (dx_vec.at(i) > dis*1.5){ kine_energy += dEdx * dis ; }else{ kine_energy += dEdx * dx_vec.at(i); } }else if (i+1 == fit_pt_vec.size()){ double dis = sqrt(pow(fit_pt_vec.at(i).x - fit_pt_vec.at(i-1).x,2) + pow(fit_pt_vec.at(i).y - fit_pt_vec.at(i-1).y,2) + pow(fit_pt_vec.at(i).z - fit_pt_vec.at(i-1).z,2)); if (dx_vec.at(i) > dis*1.5){ kine_energy += dEdx * dis ; }else{ kine_energy += dEdx * dx_vec.at(i); } }else{ kine_energy += dEdx * dx_vec.at(i); } } return kine_energy; } double WCPPID::ProtoSegment::cal_kine_range(double L){ TPCParams& mp = Singleton<TPCParams>::Instance(); TGraph *g_range = 0; if (fabs(particle_type)==11) g_range = mp.get_electron_r2ke(); else if (fabs(particle_type)==13) g_range = mp.get_muon_r2ke(); else if (fabs(particle_type)==211) g_range = mp.get_pion_r2ke(); else if (fabs(particle_type)==321) g_range = mp.get_kaon_r2ke(); else if (fabs(particle_type)==2212) g_range = mp.get_proton_r2ke(); double kine_energy = g_range->Eval(L/units::cm) * units::MeV; return kine_energy; } double WCPPID::ProtoSegment::cal_kine_range(){ TPCParams& mp = Singleton<TPCParams>::Instance(); TGraph *g_range = mp.get_muon_r2ke(); if (fabs(particle_type)==11) g_range = mp.get_electron_r2ke(); else if (fabs(particle_type)==13) g_range = mp.get_muon_r2ke(); else if (fabs(particle_type)==211) g_range = mp.get_pion_r2ke(); else if (fabs(particle_type)==321) g_range = mp.get_kaon_r2ke(); else if (fabs(particle_type)==2212) g_range = mp.get_proton_r2ke(); // std::cout << g_range << std::endl; double kine_energy = g_range->Eval(get_length()/units::cm) * units::MeV; return kine_energy; } void WCPPID::ProtoSegment::cal_4mom(){ double length = get_length(); double kine_energy = 0; if (length < 4*units::cm){ kine_energy = cal_kine_dQdx(); // short track }else if (flag_shower_trajectory){ kine_energy = cal_kine_dQdx(); }else{ kine_energy = cal_kine_range(); } kenergy_best = kine_energy; // std::cout << id << " " << cal_kine_dQdx() << " " << cal_kine_range() << " " << particle_mass << " " << particle_type << std::endl; //std::cout << kine_energy << std::endl; particle_4mom[3]= kine_energy + particle_mass; double mom = sqrt(pow(particle_4mom[3],2) - pow(particle_mass,2)); // direction vector ... TVector3 v1 = cal_dir_3vector(); particle_4mom[0] = mom * v1.X(); particle_4mom[1] = mom * v1.Y(); particle_4mom[2] = mom * v1.Z(); } TVector3 WCPPID::ProtoSegment::cal_dir_3vector(WCP::Point& p, double dis_cut){ WCP::Point p1(0,0,0); Int_t ncount = 0; for (size_t i=0;i!=fit_pt_vec.size();i++){ double dis = sqrt(pow(fit_pt_vec.at(i).x - p.x,2)+pow(fit_pt_vec.at(i).y - p.y,2)+pow(fit_pt_vec.at(i).z - p.z,2)); // std::cout << dis/units::cm << std::endl; if (dis < dis_cut){ p1.x += fit_pt_vec.at(i).x; p1.y += fit_pt_vec.at(i).y; p1.z += fit_pt_vec.at(i).z; ncount ++; } } TVector3 v1(p1.x/ncount - p.x, p1.y/ncount - p.y, p1.z/ncount - p.z); v1 = v1.Unit(); return v1; } TVector3 WCPPID::ProtoSegment::cal_dir_3vector(){ WCP::Point p(0,0,0); if (flag_dir == 1){ for (size_t i=1;i<5;i++){ if (i>= fit_pt_vec.size()) break; p.x += fit_pt_vec.at(i).x - fit_pt_vec.at(0).x; p.y += fit_pt_vec.at(i).y - fit_pt_vec.at(0).y; p.z += fit_pt_vec.at(i).z - fit_pt_vec.at(0).z; } }else if (flag_dir == -1){ for (size_t i=1;i<5;i++){ if (i+1 > fit_pt_vec.size()) break; p.x += fit_pt_vec.at(fit_pt_vec.size()-i-1).x - fit_pt_vec.back().x; p.y += fit_pt_vec.at(fit_pt_vec.size()-i-1).y - fit_pt_vec.back().y; p.z += fit_pt_vec.at(fit_pt_vec.size()-i-1).z - fit_pt_vec.back().z; } } TVector3 v1(p.x, p.y, p.z); v1 = v1.Unit(); return v1; } void WCPPID::ProtoSegment::determine_dir_track(int start_n, int end_n, bool flag_print){ flag_dir = 0; int npoints = fit_pt_vec.size(); int start_n1 = 0, end_n1 = npoints - 1; // if more than one point, exclude the vertex ... if (end_n!=1) { end_n1 = npoints - 2; npoints -= 1; } if (start_n!=1) { npoints -=1; start_n1 = 1; } // if (start_n == 1 && end_n == 1){ // end_n1 = npoints - 2; // npoints -= 1; // npoints -=1; // start_n1 = 1; // } // if (id == 1) std::cout << id << " " << npoints << " " << end_n1 << " " << start_n1 << std::endl; if (npoints ==0 || end_n1 < start_n1) return; std::vector<double> L(npoints,0); std::vector<double> dQ_dx(npoints,0); double dis = 0; // std::cout << start_n1 << " " << end_n1 << " " << dQ_vec.size() << " " << fit_pt_vec.size() << std::endl; for (size_t i = start_n1; i <= end_n1; i++){ L.at(i-start_n1) = dis; dQ_dx.at(i-start_n1) = dQ_vec.at(i)/(dx_vec.at(i)/units::cm+1e-9); if (i+1 < fit_pt_vec.size()) dis += sqrt(pow(fit_pt_vec.at(i+1).x-fit_pt_vec.at(i).x,2) + pow(fit_pt_vec.at(i+1).y-fit_pt_vec.at(i).y,2) + pow(fit_pt_vec.at(i+1).z - fit_pt_vec.at(i).z,2)); } if (npoints >=2){ // reasonably long ... if (start_n == 1 && end_n == 1 && npoints >=15){ // can use the dQ/dx to do PID and direction ... bool tmp_flag_pid = do_track_pid(L, dQ_dx, 35*units::cm, 1*units::cm, true); if (!tmp_flag_pid) tmp_flag_pid =do_track_pid(L, dQ_dx, 15*units::cm, 1*units::cm, true); }else{ // can use the dQ/dx to do PID and direction ... bool tmp_flag_pid = do_track_pid(L, dQ_dx); if (!tmp_flag_pid) tmp_flag_pid =do_track_pid(L, dQ_dx, 15*units::cm); // if (!tmp_flag_pid) tmp_flag_pid = do_track_pid(L, dQ_dx, 35*units::cm, 3*units::cm); // if (!tmp_flag_pid) tmp_flag_pid =do_track_pid(L, dQ_dx, 15*units::cm, 3*units::cm); } } double length = get_length(); // not a good idea to constraing dQ/dx for electron // short track what to do??? if (particle_type == 0){ // calculate medium dQ/dx std::vector<double> vec_dQ_dx = dQ_dx; std::nth_element(vec_dQ_dx.begin(), vec_dQ_dx.begin() + vec_dQ_dx.size()/2, vec_dQ_dx.end()); double medium_dQ_dx = *std::next(vec_dQ_dx.begin(), vec_dQ_dx.size()/2); if (medium_dQ_dx > 43e3 * 1.75) particle_type = 2212; // proton else if (medium_dQ_dx < 43e3 * 1.2) particle_type = 13; //muon type else if (medium_dQ_dx < 43e3 * 1.5 && length < 4*units::cm) particle_type = 13; // std::cout << medium_dQ_dx/(43e3) << std::endl; } // electron and both end contain stuff if (abs(particle_type)==11 && (start_n>1 && end_n >1)){ dir_weak = true; flag_dir = 0; if (particle_score < 0.15) particle_type = 13; }else if (abs(particle_type)==11 && (start_n >1 && flag_dir == -1 || end_n >1 && flag_dir == 1) ){ dir_weak = true; flag_dir = 0; if (particle_score < 0.15) particle_type = 13; }else if (length < 1.5*units::cm){ dir_weak = true; } // vertex activities ... if (length < 1.5*units::cm && (start_n == 1 || end_n == 1)){ if (start_n ==1 && end_n > 2){ flag_dir = -1; std::vector<double> vec_dQ_dx = dQ_dx; std::nth_element(vec_dQ_dx.begin(), vec_dQ_dx.begin() + vec_dQ_dx.size()/2, vec_dQ_dx.end()); double medium_dQ_dx = *std::next(vec_dQ_dx.begin(), vec_dQ_dx.size()/2); if (medium_dQ_dx > 43e3 * 1.75) particle_type = 2212; else if (medium_dQ_dx < 43e3*1.2) particle_type = 211; }else if (end_n==1 && start_n>2){ flag_dir = 1; std::vector<double> vec_dQ_dx = dQ_dx; std::nth_element(vec_dQ_dx.begin(), vec_dQ_dx.begin() + vec_dQ_dx.size()/2, vec_dQ_dx.end()); double medium_dQ_dx = *std::next(vec_dQ_dx.begin(), vec_dQ_dx.size()/2); if (medium_dQ_dx > 43e3 * 1.75) particle_type = 2212; else if (medium_dQ_dx < 43e3*1.2) particle_type = 211; } } // if the particle score is really bad, make it a shower ... if (length > 10*units::cm && particle_score > 1.0 && particle_score < 100){ particle_type = 11; particle_score = 200; flag_dir = 0; } if (particle_type!=0){ TPCParams& mp = Singleton<TPCParams>::Instance(); if (fabs(particle_type)==11) particle_mass = mp.get_mass_electron(); else if (fabs(particle_type)==13) particle_mass = mp.get_mass_muon(); else if (fabs(particle_type)==211) particle_mass = mp.get_mass_pion(); else if (fabs(particle_type)==321) particle_mass = mp.get_mass_kaon(); else if (fabs(particle_type)==2212) particle_mass = mp.get_mass_proton(); } if ((flag_dir==1 && end_n == 1 || flag_dir==-1 && start_n ==1) && particle_type!=0){ cal_4mom(); } if (flag_print) std::cout << id << " " << length/units::cm << " Track " << flag_dir << " " << is_dir_weak() << " " << particle_type << " " << particle_mass/units::MeV << " " << (particle_4mom[3]-particle_mass)/units::MeV << " " << particle_score << std::endl; } void WCPPID::ProtoSegment::determine_dir_shower_trajectory(int start_n, int end_n, bool flag_print){ flag_dir = 0; double length = get_length(); // hack for now ... particle_type = 11; TPCParams& mp = Singleton<TPCParams>::Instance(); if (start_n==1 && end_n >1){ flag_dir = -1; }else if (start_n > 1 && end_n == 1){ flag_dir = 1; }else{ determine_dir_track(start_n, end_n, false); if (particle_type!=11){ particle_type = 11; flag_dir = 0; } } particle_mass = mp.get_mass_electron(); cal_4mom(); if (flag_print) std::cout << id << " " << length/units::cm << " S_traj " << flag_dir << " " << is_dir_weak() << " " << particle_type << " " << particle_mass/units::MeV << " " << (particle_4mom[3]-particle_mass)/units::MeV << " " << particle_score << std::endl; } void WCPPID::ProtoSegment::determine_dir_shower_topology(int start_n, int end_n, bool flag_print){ double length = get_length(); // hack for now particle_type = 11; TPCParams& mp = Singleton<TPCParams>::Instance(); particle_mass = mp.get_mass_electron(); //if (start_n==1 && end_n >1){ // flag_dir = -1; //}else if (start_n > 1 && end_n == 1){ // flag_dir = 1; //} // WCP::Point center(0,0,0); // WCP::WCPointCloud<double>& cloud = pcloud_associated->get_cloud(); // for (size_t i=0;i!=cloud.pts.size();i++){ // center.x += cloud.pts.at(i).x; // center.y += cloud.pts.at(i).y; // center.z += cloud.pts.at(i).z; // } // center.x /= cloud.pts.size(); // center.y /= cloud.pts.size(); // center.z /= cloud.pts.size(); // double dis1 = sqrt(pow(center.x - fit_pt_vec.front().x ,2) + pow(center.y - fit_pt_vec.front().y,2) + pow(center.z - fit_pt_vec.front().z,2)); // double dis2 = sqrt(pow(center.x - fit_pt_vec.back().x ,2) + pow(center.y - fit_pt_vec.back().y,2) + pow(center.z - fit_pt_vec.back().z,2)); // std::cout << dis1/units::cm << " " << dis2/units::cm << std::endl; if (flag_print) std::cout << id << " " << length/units::cm << " S_topo " << flag_dir << " " << is_dir_weak() << " " << particle_type << " " << particle_mass/units::MeV << " " << (particle_4mom[3]-particle_mass)/units::MeV << " " << particle_score << std::endl; } std::tuple<WCPPID::ProtoSegment*, WCPPID::ProtoVertex*, WCPPID::ProtoSegment*> WCPPID::ProtoSegment::break_segment_at_point(WCP::Point& p, int& acc_segment_id, int& acc_vertex_id){ int nbreak = -1; double min_dis = 1e9; for (size_t i=0;i!=wcpt_vec.size(); i++){ double dis = sqrt(pow(wcpt_vec.at(i).x-p.x,2) + pow(wcpt_vec.at(i).y-p.y,2) + pow(wcpt_vec.at(i).z-p.z,2)); if (dis < min_dis){ min_dis = dis; nbreak = i; } } int nbreak_fit = -1; min_dis = 1e9; for (size_t i=0; i!=fit_pt_vec.size(); i++){ double dis = sqrt(pow(fit_pt_vec.at(i).x-p.x,2) + pow(fit_pt_vec.at(i).y-p.y,2) + pow(fit_pt_vec.at(i).z-p.z,2)); if (dis < min_dis){ min_dis = dis; nbreak_fit = i; } } if (nbreak_fit == 0 || nbreak_fit+1 == fit_pt_vec.size()){ return std::make_tuple(this, (WCPPID::ProtoVertex*)0, (WCPPID::ProtoSegment*)0); }else{ if (nbreak ==0 ) nbreak ++; if (nbreak+1==wcpt_vec.size()) nbreak --; } // Now start to construct new segment ... std::list<WCP::WCPointCloud<double>::WCPoint > path_wcps1; std::list<WCP::WCPointCloud<double>::WCPoint > path_wcps2; WCP::WCPointCloud<double>::WCPoint vertex_wcp; for (size_t i=0; i!=wcpt_vec.size(); i++){ if (i==nbreak){ path_wcps1.push_back(wcpt_vec.at(i)); path_wcps2.push_back(wcpt_vec.at(i)); vertex_wcp = wcpt_vec.at(i); }else if ( i< nbreak){ path_wcps1.push_back(wcpt_vec.at(i)); }else{ path_wcps2.push_back(wcpt_vec.at(i)); } } // create new segment vertex ... WCPPID::ProtoSegment *sg1 = new WCPPID::ProtoSegment(acc_segment_id, path_wcps1, cluster_id); acc_segment_id ++; WCPPID::ProtoVertex *vtx = new WCPPID::ProtoVertex(acc_vertex_id, vertex_wcp, cluster_id); acc_vertex_id ++; WCPPID::ProtoSegment *sg2 = new WCPPID::ProtoSegment(acc_segment_id, path_wcps2, cluster_id); acc_segment_id ++; //std::cout << cluster_id << " " << nbreak_fit << " " << fit_pt_vec.size() << " " << dQ_vec.size() << " " << fit_index_vec.size() << " " << pu_vec.size() << " " << reduced_chi2_vec.size() << " " << nbreak << " " << wcpt_vec.size() << std::endl; // if (fit_index_vec.size()==0) // fit_index_vec.resize(dQ_vec.size(),0); // fill in the vertex vtx->set_neutrino_vertex(false); vtx->set_fit_pt(fit_pt_vec.at(nbreak_fit) ); vtx->set_fit_index(fit_index_vec.at(nbreak_fit) ); vtx->set_flag_fit_fix(false); vtx->set_fit_range(1*units::cm); vtx->set_dx(dx_vec.at(nbreak_fit) ); vtx->set_fit_flag(true); vtx->set_dQ(dQ_vec.at(nbreak_fit)); vtx->set_pu(pu_vec.at(nbreak_fit)); vtx->set_pv(pv_vec.at(nbreak_fit)); vtx->set_pw(pw_vec.at(nbreak_fit)); vtx->set_pt(pt_vec.at(nbreak_fit)); vtx->set_reduced_chi2(reduced_chi2_vec.at(nbreak_fit)); // std::cout << cluster_id << " " << nbreak_fit << " " << fit_pt_vec.size() << " " << dQ_vec.size() << " " << fit_index_vec.size() << " " << pu_vec.size() << " " << reduced_chi2_vec.size() << " " << nbreak << " " << wcpt_vec.size() << std::endl; // fill in first and segments sg1->set_dir_weak(dir_weak); sg2->set_dir_weak(dir_weak); sg1->set_fit_flag(flag_fit); sg2->set_fit_flag(flag_fit); sg1->set_flag_dir(flag_dir); sg2->set_flag_dir(flag_dir); sg1->set_particle_type(particle_type); sg2->set_particle_type(particle_type); sg1->set_particle_mass(particle_mass); sg2->set_particle_mass(particle_mass); sg1->set_flag_shower_trajectory(flag_shower_trajectory); sg2->set_flag_shower_trajectory(flag_shower_trajectory); sg1->set_flag_shower_topology(flag_shower_topology); sg2->set_flag_shower_topology(flag_shower_topology); sg1->set_particle_score(particle_score); sg2->set_particle_score(particle_score); std::vector<WCP::Point >& fit_pt_vec1 = sg1->get_point_vec(); std::vector<WCP::Point >& fit_pt_vec2 = sg2->get_point_vec(); std::vector<double>& dQ_vec1 = sg1->get_dQ_vec(); std::vector<double>& dQ_vec2 = sg2->get_dQ_vec(); std::vector<double>& dx_vec1 = sg1->get_dx_vec(); std::vector<double>& dx_vec2 = sg2->get_dx_vec(); std::vector<double>& dQ_dx_vec1 = sg1->get_dQ_dx_vec(); std::vector<double>& dQ_dx_vec2 = sg2->get_dQ_dx_vec(); std::vector<double>& pu_vec1 = sg1->get_pu_vec(); std::vector<double>& pu_vec2 = sg2->get_pu_vec(); std::vector<double>& pv_vec1 = sg1->get_pv_vec(); std::vector<double>& pv_vec2 = sg2->get_pv_vec(); std::vector<double>& pw_vec1 = sg1->get_pw_vec(); std::vector<double>& pw_vec2 = sg2->get_pw_vec(); std::vector<double>& pt_vec1 = sg1->get_pt_vec(); std::vector<double>& pt_vec2 = sg2->get_pt_vec(); std::vector<double>& reduced_chi2_vec1 = sg1->get_reduced_chi2_vec(); std::vector<double>& reduced_chi2_vec2 = sg2->get_reduced_chi2_vec(); std::vector<int>& fit_index_vec1 = sg1->get_fit_index_vec(); std::vector<int>& fit_index_vec2 = sg2->get_fit_index_vec(); std::vector<bool>& fit_flag_skip1 = sg1->get_fit_flag_skip(); // vertex??? std::vector<bool>& fit_flag_skip2 = sg2->get_fit_flag_skip(); // vertex??? fit_pt_vec1.clear(); fit_pt_vec2.clear(); dQ_vec1.clear(); dQ_vec2.clear(); pu_vec1.clear(); pu_vec2.clear(); pv_vec1.clear(); pv_vec2.clear(); pw_vec1.clear(); pw_vec2.clear(); pt_vec1.clear(); pt_vec2.clear(); reduced_chi2_vec1.clear(); reduced_chi2_vec2.clear(); fit_index_vec1.clear(); fit_index_vec2.clear(); fit_flag_skip1.clear(); fit_flag_skip2.clear(); // std::cout << fit_pt_vec.size() << " " << dQ_vec.size() << " " << dx_vec.size() << " " << pu_vec.size() << " " << pv_vec.size() << " " << pw_vec.size() << " " << pt_vec.size() << " " << reduced_chi2_vec.size() << " " << fit_index_vec.size() << " " << fit_flag_skip.size() << std::endl; for (size_t i=0; i!=fit_pt_vec.size(); i++){ if (i==nbreak_fit){ fit_pt_vec1.push_back(fit_pt_vec.at(i)); fit_pt_vec2.push_back(fit_pt_vec.at(i)); dQ_vec1.push_back(dQ_vec.at(i)); dQ_vec2.push_back(dQ_vec.at(i)); dx_vec1.push_back(dx_vec.at(i)); dx_vec2.push_back(dx_vec.at(i)); dQ_dx_vec1.push_back(dQ_dx_vec.at(i)); dQ_dx_vec2.push_back(dQ_dx_vec.at(i)); pu_vec1.push_back(pu_vec.at(i)); pu_vec2.push_back(pu_vec.at(i)); pv_vec1.push_back(pv_vec.at(i)); pv_vec2.push_back(pv_vec.at(i)); pw_vec1.push_back(pw_vec.at(i)); pw_vec2.push_back(pw_vec.at(i)); pt_vec1.push_back(pt_vec.at(i)); pt_vec2.push_back(pt_vec.at(i)); reduced_chi2_vec1.push_back(reduced_chi2_vec.at(i)); reduced_chi2_vec2.push_back(reduced_chi2_vec.at(i)); fit_index_vec1.push_back(fit_index_vec.at(i)); fit_index_vec2.push_back(fit_index_vec.at(i)); fit_flag_skip1.push_back(fit_flag_skip.at(i)); fit_flag_skip2.push_back(fit_flag_skip.at(i)); }else if (i< nbreak_fit){ fit_pt_vec1.push_back(fit_pt_vec.at(i)); dQ_vec1.push_back(dQ_vec.at(i)); dx_vec1.push_back(dx_vec.at(i)); dQ_dx_vec1.push_back(dQ_dx_vec.at(i)); pu_vec1.push_back(pu_vec.at(i)); pv_vec1.push_back(pv_vec.at(i)); pw_vec1.push_back(pw_vec.at(i)); pt_vec1.push_back(pt_vec.at(i)); reduced_chi2_vec1.push_back(reduced_chi2_vec.at(i)); fit_index_vec1.push_back(fit_index_vec.at(i)); fit_flag_skip1.push_back(fit_flag_skip.at(i)); }else{ fit_pt_vec2.push_back(fit_pt_vec.at(i)); dQ_vec2.push_back(dQ_vec.at(i)); dx_vec2.push_back(dx_vec.at(i)); dQ_dx_vec2.push_back(dQ_dx_vec.at(i)); pu_vec2.push_back(pu_vec.at(i)); pv_vec2.push_back(pv_vec.at(i)); pw_vec2.push_back(pw_vec.at(i)); pt_vec2.push_back(pt_vec.at(i)); reduced_chi2_vec2.push_back(reduced_chi2_vec.at(i)); fit_index_vec2.push_back(fit_index_vec.at(i)); fit_flag_skip2.push_back(fit_flag_skip.at(i)); } } // std::cout << nbreak_fit << " " << fit_pt_vec.size() << std::endl; // std::cout << fit_pt_vec2.size() << " " << dQ_vec2.size() << " " << dx_vec2.size() << " " << pu_vec2.size() << " " << pv_vec2.size() << " " << pw_vec2.size() << " " << pt_vec2.size() << " " << reduced_chi2_vec2.size() << " " << fit_index_vec2.size() << " " << fit_flag_skip2.size() << std::endl; sg1->build_pcloud_fit(); sg2->build_pcloud_fit(); // std::cout << fit_pt_vec2.size() << " " << dQ_vec2.size() << " " << dx_vec2.size() << " " << pu_vec2.size() << " " << pv_vec2.size() << " " << pw_vec2.size() << " " << pt_vec2.size() << " " << reduced_chi2_vec2.size() << " " << fit_index_vec2.size() << " " << fit_flag_skip2.size() << std::endl; sg1->cal_4mom(); sg2->cal_4mom(); WCP::WCPointCloud<double>& cloud = pcloud_associated->get_cloud(); WCP::WC2DPointCloud<double>& cloud_u = pcloud_associated->get_cloud_u(); WCP::WC2DPointCloud<double>& cloud_v = pcloud_associated->get_cloud_v(); WCP::WC2DPointCloud<double>& cloud_w = pcloud_associated->get_cloud_w(); Int_t ncount[2]={0,0}; for (size_t i=0;i!=cloud.pts.size();i++){ Point p(cloud.pts.at(i).x, cloud.pts.at(i).y, cloud.pts.at(i).z); if (sg1->get_closest_point(p).first < sg2->get_closest_point(p).first){ sg1->add_associate_point(cloud.pts.at(i), cloud_u.pts.at(i), cloud_v.pts.at(i), cloud_w.pts.at(i)); ncount[0]++; }else{ sg2->add_associate_point(cloud.pts.at(i), cloud_u.pts.at(i), cloud_v.pts.at(i), cloud_w.pts.at(i)); ncount[1]++; } } // std::cout << ncount[0] << " " << ncount[1] << std::endl; if (ncount[0] !=0) sg1->get_associated_pcloud()->build_kdtree_index(); if (ncount[1] !=0) sg2->get_associated_pcloud()->build_kdtree_index(); // std::cout << nbreak << " " << wcpt_vec.size() << " " << nbreak_fit << " " << fit_pt_vec.size() << std::endl; return std::make_tuple(sg1, vtx, sg2); }
[ "last.qx@gmail.com" ]
last.qx@gmail.com
dab9c1ba2cb47461faa22e6a5a1c1ff9caa04ca7
0e53a83898937a811109ecc7fa44e1b887149f02
/FireWall/Player.h
076a31c4ec95eb32e10f5885d6e564c49fc2465f
[]
no_license
eric-hoffmann/cpp-games
905813de81be1da786e72723a49f6055ee123bb1
ec9c66a28c1db7cf42a1a76602e64c70f72b98af
refs/heads/master
2021-01-19T21:16:09.980994
2017-02-19T20:50:40
2017-02-19T20:50:40
82,480,899
1
0
null
null
null
null
UTF-8
C++
false
false
1,609
h
/* * Player.h * * Created on: May 27, 2015 * Author: 709252 */ #ifndef PLAYER_H_ #define PLAYER_H_ #define DARK_GREEN makecol(0,100,0) #define BRIGHT_GREEN makecol(0,255,0) #include <string> // temporary #include <sstream> #include <allegro.h> //temporary #include <vector> struct object { int x; int y; int x1; int y1; object(int xx, int yy, int xx1, int yy1) { x = xx; y = yy; x1 = xx1; y1 = yy1; } object() { x = 0; y = 0; x1 = 0; y1 = 0; } }; struct anim : object { int delay; int maxFrame; int curFrame; int counter; anim(int xx, int yy, int xx1, int yy1, int d, int m, int c) : object(xx,yy,xx1,yy1) { delay = d; maxFrame = m; curFrame = c; counter = 0; } }; using std::string; using std::stringstream; using std::vector; BITMAP* grabframe(BITMAP *source, int width, int height, int startx, int starty, int columns, int frame); class Player { private: const int SPEED_CAP; const float INCREMENT; const int MAX_COOL; const int PROJ_DELAY; int score; int shots; int count; BITMAP *blank; BITMAP *playfire; BITMAP *orbsprite; vector<BITMAP*> orb; float vel; int cool; void move(); void moveProj(); void generateProj(); void drawPlayer(); void drawProj(); public: object pos; //Player(); BITMAP *play; Player(BITMAP* map); object getPos(); vector<object> getProj(); vector<anim> proj; const int MAX_SHOTS; void act(); void addScore(int s); int getScore(); void setShots(); int getShots(); }; #endif /* PLAYER_H_ */
[ "ehcomm1@gmail.com" ]
ehcomm1@gmail.com
90a4d5728634a2c54fb27a69b9236a629decce12
40f417f765397ed1303936e5ebd66e6a4e55d548
/CrowdSimulation/Demo/src/MainWindow.h
a943a6ec83a71486dabc615ebfab378079fc0819
[]
no_license
pluggalex/LLPP
57e2f0d20c9edb7852b35a08d4b25456d0273ced
bb90c22bd7694a7a1392dad3d08c410ee7bdd92a
refs/heads/master
2021-09-08T01:49:04.663914
2018-02-27T12:48:33
2018-02-27T12:48:33
117,812,532
0
0
null
null
null
null
UTF-8
C++
false
false
762
h
#ifndef _mainwindow_h_ #define _mainwindow_h_ #include <QMainWindow> #include <QGraphicsScene> #include <vector> #include "ped_model.h" #include "ped_agent.h" #include "ViewAgent.h" class QGraphicsView; class MainWindow : public QMainWindow { public: MainWindow() = delete; MainWindow(const Ped::Model &model); // paint is called after each computational step // to repaint the window void paint(); static int cellToPixel(int val); static const int cellsizePixel = 5; ~MainWindow(); private: QGraphicsView *graphicsView; QGraphicsScene * scene; const Ped::Model &model; // the graphical representation of each agent ViewAgent* viewAgent; // The pixelmap containing the heatmap image (Assignment 4) QGraphicsPixmapItem *pixmap; }; #endif
[ "alla7073@user.uu.se" ]
alla7073@user.uu.se
0ae9207b05e6037025654e920c39bf07bd054296
6a15cee126402eb8550ff91119d10a41c128c8fb
/src/lib/GraphicsUtils/disk_cycle.cpp
9c6707119af681b2265d3d8a310c0e7b4339b6dc
[]
no_license
thecsapprentice/SBSS_Public
da407dcf53285e969108a2f7f696a6d1ccf478a1
057296aa11b2934fb3d6ea0d636139c5d93f96a4
refs/heads/master
2020-06-07T05:55:33.295414
2017-04-13T15:17:57
2017-04-13T15:17:57
192,942,024
0
0
null
null
null
null
UTF-8
C++
false
false
3,212
cpp
#include "bmesh.h" #include <algorithm> using namespace BMESH; template<class ANCHOR, class LEAF, int cycle_tag> typename ELEMENT_CYCLE<ANCHOR,LEAF,cycle_tag>::T_LINK* ELEMENT_CYCLE<ANCHOR,LEAF,cycle_tag>::get_cycle_link( LEAF l, ANCHOR a ) { T_LINK* dl; if( l->vertex1 == a ) {// Are we the first vertex? dl = &(l->v1_disk_cycle); } else if( l->vertex2 == a ) {// Are we the second vertex? dl = &(l->v2_disk_cycle); } else{ // Oops. We aren't associated with this vertex. Big Problem. throw BMeshError( "Vertex-Edge mismatch during DISK_CYCLE::get_cycle_link" ); } return dl; } template<class ANCHOR, class LEAF, int cycle_tag> LEAF ELEMENT_CYCLE<ANCHOR,LEAF,cycle_tag>::next( ANCHOR a, LEAF l, bool nothrow){ LEAF next_edge; if( !(a == l->vertex1 || a == l->vertex2) ) throw BMeshError( "Vertex-Edge mismatch during DISK_CYCLE::next" ); if( a == l->vertex1 ) next_edge = l->v1_disk_cycle.next; if( a == l->vertex2 ) next_edge = l->v2_disk_cycle.next; if( next_edge == NULL && !nothrow) throw BMeshError( "Broken cycle detected during DISK_CYCLE::next" ); return next_edge; } template<class ANCHOR, class LEAF, int cycle_tag> LEAF ELEMENT_CYCLE<ANCHOR,LEAF,cycle_tag>::prev( ANCHOR a, LEAF l, bool nothrow){ LEAF prev_edge; if( !(a == l->vertex1 || a == l->vertex2) ) throw BMeshError( "Vertex-Edge mismatch during DISK_CYCLE::next" ); if( a == l->vertex1 ) prev_edge = l->v1_disk_cycle.prev; if( a == l->vertex2 ) prev_edge = l->v2_disk_cycle.prev; if( prev_edge == NULL && !nothrow) throw BMeshError( "Broken cycle detected during DISK_CYCLE::prev" ); return prev_edge; } template<class ANCHOR, class LEAF, int cycle_tag> bool ELEMENT_CYCLE<ANCHOR,LEAF,cycle_tag>::validate( ANCHOR a ){ if( a->base == NULL ) // this may be a problem. but from the anchor's perpective, its fine return true; // Now that we have a base, traverse the cycle. We should not encounter any dead ends, and each // component should point to the anchor. LEAF current = a->base; do{ if( !(current->vertex1 == a || current->vertex2 == a) ) throw BMeshError( "Broken link between Vertex/Edge during DISK_CYCLE::validate" ); if( current->vertex1 == current->vertex2 ) throw BMeshError( "Edge points to vertex twice during DISK_CYCLE::validate" ); current = next( a, current, false ); if( current == NULL ) throw BMeshError( "Cycle dead-ends during DISK_CYCLE::validate" ); }while( current != a->base ); // Continue until we reach the base again return true; } // Disk Cycle template struct ELEMENT_CYCLE< BMeshPolicy<float, 2>::T_VERT_PTR,BMeshPolicy<float, 2>::T_EDGE_PTR, DISK_CYCLE_T>; template struct ELEMENT_CYCLE< BMeshPolicy<float, 3>::T_VERT_PTR,BMeshPolicy<float, 3>::T_EDGE_PTR, DISK_CYCLE_T>; template struct ELEMENT_CYCLE< BMeshPolicy<double, 2>::T_VERT_PTR,BMeshPolicy<double, 2>::T_EDGE_PTR, DISK_CYCLE_T>; template struct ELEMENT_CYCLE< BMeshPolicy<double, 3>::T_VERT_PTR,BMeshPolicy<double, 3>::T_EDGE_PTR, DISK_CYCLE_T>;
[ "nmitchel@cs.wisc.edu" ]
nmitchel@cs.wisc.edu
ae0f8d3f2a7b4fdd3d8d3b12a2959c64684c7c3b
e53074d668e8eea241e2afa5aa42890bedb78cd9
/Project1/Project1/Source/Application.h
7b07c45faf8da346f7668550c9947d3082765525
[]
no_license
ReU1107/Project1
9f1e2ab128744c321f56219679cdb2a33072dd9f
dfae75c51981c29a5a578b1e754524476d1a6809
refs/heads/master
2020-12-26T19:13:20.864694
2020-10-29T11:51:13
2020-10-29T11:51:13
237,610,628
1
0
null
null
null
null
UTF-8
C++
false
false
48
h
#pragma once class Application { private: };
[ "reu1107@yahoo.co.jp" ]
reu1107@yahoo.co.jp
645d956a425b429a50469d4cf457de7697f519e9
9b83b05ee31f55a80706730394dc6e54456d6634
/src/plugins/qmldesigner/components/navigator/navigatorview.cpp
e1702bdac469034dedb73ac93072657ec4db4dc3
[]
no_license
nahongyan/QtCreator
c49f6782f7407233abdb96f5cec823e855550f0a
a8a361f6057d3f79bd0ba05575e2958d498a7e14
refs/heads/master
2023-01-24T21:46:18.797698
2020-12-01T12:03:24
2020-12-01T12:03:24
317,527,105
2
1
null
null
null
null
UTF-8
C++
false
false
24,776
cpp
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #include "navigatorview.h" #include "navigatortreemodel.h" #include "navigatorwidget.h" #include "qmldesignerconstants.h" #include "qmldesignericons.h" #include "nameitemdelegate.h" #include "iconcheckboxitemdelegate.h" #include <bindingproperty.h> #include <designmodecontext.h> #include <designersettings.h> #include <nodeproperty.h> #include <nodelistproperty.h> #include <variantproperty.h> #include <qmlitemnode.h> #include <rewritingexception.h> #include <nodeinstanceview.h> #include <theme.h> #include <coreplugin/editormanager/editormanager.h> #include <coreplugin/icore.h> #include <utils/algorithm.h> #include <utils/icon.h> #include <utils/utilsicons.h> #include <utils/stylehelper.h> #include <QHeaderView> #include <QTimer> #include <QPixmap> static inline void setScenePos(const QmlDesigner::ModelNode &modelNode,const QPointF &pos) { if (modelNode.hasParentProperty() && QmlDesigner::QmlItemNode::isValidQmlItemNode(modelNode.parentProperty().parentModelNode())) { QmlDesigner::QmlItemNode parentNode = modelNode.parentProperty().parentQmlObjectNode().toQmlItemNode(); if (!parentNode.modelNode().metaInfo().isLayoutable()) { QPointF localPos = parentNode.instanceSceneTransform().inverted().map(pos); modelNode.variantProperty("x").setValue(localPos.toPoint().x()); modelNode.variantProperty("y").setValue(localPos.toPoint().y()); } else { //Items in Layouts do not have a position modelNode.removeProperty("x"); modelNode.removeProperty("y"); } } } static inline void moveNodesUp(const QList<QmlDesigner::ModelNode> &nodes) { for (const auto &node : nodes) { if (!node.isRootNode() && node.parentProperty().isNodeListProperty()) { int oldIndex = node.parentProperty().indexOf(node); int index = oldIndex; index--; if (index < 0) index = node.parentProperty().count() - 1; //wrap around if (oldIndex != index) node.parentProperty().toNodeListProperty().slide(oldIndex, index); } } } static inline void moveNodesDown(const QList<QmlDesigner::ModelNode> &nodes) { for (const auto &node : nodes) { if (!node.isRootNode() && node.parentProperty().isNodeListProperty()) { int oldIndex = node.parentProperty().indexOf(node); int index = oldIndex; index++; if (index >= node.parentProperty().count()) index = 0; //wrap around if (oldIndex != index) node.parentProperty().toNodeListProperty().slide(oldIndex, index); } } } namespace QmlDesigner { NavigatorView::NavigatorView(QObject* parent) : AbstractView(parent), m_blockSelectionChangedSignal(false) { } NavigatorView::~NavigatorView() { if (m_widget && !m_widget->parent()) delete m_widget.data(); } bool NavigatorView::hasWidget() const { return true; } WidgetInfo NavigatorView::widgetInfo() { if (!m_widget) setupWidget(); return createWidgetInfo(m_widget.data(), new WidgetInfo::ToolBarWidgetDefaultFactory<NavigatorWidget>(m_widget.data()), QStringLiteral("Navigator"), WidgetInfo::LeftPane, 0, tr("Navigator")); } void NavigatorView::modelAttached(Model *model) { AbstractView::modelAttached(model); QTreeView *treeView = treeWidget(); treeView->header()->setSectionResizeMode(NavigatorTreeModel::ColumnType::Name, QHeaderView::Stretch); treeView->header()->resizeSection(NavigatorTreeModel::ColumnType::Alias, 26); treeView->header()->resizeSection(NavigatorTreeModel::ColumnType::Visibility, 26); treeView->header()->resizeSection(NavigatorTreeModel::ColumnType::Lock, 26); treeView->setIndentation(20); m_currentModelInterface->setFilter(false); QTimer::singleShot(0, this, [this, treeView]() { m_currentModelInterface->setFilter( DesignerSettings::getValue(DesignerSettingsKey::NAVIGATOR_SHOW_ONLY_VISIBLE_ITEMS).toBool()); m_currentModelInterface->setOrder( DesignerSettings::getValue(DesignerSettingsKey::NAVIGATOR_REVERSE_ITEM_ORDER).toBool()); // Expand everything to begin with to ensure model node to index cache is populated treeView->expandAll(); if (AbstractView::model() && m_expandMap.contains(AbstractView::model()->fileUrl())) { const QHash<QString, bool> localExpandMap = m_expandMap[AbstractView::model()->fileUrl()]; auto it = localExpandMap.constBegin(); while (it != localExpandMap.constEnd()) { const QModelIndex index = indexForModelNode(modelNodeForId(it.key())); if (index.isValid()) treeWidget()->setExpanded(index, it.value()); ++it; } } }); } void NavigatorView::modelAboutToBeDetached(Model *model) { m_expandMap.remove(model->fileUrl()); if (currentModel()) { // Store expand state of the navigator tree QHash<QString, bool> localExpandMap; const ModelNode rootNode = rootModelNode(); const QModelIndex rootIndex = indexForModelNode(rootNode); std::function<void(const QModelIndex &)> gatherExpandedState; gatherExpandedState = [&](const QModelIndex &index) { if (index.isValid()) { const int rowCount = currentModel()->rowCount(index); for (int i = 0; i < rowCount; ++i) { const QModelIndex childIndex = currentModel()->index(i, 0, index); const ModelNode node = modelNodeForIndex(childIndex); // Just store collapsed states as everything is expanded by default if (node.isValid() && !treeWidget()->isExpanded(childIndex)) localExpandMap.insert(node.id(), false); gatherExpandedState(childIndex); } } }; gatherExpandedState(rootIndex); m_expandMap[model->fileUrl()] = localExpandMap; } AbstractView::modelAboutToBeDetached(model); } void NavigatorView::importsChanged(const QList<Import> &/*addedImports*/, const QList<Import> &/*removedImports*/) { treeWidget()->update(); } void NavigatorView::bindingPropertiesChanged(const QList<BindingProperty> & propertyList, PropertyChangeFlags /*propertyChange*/) { for (const BindingProperty &bindingProperty : propertyList) { /* If a binding property that exports an item using an alias property has * changed, we have to update the affected item. */ if (bindingProperty.isAliasExport()) m_currentModelInterface->notifyDataChanged(modelNodeForId(bindingProperty.expression())); } } void NavigatorView::customNotification(const AbstractView *view, const QString &identifier, const QList<ModelNode> &nodeList, const QList<QVariant> &data) { Q_UNUSED(view) Q_UNUSED(nodeList) Q_UNUSED(data) if (identifier == "asset_import_update") m_currentModelInterface->notifyIconsChanged(); } void NavigatorView::handleChangedExport(const ModelNode &modelNode, bool exported) { const ModelNode rootNode = rootModelNode(); Q_ASSERT(rootNode.isValid()); const PropertyName modelNodeId = modelNode.id().toUtf8(); if (rootNode.hasProperty(modelNodeId)) rootNode.removeProperty(modelNodeId); if (exported) { executeInTransaction("NavigatorTreeModel:exportItem", [modelNode](){ QmlObjectNode qmlObjectNode(modelNode); qmlObjectNode.ensureAliasExport(); }); } } bool NavigatorView::isNodeInvisible(const ModelNode &modelNode) const { return QmlVisualNode(modelNode).visibilityOverride(); } void NavigatorView::disableWidget() { if (m_widget) m_widget->disableNavigator(); } void NavigatorView::enableWidget() { if (m_widget) m_widget->enableNavigator(); } void NavigatorView::modelNodePreviewPixmapChanged(const ModelNode &node, const QPixmap &pixmap) { m_treeModel->updateToolTipPixmap(node, pixmap); } ModelNode NavigatorView::modelNodeForIndex(const QModelIndex &modelIndex) const { return modelIndex.model()->data(modelIndex, ModelNodeRole).value<ModelNode>(); } void NavigatorView::nodeAboutToBeRemoved(const ModelNode & /*removedNode*/) { } void NavigatorView::nodeRemoved(const ModelNode &removedNode, const NodeAbstractProperty & /*parentProperty*/, AbstractView::PropertyChangeFlags /*propertyChange*/) { m_currentModelInterface->notifyModelNodesRemoved({removedNode}); } void NavigatorView::nodeReparented(const ModelNode &modelNode, const NodeAbstractProperty & /*newPropertyParent*/, const NodeAbstractProperty & oldPropertyParent, AbstractView::PropertyChangeFlags /*propertyChange*/) { if (!oldPropertyParent.isValid()) m_currentModelInterface->notifyModelNodesInserted({modelNode}); else m_currentModelInterface->notifyModelNodesMoved({modelNode}); treeWidget()->expand(indexForModelNode(modelNode)); // make sure selection is in sync again QTimer::singleShot(0, this, &NavigatorView::updateItemSelection); } void NavigatorView::nodeIdChanged(const ModelNode& modelNode, const QString & /*newId*/, const QString & /*oldId*/) { m_currentModelInterface->notifyDataChanged(modelNode); } void NavigatorView::propertiesAboutToBeRemoved(const QList<AbstractProperty> &/*propertyList*/) { } void NavigatorView::propertiesRemoved(const QList<AbstractProperty> &propertyList) { QList<ModelNode> modelNodes; for (const AbstractProperty &property : propertyList) { if (property.isNodeAbstractProperty()) { NodeAbstractProperty nodeAbstractProperty(property.toNodeListProperty()); modelNodes.append(nodeAbstractProperty.directSubNodes()); } } m_currentModelInterface->notifyModelNodesRemoved(modelNodes); } void NavigatorView::rootNodeTypeChanged(const QString &/*type*/, int /*majorVersion*/, int /*minorVersion*/) { m_currentModelInterface->notifyDataChanged(rootModelNode()); } void NavigatorView::nodeTypeChanged(const ModelNode &modelNode, const TypeName &, int , int) { m_currentModelInterface->notifyDataChanged(modelNode); } void NavigatorView::auxiliaryDataChanged(const ModelNode &modelNode, const PropertyName &name, const QVariant &data) { Q_UNUSED(name) Q_UNUSED(data) m_currentModelInterface->notifyDataChanged(modelNode); } void NavigatorView::instanceErrorChanged(const QVector<ModelNode> &errorNodeList) { for (const ModelNode &modelNode : errorNodeList) m_currentModelInterface->notifyDataChanged(modelNode); } void NavigatorView::nodeOrderChanged(const NodeListProperty &listProperty, const ModelNode &/*node*/, int /*oldIndex*/) { m_currentModelInterface->notifyModelNodesMoved(listProperty.directSubNodes()); // make sure selection is in sync again QTimer::singleShot(0, this, &NavigatorView::updateItemSelection); } void NavigatorView::changeToComponent(const QModelIndex &index) { if (index.isValid() && currentModel()->data(index, Qt::UserRole).isValid()) { const ModelNode doubleClickNode = modelNodeForIndex(index); if (doubleClickNode.metaInfo().isFileComponent()) Core::EditorManager::openEditor(doubleClickNode.metaInfo().componentFileName(), Utils::Id(), Core::EditorManager::DoNotMakeVisible); } } QModelIndex NavigatorView::indexForModelNode(const ModelNode &modelNode) const { return m_currentModelInterface->indexForModelNode(modelNode); } QAbstractItemModel *NavigatorView::currentModel() const { return treeWidget()->model(); } void NavigatorView::leftButtonClicked() { if (selectedModelNodes().count() > 1) return; //Semantics are unclear for multi selection. bool blocked = blockSelectionChangedSignal(true); for (const ModelNode &node : selectedModelNodes()) { if (!node.isRootNode() && !node.parentProperty().parentModelNode().isRootNode()) { if (QmlItemNode::isValidQmlItemNode(node)) { QPointF scenePos = QmlItemNode(node).instanceScenePosition(); reparentAndCatch(node.parentProperty().parentProperty(), node); if (!scenePos.isNull()) setScenePos(node, scenePos); } else { reparentAndCatch(node.parentProperty().parentProperty(), node); } } } updateItemSelection(); blockSelectionChangedSignal(blocked); } void NavigatorView::rightButtonClicked() { if (selectedModelNodes().count() > 1) return; //Semantics are unclear for multi selection. bool blocked = blockSelectionChangedSignal(true); bool reverse = DesignerSettings::getValue(DesignerSettingsKey::NAVIGATOR_REVERSE_ITEM_ORDER).toBool(); for (const ModelNode &node : selectedModelNodes()) { if (!node.isRootNode() && node.parentProperty().isNodeListProperty() && node.parentProperty().count() > 1) { int index = node.parentProperty().indexOf(node); bool indexOk = false; if (reverse) { index++; indexOk = (index < node.parentProperty().count()); } else { index--; indexOk = (index >= 0); } if (indexOk) { //for the first node the semantics are not clear enough. Wrapping would be irritating. ModelNode newParent = node.parentProperty().toNodeListProperty().at(index); if (QmlItemNode::isValidQmlItemNode(node) && QmlItemNode::isValidQmlItemNode(newParent) && !newParent.metaInfo().defaultPropertyIsComponent()) { QPointF scenePos = QmlItemNode(node).instanceScenePosition(); reparentAndCatch(newParent.nodeAbstractProperty(newParent.metaInfo().defaultPropertyName()), node); if (!scenePos.isNull()) setScenePos(node, scenePos); } else { if (newParent.metaInfo().isValid() && !newParent.metaInfo().defaultPropertyIsComponent()) reparentAndCatch(newParent.nodeAbstractProperty(newParent.metaInfo().defaultPropertyName()), node); } } } } updateItemSelection(); blockSelectionChangedSignal(blocked); } void NavigatorView::upButtonClicked() { bool blocked = blockSelectionChangedSignal(true); bool reverse = DesignerSettings::getValue(DesignerSettingsKey::NAVIGATOR_REVERSE_ITEM_ORDER).toBool(); if (reverse) moveNodesDown(selectedModelNodes()); else moveNodesUp(selectedModelNodes()); updateItemSelection(); blockSelectionChangedSignal(blocked); } void NavigatorView::downButtonClicked() { bool blocked = blockSelectionChangedSignal(true); bool reverse = DesignerSettings::getValue(DesignerSettingsKey::NAVIGATOR_REVERSE_ITEM_ORDER).toBool(); if (reverse) moveNodesUp(selectedModelNodes()); else moveNodesDown(selectedModelNodes()); updateItemSelection(); blockSelectionChangedSignal(blocked); } void NavigatorView::filterToggled(bool flag) { m_currentModelInterface->setFilter(flag); treeWidget()->expandAll(); DesignerSettings::setValue(DesignerSettingsKey::NAVIGATOR_SHOW_ONLY_VISIBLE_ITEMS, flag); } void NavigatorView::reverseOrderToggled(bool flag) { m_currentModelInterface->setOrder(flag); treeWidget()->expandAll(); DesignerSettings::setValue(DesignerSettingsKey::NAVIGATOR_REVERSE_ITEM_ORDER, flag); } void NavigatorView::changeSelection(const QItemSelection & /*newSelection*/, const QItemSelection &/*deselected*/) { if (m_blockSelectionChangedSignal) return; QSet<ModelNode> nodeSet; for (const QModelIndex &index : treeWidget()->selectionModel()->selectedIndexes()) { const ModelNode modelNode = modelNodeForIndex(index); if (modelNode.isValid()) nodeSet.insert(modelNode); } bool blocked = blockSelectionChangedSignal(true); setSelectedModelNodes(Utils::toList(nodeSet)); blockSelectionChangedSignal(blocked); } void NavigatorView::selectedNodesChanged(const QList<ModelNode> &/*selectedNodeList*/, const QList<ModelNode> &/*lastSelectedNodeList*/) { // Update selection asynchronously to ensure NavigatorTreeModel's index cache is up to date QTimer::singleShot(0, this, &NavigatorView::updateItemSelection); } void NavigatorView::updateItemSelection() { if (!isAttached()) return; QItemSelection itemSelection; for (const ModelNode &node : selectedModelNodes()) { const QModelIndex index = indexForModelNode(node); if (index.isValid()) { const QModelIndex beginIndex(currentModel()->index(index.row(), 0, index.parent())); const QModelIndex endIndex(currentModel()->index(index.row(), currentModel()->columnCount(index.parent()) - 1, index.parent())); if (beginIndex.isValid() && endIndex.isValid()) itemSelection.select(beginIndex, endIndex); } else { // if the node index is invalid expand ancestors manually if they are valid. ModelNode parentNode = node; while (parentNode.hasParentProperty()) { parentNode = parentNode.parentProperty().parentQmlObjectNode(); QModelIndex parentIndex = indexForModelNode(parentNode); if (parentIndex.isValid()) treeWidget()->expand(parentIndex); else break; } } } bool blocked = blockSelectionChangedSignal(true); treeWidget()->selectionModel()->select(itemSelection, QItemSelectionModel::ClearAndSelect); blockSelectionChangedSignal(blocked); if (!selectedModelNodes().isEmpty()) treeWidget()->scrollTo(indexForModelNode(selectedModelNodes().constFirst())); // make sure selected nodes are visible for (const QModelIndex &selectedIndex : itemSelection.indexes()) { if (selectedIndex.column() == 0) expandAncestors(selectedIndex); } } QTreeView *NavigatorView::treeWidget() const { if (m_widget) return m_widget->treeView(); return nullptr; } NavigatorTreeModel *NavigatorView::treeModel() { return m_treeModel.data(); } // along the lines of QObject::blockSignals bool NavigatorView::blockSelectionChangedSignal(bool block) { bool oldValue = m_blockSelectionChangedSignal; m_blockSelectionChangedSignal = block; return oldValue; } void NavigatorView::expandAncestors(const QModelIndex &index) { QModelIndex currentIndex = index.parent(); while (currentIndex.isValid()) { if (!treeWidget()->isExpanded(currentIndex)) treeWidget()->expand(currentIndex); currentIndex = currentIndex.parent(); } } void NavigatorView::reparentAndCatch(NodeAbstractProperty property, const ModelNode &modelNode) { try { property.reparentHere(modelNode); } catch (Exception &exception) { exception.showException(); } } void NavigatorView::setupWidget() { m_widget = new NavigatorWidget(this); m_treeModel = new NavigatorTreeModel(this); #ifndef QMLDESIGNER_TEST auto navigatorContext = new Internal::NavigatorContext(m_widget.data()); Core::ICore::addContextObject(navigatorContext); #endif m_treeModel->setView(this); m_widget->setTreeModel(m_treeModel.data()); m_currentModelInterface = m_treeModel; connect(treeWidget()->selectionModel(), &QItemSelectionModel::selectionChanged, this, &NavigatorView::changeSelection); connect(m_widget.data(), &NavigatorWidget::leftButtonClicked, this, &NavigatorView::leftButtonClicked); connect(m_widget.data(), &NavigatorWidget::rightButtonClicked, this, &NavigatorView::rightButtonClicked); connect(m_widget.data(), &NavigatorWidget::downButtonClicked, this, &NavigatorView::downButtonClicked); connect(m_widget.data(), &NavigatorWidget::upButtonClicked, this, &NavigatorView::upButtonClicked); connect(m_widget.data(), &NavigatorWidget::filterToggled, this, &NavigatorView::filterToggled); connect(m_widget.data(), &NavigatorWidget::reverseOrderToggled, this, &NavigatorView::reverseOrderToggled); #ifndef QMLDESIGNER_TEST const QString fontName = "qtds_propertyIconFont.ttf"; const QIcon visibilityOnIcon = Utils::StyleHelper::getIconFromIconFont(fontName, Theme::getIconUnicode(Theme::Icon::visibilityOn), 28, 28, QColor(Qt::white)); const QIcon visibilityOffIcon = Utils::StyleHelper::getIconFromIconFont(fontName, Theme::getIconUnicode(Theme::Icon::visibilityOff), 28, 28, QColor(Qt::white)); const QIcon aliasOnIcon = Utils::StyleHelper::getIconFromIconFont(fontName, Theme::getIconUnicode(Theme::Icon::idAliasOn), 28, 28, QColor(Qt::red)); const QIcon aliasOffIcon = Utils::StyleHelper::getIconFromIconFont(fontName, Theme::getIconUnicode(Theme::Icon::idAliasOff), 28, 28, QColor(Qt::white)); const QIcon lockOnIcon = Utils::StyleHelper::getIconFromIconFont(fontName, Theme::getIconUnicode(Theme::Icon::lockOn), 28, 28, QColor(Qt::white)); const QIcon lockOffIcon = Utils::StyleHelper::getIconFromIconFont(fontName, Theme::getIconUnicode(Theme::Icon::lockOff), 28, 28, QColor(Qt::white)); auto idDelegate = new NameItemDelegate(this); IconCheckboxItemDelegate *visibilityDelegate = new IconCheckboxItemDelegate(this, visibilityOnIcon, visibilityOffIcon); IconCheckboxItemDelegate *aliasDelegate = new IconCheckboxItemDelegate(this, aliasOnIcon, aliasOffIcon); IconCheckboxItemDelegate *lockDelegate = new IconCheckboxItemDelegate(this, lockOnIcon, lockOffIcon); treeWidget()->setItemDelegateForColumn(NavigatorTreeModel::ColumnType::Name, idDelegate); treeWidget()->setItemDelegateForColumn(NavigatorTreeModel::ColumnType::Alias, aliasDelegate); treeWidget()->setItemDelegateForColumn(NavigatorTreeModel::ColumnType::Visibility, visibilityDelegate); treeWidget()->setItemDelegateForColumn(NavigatorTreeModel::ColumnType::Lock, lockDelegate); #endif //QMLDESIGNER_TEST } } // namespace QmlDesigner
[ "2468254048@qq.com" ]
2468254048@qq.com
affa6c1d5477670c12fb3cc065725c490e6f0341
2abd1954c2c75773eaedd94b2f8c2df8774331aa
/src/qt/darksendconfig.cpp
2ae36fa7eb08a066902a459ad96029be6049be8b
[ "MIT" ]
permissive
Schumbatin/TheBestBits
e9395fe6b2d2f2c57516efded4a710c401bcb4d3
cdd8c6c8c7230c157721efea325d596f970ecf41
refs/heads/master
2020-05-14T23:37:00.393884
2018-04-24T12:07:08
2018-04-24T12:07:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,435
cpp
#include "darksendconfig.h" #include "ui_darksendconfig.h" #include "bitcoinunits.h" #include "guiconstants.h" #include "optionsmodel.h" #include "walletmodel.h" #include "init.h" #include <QMessageBox> #include <QPushButton> #include <QKeyEvent> #include <QSettings> DarksendConfig::DarksendConfig(QWidget *parent) : QDialog(parent), ui(new Ui::DarksendConfig), model(0) { ui->setupUi(this); connect(ui->buttonBasic, SIGNAL(clicked()), this, SLOT(clickBasic())); connect(ui->buttonHigh, SIGNAL(clicked()), this, SLOT(clickHigh())); connect(ui->buttonMax, SIGNAL(clicked()), this, SLOT(clickMax())); } DarksendConfig::~DarksendConfig() { delete ui; } void DarksendConfig::setModel(WalletModel *model) { this->model = model; } void DarksendConfig::clickBasic() { configure(true, 1000, 2); QString strAmount(BitcoinUnits::formatWithUnit( model->getOptionsModel()->getDisplayUnit(), 1000 * COIN)); QMessageBox::information(this, tr("Darksend Configuration"), tr( "Darksend was successfully set to basic (%1 and 2 rounds). You can change this at any time by opening TheBestBits's configuration screen." ).arg(strAmount) ); close(); } void DarksendConfig::clickHigh() { configure(true, 1000, 8); QString strAmount(BitcoinUnits::formatWithUnit( model->getOptionsModel()->getDisplayUnit(), 1000 * COIN)); QMessageBox::information(this, tr("Darksend Configuration"), tr( "Darksend was successfully set to high (%1 and 8 rounds). You can change this at any time by opening TheBestBits's configuration screen." ).arg(strAmount) ); close(); } void DarksendConfig::clickMax() { configure(true, 1000, 16); QString strAmount(BitcoinUnits::formatWithUnit( model->getOptionsModel()->getDisplayUnit(), 1000 * COIN)); QMessageBox::information(this, tr("Darksend Configuration"), tr( "Darksend was successfully set to maximum (%1 and 16 rounds). You can change this at any time by opening Bitcoin's configuration screen." ).arg(strAmount) ); close(); } void DarksendConfig::configure(bool enabled, int coins, int rounds) { QSettings settings; settings.setValue("nDarksendRounds", rounds); settings.setValue("nAnonymizeTheBestBitsAmount", coins); nDarksendRounds = rounds; nAnonymizeTheBestBitsAmount = coins; }
[ "frenzel1337@mail.com" ]
frenzel1337@mail.com
5449dd1a7efdc44d9f61a8482b519aee7108363d
d4821a27d1efe7da71f09de38892d7a81c2039c9
/QtHelloShader/myglwidget.h
5de589b2dd225446d49d264953ebb44c52c85af1
[]
no_license
youngsikshin/SampleCode
f99935b25ac9a826dcec3feca36b9572282186dc
fb35dbbda763c61162c9773db260d1307ac25c3e
refs/heads/master
2021-01-12T14:26:16.185610
2017-01-11T16:54:30
2017-01-11T16:54:30
70,061,346
0
0
null
null
null
null
UTF-8
C++
false
false
554
h
#ifndef MYGLWIDGET_H #define MYGLWIDGET_H #include <QGLWidget> #include <QVector> #include <QGLShaderProgram> class MyGLWidget : public QGLWidget { Q_OBJECT public: explicit MyGLWidget(QWidget *parent = 0); ~MyGLWidget(); signals: public slots: protected: void initializeGL(); void paintGL(); void resizeGL(int width, int height); QSize minimumSizeHint() const; QSize sizeHint() const; private: QMatrix4x4 pMatrix; QGLShaderProgram shaderProgram; QVector<QVector3D> vertices; }; #endif // MYGLWIDGET_H
[ "bluevow@gmail.com" ]
bluevow@gmail.com
a0ff24dae96753d02a6b5a87eff449cde93c9c6c
afc6d75c33888d5e80b8fae850c2c867df8ac092
/Pascal's Triangle/main.cc
d5d46966c561de71b95852dc2546705e9646cac8
[]
no_license
srhodes9115/C-Plus-Plus-Work
98483d5de38b9c62916ebe30816e651c3d185498
0e83fafbd19304879c2e09d5557d124b800de2d0
refs/heads/master
2020-06-08T05:27:12.925159
2015-07-17T02:33:27
2015-07-17T02:33:27
39,230,851
0
0
null
null
null
null
UTF-8
C++
false
false
630
cc
// Shannon Rhodes // HW1 // ECE 2620 - Pascal's triangle #include <iostream> #include <stdio.h> double factorial (double n) { int solution; for (int i = 0; i <= n; i++) { if (i == 0) solution = 1; else solution = solution*i; } return solution; } double pascal_triangle (int n, int p) { int triangle = 0; triangle = factorial(n)/(factorial(p)*factorial(n-p)); return triangle; } int main() { //n is the row #, p is the column number for (int n = 0,num = 15; n <= num; n++) { for (int p = 0; p <= n; p++) { printf ("%f",pascal_triangle(n,p)); } printf ("\n"); } }
[ "srhodes91115@gmail.com" ]
srhodes91115@gmail.com
4fb7e7a6ae9de5ba955df8dfefb98b56e483152e
a55c8a91c02d76bfe32fedb291b46f950a51e0a4
/home/arimase/Desktop/ICS Lab/Lab 2/data_make.cpp
0365d529280e5b2fb3494e585c82ec27691cc52f
[]
no_license
M-Arimase/School-Project
041e971b841bfae8d35c0c83bb801114f1f3a1a5
a780121bcddbceb8888a589ec72fffafd7958167
refs/heads/master
2021-01-19T05:38:55.454194
2017-11-22T03:57:14
2017-11-22T03:57:14
87,435,407
0
1
null
null
null
null
UTF-8
C++
false
false
194
cpp
#include <cstdio> using namespace std; int main() { freopen("input.in.bak", "w", stdout); char s[6] = {1, 4, 5, 7, 11, 12}; for (int i = 0; i < 6; i++) printf("%c", s[i]); return 0; }
[ "zyk@pku.edu.cn" ]
zyk@pku.edu.cn
988c9684194a229d8e11d15cf5e8fbff2d7f53dc
8305029035791d1c7a8596412c34af80993598cd
/cnn/nodes-common.cc
2ab0b9775cb6f95f47605618523a3932d00b5357
[]
no_license
jizhihang/CNN_for_VS
6e2a6a02f01118828bb351617b4ca7664ce9518e
d98010fdc68ec637087ed37ee05eee4d5b6b8930
refs/heads/master
2020-03-18T00:46:39.517935
2015-12-22T10:16:35
2015-12-22T10:16:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,590
cc
#include "nodes.h" #include <limits> #include <cmath> #include <sstream> using namespace std; namespace cnn { inline bool LooksLikeVector(const Dim& d) { if (d.ndims() == 1) return true; if (d.ndims() > 1) { for (unsigned i = 1; i < d.ndims(); ++i) if (d[i] != 1) return false; } return true; } string Min::as_string(const vector<string>& arg_names) const { ostringstream s; s << "min{" << arg_names[0] << ", " << arg_names[1] << "}"; return s.str(); } Dim Min::dim_forward(const vector<Dim>& xs) const { if (xs.size() != 2 || xs[0] != xs[1]) { cerr << "Bad arguments in Min: " << xs << endl; throw std::invalid_argument("invalid arguments to Min"); } return xs[0].bd >= xs[1].bd ? xs[0] : xs[1]; } string Max::as_string(const vector<string>& arg_names) const { ostringstream s; s << "max{" << arg_names[0] << ", " << arg_names[1] << "}"; return s.str(); } Dim Max::dim_forward(const vector<Dim>& xs) const { if (xs.size() != 2 || xs[0] != xs[1]) { cerr << "Bad arguments in Max: " << xs << endl; throw std::invalid_argument("invalid arguments to Max"); } return xs[0].bd >= xs[1].bd ? xs[0] : xs[1]; } string TraceOfProduct::as_string(const vector<string>& arg_names) const { ostringstream s; s << "Tr(" << arg_names[0] << " * " << arg_names[1] << "^T)"; return s.str(); } Dim TraceOfProduct::dim_forward(const vector<Dim>& xs) const { if (xs.size() != 2 || xs[0] != xs[1]) { cerr << "Bad arguments in TraceOfProduct: " << xs << endl; throw std::invalid_argument("invalid arguments to TraceOfProduct"); } return Dim({1}, max(xs[0].bd, xs[1].bd)); } string ConstScalarMultiply::as_string(const vector<string>& arg_names) const { ostringstream s; s << arg_names[0] << " * " << alpha; return s.str(); } Dim ConstScalarMultiply::dim_forward(const vector<Dim>& xs) const { if (xs.size() != 1) { cerr << "ConstScalarMultiply expects one argument: " << xs << endl; throw std::invalid_argument("ConstScalarMultiply expects one argument"); } return xs[0]; } string DotProduct::as_string(const vector<string>& arg_names) const { ostringstream s; s << arg_names[0] << "^T . " << arg_names[1]; return s.str(); } Dim DotProduct::dim_forward(const vector<Dim>& xs) const { if (xs.size() != 2 || !LooksLikeVector(xs[0]) || !LooksLikeVector(xs[1]) || xs[0].rows() != xs[1].rows()) { cerr << "Bad arguments to DotProduct: " << xs << endl; throw std::invalid_argument("Bad arguments to DotProduct"); } return Dim({1}, max(xs[0].bd, xs[1].bd)); } string Transpose::as_string(const vector<string>& arg_names) const { ostringstream s; s << arg_names[0] << "^T"; return s.str(); } Dim Transpose::dim_forward(const vector<Dim>& xs) const { if (xs.size() != 1) { cerr << "Bad arguments to Transpose: " << xs << endl; throw std::invalid_argument("Bad arguments to Transpose"); } return xs[0].transpose(); } string Reshape::as_string(const vector<string>& arg_names) const { ostringstream s; s << "reshape(" << arg_names[0] << " --> " << to << ')'; return s.str(); } Dim Reshape::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 1); assert(xs[0].size() == to.size()); return to; } string SumColumns::as_string(const vector<string>& arg_names) const { ostringstream s; s << "sum_cols(matrix=" << arg_names[0]; if (arg_names.size() == 2) s << ", col_weighting=" << arg_names[1]; s << ')'; return s.str(); } Dim SumColumns::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 1 || xs.size() == 2); int bd = (xs.size() == 1 ? xs[0].bd : max(xs[0].bd, xs[1].bd)); return Dim({xs[0].rows()}, bd); } string KMHNGram::as_string(const vector<string>& arg_names) const { ostringstream s; s << "kmh-ngram(" << arg_names[0] << ')'; return s.str(); } Dim KMHNGram::dim_forward(const vector<Dim>& xs) const { assert(xs[0].ndims() == 2); const unsigned new_cols = xs[0].cols() - n + 1; if (new_cols < 1) { cerr << "Bad input dimensions in KMHNGram: " << xs << endl; abort(); } return Dim({xs[0][0], new_cols}); } string InnerProduct3D_1D::as_string(const vector<string>& arg_names) const { ostringstream s; s << "dot(" << arg_names[0] << "," << arg_names[1] << ')'; if (arg_names.size() == 3) s << " + " << arg_names[2]; return s.str(); } Dim InnerProduct3D_1D::dim_forward(const vector<Dim>& xs) const { if (xs.size() != 2 && xs.size() != 3) { cerr << "Expected two or three arguments in InnerProduct3D_1D\n"; abort(); } if (xs[0].ndims() != 3 || xs[1].ndims() != 1 || xs[0].size(2) != xs[1].size(0)) { cerr << "Bad input dimensions in InnerProduct3D_1D: " << xs << endl; abort(); } Dim d({xs[0].size(0), xs[0].size(1)}, max(xs[0].bd, xs[1].bd)); if(xs.size() == 3) d.bd = max(d.bd, xs[2].bd); if (xs.size() == 3 && xs[2] != d) { cerr << "Bad input dimensions in InnerProduct3D_1D: " << xs << endl; abort(); } return d; } string GaussianNoise::as_string(const vector<string>& arg_names) const { ostringstream s; s << arg_names[0] << " + N(0," << stddev << ')'; return s.str(); } Dim GaussianNoise::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 1); return xs[0]; } string Dropout::as_string(const vector<string>& arg_names) const { ostringstream s; s << "dropout(" << arg_names[0] << ",p=" << p << ')'; return s.str(); } Dim Dropout::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 1); return xs[0]; } string BlockDropout::as_string(const vector<string>& arg_names) const { ostringstream s; s << "block_dropout(" << arg_names[0] << ",dropout_probability=" << dropout_probability << ')'; return s.str(); } Dim BlockDropout::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 1); return xs[0]; } string ConstantPlusX::as_string(const vector<string>& arg_names) const { ostringstream s; s << c << " + " << arg_names[0]; return s.str(); } Dim ConstantPlusX::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 1); return xs[0]; } string ConstantMinusX::as_string(const vector<string>& arg_names) const { ostringstream s; s << c << " - " << arg_names[0]; return s.str(); } Dim ConstantMinusX::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 1); return xs[0]; } string LogSumExp::as_string(const vector<string>& arg_names) const { ostringstream s; s << "log(exp " << arg_names[0]; for (unsigned i = 1; i < arg_names.size(); ++i) s << " + exp " << arg_names[i]; s << ")"; return s.str(); } Dim LogSumExp::dim_forward(const vector<Dim>& xs) const { Dim d = xs[0].truncate(); for (unsigned i = 1; i < xs.size(); ++i) { if (d.single_batch() != xs[i].truncate().single_batch()) { cerr << "Mismatched input dimensions in LogSumExp: " << xs << endl; abort(); } d.bd = max(xs[i].bd, d.bd); } return d; } string Sum::as_string(const vector<string>& arg_names) const { ostringstream s; s << arg_names[0]; for (unsigned i = 1; i < arg_names.size(); ++i) s << " + " << arg_names[i]; return s.str(); } Dim Sum::dim_forward(const vector<Dim>& xs) const { Dim d = xs[0].truncate(); for (unsigned i = 1; i < xs.size(); ++i) { if (d.single_batch() != xs[i].truncate().single_batch()) { cerr << "Mismatched input dimensions in Sum: " << xs << endl; abort(); } d.bd = max(xs[i].bd, d.bd); } return d; } string SumBatches::as_string(const vector<string>& arg_names) const { ostringstream s; s << "sum_batches( " << arg_names[0] << " )"; return s.str(); } Dim SumBatches::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 1); return xs[0].single_batch(); } string Average::as_string(const vector<string>& arg_names) const { ostringstream s; s << "average(" << arg_names[0]; for (unsigned i = 1; i < arg_names.size(); ++i) s << ", " << arg_names[i]; s << ")"; return s.str(); } Dim Average::dim_forward(const vector<Dim>& xs) const { Dim d(xs[0]); for (unsigned i = 1; i < xs.size(); ++i) { if (xs[0].single_batch() != xs[1].single_batch()) { cerr << "Mismatched input dimensions in Average: " << xs << endl; abort(); } d.bd = max(xs[i].bd, d.bd); } return d; } string Tanh::as_string(const vector<string>& arg_names) const { ostringstream s; s << "tanh(" << arg_names[0] << ')'; return s.str(); } Dim Tanh::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 1); return xs[0]; } string Square::as_string(const vector<string>& arg_names) const { ostringstream s; s << "square(" << arg_names[0] << ')'; return s.str(); } Dim Square::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 1); return xs[0]; } string Cube::as_string(const vector<string>& arg_names) const { ostringstream s; s << "cube(" << arg_names[0] << ')'; return s.str(); } Dim Cube::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 1); return xs[0]; } string Exp::as_string(const vector<string>& arg_names) const { ostringstream os; os << "exp(" << arg_names[0] << ')'; return os.str(); } Dim Exp::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 1); return xs[0]; } string Log::as_string(const vector<string>& arg_names) const { ostringstream os; os << "log(" << arg_names[0] << ')'; return os.str(); } Dim Log::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 1); return xs[0]; } string Concatenate::as_string(const vector<string>& arg_names) const { ostringstream os; os << "concat(" << arg_names[0]; for (unsigned i = 1; i < arg_names.size(); ++i) { os << ',' << arg_names[i]; } os << ')'; return os.str(); } Dim Concatenate::dim_forward(const vector<Dim>& xs) const { unsigned new_rows = 0; Dim dr = xs[0]; if (LooksLikeVector(dr)) dr.resize(1); for (auto c : xs) { if (LooksLikeVector(c)) c.resize(1); new_rows += c[0]; dr.set(0, c[0]); if (dr != c) { cerr << "Bad input dimensions in Concatenate: " << xs << endl; abort(); } dr.bd = max(dr.bd, c.bd); } dr.set(0, new_rows); return dr; } string ConcatenateColumns::as_string(const vector<string>& arg_names) const { ostringstream os; os << "concat_cols(" << arg_names[0]; for (unsigned i = 1; i < arg_names.size(); ++i) { os << ',' << arg_names[i]; } os << ')'; return os.str(); } Dim ConcatenateColumns::dim_forward(const vector<Dim>& xs) const { assert(xs.size() > 0); unsigned rows = xs[0][0]; unsigned new_cols = 0; unsigned bd = 1; for (auto& d : xs) { if (d[0] != rows) { cerr << "Bad input dimensions in ConcatenateColumns: " << xs << endl; abort(); } new_cols += d[1]; bd = max(bd, d.bd); } return Dim({rows, new_cols}, bd); } string PairwiseRankLoss::as_string(const vector<string>& arg_names) const { ostringstream os; os << "max(0, " << margin << " - " << arg_names[0] << " + " << arg_names[1] << ')'; return os.str(); } Dim PairwiseRankLoss::dim_forward(const vector<Dim>& xs) const { if (xs.size() != 2 || xs[0] != xs[1] || xs[0].rows() != 1 || (xs[0].ndims() != 1 && xs[0].ndims() != 2)) { cerr << "Bad input dimensions in PairwiseRankLoss: " << xs << endl; abort(); } return xs[0].bd >= xs[1].bd ? xs[0] : xs[1]; } string Hinge::as_string(const vector<string>& arg_names) const { ostringstream os; os << "hinge(" << arg_names[0] << ", pe=" << pelement << ", m=" << margin << ')'; return os.str(); } Dim Hinge::dim_forward(const vector<Dim>& xs) const { if (xs.size() != 1 || !LooksLikeVector(xs[0])) { cerr << "Bad input dimensions in Hinge: " << xs << endl; abort(); } return Dim({1}, xs[0].bd); } string Identity::as_string(const vector<string>& arg_names) const { return arg_names[0]; } Dim Identity::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 1); return xs[0]; } string Softmax::as_string(const vector<string>& arg_names) const { ostringstream s; s << "softmax(" << arg_names[0] << ')'; return s.str(); } Dim Softmax::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 1); if (!LooksLikeVector(xs[0])) { cerr << "Bad input dimensions in Softmax: " << xs << endl; abort(); } return xs[0]; } string SoftSign::as_string(const vector<string>& arg_names) const { ostringstream s; s << "softsign(" << arg_names[0] << ')'; return s.str(); } Dim SoftSign::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 1); if (!LooksLikeVector(xs[0])) { cerr << "Bad input dimensions in Softsign: " << xs << endl; abort(); } return xs[0]; } string PickNegLogSoftmax::as_string(const vector<string>& arg_names) const { ostringstream s; if(pval) { s << "log_softmax(" << arg_names[0] << ")_{" << *pval << '}'; } else { s << "log_softmax(" << arg_names[0] << ")_{"; string sep = ""; for(auto v : *pvals) { s << sep << v; sep = ","; } s << '}'; } return s.str(); } Dim PickNegLogSoftmax::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 1); if (!LooksLikeVector(xs[0])) { cerr << "Bad input dimensions in PickNegLogSoftmax: " << xs << endl; abort(); } return Dim({1}, xs[0].bd); } string LogSoftmax::as_string(const vector<string>& arg_names) const { ostringstream s; s << "log_softmax(" << arg_names[0] << ')'; return s.str(); } Dim LogSoftmax::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 1); if (!LooksLikeVector(xs[0])) { cerr << "Bad input dimensions in LogSoftmax: " << xs << endl; abort(); } return xs[0]; } string RestrictedLogSoftmax::as_string(const vector<string>& arg_names) const { ostringstream s; s << "r_log_softmax(" << arg_names[0] << ')'; return s.str(); } Dim RestrictedLogSoftmax::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 1); if (!LooksLikeVector(xs[0])) { cerr << "Bad input dimensions in RestrictedLogSoftmax: " << xs << endl; abort(); } return xs[0]; } string PickElement::as_string(const vector<string>& arg_names) const { ostringstream s; s << "pick(" << arg_names[0] << ',' << *pval << ')'; return s.str(); } Dim PickElement::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 1); if (!LooksLikeVector(xs[0])) { cerr << "Bad input dimensions in PickElement: " << xs << endl; abort(); } return Dim({1}, xs[0].bd); } // x_1 is a vector // y = (x_1)[start:end] string PickRange::as_string(const vector<string>& arg_names) const { ostringstream s; s << "slice(" << arg_names[0] << ',' << start << ':' << end << ')'; return s.str(); } Dim PickRange::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 1); if (!LooksLikeVector(xs[0])) { cerr << "Bad input dimensions in PickElement: " << xs << endl; abort(); } assert(end <= xs[0][0]); return Dim({end - start}, xs[0].bd); } string MatrixMultiply::as_string(const vector<string>& arg_names) const { ostringstream s; s << arg_names[0] << " * " << arg_names[1]; return s.str(); } Dim MatrixMultiply::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 2); if (xs[0].cols() != xs[1].rows()) { cerr << "Mismatched input dimensions in MatrixMultiply: " << xs << endl; abort(); } if (xs[1].ndims() == 1) return Dim({xs[0].rows()}, max(xs[0].bd, xs[1].bd)); return Dim({xs[0].rows(), xs[1].cols()}, max(xs[0].bd, xs[1].bd)); } string CwiseMultiply::as_string(const vector<string>& arg_names) const { ostringstream s; s << arg_names[0] << " \\cdot " << arg_names[1]; return s.str(); } Dim CwiseMultiply::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 2); Dim d = xs[0].truncate(); if (d.single_batch() != xs[1].truncate().single_batch()) { cerr << "Mismatched input dimensions in CwiseMultiply: " << xs << endl; abort(); } d.bd = max(xs[1].bd, d.bd); return d; } string CwiseQuotient::as_string(const vector<string>& arg_names) const { ostringstream s; s << arg_names[0] << " / " << arg_names[1]; return s.str(); } Dim CwiseQuotient::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 2); Dim d = xs[0].truncate(); if (d.single_batch() != xs[1].truncate().single_batch()) { cerr << "Mismatched input dimensions in CwiseQuotient: " << xs << endl; abort(); } d.bd = max(xs[1].bd, d.bd); return d; } string AffineTransform::as_string(const vector<string>& arg_names) const { ostringstream s; s << arg_names[0]; for (unsigned i = 1; i < arg_names.size(); i += 2) s << " + " << arg_names[i] << " * " << arg_names[i+1]; return s.str(); } Dim AffineTransform::dim_forward(const vector<Dim>& xs) const { if ((xs.size() - 1) % 2 != 0) { cerr << "Bad number of inputs for AffineTransform: " << xs << endl; throw std::invalid_argument("Bad number of inputs to AffineTransform"); } Dim d = xs[0]; for (unsigned i = 1; i < xs.size(); i += 2) { if (xs[i].cols() != xs[i+1].rows() || xs[0].rows() != xs[i].rows() || xs[0].cols() != xs[i+1].cols()) { cerr << "Bad dimensions for AffineTransform: " << xs << endl; throw std::invalid_argument("Bad dimensions to AffineTransform"); } d.bd = max(max(d.bd, xs[i].bd), xs[i+1].bd); } return d; } string Negate::as_string(const vector<string>& arg_names) const { ostringstream s; s << '-' << arg_names[0]; return s.str(); } Dim Negate::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 1); return xs[0]; } string Rectify::as_string(const vector<string>& arg_names) const { ostringstream s; s << "ReLU(" << arg_names[0] << ')'; return s.str(); } Dim Rectify::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 1); return xs[0]; } string HuberDistance::as_string(const vector<string>& arg_names) const { ostringstream s; s << "|| " << arg_names[0] << " - " << arg_names[1] << " ||_H(" << d << ')'; return s.str(); } Dim HuberDistance::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 2); if (xs[0].single_batch() != xs[1].single_batch()) { cerr << "Mismatched input dimensions in HuberDistance: " << xs << endl; abort(); } return Dim({1}, max(xs[0].bd, xs[1].bd)); } string L1Distance::as_string(const vector<string>& arg_names) const { ostringstream s; s << "|| " << arg_names[0] << " - " << arg_names[1] << " ||_1"; return s.str(); } Dim L1Distance::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 2); if (xs[0].single_batch() != xs[1].single_batch()) { cerr << "Mismatched input dimensions in L1Distance: " << xs << endl; abort(); } return Dim({1}, max(xs[0].bd, xs[1].bd)); } string PoissonRegressionLoss::as_string(const vector<string>& arg_names) const { ostringstream s; s << "-log Poisson(" << pty << "; lambda=\\exp" << arg_names[0] << ')'; return s.str(); } Dim PoissonRegressionLoss::dim_forward(const vector<Dim>& xs) const { if (xs.size() != 1 || xs[0].size() != 1) { cerr << "Bad input dimensions in PoissonRegressionLoss: " << xs << endl; abort(); } return xs[0]; } string SquaredEuclideanDistance::as_string(const vector<string>& arg_names) const { ostringstream s; s << "|| " << arg_names[0] << " - " << arg_names[1] << " ||^2"; return s.str(); } Dim SquaredEuclideanDistance::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 2); if (xs[0].single_batch() != xs[1].single_batch()) { cerr << "Mismatched input dimensions in SquaredEuclideanDistance: " << xs << endl; abort(); } return Dim({1}, max(xs[0].bd, xs[1].bd)); } string LogisticSigmoid::as_string(const vector<string>& arg_names) const { ostringstream s; s << "\\sigma(" << arg_names[0] << ')'; return s.str(); } Dim LogisticSigmoid::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 1); return xs[0]; } string BinaryLogLoss::as_string(const vector<string>& arg_names) const { ostringstream os; os << "binary_log_loss(" << arg_names[0] << ", " << arg_names[1] << ')'; return os.str(); } Dim BinaryLogLoss::dim_forward(const vector<Dim>& xs) const { assert(xs.size() == 2); if (xs[0].rows() != 2 && xs[0].ndims() != 1) { cerr << "Bad input dimensions in BinaryLogLoss: " << xs << endl; abort(); } if (xs[1].rows() != 2 && xs[1].ndims() != 1) { cerr << "Bad input dimensions in BinaryLogLoss: " << xs << endl; abort(); } return Dim({1}, max(xs[0].bd, xs[1].bd)); } } // namespace cnn
[ "f.w.lrank@gmail.com" ]
f.w.lrank@gmail.com
6a0a6fb3a62542b7ab498ff6d61afb2dde3e8e4e
9621fdf991db2b113044ecbd0a064d50455838d1
/bachelor_cources/3 cource/Parallel OSI/proxy/singlethread/ConnectionHandler.h
2ff3d509124df164aab13ca6eb5f3a7bfdf3ded2
[]
no_license
comiam/NSU-Labs
10b0e669cb6c9a2b83c1f4572a35a4d5cbcf6053
1c85afeb35ca35ca200022c49539a6368bd526ca
refs/heads/master
2023-06-20T01:10:58.327153
2023-06-07T11:15:10
2023-06-07T11:15:10
253,186,656
5
5
null
null
null
null
UTF-8
C++
false
false
288
h
#ifndef SINGLETHREAD_HANDLER_H #define SINGLETHREAD_HANDLER_H class ConnectionHandler { public: virtual bool execute(int event) = 0; virtual ~ConnectionHandler() = default; virtual bool sendData() = 0; virtual bool receiveData() = 0; }; #endif //SINGLETHREAD_HANDLER_H
[ "maxim.bolshim@yandex.ru" ]
maxim.bolshim@yandex.ru
bc6b101ab8ffa92cfb5ffe442dfd9fe3159d819f
7e0013abc18fe0f788322d3cb81a0cc92901054d
/Code/joy_render_blur.cpp
c76bbd7ce670c1270d74f27453a22ae32a630868
[]
no_license
gorevojd/Joy
edbd9c3bd68fb5de410ab3d6ae83e420e57a1df3
bcfe16a30b33f9ae0534e4001457386f351034a9
refs/heads/master
2021-07-15T22:54:39.351213
2020-11-05T13:53:24
2020-11-05T13:53:24
223,946,061
3
0
null
null
null
null
UTF-8
C++
false
false
5,795
cpp
#include "joy_render_blur.h" u32 Calcualte2DGaussianBoxComponentsCount(int Radius) { int Diameter = Radius + Radius + 1; u32 Result = Diameter * Diameter; return(Result); } void Normalize2DGaussianBox(float* Box, int Radius) { //NOTE(dima): Calculate sum of all elements float TempSum = 0.0f; int Diam = Radius + Radius + 1; for (int i = 0; i < Diam * Diam; i++) { TempSum += Box[i]; } //NOTE(dima): Normalize elements float NormValueMul = 1.0f / TempSum; for (int i = 0; i < Diam * Diam; i++) { Box[i] *= NormValueMul; } } void Calculate2DGaussianBox(float* Box, int Radius) { int Diameter = Radius + Radius + 1; int Center = Radius; float Sigma = (float)Radius; float A = 1.0f / (2.0f * JOY_PI * Sigma * Sigma); float InExpDivisor = 2.0f * Sigma * Sigma; float TempSum = 0.0f; //NOTE(dima): Calculate elements for (int y = 0; y < Diameter; y++) { int PsiY = y - Center; for (int x = 0; x < Diameter; x++) { int PsiX = x - Center; float ValueToExp = -((PsiX * PsiX + PsiY * PsiY) / InExpDivisor); float Expon = Exp(ValueToExp); float ResultValue = A * Expon; Box[y * Diameter + x] = ResultValue; TempSum += ResultValue; } } //NOTE(dima): Normalize elements float NormValueMul = 1.0f / TempSum; for (int i = 0; i < Diameter * Diameter; i++) { Box[i] *= NormValueMul; } } static void BoxBlurApproximate( bmp_info* To, bmp_info* From, int BlurRadius) { int BlurDiam = 1 + BlurRadius + BlurRadius; for (int Y = 0; Y < From->Height; Y++) { for (int X = 0; X < From->Width; X++) { u32* TargetPixel = (u32*)((u8*)To->Pixels + Y * To->Pitch + X * 4); v4 VertSum = {}; int VertSumCount = 0; for (int kY = Y - BlurRadius; kY <= Y + BlurRadius; kY++) { int targetY = Clamp(kY, 0, From->Height - 1); u32* ScanPixel = (u32*)((u8*)From->Pixels + targetY * From->Pitch + X * 4); v4 UnpackedColor = UnpackRGBA(*ScanPixel); VertSum += UnpackedColor; VertSumCount++; } v4 HorzSum = {}; int HorzSumCount = 0; for (int kX = X - BlurRadius; kX <= X + BlurRadius; kX++) { int targetX = Clamp(kX, 0, From->Width - 1); u32* ScanPixel = (u32*)((u8*)From->Pixels + Y * From->Pitch + targetX * 4); v4 UnpackedColor = UnpackRGBA(*ScanPixel); HorzSum += UnpackedColor; HorzSumCount++; } VertSum = VertSum / (float)VertSumCount; HorzSum = HorzSum / (float)HorzSumCount; v4 TotalSum = (VertSum + HorzSum) * 0.5f; *TargetPixel = PackRGBA(TotalSum); } } } bmp_info BlurBitmapApproximateGaussian( bmp_info* BitmapToBlur, void* ResultBitmapMem, void* TempBitmapMem, int width, int height, int BlurRadius) { Assert(width == BitmapToBlur->Width); Assert(height == BitmapToBlur->Height); bmp_info Result = AllocateBitmapInternal( BitmapToBlur->Width, BitmapToBlur->Height, ResultBitmapMem); bmp_info TempBitmap = AllocateBitmapInternal( BitmapToBlur->Width, BitmapToBlur->Height, TempBitmapMem); /* var wIdeal = Math.sqrt((12 * sigma*sigma / n) + 1); // Ideal averaging filter width var wl = Math.floor(wIdeal); if (wl % 2 == 0) wl--; var wu = wl + 2; var mIdeal = (12 * sigma*sigma - n*wl*wl - 4 * n*wl - 3 * n) / (-4 * wl - 4); var m = Math.round(mIdeal); // var sigmaActual = Math.sqrt( (m*wl*wl + (n-m)*wu*wu - n)/12 ); var sizes = []; for (var i = 0; i<n; i++) sizes.push(i<m ? wl : wu); */ float Boxes[3]; int n = 3; float nf = 3.0f; float Sigma = (float)BlurRadius; float WIdeal = Sqrt((12.0f * Sigma * Sigma / nf) + 1.0f); float wlf = floorf(WIdeal); int wl = (float)(wlf + 0.5f); if (wl & 1 == 0) { wl--; } int wu = wl + 2; float mIdeal = (12.0f * Sigma * Sigma - nf * float(wl) * float(wl) - 4.0f * nf * float(wl) - 3.0f * nf) / (-4.0f * (float)wl - 4.0f); float mf = roundf(mIdeal); int m = float(mf + 0.5f); for (int i = 0; i < n; i++) { int ToSet = wu; if (i < m) { ToSet = wl; } Boxes[i] = ToSet; } BoxBlurApproximate(&Result, BitmapToBlur, (Boxes[0] - 1) / 2); BoxBlurApproximate(&TempBitmap, &Result, (Boxes[1] - 1) / 2); BoxBlurApproximate(&Result, &TempBitmap, (Boxes[2] - 1) / 2); return(Result); } bmp_info BlurBitmapExactGaussian( bmp_info* BitmapToBlur, void* ResultBitmapMem, int width, int height, int BlurRadius, float* GaussianBox) { Assert(width == BitmapToBlur->Width); Assert(height == BitmapToBlur->Height); bmp_info Result = AllocateBitmapInternal( BitmapToBlur->Width, BitmapToBlur->Height, ResultBitmapMem); int BlurDiam = 1 + BlurRadius + BlurRadius; bmp_info* From = BitmapToBlur; bmp_info* To = &Result; for (int Y = 0; Y < From->Height; Y++) { for (int X = 0; X < From->Width; X++) { u32* TargetPixel = (u32*)((u8*)To->Pixels + Y * To->Pitch + X * 4); v4 SumColor = {}; for (int kY = Y - BlurRadius; kY <= Y + BlurRadius; kY++) { int targetY = Clamp(kY, 0, From->Height - 1); int inboxY = kY - (Y - BlurRadius); for (int kX = X - BlurRadius; kX <= X + BlurRadius; kX++) { int targetX = Clamp(kX, 0, From->Width - 1); int inboxX = kX - (X - BlurRadius); u32* ScanPixel = (u32*)((u8*)From->Pixels + targetY * From->Pitch + targetX * 4); v4 UnpackedColor = UnpackRGBA(*ScanPixel); SumColor += UnpackedColor * GaussianBox[inboxY * BlurDiam + inboxX]; } } *TargetPixel = PackRGBA(SumColor); } } return(Result); }
[ "gorevojd27@gmail.com" ]
gorevojd27@gmail.com
a6a91fc52cc9d0125c0d16cf591e815ab3b4fe25
7efdf4fbf9e7bdea27b45c5a64bad9a115dd0d95
/pc_qt/build-st5-Desktop_Qt_5_2_1_GCC_32bit-Debug/ui_setalarm.h
12f064cf2d4ee4a0668ae938b4eddf2752487e75
[]
no_license
ittechbay/fts-xdl
011ab5cf232aeaef5ee46d8d7fcc5d51be513815
23add1bc8b89ea073457e17c4c92196ce9de66e9
refs/heads/master
2020-04-29T16:33:13.029860
2019-03-18T10:59:27
2019-03-18T10:59:27
176,236,963
0
0
null
null
null
null
UTF-8
C++
false
false
6,314
h
/******************************************************************************** ** Form generated from reading UI file 'setalarm.ui' ** ** Created by: Qt User Interface Compiler version 5.2.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_SETALARM_H #define UI_SETALARM_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QCheckBox> #include <QtWidgets/QDialog> #include <QtWidgets/QGridLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QPushButton> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_SetAlarm { public: QPushButton *pushButton_6; QPushButton *pushButton_5; QLabel *label; QWidget *layoutWidget; QGridLayout *gridLayout; QCheckBox *checkBox; QCheckBox *checkBox_4; QCheckBox *checkBox_2; QCheckBox *checkBox_5; QCheckBox *checkBox_3; QCheckBox *checkBox_6; QWidget *widget; QVBoxLayout *verticalLayout; QCheckBox *checkBox_7; QCheckBox *checkBox_8; QCheckBox *checkBox_9; void setupUi(QDialog *SetAlarm) { if (SetAlarm->objectName().isEmpty()) SetAlarm->setObjectName(QStringLiteral("SetAlarm")); SetAlarm->resize(800, 480); pushButton_6 = new QPushButton(SetAlarm); pushButton_6->setObjectName(QStringLiteral("pushButton_6")); pushButton_6->setGeometry(QRect(640, 20, 91, 41)); QFont font; font.setPointSize(16); pushButton_6->setFont(font); pushButton_5 = new QPushButton(SetAlarm); pushButton_5->setObjectName(QStringLiteral("pushButton_5")); pushButton_5->setGeometry(QRect(640, 420, 91, 41)); pushButton_5->setFont(font); label = new QLabel(SetAlarm); label->setObjectName(QStringLiteral("label")); label->setGeometry(QRect(300, 30, 54, 21)); QFont font1; font1.setPointSize(12); font1.setBold(true); font1.setWeight(75); label->setFont(font1); label->setAlignment(Qt::AlignCenter); layoutWidget = new QWidget(SetAlarm); layoutWidget->setObjectName(QStringLiteral("layoutWidget")); layoutWidget->setGeometry(QRect(90, 120, 201, 151)); gridLayout = new QGridLayout(layoutWidget); gridLayout->setObjectName(QStringLiteral("gridLayout")); gridLayout->setContentsMargins(0, 0, 0, 0); checkBox = new QCheckBox(layoutWidget); checkBox->setObjectName(QStringLiteral("checkBox")); QFont font2; font2.setPointSize(12); checkBox->setFont(font2); gridLayout->addWidget(checkBox, 0, 0, 1, 1); checkBox_4 = new QCheckBox(layoutWidget); checkBox_4->setObjectName(QStringLiteral("checkBox_4")); checkBox_4->setFont(font2); gridLayout->addWidget(checkBox_4, 0, 1, 1, 1); checkBox_2 = new QCheckBox(layoutWidget); checkBox_2->setObjectName(QStringLiteral("checkBox_2")); checkBox_2->setFont(font2); gridLayout->addWidget(checkBox_2, 1, 0, 1, 1); checkBox_5 = new QCheckBox(layoutWidget); checkBox_5->setObjectName(QStringLiteral("checkBox_5")); checkBox_5->setFont(font2); gridLayout->addWidget(checkBox_5, 1, 1, 1, 1); checkBox_3 = new QCheckBox(layoutWidget); checkBox_3->setObjectName(QStringLiteral("checkBox_3")); checkBox_3->setFont(font2); gridLayout->addWidget(checkBox_3, 2, 0, 1, 1); checkBox_6 = new QCheckBox(layoutWidget); checkBox_6->setObjectName(QStringLiteral("checkBox_6")); checkBox_6->setFont(font2); gridLayout->addWidget(checkBox_6, 2, 1, 1, 1); widget = new QWidget(SetAlarm); widget->setObjectName(QStringLiteral("widget")); widget->setGeometry(QRect(360, 120, 121, 151)); verticalLayout = new QVBoxLayout(widget); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); verticalLayout->setContentsMargins(0, 0, 0, 0); checkBox_7 = new QCheckBox(widget); checkBox_7->setObjectName(QStringLiteral("checkBox_7")); verticalLayout->addWidget(checkBox_7); checkBox_8 = new QCheckBox(widget); checkBox_8->setObjectName(QStringLiteral("checkBox_8")); verticalLayout->addWidget(checkBox_8); checkBox_9 = new QCheckBox(widget); checkBox_9->setObjectName(QStringLiteral("checkBox_9")); verticalLayout->addWidget(checkBox_9); retranslateUi(SetAlarm); QObject::connect(pushButton_5, SIGNAL(clicked()), SetAlarm, SLOT(close())); QMetaObject::connectSlotsByName(SetAlarm); } // setupUi void retranslateUi(QDialog *SetAlarm) { SetAlarm->setWindowTitle(QApplication::translate("SetAlarm", "Dialog", 0)); pushButton_6->setText(QApplication::translate("SetAlarm", "\345\244\215\344\275\215", 0)); pushButton_5->setText(QApplication::translate("SetAlarm", "\350\277\224\345\233\236", 0)); label->setText(QApplication::translate("SetAlarm", "\346\212\245\350\255\246", 0)); checkBox->setText(QApplication::translate("SetAlarm", "GNSS", 0)); checkBox_4->setText(QApplication::translate("SetAlarm", "B\347\240\201", 0)); checkBox_2->setText(QApplication::translate("SetAlarm", "\346\227\266\351\222\237", 0)); checkBox_5->setText(QApplication::translate("SetAlarm", "PTP", 0)); checkBox_3->setText(QApplication::translate("SetAlarm", "1pps", 0)); checkBox_6->setText(QApplication::translate("SetAlarm", "NTP", 0)); checkBox_7->setText(QApplication::translate("SetAlarm", "\346\227\240\346\263\225\351\224\201\345\256\232", 0)); checkBox_8->setText(QApplication::translate("SetAlarm", "\346\227\266\345\267\256\350\266\205\351\231\220", 0)); checkBox_9->setText(QApplication::translate("SetAlarm", "\345\244\251\347\272\277\346\225\205\351\232\234", 0)); } // retranslateUi }; namespace Ui { class SetAlarm: public Ui_SetAlarm {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_SETALARM_H
[ "ittechbay@163.com" ]
ittechbay@163.com
da4797a5ac33f7522a3623955384b3a1a9073ccd
35ea39a3c56339486561bc336764080a11d71105
/Maths.cpp
081d8d272f5e358d0337bfe5e94b0d7a347e26a8
[]
no_license
rainerSchmidt/AGP_Tutorial17_Excercise1
a24c0bfe7ed001ffe864fc2b35cbb58f83bb3bed
b14b828cd1470ad2492cf448e58fc82ec4be5dc6
refs/heads/master
2021-09-02T00:29:50.896545
2017-12-29T11:59:04
2017-12-29T11:59:04
115,713,346
0
0
null
null
null
null
UTF-8
C++
false
false
4,104
cpp
#include "maths.h" ObjFileModel::xyz* Maths::Normalise(ObjFileModel::xyz* v) { ObjFileModel::xyz* vector; vector->x = v->x; vector->y = v->y; vector->z = v->z; //Normalise the normal float length = sqrt((vector->x * vector->x) + (vector->y * vector->y) + (vector->z * vector->z)); vector->x /= length; vector->y /= length; vector->z /= length; return vector; } float Maths::DotProduct(ObjFileModel::xyz* v1, ObjFileModel::xyz* v2) { float dot = (v1->x * v2->x) + (v1->y * v2->y) + (v1->z * v2->z); return dot; } ObjFileModel::xyz* Maths::CrossProduct(ObjFileModel::xyz* v1, ObjFileModel::xyz* v2) { ObjFileModel::xyz* Vector3; Vector3->x = (v1->y * v2->z) - (v1->z * v2->y); Vector3->y = (v1->z * v2->x) - (v1->x * v2->z); Vector3->z = (v1->x * v2->y) - (v1->y * v2->x); return Vector3; } ObjFileModel::xyz* Maths::Normal(ObjFileModel::xyz* A, ObjFileModel::xyz* B, ObjFileModel::xyz* C) { ObjFileModel::xyz* v1; ObjFileModel::xyz* v2; v1->x = B->x - A->x; v1->y = B->y - A->y; v1->z = B->z - A->z; v2->x= C->x - A->x; v2->y = C->y - A->y; v2->z = C->z - A->z; ObjFileModel::xyz* normal = CrossProduct(v1,v2); normal = Normalise(normal); return normal; } Maths::Plane Maths::PlaneEquation(ObjFileModel::xyz* v1, ObjFileModel::xyz* v2, ObjFileModel::xyz* v3) { //calculate the normal vector to the triangle ObjFileModel::xyz* normal = Normal(v1, v2, v3); //calculate the d offset float d = -DotProduct(v1, normal); Maths::Plane plane; plane.d = d; plane.normal = *normal; return plane; } float Maths::PlaneEquationForPoint(Plane p, ObjFileModel::xyz* v) { float result = (p.normal.x * v->x) + (p.normal.y * v->y) + (p.normal.z * v->z) + p.d; return result; } ObjFileModel::xyz Maths::PlaneIntersection(Plane* plane, ObjFileModel::xyz* p1, ObjFileModel::xyz* p2) { ObjFileModel::xyz* intersection; intersection->x = 0; intersection->y = 0; intersection->z = 0; // ray ObjFileModel::xyz* ray; ray->x = p2->x - p1->x; ray->y = p2->y - p1->y; ray->z = p2->z - p1->z; //PlaneEquation for P1 and P2 int a = CheckSign(PlaneEquationForPoint(*plane, p1)); int b = CheckSign(PlaneEquationForPoint(*plane, p2)); if (a != b) //if signs are different than intersection { //calculate IntersectionPoint float t = (((-1 * plane->d) - DotProduct(&plane->normal, p1)) / DotProduct(&plane->normal, ray)); intersection->x = p1->x + (ray->x * t); intersection->y = p1->y + (ray->y * t); intersection->z = p1->z + (ray->z * t); //return IntersectionPoint return *intersection; } //return NullVector; return *intersection; } bool Maths::InTriangle(ObjFileModel::xyz* A, ObjFileModel::xyz* B, ObjFileModel::xyz* C, ObjFileModel::xyz* P) { ObjFileModel::xyz *vectorAP, *vectorAB, *vectorBP, *vectorBC, *vectorCP, *vectorCA; //set vectorAP vectorAP->x = P->x - A->x; vectorAP->y = P->y - A->y; vectorAP->z = P->z - A->z; //set vectorAB vectorAB->x = B->x - A->x; vectorAB->y = B->y - A->y; vectorAB->z = B->z - A->z; //set vectorBP vectorBP->x = P->x - B->x; vectorBP->y = P->y - B->y; vectorBP->z = P->z - B->z; //set vectorBC vectorBC->x = C->x - B->x; vectorBC->y = C->y - B->y; vectorBC->z = C->z - B->z; //set vectorCP vectorCP->x = P->x - C->x; vectorCP->y = P->y - C->y; vectorCP->z = P->z - C->z; //set vectorCA vectorCA->x = A->x - C->x; vectorCA->y = A->y - C->y; vectorCA->z = A->z - C->z; float a = CheckSign(DotProduct(CrossProduct(vectorAP, vectorAB), CrossProduct(vectorBP, vectorBC))); float b = CheckSign(DotProduct(CrossProduct(vectorBP, vectorBC), CrossProduct(vectorCP, vectorCA))); float c = CheckSign(DotProduct(CrossProduct(vectorCP, vectorCA), CrossProduct(vectorAP, vectorAB))); //have all DotProduct results the same sign if ((a > 0 && b > 0 && c > 0) || a < 0 && b < 0 && c < 0) return true; return false; } int Maths::CheckSign(float number) { return (number < 0.0f ? -1 : (number > 0.0f ? 1 : 0)); }
[ "noreply@github.com" ]
noreply@github.com
bcf1170d97e5c89c276ef9ca3813abe0994cf6e7
c8b3e1c33d24cee943a700f4a7234d981a742366
/TheCorridor/OpenCommand.h
454ea3f4e617e7930557a8bfb7d8227374b2585f
[]
no_license
CharlesWithall/TheCorridor
fdbbb333e47dae89347718f1ed73101b140d8fad
fc5a32a499499bb9e4224dc2b65aec645b1082a3
refs/heads/master
2021-01-20T02:54:53.487674
2017-08-04T11:12:38
2017-08-04T11:12:38
88,871,608
0
0
null
null
null
null
UTF-8
C++
false
false
149
h
#pragma once #include "command.h" class OpenCommand : public Command { public: OpenCommand(); ~OpenCommand(); void Execute(Player* aPlayer); };
[ "charles.withall@gmail.com" ]
charles.withall@gmail.com
8f0540833f39c9a1b72195b662b56ea9d2fa0e4d
52edee1b7d731d4855d9e3c294db38bafda669b1
/core/include/vpmatrix.h
9b3341cafcaa67456b5baf564ee844903097f3b1
[]
no_license
ARLM-Attic/vart
d5e1415d6569159f4861b960aca742bbeac15f27
8674d0f53b41492e54de6397d6b455e4de3e0488
refs/heads/master
2020-12-30T16:14:51.846922
2012-10-01T22:10:56
2012-10-01T22:10:56
90,967,803
0
0
null
null
null
null
UTF-8
C++
false
false
1,774
h
//deprecated /////////////////////////////////////////////////////////////////// // // PROJECT.....: vpat - Creating Virtual Patients // RESPONSIBLE.: Carla Freitas e Luciana Nedel // // FILE........: vpmatrix.h // DESCRIPTION.: Contain the VPMatrix class declarations. // // AUTHOR......: Anderson Maciel // DATE........: 09/June/2000 // DESCRIPTION.: Class and new methods declaration. // /////////////////////////////////////////////////////////////////// #ifndef __VPMATRIX_H #define __VPMATRIX_H #include <vppoint3d.h> //----------------------------------------------------------------------- // V P M A T R I X //----------------------------------------------------------------------- ///////////////////////////////////////////////////////////////////////// // Class Name: VPMatrix // Superclass: - // Subclass: - // Describes a 4x4 homogeneous matrix for most CG transformations typedef float mat44 [4][4]; ///\deprecated class VPMatrix{ private: float data[4][4]; protected: VPMatrix* vpGetAdjoint( void ); float vpGetDet33( float, float, float, float, float, float, float, float, float ); float vpGetDet22( float, float, float, float ); public: VPMatrix(); VPMatrix( float[] ); VPMatrix( float[][4] ); ~VPMatrix(); float vpGetValueAt( int, int ); void vpSetValueAt( int, int, float ); //mat44* vpGetMatrixF( void ); void vpGetMatrixF( float ** ); float* vpGetMatrixVF( void ); VPMatrix* vpGetInverse( void ); float vpGetDeterminent( void ); VPMatrix* vpMultiplyScalar( float ); VPMatrix* vpMultiply( VPMatrix ); VPMatrix* vpSubtract( VPMatrix ); VPMatrix* vpAdd( VPMatrix ); VPPoint3D* vpMultiply ( VPPoint3D ); }; #endif
[ "SND\\kcfelix_cp@142e9c35-602f-4880-9f37-ec48a24daa6a" ]
SND\kcfelix_cp@142e9c35-602f-4880-9f37-ec48a24daa6a
83aba456905b9738ad20dcab6133546d049a397d
cddc5063548fda3173320fe2254fc214c8fb3fe3
/Qt/C++/Qt_programming/build-setting_qt_dialog_menu-Desktop-Debug/moc_mainwindow.cpp
12b2be98fdeed0bb8380589617bb6a24639fadd2
[]
no_license
Sayoloto/AJC_C-
81ad6805d7a7ae2ac4fde085e9ed66678d8206b1
b2ab98f03f5eb333a83db4a6e433e069a101cb7b
refs/heads/master
2020-08-27T06:03:54.481799
2019-11-22T17:39:53
2019-11-22T17:39:53
217,264,309
0
0
null
null
null
null
UTF-8
C++
false
false
3,553
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'mainwindow.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.9.5) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../setting_qt_dialog_menu/mainwindow.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'mainwindow.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.9.5. 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_MainWindow_t { QByteArrayData data[4]; char stringdata0[39]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_MainWindow_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = { { QT_MOC_LITERAL(0, 0, 10), // "MainWindow" QT_MOC_LITERAL(1, 11, 13), // "dialog_window" QT_MOC_LITERAL(2, 25, 0), // "" QT_MOC_LITERAL(3, 26, 12) // "font_changer" }, "MainWindow\0dialog_window\0\0font_changer" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_MainWindow[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 2, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 24, 2, 0x08 /* Private */, 3, 0, 25, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Void, 0 // eod }; void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { MainWindow *_t = static_cast<MainWindow *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->dialog_window(); break; case 1: _t->font_changer(); break; default: ; } } Q_UNUSED(_a); } const QMetaObject MainWindow::staticMetaObject = { { &QMainWindow::staticMetaObject, qt_meta_stringdata_MainWindow.data, qt_meta_data_MainWindow, qt_static_metacall, nullptr, nullptr} }; const QMetaObject *MainWindow::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *MainWindow::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata0)) return static_cast<void*>(this); return QMainWindow::qt_metacast(_clname); } int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMainWindow::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 2) qt_static_metacall(this, _c, _id, _a); _id -= 2; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 2) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 2; } return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
[ "sayoloto@gmail.com" ]
sayoloto@gmail.com
824015909af05a68f71ec02726e6d6d66aaed85e
c6c1fbc5d9d06b60812fb0798a55c7d4ec0f873d
/Masquerade/Source/Camera.cpp
c501b4e40a69790bc331607d0d39ae94efe731da
[]
no_license
DevinWhitaker/Masqurade
f5bd1ff433310ba55ab5d3a1161cd652dbc346e8
40a3835105f6ac87ce464ab2f1f50c6d60c0c038
refs/heads/master
2021-01-01T18:41:52.751184
2013-10-24T17:38:59
2013-10-24T17:38:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,146
cpp
// Project: Masquerade // Filename: Camera.cpp // Author: Jam'D Team // Purpose: Camera implementation. #include "Camera.h" #include "TileManager.h" CCamera* CCamera::GetInstance( ) { static CCamera s_Instance; return &s_Instance; } CCamera::CCamera( ) { m_fXOffset = 0.0f; m_fYOffset = 0.0f; m_bPlayerControlled = false; m_pGame = CGame::GetInstance(); } CCamera::~CCamera( ) { } void CCamera::Update( float fElapsed ) { //m_fXOffset += 1.0f * fElapsed; if(m_fXOffset < 0) m_fXOffset = 0; if(m_fYOffset < 0) m_fYOffset = 0; CTileManager* TM = CTileManager::GetInstance(); if( m_fXOffset + GetScreenSpaceX() > TM->GetWorldWidth() ) m_fXOffset = TM->GetWorldWidth() - GetScreenSpaceX(); /*if( m_fYOffset + GetScreenSpaceY() > TM->GetWorldHeight() ) m_fYOffset = TM->GetWorldHeight() - GetScreenSpaceY();*/ } void CCamera::Input( ) { // Panning camera for Fox when in Camera Mode. } float CCamera::GetScreenSpaceX() { return (float)(m_pGame->GetWidth()); } float CCamera::GetScreenSpaceY() { return (float)(m_pGame->GetHeight()); } void CCamera::Reset( void ) { m_fXOffset = 0.0f; m_fYOffset = 0.0f; }
[ "devinjwhitaker@gmail.com" ]
devinjwhitaker@gmail.com
63f6f0c9ed230452c5129248124181ca12015478
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_repos_function_2769_last_repos.cpp
16bc4a186d451c4238aa1411b5c1e84672f79e01
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,770
cpp
static apr_status_t beam_cleanup(void *data) { h2_bucket_beam *beam = data; apr_status_t status = APR_SUCCESS; int safe_send = !beam->m_enter || (beam->owner == H2_BEAM_OWNER_SEND); int safe_recv = !beam->m_enter || (beam->owner == H2_BEAM_OWNER_RECV); /* * Owner of the beam is going away, depending on which side it owns, * cleanup strategies will differ with multi-thread protection * still in place (beam->m_enter). * * In general, receiver holds references to memory from sender. * Clean up receiver first, if safe, then cleanup sender, if safe. */ /* When modify send is not safe, this means we still have multi-thread * protection and the owner is receiving the buckets. If the sending * side has not gone away, this means we could have dangling buckets * in our lists that never get destroyed. This should not happen. */ ap_assert(safe_send || !beam->send_pool); if (!H2_BLIST_EMPTY(&beam->send_list)) { ap_assert(beam->send_pool); } if (safe_recv) { if (beam->recv_pool) { pool_kill(beam, beam->recv_pool, beam_recv_cleanup); beam->recv_pool = NULL; } recv_buffer_cleanup(beam, NULL); } else { beam->recv_buffer = NULL; beam->recv_pool = NULL; } if (safe_send && beam->send_pool) { pool_kill(beam, beam->send_pool, beam_send_cleanup); status = beam_send_cleanup(beam); } if (safe_recv) { ap_assert(H2_BPROXY_LIST_EMPTY(&beam->proxies)); ap_assert(H2_BLIST_EMPTY(&beam->send_list)); ap_assert(H2_BLIST_EMPTY(&beam->hold_list)); ap_assert(H2_BLIST_EMPTY(&beam->purge_list)); } return status; }
[ "993273596@qq.com" ]
993273596@qq.com
55ea9530f03bac1f75eef5b47b17b914b51ab81c
6b60654f5c37b788b5a0325fe22cce600794e525
/contest/amr16d.cpp
e8c18bd40357ed28996d1d770c11f4acba3d160f
[]
no_license
rsmnnit/Codes
cd45ae7a111fd7bb9e80bc85c0f273058eb3eb07
355daa783c625c3f1789f82482a7dbac12950210
refs/heads/master
2021-09-09T15:10:06.900600
2018-03-17T09:10:49
2018-03-17T09:10:49
104,431,239
0
0
null
null
null
null
UTF-8
C++
false
false
693
cpp
/* Radheshyam Lodhi radheshyamlodhi64@gmail.com CSE-MNNIT Allahabad */ #include<bits/stdc++.h> using namespace std; #define ll long long #define sfi(i) scanf("%d",&i) #define sfid(a,b) scanf("%d%d",&a,&b) #define sfl(i) scanf("%lld",&i) #define sfld(a,b) scanf("%lld%lld",&a,&b) #define pfl(a) printf("%lld\n",a) #define pfi(a) printf("%d\n",a) #define f(i,a,b) for(i=a;i<b;i++) #define pb push_back #define MP make_pair #define F first #define S second #define gc() getchar_unlocked() #define mod (1e9+7) int main() { int t; sfi(t); while(t--){ ll n,k; sfld(n,k); if(k==n-1) { printf("yes\n"); continue; } if(k%3==0) printf("no\n"); else printf("yes\n"); } return 0; }
[ "noreply@github.com" ]
noreply@github.com
804a9cab0f08dc5fe982bdc8db55c7f411c323a2
425e83de8a46ccc0dffed124994634338265add0
/Plus Minus.cpp
bbd68e18327e065d4624946d724a80cdb0cbee8a
[]
no_license
manisha069/HackerRank-Problem-Solving
6244559dc752537e2ed557bdc0a2134cdb15ed81
219f393e8883ebc71ef8dc2550fc4ef3c25d36a6
refs/heads/main
2023-06-07T04:48:37.746303
2021-06-16T04:56:46
2021-06-16T04:56:46
309,933,942
0
0
null
null
null
null
UTF-8
C++
false
false
1,751
cpp
#include <bits/stdc++.h> using namespace std; vector<string> split_string(string); // Complete the plusMinus function below. void plusMinus(vector<int> arr) { double pos, neg, zer; int size; size= arr.size(); pos=neg=zer=0; for(int i =0; i< size; i++) { if(arr[i]==0) { zer++; } else if (arr[i]>0) { pos++; } else { neg++; } } cout<<setprecision(6)<<fixed<<pos/size<<endl; cout<<setprecision(6)<<neg/size<<endl; cout<<setprecision(6)<<zer/size; } int main() { int n; cin >> n; cin.ignore(numeric_limits<streamsize>::max(), '\n'); string arr_temp_temp; getline(cin, arr_temp_temp); vector<string> arr_temp = split_string(arr_temp_temp); vector<int> arr(n); for (int i = 0; i < n; i++) { int arr_item = stoi(arr_temp[i]); arr[i] = arr_item; } plusMinus(arr); return 0; } vector<string> split_string(string input_string) { string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { return x == y and x == ' '; }); input_string.erase(new_end, input_string.end()); while (input_string[input_string.length() - 1] == ' ') { input_string.pop_back(); } vector<string> splits; char delimiter = ' '; size_t i = 0; size_t pos = input_string.find(delimiter); while (pos != string::npos) { splits.push_back(input_string.substr(i, pos - i)); i = pos + 1; pos = input_string.find(delimiter, i); } splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); return splits; }
[ "manisha.guptacs2018@indoreinstitute.com" ]
manisha.guptacs2018@indoreinstitute.com
9c551e6d0a82eb8204b30ee7f6264fff7930d755
f167e0c34673c0dad8e990b2554e9e43320c5068
/pipworker.h
e5524be0a5eb4f5bebbb65fe022ee73bb4fe705a
[]
no_license
nospam2k/Mixer-gui
7d5f5c27a922b9074f5808337e54fb3fb809c419
e3e1fab9dd9cf28810e482296eea4963e3fbf6af
refs/heads/master
2021-04-09T14:56:11.523614
2014-10-25T11:51:59
2014-10-25T11:51:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
563
h
#ifndef PIPWORKER_H #define PIPWORKER_H #include <QObject> #include <buffer.h> class PIPWorker : public QObject { Q_OBJECT public: explicit PIPWorker(QObject *parent = 0); ~PIPWorker(); void setParams(double _scale, int _offsetX, int _offsetY); void start(Buffer* buf, int outNumbe, int numBack, int numPIP); private: Buffer* buffer; double scale; int offsetX; int offsetY; uchar* output; uchar* inputBack; uchar* inputPIP; int outNumber; public slots: void processFrame(); }; #endif // PIPWORKER_H
[ "daniel.kucera@gmail.com" ]
daniel.kucera@gmail.com
36e61f656a0dac0a646b3d9f681ce9b9f848a48f
6d2d6c928e623ab13df7ee44ce122a95c96f87a2
/section3/fence.cpp
f84b7cfd69ad48ad6c8845703e7043568a035c2f
[]
no_license
kevinkwl/usaco
180f354273a3bd02add1964b595c3f2d931ed4dc
98d3a4e926ca335ad21656766ce3696f64fe718e
refs/heads/master
2021-05-31T11:38:58.745734
2016-02-13T13:54:56
2016-02-13T13:54:56
46,347,983
1
0
null
null
null
null
UTF-8
C++
false
false
1,097
cpp
/* ID: kevinli7 PROG: fence LANG: C++11 */ #include <iostream> #include <fstream> #include <set> using namespace std; struct Intsec { Intsec():deg(0){} int deg; multiset<int> adj; }; int path[2048]; int pathsize, F, a, b; int start; Intsec g[505]; void dfs(int n) { while (!g[n].adj.empty()) { int next = *(g[n].adj.begin()); g[n].adj.erase(g[n].adj.begin()); g[next].adj.erase(g[next].adj.find(n)); dfs(next); } path[pathsize] = n; ++pathsize; } int main() { ifstream fin("fence.in"); fin >> F; for (int i = 0; i < F; ++i) { fin >> a >> b; ++g[a].deg; ++g[b].deg; g[a].adj.insert(b); g[b].adj.insert(a); } fin.close(); for (int i = 1; i <= 500; ++i) { if (start == 0 && g[i].deg != 0) start = i; if (g[i].deg & 1) { start = i; break; } } dfs(start); ofstream fout("fence.out"); for (int i = pathsize - 1; i >= 0; --i) fout << path[i] << endl; fout.close(); }
[ "lingkangwei.kevin@gmail.com" ]
lingkangwei.kevin@gmail.com
cc446e78d67586e18b854e118b2fa7a0474d81f6
1f677cb97f8707c3e0384eb8d4364a6c253c9b78
/pssc/include/pssc/protocol/msgs/SubscribeMessage.h
82a014d2de405d777079e46060f5c536bdfd2924
[ "BSD-3-Clause" ]
permissive
maxvalor/sros
5e70dd613e5539d62025362717f8cdc7790fe466
95d55dbb8d1bbfabbf13afd2006f20ce9df8f38a
refs/heads/master
2023-07-06T21:05:34.682131
2021-08-10T11:04:44
2021-08-10T11:04:44
394,620,233
1
0
null
null
null
null
UTF-8
C++
false
false
1,248
h
/* * SubscribeMessage.h * * Created on: Apr 25, 2021 * Author: ubuntu */ #ifndef INCLUDE_PSSC_PROTOCOL_MSGS_SUBSCRIBEMESSAGE_H_ #define INCLUDE_PSSC_PROTOCOL_MSGS_SUBSCRIBEMESSAGE_H_ #include "PSSCMessage.h" namespace pssc { class SubscribeMessage : public PSSCMessage { public: // | INS | ID | SUBSCRIBER_ID | SIZE_OF_TOPIC | TOPIC | static const pssc_ins INS = Ins::SUBSCRIBE; static const pssc_size SIZE_OF_MESSAGE_NECCESSARY = SIZE_OF_PSSC_INS + SIZE_OF_PSSC_ID * 2 + SIZE_OF_SIZE; pssc_id subscriberId; std::string topic; SubscribeMessage() = default; // @suppress("Class members should be properly initialized") SubscribeMessage(std::shared_ptr<TCPMessage> msg) { // INS has been taken msg->NextData(messageId); msg->NextData(subscriberId); msg->NextData(topic); } std::shared_ptr<TCPMessage> toTCPMessage() override { auto msg = TCPMessage::Generate(SIZE_OF_MESSAGE_NECCESSARY + topic.size()); msg->AppendData(INS); msg->AppendData(messageId); msg->AppendData(subscriberId); msg->AppendData(topic); return msg; } }; } #endif /* INCLUDE_PSSC_PROTOCOL_MSGS_SUBSCRIBEMESSAGE_H_ */
[ "you@example.com" ]
you@example.com
fa4d24d16ff6e328083bddd1db6d740388f1ee19
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/mutt/gumtree/mutt_old_log_54.cpp
51d66b104f94334e93c8d441f1380aa5f6af93c9
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
23
cpp
(fputs(KENDRA_SEP, fp);
[ "993273596@qq.com" ]
993273596@qq.com
8cca7891ca4dc1e4616f2df5653572abf2b17c5f
be3d7c318d79cd33d306aba58a1159147cac91fd
/modules/wgd_heightmap/include/wgd/iheightmap.h
e7e5e37e0d8a7df0638da759e82c4e518bbfa6af
[]
no_license
knicos/Cadence
827149b53bb3e92fe532b0ad4234b7d0de11ca43
7e1e1cf1bae664f77afce63407b61c7b2b0a4fff
refs/heads/master
2020-05-29T13:19:07.595099
2011-10-31T13:05:48
2011-10-31T13:05:48
1,238,039
2
0
null
null
null
null
UTF-8
C++
false
false
4,647
h
#ifndef _WGD_IHEIGHTMAP_ #define _WGD_IHEIGHTMAP_ #include <wgd/common.h> #include <wgd/instance3d.h> #include <wgd/heightmapsource.h> namespace wgd { class HEIGHTMAPIMPORT IHeightmap : public wgd::Instance3D { public: IHeightmap(HeightmapSource* source); IHeightmap(const OID&); ~IHeightmap(); void draw(SceneGraph &graph, Camera3D *camera); OBJECT(Instance3D, IHeightmap); // Data source for heightmap data PROPERTY_RF(HeightmapSource, source, "source"); PROPERTY_WF(HeightmapSource, source, "source"); //LOD Patchsize - Must be a power of 2 PROPERTY_RF(int, patchSize, "patchsize"); PROPERTY_WF(int, patchSize, "patchsize"); //scale of the detailed spat textures PROPERTY_RF(wgd::vector2d, splatScale, "splatscale"); PROPERTY_WF(wgd::vector2d, splatScale, "splatscale"); void splatScale(float s) { splatScale(vector2d(s,s)); }; /** Draw the heightmap in wireframe mode */ PROPERTY_RF(bool, wireframe, "wireframe"); PROPERTY_WF(bool, wireframe, "wireframe"); /** Splat fade distance. * If this is 0, no splat textured are drawn. */ PROPERTY_RF(float, fade, "fade"); PROPERTY_WF(float, fade, "fade"); /** Level of detail metric (higher number = less detail) */ PROPERTY_RF(float, lod, "lod"); PROPERTY_WF(float, lod, "lod"); /** heightmap scale - defines how far apart the vertices are */ PROPERTY_RF(vector3d, scale, ix::scale); PROPERTY_WF(vector3d, scale, ix::scale); void scale(float s) { scale(vector3d(s,s,s)); }; /** * Get the height at any point * @param v The point to query the height at. Note y is ignored * @return height of the point (y coordinate) */ float height(const wgd::vector3d &v); /** * Get the height at any point * @param x The x coordinate of the point * @param z The z coordinate of the point * @return height of the point (y coordinate) */ float height(float x, float z); /** * Get the surface normal at any point * @param v The point to query the height at. Note y is ignored */ wgd::vector3d normal(const wgd::vector3d &v); /** * Get the point where a line segment intersects the heightmap * @param result The calculated intersection point * @param start The start point of the line in world coordinates * @param end The end point of the line in world coordinates * @return Whether the line segment intersects the heightmap */ bool intersect(wgd::vector3d &result, const wgd::vector3d &start, const wgd::vector3d &end); /** * Get the point where a ray hits the heightmap * @param result The calculated intersection point * @param point The start point of the ray in world coordinates * @param direction The direction of the ray * @return Whether the ray hits the heightmap */ bool ray(wgd::vector3d &result, const wgd::vector3d &point, const wgd::vector3d &direction); private: // Draw the region at said region coordinates void drawRegion(Camera3D *camera, int rx, int ry); //Get a patch (using patch coordinates) wgd::Patch *patch(int x, int y); //Calculate the glue values for a patch - takes absolute patch coordinates (not relative to region) unsigned int glue(wgd::Patch *p, int x, int y); // Calculate the error metric for getting mip levels from viewport distortion void errorMetric(float fovY, int viewHeight); //recursively draw patches void drawPatchR(HMRegion *region, int rx, int ry, int node, int x, int y, int size); void drawSplatR(HMRegion *region, int splat, int rx, int ry, int node, int x, int y, int size); //Index Array Generation void buildPatch (Patch *p, unsigned int glue); void acrossStrip(Patch *p, int start, int length, int step); void leftGlue (Patch *p, int nextLevel); //nextLevel being the mip level of the next patch void rightGlue (Patch *p, int nextLevel); void topGlue (Patch *p, int nextLevel); void bottomGlue (Patch *p, int nextLevel); //some local data float m_errorMetric; //Error metric to calculate mip level int m_regionSize; //Size of region in vertices int m_patchSize; //size of patch in vertices int m_patches; //Size of region in patches float m_fade; //splat fade distance (this is the cut-off distance) vector3d m_scale; //heightmap scale HeightmapSource* m_source; wgd::vector2d m_splatScale; float m_farClip; //info int m_polys; float m_maxError; int m_count; //ray debug wgd::vector3d vs, ve; }; }; #endif
[ "nwpope@gmail.com" ]
nwpope@gmail.com
edcc46edafe82350b09337fed08d581328c91755
36a9be2bbca3573ed7dfe84b52e0bf93e1258e3d
/zbus/include/MqClient.h
c3697069bea7ac5ea643171604da4efe331b5a20
[ "MIT" ]
permissive
rushmore/zbus-cpp
54b1a2d2aba668ab1b006024efc225f5f4c6abd2
61a1c020b1ce03926c4fef0af3fd7e6246ecfe94
refs/heads/master
2020-12-10T03:25:42.744845
2017-09-17T21:02:48
2017-09-17T21:02:48
95,549,953
3
0
null
null
null
null
UTF-8
C++
false
false
2,909
h
#ifndef __ZBUS_MQ_CLIENT_H__ #define __ZBUS_MQ_CLIENT_H__ #include "MessageClient.h" #include "Kit.h" #include <queue> #include <mutex> #include <condition_variable> namespace zbus { class ZBUS_API ConsumeGroup { public: std::string groupName; std::string filter; //filter on message'tag int mask = -1; std::string startCopy; //create group from another group int64_t startOffset = -1; std::string startMsgId; //create group start from offset, msgId to check valid int64_t startTime = -1; //create group start from time void load(Message& msg) { groupName = msg.getConsumeGroup(); filter = msg.getGroupFilter(); mask = msg.getGroupMask(); startCopy = msg.getGroupStartCopy(); startOffset = msg.getGroupStartOffset(); startMsgId = msg.getGroupStartMsgId(); startTime = msg.getGroupStartTime(); } void writeTo(Message& msg) { msg.setConsumeGroup(groupName); msg.setGroupFilter(filter); msg.setGroupMask(mask); msg.setGroupStartCopy(startCopy); msg.setGroupStartOffset(startOffset); msg.setGroupStartMsgId(startMsgId); msg.setGroupStartTime(startTime); } }; class ZBUS_API MqClient : public MessageClient { public: std::string token; MqClient(std::string address, bool sslEnabled = false, std::string sslCertFile = ""); virtual ~MqClient(); Message produce(Message& msg, int timeout = 3000); Message* consume(std::string topic, std::string group = "", int window = -1, int timeout = 3000); TrackerInfo queryTracker(int timeout = 3000); ServerInfo queryServer(int timeout = 3000); TopicInfo queryTopic(std::string topic, int timeout = 3000); ConsumeGroupInfo queryGroup(std::string topic, std::string group, int timeout = 3000); TopicInfo declareTopic(std::string topic, int topicMask = -1, int timeout = 3000); ConsumeGroupInfo declareGroup(std::string topic, std::string group, int timeout = 3000); ConsumeGroupInfo declareGroup(std::string topic, ConsumeGroup& group, int timeout = 3000); void removeTopic(std::string topic, int timeout = 3000); void removeGroup(std::string topic, std::string group, int timeout = 3000); void emptyTopic(std::string topic, int timeout = 3000); void emptyGroup(std::string topic, std::string group, int timeout = 3000); void route(Message& msg, int timeout = 3000); }; class ZBUS_API MqClientPool { public: MqClientPool(std::string serverAddress, int maxSize = 32, bool sslEnabled = false, std::string sslCertFile = ""); virtual ~MqClientPool(); void returnClient(MqClient* value); MqClient* borrowClient(); MqClient* makeClient(); ServerAddress getServerAddress(); private: std::string serverAddress; bool sslEnabled; std::string sslCertFile; int size; int maxSize; std::queue<MqClient*> queue; mutable std::mutex mutex; std::condition_variable signal; }; }//namespace #endif
[ "44194462@qq.com" ]
44194462@qq.com
ec6e0ea20cc2c0f119e0a672e1fcee222a95b759
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/arduino/hardware/arduino/cores/arduino/main.cpp
cc6e81d906c85233998836bc5dbc383e507309db
[ "MIT", "GPL-2.0-only", "LGPL-2.1-only" ]
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
108
cpp
#include <WProgram.h> int main(void) { init(); setup(); for (;;) loop(); return 0; }
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
c9eabf4c0c527c2f6a33c2ba28ca4e4c77674033
ac316dc53e018ee84008fe2cdacc75c73cb4a12a
/c++_language_programming/C++_lab/ch02/ex2-18/ex2-18.cpp
61e178ddc6a87d70f20a7173f8bf12c1c1199c0d
[]
no_license
shixu312349410/vscode_cplusplus
7701913254aa1754dc0853716338d4cf8536e31d
a961759431054d58a0eb9edc27f5957f55b2d83a
refs/heads/master
2023-03-18T02:07:38.104946
2021-03-09T12:45:44
2021-03-09T12:45:44
339,215,392
0
0
null
null
null
null
UTF-8
C++
false
false
122
cpp
#include <iostream> using namespace std ; int main() { for (int i = 32; i<128; i++) cout << (char) i; return 0; }
[ "312349410@qq.com" ]
312349410@qq.com
1b4228bfdd31fa688ab7a01c78c9bc9f2d20ef0b
9feb6f0bea11ea627c0e4f3a86b1def363d3acc5
/Fogo/src/Fogo/Utility/Keyboard.h
8c0e23bdd618d1de45958e4e720e2a3942e2ef80
[]
no_license
ekuinox/Fogo
5176beace73f919c32ba0526de7591da35fcf303
e9c5be4297280a05f62d0766bdcff1900b81939c
refs/heads/master
2020-04-08T15:24:45.766117
2019-03-12T02:33:11
2019-03-12T02:33:11
159,477,629
0
0
null
null
null
null
UTF-8
C++
false
false
676
h
#pragma once #include <dinput.h> namespace Fogo { class Keyboard { private: static constexpr unsigned int NUM_KEY_MAX = 256; static constexpr unsigned int LIMIT_COUNT_REPEAT = 20; LPDIRECTINPUTDEVICE8 __device; BYTE __buffer[NUM_KEY_MAX]; struct { BYTE trigger; BYTE repeat; BYTE release; unsigned int repeat_count; } __states[NUM_KEY_MAX]; public: Keyboard(LPDIRECTINPUT8 input); ~Keyboard(); void update(); bool getPress(unsigned int key) const; bool getTrigger(unsigned int key) const; bool getRepeat(unsigned int key) const; bool getRelease(unsigned int key) const; bool getAnyPress() const; bool getAnyTrigger() const; }; }
[ "depkey@me.com" ]
depkey@me.com
5302b48c0e05b72adf38746782d1b21da8a568ba
72d9009d19e92b721d5cc0e8f8045e1145921130
/image.libfacedetection/inst/testfiles/detect_faces/detect_faces_DeepState_TestHarness.cpp
52ce28aee3a132e0effacc5c05507c63151507e6
[]
no_license
akhikolla/TestedPackages-NoIssues
be46c49c0836b3f0cf60e247087089868adf7a62
eb8d498cc132def615c090941bc172e17fdce267
refs/heads/master
2023-03-01T09:10:17.227119
2021-01-25T19:44:44
2021-01-25T19:44:44
332,027,727
1
0
null
null
null
null
UTF-8
C++
false
false
1,808
cpp
// AUTOMATICALLY GENERATED BY RCPPDEEPSTATE PLEASE DO NOT EDIT BY HAND, INSTEAD EDIT // detect_faces_DeepState_TestHarness_generation.cpp and detect_faces_DeepState_TestHarness_checks.cpp #include <fstream> #include <RInside.h> #include <iostream> #include <RcppDeepState.h> #include <qs.h> #include <DeepState.hpp> Rcpp::List detect_faces(IntegerVector x, int width, int height, int step); TEST(image.libfacedetection_deepstate_test,detect_faces_test){ RInside R; std::cout << "input starts" << std::endl; IntegerVector x = RcppDeepState_IntegerVector(); qs::c_qsave(x,"/home/akhila/fuzzer_packages/fuzzedpackages/image.libfacedetection/inst/testfiles/detect_faces/inputs/x.qs", "high", "zstd", 1, 15, true, 1); std::cout << "x values: "<< x << std::endl; IntegerVector width(1); width[0] = RcppDeepState_int(); qs::c_qsave(width,"/home/akhila/fuzzer_packages/fuzzedpackages/image.libfacedetection/inst/testfiles/detect_faces/inputs/width.qs", "high", "zstd", 1, 15, true, 1); std::cout << "width values: "<< width << std::endl; IntegerVector height(1); height[0] = RcppDeepState_int(); qs::c_qsave(height,"/home/akhila/fuzzer_packages/fuzzedpackages/image.libfacedetection/inst/testfiles/detect_faces/inputs/height.qs", "high", "zstd", 1, 15, true, 1); std::cout << "height values: "<< height << std::endl; IntegerVector step(1); step[0] = RcppDeepState_int(); qs::c_qsave(step,"/home/akhila/fuzzer_packages/fuzzedpackages/image.libfacedetection/inst/testfiles/detect_faces/inputs/step.qs", "high", "zstd", 1, 15, true, 1); std::cout << "step values: "<< step << std::endl; std::cout << "input ends" << std::endl; try{ detect_faces(x,width[0],height[0],step[0]); } catch(Rcpp::exception& e){ std::cout<<"Exception Handled"<<std::endl; } }
[ "akhilakollasrinu424jf@gmail.com" ]
akhilakollasrinu424jf@gmail.com
d8bf77d6accea037bbddb29d90507548905737ab
46323ea33d41bd31aa8eb65afbec8ebbab89b818
/Proximity/Proximity.ino
29a0806f28f15e6497acd04199df8f6ad8eb82e6
[ "MIT" ]
permissive
smcolash/proximity
712b4a7b6dee579eec18ef4003c82b5e47e69070
e7ebc2e0a7cbc684fd7c90886425c95ed17344a1
refs/heads/main
2023-07-06T05:40:58.777237
2021-08-10T01:49:25
2021-08-10T01:49:25
394,466,698
1
0
null
null
null
null
UTF-8
C++
false
false
7,489
ino
// // include the standard Arduino WIFI definitions // #include <WiFi.h> // // also include the low-level ESP32 WIFI definitions // #include "esp_wifi.h" /** Set the status update interval to be one second, in milliseconds. */ const int INTERVAL_MS = 1 * 1000; /** Device configuration structure definition. */ typedef struct { String name; uint8_t macid[6]; int max_ttl_ms; int ttl_ms; } DEVICE; /** Access point configuration structure definition. */ typedef struct { String ssid; String password; } NETWORK; /** WIFI payload header structure: 802.11 Wireless LAN MAC frame. */ typedef struct { int16_t fctl; int16_t duration; uint8_t dest_mac[6]; // the device MACID may appear here uint8_t source_mac[6]; // ...or it may appear here uint8_t bssid[6]; // ...or or it may appear here int16_t seqctl; uint8_t payload[]; } sniffer_payload_t; /** Index to the current access point configuration record. */ int network = -1; /** Access point channel on which to sniff packets. */ int channel = 5; /** * All of the user-specific or site-specific configuration data. */ #include "Configuration.h" /** Packet sniffer callback function. */ void sniffer (void* buffer, wifi_promiscuous_pkt_type_t type) { // // this code runs as a callback _within_ the WiFi handler and must be as fast as possible, // if this code is slower than the input data rate then the code will crash // wifi_promiscuous_pkt_t *packet = (wifi_promiscuous_pkt_t*) buffer; int length = packet->rx_ctrl.sig_len - sizeof (sniffer_payload_t); sniffer_payload_t *payload = (sniffer_payload_t*) packet->payload; // // define an an array of parts of the frame to inspect as a way to simplify the code // uint8_t *macids[] = { payload->dest_mac, payload->source_mac, payload->bssid }; // // loop over the devices and the items in the frame to compare // if (length > 0) { for (int loop = 0; loop < sizeof (devices) / sizeof (devices[0]); loop++) { for (int id = 0; id < sizeof (macids) / sizeof (macids[0]); id++) { if (memcmp (macids[id], devices[loop].macid, sizeof (devices[loop].macid)) == 0) { devices[loop].ttl_ms = devices[loop].max_ttl_ms; } } } } } /** Function to initialize sniffing/promiscuous mode. */ void init_sniffing (void) { // // totally de-initialize the Arduino WIFI stack first // WiFi.disconnect (true); WiFi.mode (WIFI_OFF); esp_wifi_deinit (); // // use the low-level ESP32 code to do the sniffing // wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); esp_wifi_init (&cfg); esp_wifi_set_storage (WIFI_STORAGE_RAM); esp_wifi_set_mode (WIFI_MODE_NULL); esp_wifi_start (); esp_wifi_set_promiscuous_rx_cb (&sniffer); esp_wifi_set_promiscuous (true); esp_wifi_set_channel (channel, WIFI_SECOND_CHAN_NONE); Serial.print ("scanning channel "); Serial.print (channel); Serial.print (" on "); Serial.print (networks[network].ssid); Serial.println (); } /** Function to initialize normal station access mode. */ void init_station (void) { // // disable sniffing before using the Arduino WIFI stack // esp_wifi_set_promiscuous (false); // // set the network hostname // WiFi.config (INADDR_NONE, INADDR_NONE, INADDR_NONE, INADDR_NONE); WiFi.setHostname ("proximity"); // // typical Arduino WIFI station initialization // WiFi.mode (WIFI_STA); WiFi.begin (networks[network].ssid.c_str (), networks[network].password.c_str ()); while (WiFi.status () != WL_CONNECTED) { delay (500); Serial.print ("."); } Serial.println (); Serial.print ("connected to "); Serial.print (networks[network].ssid); Serial.print (" as "); Serial.print (WiFi.localIP ()); Serial.println (); } /** Function to send IOT control update requests. */ void toggle (bool state) { // // get into station mode first // init_station (); // // form the IOT request message // String trigger = "proximity_false"; if (state) { Serial.println ("TURN ON"); trigger = webhook_trigger_on; } else { Serial.println ("TURN OFF"); trigger = webhook_trigger_off; } String host = "maker.ifttt.com"; const int port = 80; const String url = "/trigger/" + trigger + "/with/key/" + webhook_key; // // send the IFTTT Webhook request message and process the response // Serial.println ("----------------------------------------"); Serial.println ("http://" + host + ":" + String (port) + url); Serial.println ("----------------------------------------"); WiFiClient client; if (client.connect (host.c_str (), port)) { try { client.print ("GET " + url + " HTTP/1.1\r\n"); client.print ("Host: " + host + "\r\n"); client.print ("Connection: close\r\n"); client.print ("\r\n"); unsigned long timeout = millis (); while (client.available () == 0) { if (millis () - timeout > 5000) { Serial.println ("** client timeout **"); throw true; } } while (client.available ()) { String line = client.readStringUntil ('\r'); Serial.print (line); } } catch (...) { } client.stop (); Serial.println (); } Serial.println ("----------------------------------------"); // // start examining packets again // init_sniffing (); } /** Arduino sketch setup function to identify the local network and start packet sniffing. */ void setup () { // // initalize the serial/USB output for debugging/etc. // Serial.begin (115200); delay (250); // // set the network hostname // WiFi.config (INADDR_NONE, INADDR_NONE, INADDR_NONE, INADDR_NONE); WiFi.setHostname ("proximity"); // // find the first available/configured access point to use // WiFi.mode (WIFI_STA); while (true) { int count = WiFi.scanNetworks (); for (int j = 0; j < sizeof (networks) / sizeof (networks[0]); j++) { for (int i = 0; i < count; i++) { if (WiFi.SSID (i) == networks[j].ssid) { network = j; channel = WiFi.channel (i); } } } if (network < 0) { Serial.println ("error - failed to locate access point"); delay (30 * 1000); } else { break; } } // // get into station mode first // init_station (); // // start examining packets // init_sniffing (); } /** Arduino sketch loop function to determine of IOT updates are required. */ void loop () { // // hold the latest IOT control state // static bool state = false; // // update the device status and determine if any devices are in range // int ttl_ms = 0; for (int loop = 0; loop < sizeof (devices) / sizeof (devices[0]); loop++) { devices[loop].ttl_ms = max (devices[loop].ttl_ms - INTERVAL_MS, 0); ttl_ms = ttl_ms + devices[loop].ttl_ms; } #if 1 Serial.print (ttl_ms); Serial.print (" "); Serial.print (state); Serial.println (); #endif // // turn on the IOT device is any devices are in range // if ((state == false) && (ttl_ms > 0)) { state = true; toggle (state); } // // turn off the IOT device is no devices are in range // if ((state == true) && (ttl_ms == 0)) { state = false; toggle (state); } // // wait for more time/samples // delay (INTERVAL_MS); }
[ "s.mcolash@ieee.org" ]
s.mcolash@ieee.org
e2e7dbddb2824889bda2addf4e58a5fe798dce6f
7a32e5beb3e0af8ee35028f897af2d7bd0aa69c9
/考試-期初考練習/LinearSearch 陣列/A2.cpp
9b279857a3bf491bd64aac04842368bbf1c9532a
[]
no_license
redblaze1/Programming-C
86fdfb0f328ab27f92adbda25b089443e7f238c7
dbb60ed00e5b5dc25947ab3e283510233dc63841
refs/heads/master
2021-04-27T12:21:09.915109
2018-05-25T09:06:52
2018-05-25T09:06:52
122,579,448
0
0
null
null
null
null
UTF-8
C++
false
false
193
cpp
#include<iostream> using namespace std; int main (){ int a[7]={3, 5, 7, 2, 4, 8, 6}; int count=0,b; cin >> b; for(int i=0;i<=6;i++){ if(a[i]==b) break; count++; } cout << count; }
[ "cccvvv2108@gmail.com" ]
cccvvv2108@gmail.com
b3feb6d8a3a3a990fd2450bd45b76ebbe5aeb278
beaaa927185dcd17184e3e6ea346d003916a1068
/platforms/m3/pre_v21e/software/mbc_code/decoder/decoder.cpp
20a9c10a173d74bdb3491217389ccc4d8604b970
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
lab11/M-ulator
aeb65cb46c4e2ceaf9e014edbca4d41b3e97dc20
a7debc76a22aed467f3135c9be6913c74d5794f1
refs/heads/master
2023-08-31T14:48:24.603783
2023-08-25T19:05:00
2023-08-25T19:05:00
5,779,032
23
11
NOASSERTION
2021-01-22T16:34:47
2012-09-12T11:51:41
C
UTF-8
C++
false
false
18,994
cpp
/******************************* * * Monarch decoder v1.0.7 * Author: Roger Hsiao * * Works with mbc_code.c v5.2.3 and above * Usage: ./decoder.exe [packets] [date.log | 0] [time.log | 0] [light out file] [temp out file] [delimeter] * * v1.0.0: * Added automatic time translation * * v1.0.1: * Decoding doesn't halt when encountering an Unrecognized code anymore * * v1.0.2: * Updated decoder to use local date instead of epoch date * * v1.0.3: * Not subtracting timezone difference in time.log to get GMT time * * v1.0.4: * Fixed decoder index bug that doesn't update index properly, which causes a timeshift * * v1.0.5: * Reading date_tz correctly now. And adding date_tz to the temp timestamps * * v1.0.6: * Adding delimeter option * Adding support for missing packets XXX * * v1.0.7: * The program now takes in different options: -d for delimeter and -c for config files * The config files now set up the correct resampling indices * * *******************************/ #include <iostream> #include <fstream> #include <bitset> #include <string> #include <map> #include <cmath> #include <unistd.h> #include <stdexcept> #include <getopt.h> #include <vector> #include <memory> #include "../huffman_encodings.h" // #include "/home/rogerhh/M-ulator/platforms/m3/pre_v20e/software/mbc_code/huffman_encodings.h" #define DAWN 0 #define NOON 1 #define DUSK 2 #define NIGHT 3 using namespace std; // using Unit = bitset<272>; struct Unit { int len = 0; bitset<272> data; }; struct NoMoreData { string str = "No more data in unit\n"; }; Unit create_unit(const string packets[]); uint32_t get_data(Unit& u, int len); vector<uint16_t> resample_indices = {32, 40, 44, 1000}; uint16_t intervals[4] = {1, 2, 8, 32}; class LightParser { public: uint32_t sys_time_in_min = 0; int day_state = 0; int index = 0; map<uint32_t, double> data; map<int, map<int, int>> codes; void parse_unit(Unit& u); void read_header(Unit& u); void read_timestamp(Unit& u); LightParser(); }; class TempParser { public: map<uint32_t, double> data; map<int, map<int, int>> codes; void parse_unit(Unit& u); TempParser(); }; struct RAII_File { string filename; RAII_File(string filename_in) : filename(filename_in) {} ~RAII_File() { cout << "Removing temp file: " << filename << endl; int rc = system(("rm " + filename).c_str()); } }; vector<unique_ptr<RAII_File>> temp_files; static struct option long_options[] = { {"delimeter", required_argument, NULL, 'd'}, {"config", required_argument, NULL, 'c'} }; void make_python_yaml_parser(const string& filename); int main(int argc, char** argv) { if(argc < 6) { cerr << "Usage: ./decoder.exe packet_file date.log time.log <light_output_file> <temp_output_file> [-d <delimeter>] [-c <config_file>]" << endl; return 1; } string packet_filename = string(argv[1]); ifstream fin(packet_filename); if(!fin.is_open()) { cerr << "Error opening: " << packet_filename << endl; return 1; } string date_log = string(argv[2]); ifstream date_fin(date_log); if(date_log != "0" && !date_fin.is_open()) { cerr << "Error opening: " << date_log << endl; return 1; } string time_log = string(argv[3]); ifstream time_fin(time_log); if(time_log != "0" && !time_fin.is_open()) { cerr << "Error opening: " << time_log << endl; return 1; } bool no_time_translation = date_log == "0"; string light_filename = string(argv[4]); ofstream light_fout(light_filename); if(!light_fout.is_open()) { cerr << "Error opening: " << light_filename << endl; return 1; } string temp_filename = string(argv[5]); ofstream temp_fout(temp_filename); if(!temp_fout.is_open()) { cerr << "Error opening: " << temp_filename << endl; return 1; } string config_filename = ""; bool using_config = false; char delim = ','; char ch; while((ch = getopt_long(argc, argv, "c:d:", long_options, NULL)) != -1) { switch(ch) { case 'd': delim = optarg[0]; break; case 'c': config_filename = string(optarg); using_config = true; break; default: cerr << "Unrecognized option: " << ch << endl; return 1; } } // We're running the python parser outside of the c++ code because I don't want // everyone to have to download and install yaml-cpp if(using_config) { int rc = system(("ls " + config_filename + " 2> /dev/null").c_str()); if(rc != 0) { cerr << "Unable to find file: " << config_filename << endl; return 1; } rc = system("ls read_yaml.py 2> /dev/null"); if(rc != 0) { cerr << "Unable to find python parser: read_yaml.py in the decoder directory. Creating one temporarily." << endl; make_python_yaml_parser("read_yaml.py"); } string tmp_name = "decoder_yaml_parser.tmp"; rc = system(("ls " + tmp_name + " 2> /dev/null").c_str()); if(rc == 0) { cerr << "Temporary file: " + tmp_name + " exists! Manually deleting it." << endl; rc = system(("rm " + tmp_name + " 2> /dev/null").c_str()); } unique_ptr<RAII_File> ptr(new RAII_File(tmp_name)); temp_files.push_back(move(ptr)); rc = system(("python read_yaml.py " + config_filename + " " + tmp_name + " > /dev/null").c_str()); if(rc != 0) { cerr << "yaml parsing failed. Please contact maintainer" << endl; return 1; } // all config related stuff should be parsed here ifstream config_fin(tmp_name); if(!config_fin.is_open()) { cerr << " Error opening file: " << tmp_name << endl; return 1; } int resample_indices_len; config_fin >> resample_indices_len; resample_indices.resize(resample_indices_len); for(int i = 0; i < resample_indices_len; i++) { config_fin >> resample_indices[i]; } } double abs_time = 0, programmed_time = 0, tz = 0, trigger_fire_date = 0, date_tz = 0; if(!no_time_translation) { // Read UTC offset int programmed_date = 0; string trash; getline(date_fin, trash, ':'); date_fin >> trigger_fire_date; getline(date_fin, trash, '('); date_fin >> date_tz; getline(date_fin, trash, ':'); date_fin >> programmed_date; cout << trigger_fire_date << " " << programmed_date << endl; char c; getline(time_fin, trash, ':'); time_fin >> abs_time; getline(time_fin, trash, ':'); time_fin >> programmed_time >> c >> c >> tz; cout << programmed_date << " " << (int) abs_time << " " << programmed_time << " " << tz << endl; } else { cout << "No auto time translation" << endl; } LightParser lp; TempParser tp; string packets[4]; while(fin >> packets[0] >> packets[1] >> packets[2] >> packets[3]) { auto u = create_unit(packets); if(u.len > 0) { cout << u.len << endl; cout << packets[0].substr(0, 1) << endl; if(stoi(packets[0].substr(0, 1), 0, 16) & 0b1000) { // is light lp.parse_unit(u); } else { // is temp tp.parse_unit(u); } } } for(auto p : lp.data) { // Not doing anything with timezone because it seems like it's already done by python light_fout << fixed << p.first << delim << p.first + abs_time + 0 * tz << delim << p.second << delim << pow(2, (p.second / 32.0)) << endl; } for(auto p : tp.data) { temp_fout << fixed << p.first + trigger_fire_date * 86400 + date_tz << delim << pow(2, ((p.second + 128) / 16.0)) << endl; } } Unit create_unit(const string packets[]) { Unit u; u.data = bitset<272>(0); bool flag = false; for(int i = 0; i < 4; i++) { for(int j = 3; j < packets[i].size(); j++) { // If found an X, stop reading unit if(packets[i].substr(j, 1) == "X") { flag = true; break; } u.len += 4; u.data <<= 4; u.data |= bitset<272>(stoi(packets[i].substr(j, 1), 0, 16)); } if(flag) { break; } } // Fill in 0s for the rest of the unit that was not read in due to a missing packet u.data <<= (272 - u.len); cout << u.data << endl; return u; } uint32_t get_data(Unit& u, int len) { // if len > maximum valid data, throw an error if(u.len < len) { throw NoMoreData{}; } u.len -= len; uint32_t mask = (1 << len) - 1; auto temp = u.data; temp >>= (272 - len); temp &= mask; u.data <<= len; return temp.to_ulong(); } LightParser::LightParser() { // preprocess codes for(int i = 0; i < 67; i++) { auto code = light_diff_codes[i]; auto len = light_code_lengths[i]; if(i == 64) { codes[len][code] = 0x1FF; } else if(i == 65) { codes[len][code] = 0x7FF; } else if(i == 66) { codes[len][code] = 0x1000; } else { codes[len][code] = i - 32; } } } uint32_t sign_extend(uint32_t src, int len) { if(src & (1 << (len - 1))) { cout << "sign extend neg" << endl; return src - (1 << len); } else { return src; } } void LightParser::read_timestamp(Unit& u) { auto t = get_data(u, 17); // Not worried about overflow for now // TODO: add support for potential overflow of the 17bits of time sys_time_in_min = t; cout << "parsed time in min = " << sys_time_in_min << endl; } void LightParser::read_header(Unit& u) { day_state = get_data(u, 2); cout << "day state = " << day_state << endl; if(day_state == NIGHT) { throw runtime_error("Invalid day state!"); } index = get_data(u, 7); cout << "index: " << index << endl; cout << "day state = " << day_state << endl; } void LightParser::parse_unit(Unit& u) { bool has_header = false; bool has_timestamp = false; bool has_cur = false; int cur = 0; cout << "light_unit" << endl; if(u.len != 272) { // missing packet in this unit cout << "Warning: Missing packet in this unit" << endl; } try { // If an error is throw, it means that there is no more valid data in this unit // it could be that there is a missing packet or there is no space in the last packet to put // in the ending code of the unit. In both cases, just abort reading the unit while(u.data.any()) { cout << "u any = " << u.data.any() << " " << u.data << endl; if(!has_timestamp) { read_timestamp(u); has_timestamp = true; } if(!has_header) { read_header(u); has_header = true; } if(!has_cur) { // read initial val cur = get_data(u, 11); has_cur = true; } else { // else read code int len = 0; int tmp = 0; bool flag = false; // According to the Huffman encoding table, there cannot be a code longer than 12 bits while(len < 12) { int b = get_data(u, 1); tmp <<= 1; tmp |= b; len++; cout << "codes: " << len << " " << tmp << " " << bitset<12>(tmp) << endl; auto it = codes.find(len); if(it == codes.end()) { continue; } auto it2 = codes[len].find(tmp); if(it2 == codes[len].end()) { continue; } auto code = it2->second; cout << "code: " << code << endl; if(code == 0x1000) { day_state = (day_state + 1) & 0b11; if(day_state == NIGHT) { day_state = DAWN; } index = 0; cout << "end day state" << endl; cout << "day state = " << day_state << "; index = " << 0 << endl; has_timestamp = false; } else if(code == 0x7FF) { // don't use diff code = get_data(u, 11); cout << "diff 11" << endl; cur = code; } else if(code == 0x1FF) { code = get_data(u, 9); cout << "diff 9: code: " << bitset<9>(code) << endl; code = sign_extend(code, 9); cout << "exteneded: " << code << endl; cur += code; } else { cur += code; } // set flag to true if found code flag = true; break; } if(!flag) { cout << u.data << endl; cout << "Unrecognized code" << endl; continue; throw runtime_error("Unrecognized code: " + to_string(tmp)); } if(!has_timestamp) { continue; } } data[sys_time_in_min * 60] = cur; cout << sys_time_in_min << " " << sys_time_in_min * 60 << " " << cur << endl; index++; // update sys_time_in_min for next data point if(u.data.any()) { if(day_state == DAWN) { for(int i = 0; i < 4; i++) { if(index < resample_indices[i]) { sys_time_in_min += intervals[i]; cout << " test" << endl; break; } } } else if(day_state == DUSK) { for(int i = 0; i < 4; i++) { if(index < resample_indices[i]) { sys_time_in_min -= intervals[i]; break; } } } else { sys_time_in_min += 32; } } } } catch(NoMoreData& e) { cout << "No more valid data in this unit." << endl; } cout << "End unit. sys_time_in_min = " << sys_time_in_min << endl << endl; return; } void TempParser::parse_unit(Unit& u) { uint32_t day_count = get_data(u, 7); uint32_t timestamp_in_half_hour = get_data(u, 6); uint32_t cur_value = get_data(u, 7); data[day_count * 86400 + timestamp_in_half_hour * 1800] = cur_value; cout << day_count * 86400 + timestamp_in_half_hour * 1800 << " " << cur_value << endl; if(u.len != 272) { // missing packet in this unit cout << "Warning: Missing packet in this unit" << endl; } try { while(u.data.any()) { cout << u.data << endl; int len = 0; int tmp = 0; bool flag = false; while(len < 4) { int b = get_data(u, 1); tmp <<= 1; tmp |= b; len++; cout << "temp codes: " << len << " " << tmp << " " << bitset<4>(tmp) << endl; auto it = codes.find(len); if(it == codes.end()) { continue; } auto it2 = codes[len].find(tmp); if(it2 == codes[len].end()) { continue; } auto code = it2->second; cout << "temp code: " << code << endl; if(code == 0x7F) { code = get_data(u, 7); cout << "diff 7" << endl; cur_value = code; } else { cur_value += code; } flag = true; break; } if(!flag) { cout << "Unrecognized code" << endl; continue; throw runtime_error("Unrecognized code: " + to_string(tmp)); } timestamp_in_half_hour++; if(timestamp_in_half_hour >= 48) { timestamp_in_half_hour = 0; day_count++; } data[day_count * 86400 + timestamp_in_half_hour * 1800] = cur_value; cout << day_count << " " << timestamp_in_half_hour << endl; cout << day_count * 86400 + timestamp_in_half_hour * 1800 << " " << cur_value << endl; } } catch(NoMoreData& e) { cout << "No more valid data in this unit." << endl; } cout << "End temp unit" << endl; return; } TempParser::TempParser() { // preprocess codes for(int i = 0; i < 5; i++) { auto code = temp_diff_codes[i]; auto len = temp_code_lengths[i]; if(i == 4) { codes[len][code] = 0x7F; } else { codes[len][code] = i - 2; } } } // convoluted workaround solution to getting a yaml parser working in c++ // We are literally creating a python script to handle it void make_python_yaml_parser(const string& filename) { ofstream fout(filename); unique_ptr<RAII_File> ptr(new RAII_File(filename)); temp_files.push_back(std::move(ptr)); if(!fout.is_open()) { cerr << "Error opening filename: " << filename << endl; } fout << "import yaml\n" << "import sys\n" << "config_file = sys.argv[1]\n" << "with open(config_file, 'r') as file:\n" << " l = yaml.load(file, Loader=yaml.FullLoader)\n" << " samplings_indices = l['sample_indices']['val']\n" << " print(samplings_indices)\n" << "output_file = sys.argv[2]\n" << "with open(output_file, 'w') as file:\n" << " file.write('{}\\n'.format(len(samplings_indices)))\n" << " for i in samplings_indices:\n" << " file.write('{}\\n'.format(i))\n"; fout.close(); }
[ "rogerhh@umich.edu" ]
rogerhh@umich.edu
b07de473d4fb3a4c8acf07cb5aedbf6fc77e9b00
e0b91d640cf481aa9344fefe248b48f06eeb6ba3
/tests/unit/addmult.cpp
c31a97180a3bce4064dac72251db56644313f7a3
[]
no_license
hofstee/coreir
fbe983d46dc884c34c0db38ad2c46bcabc5fdedc
781587d6807f4198a9d84fb80a7b0dfbf3c36228
refs/heads/master
2021-09-06T21:47:59.981437
2017-04-20T22:35:00
2017-04-20T22:35:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,872
cpp
#include "context.hpp" #include "stdlib.hpp" #include "passes.hpp" using namespace CoreIR; // Create the following circuit // // in1 // \ // in0 - Add - Mult - out // / // C int main() { Context* c = newContext(); Namespace* stdlib = getStdlib(c); //Declare a brand new generator for some reason int constC = 3; //Type of module Type* addmultType = c->Record({ {"in",c->Array(16,c->BitIn())}, {"out",c->Array(16,c->BitOut())} }); //These will eventually be generators where you can pass in '16' Module* add2_16 = stdlib->getModule("add2_16"); Module* mult2_16 = stdlib->getModule("mult2_16"); Module* const_16 = stdlib->getModule("const_16"); Module* addmult = c->getGlobal()->newModuleDecl("addmult",addmultType); ModuleDef* def = addmult->newModuleDef(); Wireable* self = def->sel("self"); Wireable* addinst = def->addInstance("addinst",add2_16); Wireable* multinst = def->addInstance("multinst",mult2_16); Wireable* constinst = def->addInstance("const3",const_16,{{"value",c->int2Arg(constC)}}); def->wire(self->sel("in"),addinst->sel("in0")); def->wire(constinst->sel("out"),addinst->sel("in1")); def->wire(constinst->sel("out"),multinst->sel("in0")); def->wire(addinst->sel("out"),multinst->sel("in1")); addmult->addDef(def); addmult->print(); bool err = false; //Do typechecking typecheck(c,addmult,&err); if(err) c->die(); //Save to Json cout << "Saving 2 json" << endl; saveModule(addmult,"_addmult.json",&err); if(err) c->die(); deleteContext(c); c = newContext(); getStdlib(c); cout << "Loading json" << endl; Module* m = loadModule(c,"_addmult.json",&err); if(err) c->die(); cout << "Saving json again" << endl; saveModule(m,"_addmult2.json",&err); c->getGlobal()->print(); deleteContext(c); return 0; }
[ "rdaly525@stanford.edu" ]
rdaly525@stanford.edu
0acb0e1537e44b424e4e2870ec70325838d13ad1
27d530104fdaffdd29d86591326711b77516727e
/PBRT/src/cameras/fibonacci_sphere.cpp
334e9d7d5316585f31a15541e87a6825fc04185f
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
blockspacer/GIRadianceRegressionFunction
5dbc2c652d1d4c110000375d08891cfc2eda935f
4ea0cfa600c9ed85bf04ed308aa70d4dceff82f5
refs/heads/master
2021-03-23T19:31:01.678141
2018-11-27T18:11:31
2018-11-27T18:11:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,855
cpp
#include "fibonacci_sphere.h" #include "paramset.h" namespace pbrt { FibonacciCamera::FibonacciCamera(const AnimatedTransform &CameraToWorld, Float shutterOpen, Float shutterClose, Film *film, const Medium *medium) : Camera(CameraToWorld, shutterOpen, shutterClose, film, medium) { } Float FibonacciCamera::GenerateRay(const CameraSample &sample, Ray *ray) const { const Point2i res = this->film->fullResolution; const float PHI = 1.618f, PI = 3.141; ProfilePhase prof(Prof::GenerateCameraRay); //Direction calculation float x = std::min(std::max(sample.pFilm.x, 0.f), (float)res.x - 0.01f); float y = std::min(std::max(sample.pFilm.y, 0.f), (float)res.y - 0.01f); Float i = floor(y) * res.x + floor(x); Float n = res.y * res.x; Float p = 2.0f * PI * (i / PHI - floor(i / PHI)); Float z = 1.0f - ((2.0f * i) + 1.0f) / n; z = std::min(std::max(z, -1.0f), 1.0f); Float t = acos(z); Vector3f v = Vector3f(cos(p)*sin(t), sin(p)*sin(t), z); *ray = Ray(Point3f(0.0f, 0.0f, 0.0f), v / v.Length()); ray->time = Lerp(sample.time, shutterOpen, shutterClose); ray->medium = medium; *ray = CameraToWorld(*ray); return 1.0f; } FibonacciCamera *CreateRandomCamera(const ParamSet &params, const AnimatedTransform &cam2world, Film *film, const Medium *medium) { Float shutteropen = params.FindOneFloat("shutteropen", 0.f); Float shutterclose = params.FindOneFloat("shutterclose", 1.f); if (shutterclose < shutteropen) { Warning("Shutter close time [%f] < shutter open [%f]. Swapping them.", shutterclose, shutteropen); std::swap(shutterclose, shutteropen); } return new FibonacciCamera(cam2world, shutteropen, shutterclose, film, medium); } }
[ "kalach11491@gmail.com" ]
kalach11491@gmail.com
39a35a0d2f7ae3537e12a92be239ab3d2c2b16fd
60db84d8cb6a58bdb3fb8df8db954d9d66024137
/android-cpp-sdk/platforms/android-4/java/text/RuleBasedCollator.hpp
daf42c3a2544196333adf0e280a0c6982a858870
[ "BSL-1.0" ]
permissive
tpurtell/android-cpp-sdk
ba853335b3a5bd7e2b5c56dcb5a5be848da6550c
8313bb88332c5476645d5850fe5fdee8998c2415
refs/heads/master
2021-01-10T20:46:37.322718
2012-07-17T22:06:16
2012-07-17T22:06:16
37,555,992
5
4
null
null
null
null
UTF-8
C++
false
false
8,109
hpp
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: java.text.RuleBasedCollator ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_TEXT_RULEBASEDCOLLATOR_HPP_DECL #define J2CPP_JAVA_TEXT_RULEBASEDCOLLATOR_HPP_DECL namespace j2cpp { namespace java { namespace util { class Comparator; } } } namespace j2cpp { namespace java { namespace lang { class Cloneable; } } } namespace j2cpp { namespace java { namespace lang { class String; } } } namespace j2cpp { namespace java { namespace lang { class Object; } } } namespace j2cpp { namespace java { namespace text { class CollationKey; } } } namespace j2cpp { namespace java { namespace text { class Collator; } } } namespace j2cpp { namespace java { namespace text { class CharacterIterator; } } } namespace j2cpp { namespace java { namespace text { class CollationElementIterator; } } } #include <java/lang/Cloneable.hpp> #include <java/lang/Object.hpp> #include <java/lang/String.hpp> #include <java/text/CharacterIterator.hpp> #include <java/text/CollationElementIterator.hpp> #include <java/text/CollationKey.hpp> #include <java/text/Collator.hpp> #include <java/util/Comparator.hpp> namespace j2cpp { namespace java { namespace text { class RuleBasedCollator; class RuleBasedCollator : public object<RuleBasedCollator> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) J2CPP_DECLARE_METHOD(4) J2CPP_DECLARE_METHOD(5) J2CPP_DECLARE_METHOD(6) J2CPP_DECLARE_METHOD(7) J2CPP_DECLARE_METHOD(8) explicit RuleBasedCollator(jobject jobj) : object<RuleBasedCollator>(jobj) { } operator local_ref<java::util::Comparator>() const; operator local_ref<java::lang::Cloneable>() const; operator local_ref<java::lang::Object>() const; operator local_ref<java::text::Collator>() const; RuleBasedCollator(local_ref< java::lang::String > const&); local_ref< java::text::CollationElementIterator > getCollationElementIterator(local_ref< java::text::CharacterIterator > const&); local_ref< java::text::CollationElementIterator > getCollationElementIterator(local_ref< java::lang::String > const&); local_ref< java::lang::String > getRules(); local_ref< java::lang::Object > clone(); jint compare(local_ref< java::lang::String > const&, local_ref< java::lang::String > const&); local_ref< java::text::CollationKey > getCollationKey(local_ref< java::lang::String > const&); jint hashCode(); jboolean equals(local_ref< java::lang::Object > const&); }; //class RuleBasedCollator } //namespace text } //namespace java } //namespace j2cpp #endif //J2CPP_JAVA_TEXT_RULEBASEDCOLLATOR_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_TEXT_RULEBASEDCOLLATOR_HPP_IMPL #define J2CPP_JAVA_TEXT_RULEBASEDCOLLATOR_HPP_IMPL namespace j2cpp { java::text::RuleBasedCollator::operator local_ref<java::util::Comparator>() const { return local_ref<java::util::Comparator>(get_jobject()); } java::text::RuleBasedCollator::operator local_ref<java::lang::Cloneable>() const { return local_ref<java::lang::Cloneable>(get_jobject()); } java::text::RuleBasedCollator::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } java::text::RuleBasedCollator::operator local_ref<java::text::Collator>() const { return local_ref<java::text::Collator>(get_jobject()); } java::text::RuleBasedCollator::RuleBasedCollator(local_ref< java::lang::String > const &a0) : object<java::text::RuleBasedCollator>( call_new_object< java::text::RuleBasedCollator::J2CPP_CLASS_NAME, java::text::RuleBasedCollator::J2CPP_METHOD_NAME(0), java::text::RuleBasedCollator::J2CPP_METHOD_SIGNATURE(0) >(a0) ) { } local_ref< java::text::CollationElementIterator > java::text::RuleBasedCollator::getCollationElementIterator(local_ref< java::text::CharacterIterator > const &a0) { return call_method< java::text::RuleBasedCollator::J2CPP_CLASS_NAME, java::text::RuleBasedCollator::J2CPP_METHOD_NAME(1), java::text::RuleBasedCollator::J2CPP_METHOD_SIGNATURE(1), local_ref< java::text::CollationElementIterator > >(get_jobject(), a0); } local_ref< java::text::CollationElementIterator > java::text::RuleBasedCollator::getCollationElementIterator(local_ref< java::lang::String > const &a0) { return call_method< java::text::RuleBasedCollator::J2CPP_CLASS_NAME, java::text::RuleBasedCollator::J2CPP_METHOD_NAME(2), java::text::RuleBasedCollator::J2CPP_METHOD_SIGNATURE(2), local_ref< java::text::CollationElementIterator > >(get_jobject(), a0); } local_ref< java::lang::String > java::text::RuleBasedCollator::getRules() { return call_method< java::text::RuleBasedCollator::J2CPP_CLASS_NAME, java::text::RuleBasedCollator::J2CPP_METHOD_NAME(3), java::text::RuleBasedCollator::J2CPP_METHOD_SIGNATURE(3), local_ref< java::lang::String > >(get_jobject()); } local_ref< java::lang::Object > java::text::RuleBasedCollator::clone() { return call_method< java::text::RuleBasedCollator::J2CPP_CLASS_NAME, java::text::RuleBasedCollator::J2CPP_METHOD_NAME(4), java::text::RuleBasedCollator::J2CPP_METHOD_SIGNATURE(4), local_ref< java::lang::Object > >(get_jobject()); } jint java::text::RuleBasedCollator::compare(local_ref< java::lang::String > const &a0, local_ref< java::lang::String > const &a1) { return call_method< java::text::RuleBasedCollator::J2CPP_CLASS_NAME, java::text::RuleBasedCollator::J2CPP_METHOD_NAME(5), java::text::RuleBasedCollator::J2CPP_METHOD_SIGNATURE(5), jint >(get_jobject(), a0, a1); } local_ref< java::text::CollationKey > java::text::RuleBasedCollator::getCollationKey(local_ref< java::lang::String > const &a0) { return call_method< java::text::RuleBasedCollator::J2CPP_CLASS_NAME, java::text::RuleBasedCollator::J2CPP_METHOD_NAME(6), java::text::RuleBasedCollator::J2CPP_METHOD_SIGNATURE(6), local_ref< java::text::CollationKey > >(get_jobject(), a0); } jint java::text::RuleBasedCollator::hashCode() { return call_method< java::text::RuleBasedCollator::J2CPP_CLASS_NAME, java::text::RuleBasedCollator::J2CPP_METHOD_NAME(7), java::text::RuleBasedCollator::J2CPP_METHOD_SIGNATURE(7), jint >(get_jobject()); } jboolean java::text::RuleBasedCollator::equals(local_ref< java::lang::Object > const &a0) { return call_method< java::text::RuleBasedCollator::J2CPP_CLASS_NAME, java::text::RuleBasedCollator::J2CPP_METHOD_NAME(8), java::text::RuleBasedCollator::J2CPP_METHOD_SIGNATURE(8), jboolean >(get_jobject(), a0); } J2CPP_DEFINE_CLASS(java::text::RuleBasedCollator,"java/text/RuleBasedCollator") J2CPP_DEFINE_METHOD(java::text::RuleBasedCollator,0,"<init>","(Ljava/lang/String;)V") J2CPP_DEFINE_METHOD(java::text::RuleBasedCollator,1,"getCollationElementIterator","(Ljava/text/CharacterIterator;)Ljava/text/CollationElementIterator;") J2CPP_DEFINE_METHOD(java::text::RuleBasedCollator,2,"getCollationElementIterator","(Ljava/lang/String;)Ljava/text/CollationElementIterator;") J2CPP_DEFINE_METHOD(java::text::RuleBasedCollator,3,"getRules","()Ljava/lang/String;") J2CPP_DEFINE_METHOD(java::text::RuleBasedCollator,4,"clone","()Ljava/lang/Object;") J2CPP_DEFINE_METHOD(java::text::RuleBasedCollator,5,"compare","(Ljava/lang/String;Ljava/lang/String;)I") J2CPP_DEFINE_METHOD(java::text::RuleBasedCollator,6,"getCollationKey","(Ljava/lang/String;)Ljava/text/CollationKey;") J2CPP_DEFINE_METHOD(java::text::RuleBasedCollator,7,"hashCode","()I") J2CPP_DEFINE_METHOD(java::text::RuleBasedCollator,8,"equals","(Ljava/lang/Object;)Z") } //namespace j2cpp #endif //J2CPP_JAVA_TEXT_RULEBASEDCOLLATOR_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
[ "baldzar@gmail.com" ]
baldzar@gmail.com
c5412c57e07d2d4adb729e16ba0e2676891e4c26
4c321372541e986449b150fb9ef268e2c619cfab
/gitTestQt/main.cpp
786218248d0fe335042e5d1b0ba08f3ba8235047
[]
no_license
cj123sn/testPro
df704fe32e9fef7a12d5534bff8274a1b6ac9a83
8d0d2125d3a501b278077db0d12de61338c44e92
refs/heads/master
2020-03-28T20:15:14.711228
2018-09-17T07:36:01
2018-09-17T07:36:01
149,053,387
0
0
null
null
null
null
UTF-8
C++
false
false
152
cpp
#include "GitWgt.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); GitWgt w; w.show(); return a.exec(); }
[ "331324937@qq.com" ]
331324937@qq.com
4b6590c093f1a024981a2b0d150d6b489ad55bfe
6310271905b4bf8c4edab06671ee3ceeb635174e
/controller_camera/cameracontrol.h
799bb347bacf8c935e825445feee931849ee8a9c
[]
no_license
Pacifist117/Project-Deathblade
096a9cac6a844e13f2343d50cb2abd0028e80b9e
c20525173511891ad8d544beaf7989e8ec53554d
refs/heads/master
2021-01-21T03:02:53.877839
2015-05-01T04:23:19
2015-05-01T04:23:19
29,574,183
0
1
null
2020-10-01T15:25:12
2015-01-21T05:58:50
C++
UTF-8
C++
false
false
6,700
h
#ifndef CAMERACONTROL_H #define CAMERACONTROL_H #include "controller_base/gameenums.h" #include "controller_base/tempsettings.h" #include "controller_base/controlbaseclass.h" #include <iostream> #include <cmath> #include <vector> #include "SDL.h" /*! * \brief The CameraControl class moves the camera according to mouse and mouse wheel inputs. * * This class functions on the concept that the camera is an object in the game's 3D space. The * x,y dimension are the plane of the game with (0,0) being the top left corner, and the z dimension * is 'above' the game. */ class CameraControl : public ControlBaseClass { public: /*! * \brief Constructor for class * \param gamesettings The pointer to the main game controller. (sort of a parent object) */ CameraControl(TempSettings *gamesettings); ~CameraControl(); /*! * \brief Based on input (usually from the mouse wheel), changes the z-value of the camera. * * \param input Negative values zoom out and positive values zoom in. * \param mouse_x Used to zoom in where mouse is pointing. In pixels. * \param mouse_y Used to zoom in where mouse is pointing. In pixels. */ void adjust_zoom(int input, double mouse_x, double mouse_y); /*! * \brief Moves the camera based on mouse movement if mouse_control==true * \param relative_x X movement of the mouse in pixels * \param relative_y Y movement of the mouse in pixels */ void mousecontrol_move(int mouse_x, int mouse_y, int relative_x, int relative_y, bool rotating); /*! * \brief Moves the camera based on input from wasd/arrows/mouse(not yet). Speed is pan_speed setting. * \param xdirection -1 for left, +1 for right */ void pan_leftright(int xdirection); /*! * \brief Moves the camera based on input from wasd/arrows/mouse(not yet). Speed is pan_speed setting. * \param xdirection -1 for up, +1 for down */ void pan_updown(int ydirection); /*! * \brief Rotates the camera clockwise on input from ctrl+mouse movement. * \param delta_theta Change in camera angle to rotate. */ void rotate_view(double delta_theta); /*! * \brief Given a position in space, calculates the pixel destination. * \param x X position in space * \param y Y position in space * \param w Width of object in space * \param h Height of object in space * \param zplane Which plane the object is on. * \return Destination rectangle for rendering. */ SDL_Rect calculate_display_destination ( double x, double y, double w, double h, db::ZPlane zplane); /*! * \brief Uses the pointers to an objects x,y as camx,y inputs. * \param objectx Pointer to the x value of the object to be tracked. * \param objecty Pointer to the y value of the object to be tracked. */ void track_object(double* objectx, double* objecty); /*! * \brief Sets tracking_on to false and the x,y pointers to null. */ void stop_tracking(); // These functions calculate space coordinates from pixel dimensions double xfrompixel(int pixelX, int pixelY, db::ZPlane z); double yfrompixel(int pixelX, int pixelY, db::ZPlane z); double wfrompixel(int pixelW, db::ZPlane z); double hfrompixel(int pixelH, db::ZPlane z); // These functions calculate pixel coordinates from space dimensions int pixelfromx(double x, double y, db::ZPlane z); int pixelfromy(double x, double y, db::ZPlane z); int pixelfromw(double w, db::ZPlane z); int pixelfromh(double h, db::ZPlane z); // inherited functions void update_settings(); std::string parse_arguments(std::vector<std::string> args); // Basic private member manipulation void mousecontrol_on(){ mouse_control = true;} void mousecontrol_off(){ mouse_control = false;} bool mouse_controlling(){ return mouse_control;} bool is_tracking(){ return tracking_on;} double camyaw; //!< Yaw of of the camera (rotate view) (in radians) protected: /*! * \brief Checks camx and camy versus the max and min of each. * * This calculation is based on max/min_x/y of course, but also * tanfovx/y and x/y_sidebuffer. */ void checkcamxy(); /*! * \brief Based on the rotation of the camera, this function calculates the min/max 'x/y' the camera can see. * * x and y are in quotation because it is really the x/y projected onto the camera's horizontal/vertical axes. */ void calculate_camera_bounds(); /*! * \brief Pointer to the object dealing with basic game settings such as resolution. */ TempSettings *game_settings; double camx; //!< X world coordinate of camera double camy; //!< Y world coordinate of camera double camz; //!< Z world coordinate of camera double* xtracking; //!< X world coordinate to track double* ytracking; //!< Y world coordinate to track double maxview_w; //!< Max horizontal view distance of the camera double minview_w; //!< Min horizontal view distance of the camera double maxview_h; //!< Max vertical view distance of the camera double minview_h; //!< Min vertical view distance of the camera double max_z; //!< Max Z world coordinate of camera double min_z; //!< Min Z world coordinate of camera bool mouse_control; //!< Toggle for when mouse is in control bool tracking_on; //!< Toggle for camx/y tracks x/ytracking pointers // player prefernce settings double zoomin_speed; //!< Sensitivity of mousewheel up: zoom in double zoomout_speed; //!< Sensitivity of mousewheel down: zoom out double zoom_friction; //!< How quickly the camera loses momentum bool momentum_on; //!< Turn momentum off double sidebuffer; //!< Viewable distance of map double pan_speed; //!< Speed of panning with wasd/arrows/mouse double fieldofview_w; //!< Field of view in the x direction (in radians) double fieldofview_h; //!< Field of view in the y direction (in radians) // Other variables used internally. std::vector<double> planeZs; //!< The depths associated with each ZPlane std::vector<double> pixelratio; //!< Pixels per world unit, for each ZPlane double dx,dy,dz; //!< Speed of camera movement used for momentum. //convenient double tanfov_w; //!< tangent of fieldofview_w/2 double tanfov_h; //!> tangent of fieldofview_h/2 }; #endif // CAMERACONTROL_H
[ "jamesianburns@gmail.com" ]
jamesianburns@gmail.com
351d47c8d805d6e8ab217011b1eb348158d993c6
5d2c1d49ebcd7f10cb6bd1550f8549da370091e6
/modules/pixkit-image/src/multitoning/DMS2012/ChanduStanichWuTrager2014.cpp
a261e1872ed0c1f2bee36776d77aa0815dad2632
[]
no_license
ggookey123/pixkit
1b2aab2c37e5af34e92e941a6ed281b41baa9523
0a1c53c554ada46859fe761f2b91f875ca6c188d
refs/heads/master
2020-12-25T23:08:19.703218
2015-10-16T08:20:06
2015-10-16T08:20:06
44,241,408
1
0
null
2015-10-14T10:45:18
2015-10-14T10:45:18
null
ISO-8859-1
C++
false
false
17,756
cpp
#include "../../../include/pixkit-image.hpp" using namespace cv; using namespace std; Mat get_presentable_color(const int nColors){ // get presentable colors // input: number of colors // output: 32FC1 Mat of absorption, from small to large value, afa_1 to afa_S Mat vec1f(Size(nColors,1),CV_32FC1); for(int i=0;i<nColors;i++){ vec1f.ptr<float>(0)[i] = (float)i/((float)(nColors-1.)); } return vec1f.clone(); } map<float,int> get_map_of_absorption_to_daindex(const int nColors){ map<float,int> mapfi; Mat tones1f = get_presentable_color(nColors); for(int i=0;i<nColors-1;i++){ // the number of dither array mapfi.insert(pair<float,int>(tones1f.ptr<float>(0)[i],i)); } return mapfi; } // coordination correction inline int cirCC(int cor,int limitation){ int tempv = cor%limitation; if(tempv>=0){ return tempv; }else{ // if(tempv<0) return limitation+tempv; } } bool get_mode_param(bool &is_swap,const int mode,int &m,int &n,float &a0,float &a1,const Mat &tones1f,const Mat &dst1f,const Mat &init1f,const int &i,const int &j,float &new_cur_v,float &new_nei_v){ ////////////////////////////////////////////////////////////////////////// ///// position // swap, mode=0~7 if(mode==0){ m=1; n=-1; }else if(mode==1){ m=1; n=0; }else if(mode==2){ m=1; n=1; }else if(mode==3){ m=0; n=1; }else if(mode==4){ m=-1; n=1; }else if(mode==5){ m=-1; n=0; }else if(mode==6){ m=-1; n=-1; }else if(mode==7){ m=0; n=-1; }else{ m=0; n=0; } ////////////////////////////////////////////////////////////////////////// ///// get a0 and a1 if(mode>=0&&mode<=7){ // swap is_swap=true; new_cur_v = dst1f.ptr<float>(cirCC(i+m,dst1f.rows))[cirCC(j+n,dst1f.cols)]; new_nei_v = dst1f.ptr<float>(i)[j]; if(new_cur_v>=init1f.ptr<float>(i)[j]&&new_nei_v>=init1f.ptr<float>(cirCC(i+m,dst1f.rows))[cirCC(j+n,dst1f.cols)]){ a0 = new_cur_v - new_nei_v; }else{ a0 = 0.; // to inherit } a1 = -a0; }else{ // toggle is_swap=false; new_cur_v = tones1f.ptr<float>(0)[mode-8]; new_nei_v = 0.; if(new_cur_v>=init1f.ptr<float>(i)[j]){ a0 = new_cur_v - dst1f.ptr<float>(i)[j]; }else{ a0 = 0.; // to inherit } a1=0.; } return true; } void get_euclidean_map(const Mat &src1f,Mat &dst1f,Mat &clas1i,int &n_seed_points){ // calculate the Euclidean map as defined in paper, by the given src // calculate the number of seed points and assign labels for them clas1i.create(src1f.size(),CV_32SC1); clas1i.setTo(-1); n_seed_points=0; for(int i=0;i<src1f.rows;i++){ for(int j=0;j<src1f.cols;j++){ if(src1f.ptr<float>(i)[j]!=0){ n_seed_points++; clas1i.ptr<int>(i)[j] = n_seed_points; } } } // calculate distance dst1f.create(src1f.size(),CV_32FC1); for(int i=0;i<src1f.rows;i++){ for(int j=0;j<src1f.cols;j++){ int ne_half_size = 0; // the half size of the search region while(true){ // calculate the minimum distance with the given `ne_half_size` double temp_min_dist=99999.,this_distance=0.; int temp_min_x=0,temp_min_y=0; for(int k=-ne_half_size;k<=ne_half_size;k++){ bool is_seed_found = false; if(src1f.ptr<float>(cirCC(i+k,src1f.rows))[cirCC(j-ne_half_size,src1f.cols)]!=0){ // seed point is found is_seed_found = true; this_distance = sqrtf((float)k*k+(float)ne_half_size*ne_half_size); if(this_distance<temp_min_dist){ temp_min_dist = this_distance; temp_min_x = cirCC(j-ne_half_size,src1f.cols); temp_min_y = cirCC(i+k,src1f.rows); } } if(src1f.ptr<float>(cirCC(i+k,src1f.rows))[cirCC(j+ne_half_size,src1f.cols)]!=0){ // seed point is found is_seed_found = true; this_distance = sqrtf((float)k*k+(float)ne_half_size*ne_half_size); if(this_distance<temp_min_dist){ temp_min_dist = this_distance; temp_min_x = cirCC(j+ne_half_size,src1f.cols); temp_min_y = cirCC(i+k,src1f.rows); } } if(src1f.ptr<float>(cirCC(i-ne_half_size,src1f.rows))[cirCC(j+k,src1f.cols)]!=0){ // seed point is found is_seed_found = true; this_distance = sqrtf((float)k*k+(float)ne_half_size*ne_half_size); if(this_distance<temp_min_dist){ temp_min_dist = this_distance; temp_min_x = cirCC(j+k,src1f.cols); temp_min_y = cirCC(i-ne_half_size,src1f.rows); } } if(src1f.ptr<float>(cirCC(i+ne_half_size,src1f.rows))[cirCC(j+k,src1f.cols)]!=0){ // seed point is found is_seed_found = true; this_distance = sqrtf((float)k*k+(float)ne_half_size*ne_half_size); if(this_distance<temp_min_dist){ temp_min_dist = this_distance; temp_min_x = cirCC(j+k,src1f.cols); temp_min_y = cirCC(i+ne_half_size,src1f.rows); } } } if(temp_min_dist<50000.){ // means the points is found. dst1f.ptr<float>(i)[j] = temp_min_dist; clas1i.ptr<int>(i)[j] = clas1i.ptr<int>(temp_min_y)[temp_min_x]; break; } ne_half_size++; // for the next round, if is_seed_found is still false. } } } } double calc_distance(const Mat &src1f){ // calculate the average distance among dots by theory double distance=0.; for(int i=0;i<src1f.rows;i++){ for(int j=0;j<src1f.cols;j++){ if(src1f.ptr<float>(i)[j]!=0.){ distance+=1.; } } } distance/=(double)src1f.total(); if(distance>=0.5){ return 1./sqrtf(1.-distance); }else{ return 1./sqrtf(distance); } } void update_pixel_validation_map(const Mat &dst1f,const Mat &clasmap1i,const Mat &eucmap1f,Mat &pvmap1b,int n_seed_points){ // get min dist of each seed point Mat min_dist1f(Size(n_seed_points+1,1),CV_32FC1); // used to put the minimum distance of every seed point. min_dist1f.setTo(99999.); for(int i=0;i<pvmap1b.rows;i++){ for(int j=0;j<pvmap1b.cols;j++){ const int &seed_idx = clasmap1i.ptr<int>(i)[j]; const float &dist = eucmap1f.ptr<float>(i)[j]; if(dst1f.ptr<float>(i)[j]!=1){ // is not the maximum absorptance if(dist<min_dist1f.ptr<float>(0)[seed_idx]){ // and gets a smaller distance min_dist1f.ptr<float>(0)[seed_idx] = dist; } } } } // update pixel validation map pvmap1b.setTo(0); for(int i=0;i<pvmap1b.rows;i++){ for(int j=0;j<pvmap1b.cols;j++){ const int &seed_idx = clasmap1i.ptr<int>(i)[j]; const float &dist = eucmap1f.ptr<float>(i)[j]; if(dist<=min_dist1f.ptr<float>(0)[seed_idx]){ pvmap1b.ptr<uchar>(i)[j] = 1; // on, available point } } } } // SCDBS bool SCDBS(const cv::Mat &src1b, const cv::Mat &init1f,const bool is_first_grayscale,cv::Mat &dst1f,double *c_ppData,int FilterSize,const Mat &tones,const Mat &pixel_validation_map1b){ ////////////////////////////////////////////////////////////////////////// /// exceptions if(src1b.type()!=CV_8UC1){ assert(false); } if(FilterSize==1){ assert(false); }else if(FilterSize%2==0){ assert(false); } ////////////////////////////////////////////////////////////////////////// /// initialization const int &height = src1b.rows; const int &width = src1b.cols; dst1f.create(src1b.size(),CV_32FC1); ////////////////////////////////////////////////////////////////////////// /// get autocorrelation. int exFS=FilterSize; int halfFS=cvFloor((float)FilterSize/2.); double ** c_pp = new double * [exFS]; for(int i=0;i<exFS;i++){ c_pp[i]=&c_ppData[i*exFS]; } ////////////////////////////////////////////////////////////////////////// /// load original image Mat src1f(src1b.size(),CV_32FC1); src1b.convertTo(src1f,CV_32FC1); // get initial image dst1f = init1f.clone(); ////////////////////////////////////////////////////////////////////////// /// Change grayscale to absorb src1f = 1.-src1f/255.; /// get error matrix Mat em1f(src1b.size(),CV_32FC1); em1f = dst1f - src1f; /// get cross correlation Mat crosscoe1d(Size(width,height),CV_64FC1); crosscoe1d.setTo(0); for(int i=0;i<crosscoe1d.rows;i++){ for(int j=0;j<crosscoe1d.cols;j++){ for(int m=i-halfFS;m<=i+halfFS;m++){ for(int n=j-halfFS;n<=j+halfFS;n++){ crosscoe1d.ptr<double>(i)[j]+=em1f.ptr<float>(cirCC(m,height))[cirCC(n,width)]*c_pp[halfFS+m-i][halfFS+n-j]; } } } } ////////////////////////////////////////////////////////////////////////// ///// DBS process int BenefitPixelNumber; int nModes = 8+tones.cols; // number of modes, to all possibilities, thus 8 (swap) + different tones Mat dE1d(Size(nModes,1),CV_64FC1); while(1){ BenefitPixelNumber=0; for(int i=0;i<height;i++){ // entire image for(int j=0;j<width;j++){ ////////////////////////////////////////////////////////////////////////// // = = = = = trial part = = = = = // // initialize err 0: original err, 0~7: Swap, >=8: toggle. // 0 1 2 // 7 x 3 // 6 5 4 dE1d.setTo(0.); // original error =0 // change the delta error as per different replacement methods for(int mode=0;mode<nModes;mode++){ // get parameters int m,n; float a0=0.,a1=0.; bool is_swap=false; float new_cur_v,new_nei_v; get_mode_param(is_swap,mode,m,n,a0,a1,tones,dst1f,init1f,i,j,new_cur_v,new_nei_v); // set position // make sure all the candidate points are available under the given pixel_validation_map1b. They need to be all 'on'(1) to perform, o.w., avoid it. if(pixel_validation_map1b.ptr<uchar>(i)[j]!=0&&pixel_validation_map1b.ptr<uchar>(cirCC(i+m,height))[cirCC(j+n,width)]!=0){ // get error dE1d.ptr<double>(0)[mode]=(a0*a0+a1*a1) *c_pp[halfFS][halfFS] +2.*a0 *crosscoe1d.ptr<double>(i)[j] +2.*a0*a1 * c_pp[halfFS+m][halfFS+n] +2.*a1 * crosscoe1d.ptr<double>(cirCC(i+m,height))[cirCC(j+n,width)]; }else{ dE1d.ptr<double>(0)[mode]=0.; // assign a 0 to avoid this chagne. } } ////////////////////////////////////////////////////////////////////////// ///// get minimum delta error and its position int tempMinNumber =0; double tempMindE =dE1d.ptr<double>(0)[0]; // original error =0 for(int x=1;x<nModes;x++){ if(dE1d.ptr<double>(0)[x]<tempMindE){ // get smaller error only tempMindE =dE1d.ptr<double>(0)[x]; tempMinNumber =x; } } ////////////////////////////////////////////////////////////////////////// // = = = = = update part = = = = = // if(tempMindE<0.){ // error is reduced // get position, and check swap position int nm,nn; float a0=0.,a1=0.; bool is_swap=false; float new_cur_v,new_nei_v; get_mode_param(is_swap,tempMinNumber,nm,nn,a0,a1,tones,dst1f,init1f,i,j,new_cur_v,new_nei_v); // update current hft position dst1f.ptr<float>(i)[j] = new_cur_v; // update for(int m=-halfFS;m<=halfFS;m++){ for(int n=-halfFS;n<=halfFS;n++){ crosscoe1d.ptr<double>(cirCC(i+m,height))[cirCC(j+n,width)]+=a0*c_pp[halfFS+m][halfFS+n]; } } // update if(is_swap){ // swap case // update swapped hft position dst1f.ptr<float>(cirCC(i+nm,height))[cirCC(j+nn,width)] = new_nei_v; // update cross correlation for(int m=-halfFS;m<=halfFS;m++){ for(int n=-halfFS;n<=halfFS;n++){ crosscoe1d.ptr<double>(cirCC(i+m+nm,height))[cirCC(j+n+nn,width)]+=a1*c_pp[halfFS+m][halfFS+n]; } } } BenefitPixelNumber++; } // end of entire image } } if(BenefitPixelNumber==0){ break; } } ////////////////////////////////////////////////////////////////////////// /// release space delete [] c_pp; return true; } bool check_vec_stacking_constraint(vector<Mat> &vec_dst1f){ // make sure the vector conforms the property of stacking constraint. int ng = vec_dst1f.size(); CV_Assert(ng==256); for(int i=0;i<vec_dst1f[0].rows;i++){ for(int j=0;j<vec_dst1f[0].cols;j++){ for(int g=1;g<ng;g++){ if(vec_dst1f[g].ptr<float>(i)[j]<=vec_dst1f[g-1].ptr<float>(i)[j]){ //²Å¦Xstacking constraint // do nothing }else{ CV_Assert(false); } } } } return true; } ////////////////////////////////////////////////////////////////////////// bool pixkit::multitoning::ordereddithering::ChanduStanichWuTrager2014_genDitherArray(std::vector<cv::Mat> &vec_DA1b, int daSize, int nColors,float D_min){ // the N defined in paper is supposed as daSize in this program. ////////////////////////////////////////////////////////////////////////// ///// exceptions if(nColors<2){ CV_Error(CV_StsBadArg,"nColors should >= 2."); } if(daSize<1){ CV_Error(CV_StsBadArg,"daSize should >= 1."); } ////////////////////////////////////////////////////////////////////////// ///// init const uchar MAX_GRAYSCALE = 255; // defined R in paper const uchar MIN_GRAYSCALE = 0; const float afa_1 = 0; // parameter defined in paper ////////////////////////////////////////////////////////////////////////// // tones Mat tones = get_presentable_color(nColors); ////////////////////////////////////////////////////////////////////////// ///// initialization cv::Mat src1b, dst1f; src1b.create(Size(daSize, daSize), CV_8UC1); dst1f.create(Size(daSize, daSize), CV_32FC1); src1b.setTo(MIN_GRAYSCALE); dst1f.setTo(MIN_GRAYSCALE); // get coe Mat hvs_model_cpp; pixkit::halftoning::ungrouped::generateTwoComponentGaussianModel(hvs_model_cpp,43.2,38.7,0.02,0.06); // defined in their paper ////////////////////////////////////////////////////////////////////////// ///// process for masks of 0 to 255 Mat pre_dst1f; Mat init1f(Size(daSize, daSize), CV_32FC1); init1f.setTo(afa_1); // as described in paper, this value should be zero. cout<<"Generating screens..."<<endl; bool is_seed_pattern_generate = false; Mat pixel_validation_map1b(Size(daSize,daSize),CV_8UC1); // as defined in paper. It is used to determine which point is allowed to put dot on it. 1: accept; 0: not accept. pixel_validation_map1b.setTo(1); // initialize as all are acceptable. Mat euclidean_map1f,euclidean_clas_map1i; int n_seed_points; vector<Mat> vec_dst1f(256); // the number of masks. for(int i=0;i<256;i++){ vec_dst1f[i].create(Size(daSize,daSize),CV_32FC1); vec_dst1f[i].setTo(0.); } for (int eta = MAX_GRAYSCALE; eta >= MIN_GRAYSCALE; eta--){ // eta is defined as a grayscale in paper cout << "\tgrayscale = " << (int)eta << endl; ////////////////////////////////////////////////////////////////////////// ///// init src1b.setTo(eta); pre_dst1f = dst1f.clone(); // recode the result of dst(g-1) ////////////////////////////////////////////////////////////////////////// ///// process // check whether it's the first grayscale bool first_grayscale =false; if(cv::sum(init1f)[0]==0){ first_grayscale = true; } // process SCDBS(src1b,init1f,first_grayscale,dst1f,&(double&)hvs_model_cpp.data[0],hvs_model_cpp.rows,tones,pixel_validation_map1b); vec_dst1f[eta] = dst1f.clone(); ////////////////////////////////////////////////////////////////////////// ///// calc current distance if(!is_seed_pattern_generate){ double distance = calc_distance(dst1f); if(distance<=D_min){ // use seed pattern, and update pixel_validation_map1b is_seed_pattern_generate = true; // get euclidean_map get_euclidean_map(dst1f,euclidean_map1f,euclidean_clas_map1i,n_seed_points); } } ////////////////////////////////////////////////////////////////////////// ///// update the pixel validation map if(is_seed_pattern_generate){ update_pixel_validation_map(dst1f,euclidean_clas_map1i,euclidean_map1f,pixel_validation_map1b,n_seed_points); } ////////////////////////////////////////////////////////////////////////// ///// get init init1f = dst1f.clone(); } ////////////////////////////////////////////////////////////////////////// ///// get screens ///// record position that the white point is firstly toggled // check check_vec_stacking_constraint(vec_dst1f); // initialize the dither arrays vec_DA1b.resize(nColors-1); for(int di=0;di<vec_DA1b.size();di++){ vec_DA1b[di].create(Size(daSize, daSize), CV_8UC1); vec_DA1b[di].setTo((float)MAX_GRAYSCALE); } // get screen map<float,int> mapfi = get_map_of_absorption_to_daindex(nColors); for(int gray=1;gray<=255;gray++){ for (int i = 0; i < vec_dst1f[gray].rows; i++){ for (int j = 0; j < vec_dst1f[gray].cols; j++){ if(vec_dst1f[gray].ptr<float>(i)[j]!=vec_dst1f[gray-1].ptr<float>(i)[j]){ // changed // get index int index = mapfi[vec_dst1f[gray].ptr<float>(i)[j]]; // absorption to index of da for(int iidx=index;iidx>=0;iidx--){ vec_DA1b[iidx].ptr<uchar>(i)[j] = gray; } } } } } return true; } bool pixkit::multitoning::ordereddithering::ChanduStanichWuTrager2014(const cv::Mat &src1b, const std::vector<cv::Mat> &vec_DA1b,cv::Mat &dst1b){ // perform DMS screening process // output: dst1b ////////////////////////////////////////////////////////////////////////// ///// initialization const int MAX_GRAYSCALE = 255; int nColors = vec_DA1b.size()+1; // presentable number of colors Mat tones1f = get_presentable_color(nColors); // from range of 0 to 1 tones1f = (1.-tones1f) * ((float) MAX_GRAYSCALE); // absorption to grayscale ////////////////////////////////////////////////////////////////////////// dst1b.create(src1b.size(),src1b.type()); for(int i=0;i<src1b.rows;i++){ for(int j=0;j<src1b.cols;j++){ const uchar &curr_tone = src1b.ptr<uchar>(i)[j]; bool ishalftoned = false; for(int g=0;g<nColors-1;g++){ // try every dither array const uchar &thres = vec_DA1b[g].ptr<uchar>(i%vec_DA1b[g].rows)[j%vec_DA1b[g].cols]; if(curr_tone>=thres){ dst1b.ptr<uchar>(i)[j] = cvRound(tones1f.ptr<float>(0)[g]); ishalftoned = true; break; } } if(!ishalftoned){ dst1b.ptr<uchar>(i)[j] = cvRound(tones1f.ptr<float>(0)[nColors-1]); } } } return true; }
[ "yunfuliu@gmail.com" ]
yunfuliu@gmail.com
deab08acca5b8883a0c74410cb30a43bf74c0838
16edc75f0a71f87b253d3414eb48b0dfbe63bf6d
/trunk/src/protocol/srs_raw_avc.hpp
0c7854adda33f6dd674a751bf5d9e0095fcdc4a8
[]
no_license
shilonghai/srs-with-hevc-support
26733a3f147ebb21f97bcfd1da207f97dc94bc66
0b51931aa2172bd9ac62e4e2295edfdf51573445
refs/heads/master
2020-04-28T23:18:32.863563
2019-03-15T13:02:42
2019-03-15T13:02:42
175,650,022
2
2
null
null
null
null
WINDOWS-1252
C++
false
false
6,961
hpp
/* The MIT License (MIT) Copyright (c) 2013-2015 SRS(ossrs) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef SRS_PROTOCOL_RAW_AVC_HPP #define SRS_PROTOCOL_RAW_AVC_HPP /* #include <srs_raw_avc.hpp> */ #include <srs_core.hpp> #include <string> #include <srs_kernel_codec.hpp> class SrsStream; /** * Table 7-1 – NAL unit type codes and NAL unit type classes in * T-REC-H.265-201802 */ /** * the raw h.264 stream, in annexb. */ class SrsRawH264Stream { public: SrsRawH264Stream(); virtual ~SrsRawH264Stream(); public: /** * demux the stream in annexb format. * @param stream the input stream bytes. * @param pframe the output h.264 frame in stream. user should never free it. * @param pnb_frame the output h.264 frame size. */ virtual int annexb_demux(SrsStream* stream, char** pframe, int* pnb_frame); /** * whether the frame is sps or pps. */ virtual bool is_sps(char* frame, int nb_frame); virtual bool is_pps(char* frame, int nb_frame); /** * demux the sps or pps to string. * @param sps output the sps/pps. */ virtual int sps_demux(char* frame, int nb_frame, std::string& sps); virtual int pps_demux(char* frame, int nb_frame, std::string& pps); public: /** * h264 raw data to h264 packet, without flv payload header. * mux the sps/pps to flv sequence header packet. * @param sh output the sequence header. */ virtual int mux_sequence_header(std::string sps, std::string pps, u_int32_t dts, u_int32_t pts, std::string& sh); /** * h264 raw data to h264 packet, without flv payload header. * mux the ibp to flv ibp packet. * @param ibp output the packet. */ virtual int mux_ipb_frame(char* frame, int nb_frame, std::string& ibp); /** * mux the avc video packet to flv video packet. * @param frame_type SrsCodecVideoAVCFrameKeyFrame or SrsCodecVideoAVCFrameInterFrame. * @param avc_packet_type SrsCodecVideoAVCTypeSequenceHeader or SrsCodecVideoAVCTypeNALU. * @param video the h.264 raw data. * @param flv output the muxed flv packet. * @param nb_flv output the muxed flv size. */ virtual int mux_avc2flv(std::string video, int8_t frame_type, int8_t avc_packet_type, u_int32_t dts, u_int32_t pts, char** flv, int* nb_flv); }; /** * the raw h.265 stream */ class SrsRawH265Stream { public: SrsRawH265Stream(); virtual ~SrsRawH265Stream(); public: /** * demux the stream in annexb format. * @param stream the input stream bytes. * @param pframe the output h.265 frame in stream. user should never free it. * @param pnb_frame the output h.265 frame size. */ virtual int annexb_demux(SrsStream* stream, char** pframe, int* pnb_frame); /** * whether the frame is sps or pps. */ virtual bool is_sps(char* frame, int nb_frame); virtual bool is_pps(char* frame, int nb_frame); virtual bool is_vps(char* frame, int nb_frame); virtual bool is_sei(char* frame, int nb_frame); /** * demux the sps or pps to string. * @param sps output the sps/pps. */ virtual int sps_demux(char* frame, int nb_frame, std::string& sps); virtual int pps_demux(char* frame, int nb_frame, std::string& pps); virtual int vps_demux(char* frame, int nb_frame, std::string& vps); public: /** * h265 raw data to h265 packet, without flv payload header. * mux the sps/pps/vps to flv sequence header packet. * @param sh output the sequence header. */ virtual int mux_sequence_header(std::string vps, std::string sps, std::string pps, u_int32_t dts, u_int32_t pts, std::string& sh); /** * h265 raw data to h265 packet, without flv payload header. * mux the ibp to flv ibp packet. * @param ibp output the packet. */ virtual int mux_ipb_frame(char* frame, int nb_frame, std::string& ibp); /** * mux the hevc video packet to flv video packet. * @param frame_type SrsCodecVideoAVCFrameKeyFrame or SrsCodecVideoAVCFrameInterFrame. * @param avc_packet_type SrsCodecVideoAVCTypeSequenceHeader or SrsCodecVideoAVCTypeNALU. * @param video the h.265 raw data. * @param flv output the muxed flv packet. * @param nb_flv output the muxed flv size. */ virtual int mux_hevc2flv(std::string video, int8_t frame_type, int8_t avc_packet_type, u_int32_t dts, u_int32_t pts, char** flv, int* nb_flv); }; /** * the header of adts sample. */ struct SrsRawAacStreamCodec { int8_t protection_absent; SrsAacObjectType aac_object; int8_t sampling_frequency_index; int8_t channel_configuration; int16_t frame_length; char sound_format; char sound_rate; char sound_size; char sound_type; // 0 for sh; 1 for raw data. int8_t aac_packet_type; }; /** * the raw aac stream, in adts. */ class SrsRawAacStream { public: SrsRawAacStream(); virtual ~SrsRawAacStream(); public: /** * demux the stream in adts format. * @param stream the input stream bytes. * @param pframe the output aac frame in stream. user should never free it. * @param pnb_frame the output aac frame size. * @param codec the output codec info. */ virtual int adts_demux(SrsStream* stream, char** pframe, int* pnb_frame, SrsRawAacStreamCodec& codec); /** * aac raw data to aac packet, without flv payload header. * mux the aac specific config to flv sequence header packet. * @param sh output the sequence header. */ virtual int mux_sequence_header(SrsRawAacStreamCodec* codec, std::string& sh); /** * mux the aac audio packet to flv audio packet. * @param frame the aac raw data. * @param nb_frame the count of aac frame. * @param codec the codec info of aac. * @param flv output the muxed flv packet. * @param nb_flv output the muxed flv size. */ virtual int mux_aac2flv(char* frame, int nb_frame, SrsRawAacStreamCodec* codec, u_int32_t dts, char** flv, int* nb_flv); }; #endif
[ "timedog1@sina.com" ]
timedog1@sina.com
3d066ef55a133448b516946e5e2495fc106dbd87
6aeccfb60568a360d2d143e0271f0def40747d73
/sandbox/fmhess/boost/generic_ptr/cloning.hpp
3c239483ebdd6c3001f720d3ba4d28e25e023982
[]
no_license
ttyang/sandbox
1066b324a13813cb1113beca75cdaf518e952276
e1d6fde18ced644bb63e231829b2fe0664e51fac
refs/heads/trunk
2021-01-19T17:17:47.452557
2013-06-07T14:19:55
2013-06-07T14:19:55
13,488,698
1
3
null
2023-03-20T11:52:19
2013-10-11T03:08:51
C++
UTF-8
C++
false
false
16,999
hpp
// // generic_ptr/cloning.hpp // // Copyright (c) 2009 Frank Mori Hess // Copyright (c) 2001, 2002 Peter Dimov // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/generic_ptr for documentation. // #ifndef BOOST_GENERIC_PTR_CLONING_HPP_INCLUDED #define BOOST_GENERIC_PTR_CLONING_HPP_INCLUDED #include <boost/config.hpp> #include <boost/aligned_storage.hpp> #include <boost/generic_ptr/detail/util.hpp> #include <boost/generic_ptr/pointer_cast.hpp> #include <boost/generic_ptr/pointer_traits.hpp> #include <boost/generic_ptr/shared.hpp> #include <boost/mpl/identity.hpp> #include <boost/noncopyable.hpp> #include <boost/ptr_container/clone_allocator.hpp> #include <boost/type_traits/alignment_of.hpp> #include <boost/type_traits/is_convertible.hpp> #include <boost/type_traits/remove_const.hpp> #include <boost/utility/addressof.hpp> #include <boost/utility/enable_if.hpp> #include <boost/utility/swap.hpp> #include <memory> namespace boost { namespace generic_ptr { template<typename T> T* construct_clone(void *location, T *p) { if(p == 0) return 0; // based on boost::new_clone T* result = new(location) T(*p); BOOST_ASSERT ( typeid(*p) == typeid(*result) && "Default construct_clone() sliced object!" ); return result; } template<typename GenericPointer> GenericPointer construct_clone ( void *location, const GenericPointer &p, typename pointer_traits<GenericPointer>::value_type * = 0 ) { return GenericPointer(construct_clone(location, get_pointer(p))); } template<typename T> void destroy_clone(T *p) { if(p == 0) return; // make sure type is complete: based on boost::checked_delete typedef char type_must_be_complete[ sizeof(T)? 1: -1 ]; (void) sizeof(type_must_be_complete); p->~T(); } template<typename GenericPointer> void destroy_clone ( const GenericPointer &p, typename pointer_traits<GenericPointer>::value_type * = 0 ) { return destroy_clone(get_pointer(p)); } namespace detail { template<typename GenericVoidPointer> class clone_factory_impl_base { public: virtual ~clone_factory_impl_base() {} virtual GenericVoidPointer get_pointer() = 0; virtual clone_factory_impl_base* make_clone() = 0; virtual void delete_self() = 0; }; template<typename GenericPointer, typename Cloner, typename Allocator> class clone_factory_impl: public clone_factory_impl_base < typename rebind<GenericPointer, void>::other > { public: typedef typename Allocator::template rebind<clone_factory_impl>::other allocator_type; clone_factory_impl(GenericPointer p, Cloner c, allocator_type a): cloner(c), px(cloner.allocate_clone(p)), allocator(a) {} clone_factory_impl(const clone_factory_impl &other): cloner(other.cloner), px(cloner.allocate_clone(other.px)), allocator(other.allocator) {} ~clone_factory_impl() { cloner.deallocate_clone(px); } virtual typename rebind<GenericPointer, void>::other get_pointer() { return const_pointer_cast < typename remove_const < typename pointer_traits<GenericPointer>::value_type >::type >(px); } virtual clone_factory_impl* make_clone() { clone_factory_impl *result = allocator.allocate(1); try { allocator.construct(result, clone_factory_impl(px, cloner, allocator)); } catch(...) { allocator.deallocate(result, 1); throw; } return result; } virtual void delete_self() { // need to local copy of allocator, since original will be destroyed by destructor allocator_type local_allocator(allocator); local_allocator.destroy(this); local_allocator.deallocate(this, 1); } private: clone_factory_impl & operator=(const clone_factory_impl &other); // could be implemented if we needed it Cloner cloner; GenericPointer px; allocator_type allocator; }; template<typename GenericVoidPointer> class clone_factory { public: clone_factory(): _impl() {} template<typename T, typename Cloner, typename Allocator> clone_factory(T p, Cloner c, Allocator a): _impl(0) { typedef clone_factory_impl<T, Cloner, Allocator> impl_type; typename impl_type::allocator_type allocator(a); impl_type *storage = allocator.allocate(1); try { allocator.construct(storage, impl_type(p, c, allocator)); } catch(...) { allocator.deallocate(storage, 1); throw; } _impl = storage; } clone_factory(const clone_factory &other): _impl(other._impl->make_clone()) {} #ifndef BOOST_NO_RVALUE_REFERENCES clone_factory(clone_factory && other) { _impl = other._impl; other._impl = 0; } #endif ~clone_factory() { if(_impl) _impl->delete_self(); } GenericVoidPointer get_pointer() { if(_impl == 0) return GenericVoidPointer(); return _impl->get_pointer(); } void swap(clone_factory &other) { boost::swap(_impl, other._impl); } private: clone_factory& operator=(const clone_factory &); // could be implemented and made public if we needed it clone_factory_impl_base<GenericVoidPointer> *_impl; }; template<typename T> void swap(clone_factory<T> &a, clone_factory<T> &b) { a.swap(b); } } template<typename T> class default_cloner { public: default_cloner(): _allocated(false) {} default_cloner(const default_cloner &): _allocated(false) {} default_cloner & operator=(const default_cloner &) {} template<typename GenericPointer> GenericPointer allocate_clone(const GenericPointer & p) { BOOST_ASSERT(_allocated == false); using boost::generic_ptr::construct_clone; GenericPointer result(construct_clone(storage(), p)); _allocated = true; return result; } template<typename GenericPointer> void deallocate_clone(const GenericPointer & p) { typename pointer_traits<GenericPointer>::value_type *pop = get_plain_old_pointer(p); if(pop == 0) return; BOOST_ASSERT(pop == storage()); BOOST_ASSERT(_allocated); _allocated = false; using boost::generic_ptr::destroy_clone; destroy_clone(p); } private: void * storage() {return boost::addressof(_storage);} boost::aligned_storage<sizeof(T), boost::alignment_of<T>::value> _storage; bool _allocated; }; template<typename T> class cloning { typedef cloning this_type; // for detail/operator_bool.hpp template<typename U> friend class cloning; typedef detail::clone_factory<typename generic_ptr::rebind<T, void>::other> clone_factory_type; public: typedef typename pointer_traits<T>::value_type value_type; typedef T pointer; typedef typename pointer_traits<T>::reference reference; template<typename ValueType> struct rebind { typedef cloning<typename generic_ptr::rebind<pointer, ValueType>::other> other; }; cloning(): _clone_factory(), px() {} template<typename U> cloning ( U p #ifndef BOOST_NO_SFINAE , typename enable_if<is_convertible<U, T> >::type * = 0 #endif // BOOST_NO_SFINAE ): _clone_factory ( typename generic_ptr::rebind<T, typename pointer_traits<U>::value_type>::other(p), default_cloner<typename pointer_traits<U>::value_type>(), std::allocator<void>() ), px ( static_pointer_cast < typename pointer_traits<U>::value_type >(_clone_factory.get_pointer()) ) {} #ifndef BOOST_NO_SFINAE template<typename U> explicit cloning ( U p , typename disable_if<is_convertible<U, T> >::type * = 0 ): _clone_factory ( typename generic_ptr::rebind<T, typename pointer_traits<U>::value_type>::other(p), default_cloner<typename pointer_traits<U>::value_type>(), std::allocator<void>() ), px ( static_pointer_cast < typename pointer_traits<U>::value_type >(_clone_factory.get_pointer()) ) {} #endif // BOOST_NO_SFINAE template<typename U, typename Cloner> cloning(U p, Cloner c): _clone_factory ( typename generic_ptr::rebind<T, typename pointer_traits<U>::value_type>::other(p), c, std::allocator<void>() ), px ( static_pointer_cast < typename pointer_traits<U>::value_type >(_clone_factory.get_pointer()) ) {} template<typename U, typename Cloner, typename Allocator> cloning(U p, Cloner c, Allocator a): _clone_factory ( typename generic_ptr::rebind<T, typename pointer_traits<U>::value_type>::other(p), c, a ), px ( static_pointer_cast < typename pointer_traits<U>::value_type >(_clone_factory.get_pointer()) ) {} cloning(const cloning & other): _clone_factory(other._clone_factory), px ( static_pointer_cast<value_type>(_clone_factory.get_pointer()) ) {} template<typename U> cloning ( const cloning<U> & other #ifndef BOOST_NO_SFINAE , typename enable_if<is_convertible<U, T> >::type * = 0 #endif // BOOST_NO_SFINAE ): _clone_factory(other._clone_factory), px ( static_pointer_cast < typename pointer_traits<U>::value_type >(_clone_factory.get_pointer()) ) {} // casts template<typename U> cloning(const cloning<U> & other, detail::static_cast_tag): _clone_factory(other._clone_factory), px ( static_pointer_cast < value_type > ( static_pointer_cast < typename pointer_traits<U>::value_type >(_clone_factory.get_pointer()) ) ) {} template<typename U> cloning(const cloning<U> & other, detail::const_cast_tag): _clone_factory(other._clone_factory), px ( const_pointer_cast < value_type > ( static_pointer_cast < typename pointer_traits<U>::value_type >(_clone_factory.get_pointer()) ) ) {} template<typename U> cloning(const cloning<U> & other, detail::dynamic_cast_tag): _clone_factory(other._clone_factory), px ( dynamic_pointer_cast < value_type > ( static_pointer_cast < typename pointer_traits<U>::value_type >(_clone_factory.get_pointer()) ) ) { // reset _clone_factory if dynamic cast failed if(get_plain_old_pointer(px) == 0) { clone_factory_type().swap(_clone_factory); } } #ifndef BOOST_NO_RVALUE_REFERENCES cloning(cloning && other): _clone_factory(std::move(other._clone_factory)), px(std::move(other.px)) { detail::set_plain_old_pointer_to_null(other.px); } template<typename U> cloning ( cloning<U> && other #ifndef BOOST_NO_SFINAE , typename enable_if<is_convertible<U, T> >::type * = 0 #endif // BOOST_NO_SFINAE ): _clone_factory(std::move(other._clone_factory)), px(std::move(other.px)) { detail::set_plain_old_pointer_to_null(other.px); } #endif void swap(cloning & other) { boost::swap(px, other.px); boost::swap(_clone_factory, other._clone_factory); } cloning & operator=(const cloning & other) { cloning(other).swap(*this); return *this; } template<typename U> cloning & operator=(const cloning<U> & other) { cloning(other).swap(*this); return *this; } #ifndef BOOST_NO_RVALUE_REFERENCES cloning & operator=(cloning && other) { cloning(std::move(other)).swap(*this); return *this; } template<typename U> cloning & operator=(cloning<U> && other) { cloning(std::move(other)).swap(*this); return *this; } #endif void reset() { cloning().swap(*this); } template<typename U> void reset(U p) { cloning(p).swap(*this); } template<typename U, typename D> void reset(U p, D d) { cloning(p, d).swap(*this); } template<typename U, typename D, typename C> void reset(U p, D d, C c) { cloning(p, d, c).swap(*this); } pointer get() const {return px;} // implicit conversion to "bool" #include <boost/generic_ptr/detail/operator_bool.hpp> pointer operator->() const { detail::assert_plain_old_pointer_not_null(px); return px; } reference operator*() const { detail::assert_plain_old_pointer_not_null(px); return *px; } private: clone_factory_type _clone_factory; pointer px; }; template<typename T> T get_pointer(const cloning<T> &p) { return p.get(); } // casts template<typename ToValueType, typename U> typename rebind<cloning<U>, ToValueType>::other static_pointer_cast ( cloning<U> const & cp, mpl::identity<ToValueType> to_type_iden = mpl::identity<ToValueType>() ) { typedef typename rebind<cloning<U>, ToValueType>::other result_type; return result_type(cp, detail::static_cast_tag()); } template<typename ToValueType, typename U> typename rebind<cloning<U>, ToValueType>::other const_pointer_cast ( cloning<U> const & cp, mpl::identity<ToValueType> to_type_iden = mpl::identity<ToValueType>() ) { typedef typename rebind<cloning<U>, ToValueType>::other result_type; return result_type(cp, detail::const_cast_tag()); } template<typename ToValueType, typename U> typename rebind<cloning<U>, ToValueType>::other dynamic_pointer_cast ( cloning<U> const & cp, mpl::identity<ToValueType> to_type_iden = mpl::identity<ToValueType>() ) { typedef typename rebind<cloning<U>, ToValueType>::other result_type; return result_type(cp, detail::dynamic_cast_tag()); } // comparisons template<class T, class U> inline bool operator==(cloning<T> const & a, cloning<U> const & b) { return a.get() == b.get(); } template<class T, class U> inline bool operator!=(cloning<T> const & a, cloning<U> const & b) { return a.get() != b.get(); } template<class T, class U> inline bool operator==(cloning<T> const & a, U const & b) { return a.get() == b; } template<class T, class U> inline bool operator!=(cloning<T> const & a, U const & b) { return a.get() != b; } template<class T, class U> inline bool operator==(T const & a, cloning<U> const & b) { return a == b.get(); } template<class T, class U> inline bool operator!=(T const & a, cloning<U> const & b) { return a != b.get(); } #if __GNUC__ == 2 && __GNUC_MINOR__ <= 96 // Resolve the ambiguity between our op!= and the one in rel_ops template<class T> inline bool operator!=(cloning<T> const & a, cloning<T> const & b) { return a.get() != b.get(); } #endif template<class T> inline bool operator<(cloning<T> const & a, cloning<T> const & b) { return std::less<typename cloning<T>::pointer>()(a.get(), b.get()); } } // namespace generic_ptr } // namespace boost #endif // #ifndef BOOST_GENERIC_PTR_CLONING_HPP_INCLUDED
[ "fmh6jj@gmail.com" ]
fmh6jj@gmail.com
5aed3c75460e4cfc7a116a080fc10c709ff84bd5
0868235424f294a4866fb5e3e8148b2f88be51dc
/c++/nio/util/socket.h
e1eda46f1b134cdaaf55a3c2250e74345ae6a798
[]
no_license
BackupTheBerlios/bmws-svn
27abdb417b082020d680668a42953f781ade5696
a4486eaa03af3d91ba878bf0066a662f92840f8c
refs/heads/master
2016-09-01T19:20:17.429307
2007-06-07T07:54:46
2007-06-07T07:54:46
40,669,489
0
0
null
null
null
null
ISO-8859-1
C++
false
false
4,877
h
//////////////////////////////////////////////////////////////////////// // socketclass.h // // (C)2000 by Axel Sammet // // Klasse für einfache Socketverbindungen // // unter Win mit ws2_32.lib zu linken // //////////////////////////////////////////////////////////////////////// #ifndef SOCKETCL_H #define SOCKETCL_H #include "string.h" #include "excclass.h" //#include "bytearrayclass.h" #ifdef UNIX #include <sys/types.h> #include <sys/socket.h> #include <sys/socketvar.h> #include <netdb.h> #endif #ifdef WIN32 #include <winsock2.h> #endif namespace util { //////////////////////////////////////////////////////////////////////// class SocketException : public Exception { public: SocketException(String met, String mes) { method = met; message = mes; } }; class SocketTimeoutException : public SocketException { public: SocketTimeoutException(String met, String mes) : SocketException(met,mes) { } }; class SocketBrokenException : public SocketException { public: SocketBrokenException(String met, String mes) : SocketException(met,mes) { } }; ///////////////////////////////////////////////////////////////////////// class Socket { protected: // Membervariablen int m_Socket; sockaddr_in m_Sockaddr; static int s_NrOfInstances; static int s_Initialized; public: // Methoden // Konstruktor / Destruktor Socket(); virtual ~Socket(); static void Init(); static void Cleanup(); // initialize and cleanup winsocks // only required for WIN32, calling doesn't harm though void Connect(char* address, int port); // connect to a listening server socket // address : hostname or ip // port : port number void WriteString(String s); // sends a String to the other side of the socket connection // the String can contain \0. Thus the length is send first. // Do not use to send ASCII, use Write(char*) instead. // s : string to send String ReadString(long timeout=-1); // reads a String from the socket connection // timeout : in msecs, -1 indefinetly // returns : String read from socket // throws : SocketException, SocketTimeoutException String ReadLine(long timeout=-1); // reads characters from the socket up to the next \n // timeout : in msecs, -1 indefinetly // returns : String read from socket // throws : SocketException, SocketTimeoutException void WriteLong(long nr); long ReadLong(long timeout=-1); /* void Write(const ByteArray &ba); // not yet implemented ByteArray Read(long timeout=-1); // not yet implemented */ void Write(char* pt,int len=-1); // writes a character array with the given length. // If no length is given, a String is assumed and strlen(pt) // bytes will be send. // pt : first character // len : length of array int Read(char* pt,int len, long timeout=-1); // reads a charater array of a given length // pt : first character of the array // len : length of array // timeout : in msec int DataTransferred(); // checks if written data has been transmitted int WaitForData(long wait=-1); // checks if there is data available on the connection // wait : time to wait in msec, if -1 wait indefinetly // return : true if data available else false int ConnectionBroken(); // returns true if the other side has disconnected. // WORKS ONLY IF no more data in the queue is available. // If data exists in the queue or connection is online // returns false. Unfortunately breaking the connection looks // like new data. Best method to check for broken connection is: // try { WaitForData(100); Read??? } catch(SocketBrokenException exc) String GetAddressString(); // returns ip-address of connected socket // seems to have a bug sometimes int GetSocket(); // returns socket handle void SetSocket(int soc); // sets a previous created socket void SetSockAddr(sockaddr_in sa); // sets an inet socket address void Close(); // closes the socket (will also be called by destructor) }; ////////////////////////////////////////////////////////////////////////// // class ServerSocket class ServerSocket : public Socket { public: ServerSocket(int port); // creates a server socket which can accept connections on // the given port // port : number of the port virtual ~ServerSocket(); // destructor int Accept(Socket& soc, long wait=-1); // waits for a client to connect // soc : holds the socket for the accepted connection // after Accept() returns // wait : time the server waits for a client connection in msec // returns : true if a new connection was accepted, false otherwise }; } #endif
[ "crypter@5ae0fa9c-bcfc-0310-8243-f99ef3d6a034" ]
crypter@5ae0fa9c-bcfc-0310-8243-f99ef3d6a034
2898f9bd0e84c3d913367b7b996adbd6c4ea169a
61991c99981ee3d9bcef98d2a405c35ee55240fc
/src/qt/bitcoinunits.cpp
fa35ce63af16d216af7bb0957dd87319e4f9ffee
[ "MIT" ]
permissive
gocodevs/GoMasternode
43204f252048854ff9bf51b1b8d7eed3d5a5fd26
b58c381af19ddce63aaa5444e627b0abfd002229
refs/heads/master
2020-04-30T20:20:03.976322
2019-03-23T08:53:54
2019-03-23T08:53:54
171,640,901
0
0
null
null
null
null
UTF-8
C++
false
false
8,126
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2018 The Gocoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bitcoinunits.h" #include "chainparams.h" #include "primitives/transaction.h" #include <QSettings> #include <QStringList> BitcoinUnits::BitcoinUnits(QObject* parent) : QAbstractListModel(parent), unitlist(availableUnits()) { } QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits() { QList<BitcoinUnits::Unit> unitlist; unitlist.append(GOC); unitlist.append(mGOC); unitlist.append(uGOC); return unitlist; } bool BitcoinUnits::valid(int unit) { switch (unit) { case GOC: case mGOC: case uGOC: return true; default: return false; } } QString BitcoinUnits::id(int unit) { switch (unit) { case GOC: return QString("gocoin"); case mGOC: return QString("mgocoin"); case uGOC: return QString::fromUtf8("ugocoin"); default: return QString("???"); } } QString BitcoinUnits::name(int unit) { if (Params().NetworkID() == CBaseChainParams::MAIN) { switch (unit) { case GOC: return QString("GOC"); case mGOC: return QString("mGOC"); case uGOC: return QString::fromUtf8("μGOC"); default: return QString("???"); } } else { switch (unit) { case GOC: return QString("tGOC"); case mGOC: return QString("mtGOC"); case uGOC: return QString::fromUtf8("μtGOC"); default: return QString("???"); } } } QString BitcoinUnits::description(int unit) { if (Params().NetworkID() == CBaseChainParams::MAIN) { switch (unit) { case GOC: return QString("GOC"); case mGOC: return QString("Milli-GOC (1 / 1" THIN_SP_UTF8 "000)"); case uGOC: return QString("Micro-GOC (1 / 1" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)"); default: return QString("???"); } } else { switch (unit) { case GOC: return QString("TestGOCs"); case mGOC: return QString("Milli-TestGOC (1 / 1" THIN_SP_UTF8 "000)"); case uGOC: return QString("Micro-TestGOC (1 / 1" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)"); default: return QString("???"); } } } qint64 BitcoinUnits::factor(int unit) { switch (unit) { case GOC: return COIN; case mGOC: return COIN / 1000; case uGOC: return COIN / 1000000; default: return COIN; } } int BitcoinUnits::decimals(int unit) { switch (unit) { case GOC: return 6; case mGOC: return 3; case uGOC: return 0; default: return 0; } } QString BitcoinUnits::format(int unit, const CAmount& nIn, bool fPlus, SeparatorStyle separators) { // Note: not using straight sprintf here because we do NOT want // localized number formatting. if (!valid(unit)) return QString(); // Refuse to format invalid unit qint64 n = (qint64)nIn; qint64 coin = factor(unit); int num_decimals = decimals(unit); qint64 n_abs = (n > 0 ? n : -n); qint64 quotient = n_abs / coin; qint64 remainder = n_abs % coin; QString quotient_str = QString::number(quotient); QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0'); // Use SI-style thin space separators as these are locale independent and can't be // confused with the decimal marker. QChar thin_sp(THIN_SP_CP); int q_size = quotient_str.size(); if (separators == separatorAlways || (separators == separatorStandard && q_size > 4)) for (int i = 3; i < q_size; i += 3) quotient_str.insert(q_size - i, thin_sp); if (n < 0) quotient_str.insert(0, '-'); else if (fPlus && n > 0) quotient_str.insert(0, '+'); if (num_decimals <= 0) return quotient_str; return quotient_str + QString(".") + remainder_str; } // TODO: Review all remaining calls to BitcoinUnits::formatWithUnit to // TODO: determine whether the output is used in a plain text context // TODO: or an HTML context (and replace with // TODO: BtcoinUnits::formatHtmlWithUnit in the latter case). Hopefully // TODO: there aren't instances where the result could be used in // TODO: either context. // NOTE: Using formatWithUnit in an HTML context risks wrapping // quantities at the thousands separator. More subtly, it also results // in a standard space rather than a thin space, due to a bug in Qt's // XML whitespace canonicalisation // // Please take care to use formatHtmlWithUnit instead, when // appropriate. QString BitcoinUnits::formatWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators) { return format(unit, amount, plussign, separators) + QString(" ") + name(unit); } QString BitcoinUnits::formatHtmlWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators) { QString str(formatWithUnit(unit, amount, plussign, separators)); str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML)); return QString("<span style='white-space: nowrap;'>%1</span>").arg(str); } QString BitcoinUnits::floorWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators) { QSettings settings; int digits = settings.value("digits").toInt(); QString result = format(unit, amount, plussign, separators); if (decimals(unit) > digits) result.chop(decimals(unit) - digits); return result + QString(" ") + name(unit); } QString BitcoinUnits::floorHtmlWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators) { QString str(floorWithUnit(unit, amount, plussign, separators)); str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML)); return QString("<span style='white-space: nowrap;'>%1</span>").arg(str); } bool BitcoinUnits::parse(int unit, const QString& value, CAmount* val_out) { if (!valid(unit) || value.isEmpty()) return false; // Refuse to parse invalid unit or empty string int num_decimals = decimals(unit); // Ignore spaces and thin spaces when parsing QStringList parts = removeSpaces(value).split("."); if (parts.size() > 2) { return false; // More than one dot } QString whole = parts[0]; QString decimals; if (parts.size() > 1) { decimals = parts[1]; } if (decimals.size() > num_decimals) { return false; // Exceeds max precision } bool ok = false; QString str = whole + decimals.leftJustified(num_decimals, '0'); if (str.size() > 18) { return false; // Longer numbers will exceed 63 bits } CAmount retvalue(str.toLongLong(&ok)); if (val_out) { *val_out = retvalue; } return ok; } QString BitcoinUnits::getAmountColumnTitle(int unit) { QString amountTitle = QObject::tr("Amount"); if (BitcoinUnits::valid(unit)) { amountTitle += " (" + BitcoinUnits::name(unit) + ")"; } return amountTitle; } int BitcoinUnits::rowCount(const QModelIndex& parent) const { Q_UNUSED(parent); return unitlist.size(); } QVariant BitcoinUnits::data(const QModelIndex& index, int role) const { int row = index.row(); if (row >= 0 && row < unitlist.size()) { Unit unit = unitlist.at(row); switch (role) { case Qt::EditRole: case Qt::DisplayRole: return QVariant(name(unit)); case Qt::ToolTipRole: return QVariant(description(unit)); case UnitRole: return QVariant(static_cast<int>(unit)); } } return QVariant(); } CAmount BitcoinUnits::maxMoney() { return Params().MaxMoneyOut(); }
[ "support@gomasternode.co" ]
support@gomasternode.co
d4cd2dc48a9590167d75fdd0f6237751a7d96dca
55f04305a34567acbccc9106d03919a7ce9bbd3b
/Primero/Programacion_CITM/Ejercicios/funciones 1/structs 1/Project1/main.cpp
34aac5ca27cfb3c12fcafea4e1b0d52cf4307983
[]
no_license
dusthandler/CITM
9f4d695858e3c1df9d9b75dd4f770e3a52cb40c7
507f74f1b2b0a9f85671e7890bc1ab5bb94197c4
refs/heads/master
2021-09-28T08:02:18.480152
2018-11-15T17:37:01
2018-11-15T17:37:01
151,699,384
0
0
null
null
null
null
UTF-8
C++
false
false
563
cpp
#include<iostream> #include<string> using namespace std; struct Fecha { int dia; int mes; int anyo; }; struct Nombre { string nombre; string apellido1; string apellido2; }; struct NIF { int numero; char letra; }; int main() { Fecha a, b, c; NIF kev; a.dia = 1; a.mes = 5; a.anyo = 1531; b.dia = 2; b.mes = 2; b.anyo = 2155; c.dia = 10; c.mes = 12; c.anyo = 0; kev.numero = 12345678; kev.letra = 'h'; cout << a.dia << "/" << a.mes << "/" << a.anyo << "\n"; cout << kev.numero<<kev.letra<<"\n"; system("pause"); return 0; }
[ "32524211+dusthandler@users.noreply.github.com" ]
32524211+dusthandler@users.noreply.github.com
814e772c96cd24a86570e7bb51ec0c09967cbd7e
d6258ae3c0fd9f36efdd859a2c93ab489da2aa9b
/fulldocset/add/codesnippet/CPP/e-system.windows.forms.d_69_1.cpp
07ed5fdb6bb1a0b93d8cd6e41c333316549c555c
[ "CC-BY-4.0", "MIT" ]
permissive
OpenLocalizationTestOrg/ECMA2YamlTestRepo2
ca4d3821767bba558336b2ef2d2a40aa100d67f6
9a577bbd8ead778fd4723fbdbce691e69b3b14d4
refs/heads/master
2020-05-26T22:12:47.034527
2017-03-07T07:07:15
2017-03-07T07:07:15
82,508,764
1
0
null
2017-02-28T02:14:26
2017-02-20T02:36:59
Visual Basic
UTF-8
C++
false
false
839
cpp
// Attach to event handler. private: void AttachReadOnlyChanged() { this->myDataGrid->ReadOnlyChanged += gcnew EventHandler( this, &MyDataGridClass_FlatMode_ReadOnly::myDataGrid_ReadOnlyChanged ); } // Check if the 'ReadOnly' property is changed. void myDataGrid_ReadOnlyChanged( Object^ /*sender*/, EventArgs^ /*e*/ ) { String^ strMessage = "false"; if ( myDataGrid->ReadOnly == true ) strMessage = "true"; MessageBox::Show( "Read only changed to " + strMessage, "Message", MessageBoxButtons::OK, MessageBoxIcon::Exclamation ); } // Toggle the 'ReadOnly' property. void button2_Click( Object^ /*sender*/, EventArgs^ /*e*/ ) { if ( myDataGrid->ReadOnly == true ) myDataGrid->ReadOnly = false; else myDataGrid->ReadOnly = true; }
[ "tianzh@microsoft.com" ]
tianzh@microsoft.com
8bc9113802650f8bf8e848acadab4fb615f9081f
ddee0cf5c359ae5a3417b7c400f6a35654b76b5a
/binding-cpp/include/gym-uds.h
35a39be08feec9731f3b82a6a7a9bb8a53aa5380
[ "MIT" ]
permissive
tiberiu92/gym-uds-api
8a3fddcda292272e486991490812877dfde79397
65ff4a4368197ce43e954d66ed0daa31a93236af
refs/heads/master
2020-03-22T09:47:47.860461
2018-04-23T13:56:51
2018-04-23T13:56:51
139,135,993
1
0
null
null
null
null
UTF-8
C++
false
false
567
h
#ifndef GYM_H #define GYM_H #include <string> #include <tuple> #include <vector> #include <grpcpp/grpcpp.h> #include "gym-uds.pb.h" #include "gym-uds.grpc.pb.h" namespace gym_uds { using action_t = int; using observation_t = std::vector<float>; using state_t = std::tuple<observation_t, float, bool>; class EnvironmentClient { private: std::unique_ptr<Environment::Stub> stub; public: EnvironmentClient(const std::string&); observation_t reset(); state_t step(const action_t&); action_t sample(); }; } #endif
[ "francesco.cagnin@gmail.com" ]
francesco.cagnin@gmail.com
3571b068c91147d99e8a3cc199e21df89939ac3b
cdc4b28a1f04aa31b07373a9cad47574c2b986e2
/t6_25.cpp
e973d1c04e26300c9f15ef31d2f791160fa7cf38
[]
no_license
pw-ethan/CPP-Primer
fe2fbe900c1cf01f5dfd93550a0d581d062dfe7c
fde28b2de88372a94eead514b99131014fbccac2
refs/heads/master
2021-01-25T06:06:41.332946
2017-06-06T13:51:31
2017-06-06T13:51:31
93,523,811
0
0
null
null
null
null
UTF-8
C++
false
false
212
cpp
#include <iostream> #include <string> using namespace std; int main(int argc, char *argv[]) { string s; for(int i = 1; i < argc; ++i){ s += argv[i]; } cout << s << endl; return 0; }
[ "pw-ethan@localhost.localdomain" ]
pw-ethan@localhost.localdomain
adc4d06ab82325200692f63967fd8055bd3b9fe6
1f7618ab0a6b5712d6d991fd4d1cf1ba93008acc
/TetrisLib/Square.h
0a39394a71f06ab343d067d11f211b78cb0349a6
[]
no_license
joyoon/tetrisclone
24f4211f5b110051940219e710b90fad4390f602
b03814ca8e97b8833ffc3c9c5fa2fca336ba4489
refs/heads/master
2020-05-31T17:23:45.192447
2014-05-06T21:26:04
2014-05-06T21:26:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
373
h
#include "Shape.h" using namespace std; #pragma once namespace TetrisLib { class Square : public Shape { protected: void init(); public: Square(void); Square(Square const&); Square* create() const; Square* clone() const; Square(void (*onSetCallback)(SDL_Rect* blocks)); ~Square(void); void rotate(int angle); void setPosition(int x, int y); }; }
[ "johnyoon20@gmail.com" ]
johnyoon20@gmail.com
00d5612d294ea2cc181a0d3a43768ec2080397ea
230b7714d61bbbc9a75dd9adc487706dffbf301e
/chrome/browser/download/offline_item_utils.cc
6200d1ff91d690da45ea9c7615afb8e1dccbed03
[ "BSD-3-Clause" ]
permissive
byte4byte/cloudretro
efe4f8275f267e553ba82068c91ed801d02637a7
4d6e047d4726c1d3d1d119dfb55c8b0f29f6b39a
refs/heads/master
2023-02-22T02:59:29.357795
2021-01-25T02:32:24
2021-01-25T02:32:24
197,294,750
1
2
BSD-3-Clause
2019-09-11T19:35:45
2019-07-17T01:48:48
null
UTF-8
C++
false
false
12,812
cc
// Copyright (c) 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 "chrome/browser/download/offline_item_utils.h" #include "build/build_config.h" #include "chrome/grit/generated_resources.h" #include "components/download/public/common/auto_resumption_handler.h" #include "components/download/public/common/download_utils.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/download_item_utils.h" #include "third_party/blink/public/common/mime_util/mime_util.h" #include "ui/base/l10n/l10n_util.h" #if defined(OS_ANDROID) #include "chrome/browser/android/download/download_utils.h" #endif using DownloadItem = download::DownloadItem; using ContentId = offline_items_collection::ContentId; using OfflineItem = offline_items_collection::OfflineItem; using OfflineItemFilter = offline_items_collection::OfflineItemFilter; using OfflineItemState = offline_items_collection::OfflineItemState; using OfflineItemProgressUnit = offline_items_collection::OfflineItemProgressUnit; using FailState = offline_items_collection::FailState; using PendingState = offline_items_collection::PendingState; namespace { // The namespace for downloads. const char kDownloadNamespace[] = "LEGACY_DOWNLOAD"; // The namespace for incognito downloads. const char kDownloadIncognitoNamespace[] = "LEGACY_DOWNLOAD_INCOGNITO"; // Prefix that all download namespaces should start with. const char kDownloadNamespacePrefix[] = "LEGACY_DOWNLOAD"; // The remaining time for a download item if it cannot be calculated. constexpr int64_t kUnknownRemainingTime = -1; OfflineItemFilter MimeTypeToOfflineItemFilter(const std::string& mime_type) { OfflineItemFilter filter = OfflineItemFilter::FILTER_OTHER; if (base::StartsWith(mime_type, "audio/", base::CompareCase::SENSITIVE)) { filter = OfflineItemFilter::FILTER_AUDIO; } else if (base::StartsWith(mime_type, "video/", base::CompareCase::SENSITIVE)) { filter = OfflineItemFilter::FILTER_VIDEO; } else if (base::StartsWith(mime_type, "image/", base::CompareCase::SENSITIVE)) { filter = OfflineItemFilter::FILTER_IMAGE; } else if (base::StartsWith(mime_type, "text/", base::CompareCase::SENSITIVE)) { filter = OfflineItemFilter::FILTER_DOCUMENT; } else { filter = OfflineItemFilter::FILTER_OTHER; } return filter; } bool IsInterruptedDownloadAutoResumable(download::DownloadItem* item) { int auto_resumption_size_limit = 0; #if defined(OS_ANDROID) auto_resumption_size_limit = DownloadUtils::GetAutoResumptionSizeLimit(); #endif return download::AutoResumptionHandler::IsInterruptedDownloadAutoResumable( item, auto_resumption_size_limit); } } // namespace OfflineItem OfflineItemUtils::CreateOfflineItem(const std::string& name_space, DownloadItem* download_item) { auto* browser_context = content::DownloadItemUtils::GetBrowserContext(download_item); bool off_the_record = browser_context ? browser_context->IsOffTheRecord() : false; OfflineItem item; item.id = ContentId(name_space, download_item->GetGuid()); item.title = download_item->GetFileNameToReportUser().AsUTF8Unsafe(); item.description = download_item->GetFileNameToReportUser().AsUTF8Unsafe(); item.filter = MimeTypeToOfflineItemFilter(download_item->GetMimeType()); item.is_transient = download_item->IsTransient(); item.is_suggested = false; item.is_accelerated = download_item->IsParallelDownload(); item.total_size_bytes = download_item->GetTotalBytes(); item.externally_removed = download_item->GetFileExternallyRemoved(); item.creation_time = download_item->GetStartTime(); item.last_accessed_time = download_item->GetLastAccessTime(); item.is_openable = download_item->CanOpenDownload(); item.file_path = download_item->GetTargetFilePath(); item.mime_type = download_item->GetMimeType(); #if defined(OS_ANDROID) item.mime_type = DownloadUtils::RemapGenericMimeType( item.mime_type, download_item->GetOriginalUrl(), download_item->GetTargetFilePath().value()); #endif item.page_url = download_item->GetTabUrl(); item.original_url = download_item->GetOriginalUrl(); item.is_off_the_record = off_the_record; item.is_resumable = download_item->CanResume(); item.allow_metered = download_item->AllowMetered(); item.received_bytes = download_item->GetReceivedBytes(); item.is_dangerous = download_item->IsDangerous(); base::TimeDelta time_delta; bool time_remaining_known = download_item->TimeRemaining(&time_delta); item.time_remaining_ms = time_remaining_known ? time_delta.InMilliseconds() : kUnknownRemainingTime; item.fail_state = ConvertDownloadInterruptReasonToFailState(download_item->GetLastReason()); item.can_rename = download_item->GetState() == DownloadItem::COMPLETE; switch (download_item->GetState()) { case DownloadItem::IN_PROGRESS: item.state = download_item->IsPaused() ? OfflineItemState::PAUSED : OfflineItemState::IN_PROGRESS; break; case DownloadItem::COMPLETE: item.state = download_item->GetReceivedBytes() == 0 ? OfflineItemState::FAILED : OfflineItemState::COMPLETE; break; case DownloadItem::CANCELLED: item.state = OfflineItemState::CANCELLED; break; case DownloadItem::INTERRUPTED: { bool is_auto_resumable = IsInterruptedDownloadAutoResumable(download_item); bool max_retry_limit_reached = download_item->GetAutoResumeCount() >= download::DownloadItemImpl::kMaxAutoResumeAttempts; if (download_item->IsDone()) { item.state = OfflineItemState::FAILED; } else if (download_item->IsPaused() || max_retry_limit_reached) { item.state = OfflineItemState::PAUSED; } else if (is_auto_resumable) { item.state = OfflineItemState::PENDING; } else { item.state = OfflineItemState::INTERRUPTED; } } break; default: NOTREACHED(); } // TODO(crbug.com/857549): Set pending_state correctly. item.pending_state = item.state == OfflineItemState::PENDING ? PendingState::PENDING_NETWORK : PendingState::NOT_PENDING; item.progress.value = download_item->GetReceivedBytes(); if (download_item->PercentComplete() != -1) item.progress.max = download_item->GetTotalBytes(); item.progress.unit = OfflineItemProgressUnit::BYTES; return item; } std::string OfflineItemUtils::GetDownloadNamespacePrefix( bool is_off_the_record) { return is_off_the_record ? kDownloadIncognitoNamespace : kDownloadNamespace; } bool OfflineItemUtils::IsDownload(const ContentId& id) { return id.name_space.find(kDownloadNamespacePrefix) != std::string::npos; } // static FailState OfflineItemUtils::ConvertDownloadInterruptReasonToFailState( download::DownloadInterruptReason reason) { switch (reason) { case download::DOWNLOAD_INTERRUPT_REASON_NONE: return offline_items_collection::FailState::NO_FAILURE; #define INTERRUPT_REASON(name, value) \ case download::DOWNLOAD_INTERRUPT_REASON_##name: \ return offline_items_collection::FailState::name; #include "components/download/public/common/download_interrupt_reason_values.h" #undef INTERRUPT_REASON } } // static download::DownloadInterruptReason OfflineItemUtils::ConvertFailStateToDownloadInterruptReason( offline_items_collection::FailState fail_state) { switch (fail_state) { case offline_items_collection::FailState::NO_FAILURE: // These two enum values are not converted from download interrupted reason, // maps them to none error. case offline_items_collection::FailState::CANNOT_DOWNLOAD: case offline_items_collection::FailState::NETWORK_INSTABILITY: return download::DOWNLOAD_INTERRUPT_REASON_NONE; #define INTERRUPT_REASON(name, value) \ case offline_items_collection::FailState::name: \ return download::DOWNLOAD_INTERRUPT_REASON_##name; #include "components/download/public/common/download_interrupt_reason_values.h" #undef INTERRUPT_REASON } } // static base::string16 OfflineItemUtils::GetFailStateMessage(FailState fail_state) { int string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS; switch (fail_state) { case FailState::FILE_ACCESS_DENIED: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_ACCESS_DENIED; break; case FailState::FILE_NO_SPACE: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_DISK_FULL; break; case FailState::FILE_NAME_TOO_LONG: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_PATH_TOO_LONG; break; case FailState::FILE_TOO_LARGE: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_FILE_TOO_LARGE; break; case FailState::FILE_VIRUS_INFECTED: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_VIRUS; break; case FailState::FILE_TRANSIENT_ERROR: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_TEMPORARY_PROBLEM; break; case FailState::FILE_BLOCKED: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_BLOCKED; break; case FailState::FILE_SECURITY_CHECK_FAILED: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_SECURITY_CHECK_FAILED; break; case FailState::FILE_TOO_SHORT: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_FILE_TOO_SHORT; break; case FailState::FILE_SAME_AS_SOURCE: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_FILE_SAME_AS_SOURCE; break; case FailState::NETWORK_INVALID_REQUEST: FALLTHROUGH; case FailState::NETWORK_FAILED: FALLTHROUGH; case FailState::NETWORK_INSTABILITY: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_NETWORK_ERROR; break; case FailState::NETWORK_TIMEOUT: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_NETWORK_TIMEOUT; break; case FailState::NETWORK_DISCONNECTED: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_NETWORK_DISCONNECTED; break; case FailState::NETWORK_SERVER_DOWN: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_SERVER_DOWN; break; case FailState::SERVER_FAILED: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_SERVER_PROBLEM; break; case FailState::SERVER_BAD_CONTENT: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_NO_FILE; break; case FailState::USER_CANCELED: string_id = IDS_DOWNLOAD_STATUS_CANCELLED; break; case FailState::USER_SHUTDOWN: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_SHUTDOWN; break; case FailState::CRASH: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_CRASH; break; case FailState::SERVER_UNAUTHORIZED: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_UNAUTHORIZED; break; case FailState::SERVER_CERT_PROBLEM: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_SERVER_CERT_PROBLEM; break; case FailState::SERVER_FORBIDDEN: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_FORBIDDEN; break; case FailState::SERVER_UNREACHABLE: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_UNREACHABLE; break; case FailState::SERVER_CONTENT_LENGTH_MISMATCH: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_CONTENT_LENGTH_MISMATCH; break; case FailState::NO_FAILURE: NOTREACHED(); FALLTHROUGH; case FailState::CANNOT_DOWNLOAD: FALLTHROUGH; case FailState::SERVER_NO_RANGE: FALLTHROUGH; case FailState::SERVER_CROSS_ORIGIN_REDIRECT: FALLTHROUGH; case FailState::FILE_FAILED: FALLTHROUGH; case FailState::FILE_HASH_MISMATCH: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS; } return l10n_util::GetStringUTF16(string_id); } // static RenameResult OfflineItemUtils::ConvertDownloadRenameResultToRenameResult( DownloadRenameResult download_rename_result) { assert(static_cast<int>(DownloadRenameResult::RESULT_MAX) == static_cast<int>(RenameResult::kMaxValue)); switch (download_rename_result) { case DownloadRenameResult::SUCCESS: return RenameResult::SUCCESS; case DownloadRenameResult::FAILURE_NAME_CONFLICT: return RenameResult::FAILURE_NAME_CONFLICT; case DownloadRenameResult::FAILURE_NAME_TOO_LONG: return RenameResult::FAILURE_NAME_TOO_LONG; case DownloadRenameResult::FAILURE_NAME_INVALID: return RenameResult::FAILURE_NAME_INVALID; case DownloadRenameResult::FAILURE_UNAVAILABLE: return RenameResult::FAILURE_UNAVAILABLE; case DownloadRenameResult::FAILURE_UNKNOWN: return RenameResult::FAILURE_UNKNOWN; } }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
a2233f4df89e31573ef5fffcfcec1ed00092090a
62de81dbbbe5fb50963e600f366ae6ea5915e40d
/graphicsview/graphicsview.h
8f0b146db94c219e9148ae874d06b66b20aba93b
[]
no_license
openmy/GERBER_X2
37ec6e506591795d44891f69590a4fd0ee844655
17daee06b287dcc4fca47d11a9bd0d31700b2453
refs/heads/master
2020-05-30T20:47:02.450061
2019-06-02T23:52:39
2019-06-02T23:52:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,439
h
#ifndef VIEW_H #define VIEW_H #include <QGraphicsItem> #include <QGraphicsView> #include <QSettings> //#define ANIM class QDRuler; class GraphicsView : public QGraphicsView { Q_OBJECT public: explicit GraphicsView(QWidget* parent = 0); ~GraphicsView(); void setScene(QGraphicsScene* Scene); void zoom100(); void zoomFit(); void zoomToSelected(); void zoomIn(); void zoomOut(); static GraphicsView* self; static double scaleFactor() { return 1.0 / GraphicsView::self->matrix().m11(); } signals: void fileDroped(const QString&); void mouseMove(const QPointF&); private: QDRuler* hRuler; QDRuler* vRuler; const double zoomFactor = 1.5; #ifdef ANIM void AnimFinished(); void ScalingTime(qreal x); QPointF centerPoint; double zoom = 100; double numScheduledScalings = 0; #endif void UpdateRuler(); // QWidget interface protected: void dragEnterEvent(QDragEnterEvent* event) override; void dragMoveEvent(QDragMoveEvent* event) override; void dropEvent(QDropEvent* event) override; void resizeEvent(QResizeEvent* event) override; void wheelEvent(QWheelEvent* event) override; void mousePressEvent(QMouseEvent* event) override; void mouseReleaseEvent(QMouseEvent* event) override; void mouseDoubleClickEvent(QMouseEvent* event) override; void mouseMoveEvent(QMouseEvent* event) override; }; #endif // VIEW_H
[ "xray3d@ya.ru" ]
xray3d@ya.ru
fa4079b8b60380ea9cf60c2c5e61fbe128461406
fc0664a076eeb69a3a8a89e7af25329c3998dd07
/Engine/PipelineCompiler/Pipelines/ComputePipeline.h
e316452331d804ce287862bcf0eaa3f61cd58daf
[ "BSD-2-Clause" ]
permissive
azhirnov/ModularGraphicsFramework
fabece2887da16c8438748c9dd5f3091a180058d
348be601f1991f102defa0c99250529f5e44c4d3
refs/heads/master
2021-07-14T06:31:31.127788
2018-11-19T14:28:16
2018-11-19T14:28:16
88,896,906
14
0
null
null
null
null
UTF-8
C++
false
false
714
h
// Copyright (c) Zhirnov Andrey. For more information see 'LICENSE.txt' #pragma once #include "Engine/PipelineCompiler/Pipelines/BasePipeline.h" namespace PipelineCompiler { // // Compute Pipeline // class ComputePipeline : public BasePipeline { // variables protected: ShaderModule shader { EShader::Compute }; // methods protected: explicit ComputePipeline (StringCRef name); private: bool Prepare (const ConverterConfig &cfg) override final; bool Convert (OUT String &src, Ptr<ISerializer> ser, const ConverterConfig &cfg) const override final; bool _ConvertComputeShader (INOUT String &src, Ptr<ISerializer> ser, const ConverterConfig &cfg) const; }; } // PipelineCompiler
[ "zh1dron@gmail.com" ]
zh1dron@gmail.com
37b9c1f924d6a04b9bf5ef33b4bc05f94457aff5
08577251e95727c9a38dc53b9daa4525c81eb391
/BufferUploads/DataPacket.h
6506cf75791905e13e6d881d7e55948c3cb317b2
[ "MIT" ]
permissive
hck509/XLE
0ee2354fb81defe738c4b43d9908e1c83f0181a7
e65efd74c86fda3e38155ad386eca9aac061f7ba
refs/heads/master
2021-01-17T10:42:36.437417
2015-03-02T08:28:38
2015-03-02T08:28:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,572
h
// Copyright 2015 XLGAMES Inc. // // Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) #pragma once #include "IBufferUploads.h" #include "../Utility/MemoryUtils.h" namespace BufferUploads { class BasicRawDataPacket : public RawDataPacket { public: virtual void* GetData(unsigned mipIndex=0, unsigned arrayIndex=0); virtual std::pair<unsigned,unsigned> GetRowAndSlicePitch(unsigned mipIndex=0, unsigned arrayIndex=0) const; virtual size_t GetDataSize(unsigned mipIndex=0, unsigned arrayIndex=0) const; BasicRawDataPacket(size_t dataSize, const void* data = nullptr, std::pair<unsigned,unsigned> rowAndSlicePitch = std::make_pair(0,0)); virtual ~BasicRawDataPacket(); protected: std::unique_ptr<uint8, AlignedDeletor> _data; size_t _dataSize; std::pair<unsigned,unsigned> _rowAndSlicePitch; BasicRawDataPacket(const BasicRawDataPacket&); BasicRawDataPacket& operator=(const BasicRawDataPacket&); }; buffer_upload_dll_export intrusive_ptr<BasicRawDataPacket> CreateBasicPacket( size_t dataSize, const void* data = nullptr, std::pair<unsigned,unsigned> rowAndSlicePitch = std::make_pair(0,0)); buffer_upload_dll_export intrusive_ptr<BasicRawDataPacket> CreateEmptyPacket( const BufferDesc& desc); buffer_upload_dll_export intrusive_ptr<RawDataPacket> CreateFileDataSource( const void* fileHandle, size_t offset, size_t dataSize); }
[ "djewsbury@xlgames.com" ]
djewsbury@xlgames.com
f4131a9abfc9d95799433a1b4ef446a1000749bb
8682a1e82d1e1472daf1135fa177aef68c1bca6e
/neatmain.cpp
a11928c2ad3a85f7b5809d5e47bcf1090aed3664
[ "Apache-2.0" ]
permissive
sanchitanand/SnakeNeuralNetworks
46a534f8a56ec1b26b9a59aa15f67485eff63731
67d0c3bf960a977bdbc9eed2c2f5e1eec07c6cce
refs/heads/master
2021-01-13T11:51:14.112666
2016-12-28T03:43:14
2016-12-28T03:43:14
77,500,963
0
0
null
null
null
null
UTF-8
C++
false
false
3,792
cpp
/* Copyright 2001 The University of Texas at Austin 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 <stdlib.h> //#include <stdio.h> //#include <iostream> //#include <iomanip> //#include <sstream> //#include <list> //#include <vector> //#include <algorithm> //#include <cmath> //#include <iostream.h> //#include "networks.h" //#include "neat.h" //#include "genetics.h" //#include "experiments.h" //#include "neatmain.h" #include <iostream> #include <vector> #include "neat.h" #include "population.h" #include "experiments.h" #include "snake_experiment.h" #include "snake_test.h" using namespace std; // double testdoubval() { // return *testdoub; // } // double testdoubset(double val) { // *testdoub=val; // } int main(int argc, char *argv[]) { //list<NNode*> nodelist; int pause; NEAT::Population *p=0; /* GTKMM */ // myapp=new Gtk::Main(argc, argv); // testdoub=&val; //***********RANDOM SETUP***************// /* Seed the random-number generator with current time so that the numbers will be different every time we run. */ srand( (unsigned)time( NULL ) ); if (argc != 2) { cerr << "A NEAT parameters file (.ne file) is required to run the experiments!" << endl; return -1; } //Load in the params NEAT::load_neat_params(argv[1],true); cout<<"loaded"<<endl; /* //Test a genome file on pole balancing Genome *g; Network *n; CartPole *thecart; thecart=new CartPole(true,0); g=Genome::new_Genome_load("tested"); n=g->genesis(1); Organism *org= new Organism(0, g, 1); thecart->nmarkov_long=true; thecart->generalization_test=false; pole2_evaluate(org,0,thecart); cout<<"made score "<<org->fitness<<endl; cin>>pause; */ //Here is an example of how to run an experiment directly from main //and then visualize the speciation that took place //p=xor_test(100); //100 generation XOR experiment int choice, id; char filename[50]; char temp_name[50]; cout<<"Please choose an experiment: "<<endl; cout<<"1 - 1-pole balancing"<<endl; cout<<"2 - 2-pole balancing, velocity info provided"<<endl; cout<<"3 - 2-pole balancing, no velocity info provided (non-markov)"<<endl; cout<<"4 - XOR"<<endl; cout<<"5 - Snake solver"<<endl; cout<<"6 - Snake_tester"<<endl; cout<<"Number: "; cin>>choice; switch ( choice ) { case 1: p = pole1_test(100); break; case 2: p = pole2_test(100,1); break; case 3: p = pole2_test(100,0); break; case 4: p=xor_test(100); break; case 5: cout<<"Enter gene id: "<<endl; cin>> id; cout<<"Enter gen file name:"<<endl; cin>> filename; cout<<"Enter temp name:"<<endl; cin >> temp_name; p=snake_test(200, id, filename, temp_name); break; case 6: cout<<"Enter gene id: "<<endl; cin>> id; cout<<"Enter gen file name"<<endl; cin>> filename; snake_test_routine(id, filename); break; default: cout<<"Not an available option."<<endl; } //p = pole1_test(100); // 1-pole balancing //p = pole2_test(100,1); // 2-pole balancing, velocity //p = pole2_test(100,0); // 2-pole balancing, no velocity (non-markov) if (p) delete p; return(0); }
[ "sanxchit@gmail.com" ]
sanxchit@gmail.com
727abd9a70b9da148cf68f7d2176b7756f26912a
f742ca21bd501555db53624419cb77b37125588e
/src/rpcwallet.cpp
d1bb34ba0cf69461b74c126693c15c6160113b98
[ "MIT" ]
permissive
BlockchainCloud/Bitalpha
dc983d64508a174c385e7576bdcdfcfc5d708e96
8be8562d6902358afd0c191b41785f02d0fdfe46
refs/heads/master
2021-05-29T03:56:49.419683
2015-05-12T02:26:02
2015-05-12T02:26:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
54,601
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "base58.h" #include "rpcserver.h" #include "init.h" #include "net.h" #include "netbase.h" #include "timedata.h" #include "util.h" #include "wallet.h" #include "walletdb.h" using namespace std; using namespace json_spirit; int64_t nWalletUnlockTime; static CCriticalSection cs_nWalletUnlockTime; extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry); static void accountingDeprecationCheck() { if (!GetBoolArg("-enableaccounts", false)) throw runtime_error( "Accounting API is deprecated and will be removed in future.\n" "It can easily result in negative or odd balances if misused or misunderstood, which has happened in the field.\n" "If you still want to enable it, add to your config file enableaccounts=1\n"); if (GetBoolArg("-staking", true)) throw runtime_error("If you want to use accounting API, staking must be disabled, add to your config file staking=0\n"); } std::string HelpRequiringPassphrase() { return pwalletMain && pwalletMain->IsCrypted() ? "\nrequires wallet passphrase to be set with walletpassphrase first" : ""; } void EnsureWalletIsUnlocked() { if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); if (fWalletUnlockStakingOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Wallet is unlocked for staking only."); } void WalletTxToJSON(const CWalletTx& wtx, Object& entry) { int confirms = wtx.GetDepthInMainChain(); entry.push_back(Pair("confirmations", confirms)); if (wtx.IsCoinBase() || wtx.IsCoinStake()) entry.push_back(Pair("generated", true)); if (confirms > 0) { entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex())); entry.push_back(Pair("blockindex", wtx.nIndex)); entry.push_back(Pair("blocktime", (int64_t)(mapBlockIndex[wtx.hashBlock]->nTime))); } entry.push_back(Pair("txid", wtx.GetHash().GetHex())); entry.push_back(Pair("time", (int64_t)wtx.GetTxTime())); entry.push_back(Pair("timereceived", (int64_t)wtx.nTimeReceived)); BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue) entry.push_back(Pair(item.first, item.second)); } string AccountFromValue(const Value& value) { string strAccount = value.get_str(); if (strAccount == "*") throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name"); return strAccount; } Value getnewpubkey(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getnewpubkey [account]\n" "Returns new public key for coinbase generation."); // Parse the account first so we don't generate a key if there's an error string strAccount; if (params.size() > 0) strAccount = AccountFromValue(params[0]); if (!pwalletMain->IsLocked()) pwalletMain->TopUpKeyPool(); // Generate a new key that is added to wallet CPubKey newKey; if (!pwalletMain->GetKeyFromPool(newKey)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); CKeyID keyID = newKey.GetID(); pwalletMain->SetAddressBookName(keyID, strAccount); return HexStr(newKey.begin(), newKey.end()); } Value getnewaddress(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getnewaddress [account]\n" "Returns a new BitAlpha address for receiving payments. " "If [account] is specified, it is added to the address book " "so payments received with the address will be credited to [account]."); // Parse the account first so we don't generate a key if there's an error string strAccount; if (params.size() > 0) strAccount = AccountFromValue(params[0]); if (!pwalletMain->IsLocked()) pwalletMain->TopUpKeyPool(); // Generate a new key that is added to wallet CPubKey newKey; if (!pwalletMain->GetKeyFromPool(newKey)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); CKeyID keyID = newKey.GetID(); pwalletMain->SetAddressBookName(keyID, strAccount); return CBitcoinAddress(keyID).ToString(); } CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false) { CWalletDB walletdb(pwalletMain->strWalletFile); CAccount account; walletdb.ReadAccount(strAccount, account); bool bKeyUsed = false; // Check if the current key has been used if (account.vchPubKey.IsValid()) { CScript scriptPubKey; scriptPubKey.SetDestination(account.vchPubKey.GetID()); for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid(); ++it) { const CWalletTx& wtx = (*it).second; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) bKeyUsed = true; } } // Generate a new key if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed) { if (!pwalletMain->GetKeyFromPool(account.vchPubKey)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount); walletdb.WriteAccount(strAccount, account); } return CBitcoinAddress(account.vchPubKey.GetID()); } Value getaccountaddress(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaccountaddress <account>\n" "Returns the current BitAlpha address for receiving payments to this account."); // Parse the account first so we don't generate a key if there's an error string strAccount = AccountFromValue(params[0]); Value ret; ret = GetAccountAddress(strAccount).ToString(); return ret; } Value setaccount(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "setaccount <bitalphaaddress> <account>\n" "Sets the account associated with the given address."); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid BitAlpha address"); string strAccount; if (params.size() > 1) strAccount = AccountFromValue(params[1]); // Detect when changing the account of an address that is the 'unused current key' of another account: if (pwalletMain->mapAddressBook.count(address.Get())) { string strOldAccount = pwalletMain->mapAddressBook[address.Get()]; if (address == GetAccountAddress(strOldAccount)) GetAccountAddress(strOldAccount, true); } pwalletMain->SetAddressBookName(address.Get(), strAccount); return Value::null; } Value getaccount(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaccount <bitalphaaddress>\n" "Returns the account associated with the given address."); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid BitAlpha address"); string strAccount; map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get()); if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty()) strAccount = (*mi).second; return strAccount; } Value getaddressesbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaddressesbyaccount <account>\n" "Returns the list of addresses for the given account."); string strAccount = AccountFromValue(params[0]); // Find all addresses that have the given account Array ret; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strName = item.second; if (strName == strAccount) ret.push_back(address.ToString()); } return ret; } Value sendtoaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) throw runtime_error( "sendtoaddress <bitalphaaddress> <amount> [comment] [comment-to]\n" "<amount> is a real and is rounded to the nearest 0.000001" + HelpRequiringPassphrase()); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid BitAlpha address"); // Amount int64_t nAmount = AmountFromValue(params[1]); // Wallet comments CWalletTx wtx; if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty()) wtx.mapValue["comment"] = params[2].get_str(); if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()) wtx.mapValue["to"] = params[3].get_str(); if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); if (strError != "") throw JSONRPCError(RPC_WALLET_ERROR, strError); return wtx.GetHash().GetHex(); } Value listaddressgroupings(const Array& params, bool fHelp) { if (fHelp) throw runtime_error( "listaddressgroupings\n" "Lists groups of addresses which have had their common ownership\n" "made public by common use as inputs or as the resulting change\n" "in past transactions"); Array jsonGroupings; map<CTxDestination, int64_t> balances = pwalletMain->GetAddressBalances(); BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings()) { Array jsonGrouping; BOOST_FOREACH(CTxDestination address, grouping) { Array addressInfo; addressInfo.push_back(CBitcoinAddress(address).ToString()); addressInfo.push_back(ValueFromAmount(balances[address])); { LOCK(pwalletMain->cs_wallet); if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end()) addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second); } jsonGrouping.push_back(addressInfo); } jsonGroupings.push_back(jsonGrouping); } return jsonGroupings; } Value signmessage(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "signmessage <bitalphaaddress> <message>\n" "Sign a message with the private key of an address"); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); string strMessage = params[1].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); CKey key; if (!pwalletMain->GetKey(keyID, key)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available"); CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; vector<unsigned char> vchSig; if (!key.SignCompact(ss.GetHash(), vchSig)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed"); return EncodeBase64(&vchSig[0], vchSig.size()); } Value getreceivedbyaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getreceivedbyaddress <bitalphaaddress> [minconf=1]\n" "Returns the total amount received by <bitalphaaddress> in transactions with at least [minconf] confirmations."); // Bitcoin address CBitcoinAddress address = CBitcoinAddress(params[0].get_str()); CScript scriptPubKey; if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid BitAlpha address"); scriptPubKey.SetDestination(address.Get()); if (!IsMine(*pwalletMain,scriptPubKey)) return (double)0.0; // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Tally int64_t nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || wtx.IsCoinStake() || !IsFinalTx(wtx)) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } return ValueFromAmount(nAmount); } void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook) { const CTxDestination& address = item.first; const string& strName = item.second; if (strName == strAccount) setAddress.insert(address); } } Value getreceivedbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getreceivedbyaccount <account> [minconf=1]\n" "Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations."); accountingDeprecationCheck(); // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Get the set of pub keys assigned to account string strAccount = AccountFromValue(params[0]); set<CTxDestination> setAddress; GetAccountAddresses(strAccount, setAddress); // Tally int64_t nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || wtx.IsCoinStake() || !IsFinalTx(wtx)) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address)) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } } return (double)nAmount / (double)COIN; } int64_t GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth) { int64_t nBalance = 0; // Tally wallet transactions for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!IsFinalTx(wtx) || wtx.GetDepthInMainChain() < 0) continue; int64_t nReceived, nSent, nFee; wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee); if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth && wtx.GetBlocksToMaturity() == 0) nBalance += nReceived; nBalance -= nSent + nFee; } // Tally internal accounting entries nBalance += walletdb.GetAccountCreditDebit(strAccount); return nBalance; } int64_t GetAccountBalance(const string& strAccount, int nMinDepth) { CWalletDB walletdb(pwalletMain->strWalletFile); return GetAccountBalance(walletdb, strAccount, nMinDepth); } Value getbalance(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getbalance [account] [minconf=1]\n" "If [account] is not specified, returns the server's total available balance.\n" "If [account] is specified, returns the balance in the account."); if (params.size() == 0) return ValueFromAmount(pwalletMain->GetBalance()); int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); if (params[0].get_str() == "*") { // Calculate total balance a different way from GetBalance() // (GetBalance() sums up all unspent TxOuts) // getbalance and getbalance '*' 0 should return the same number. int64_t nBalance = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!wtx.IsTrusted()) continue; int64_t allFee; string strSentAccount; list<pair<CTxDestination, int64_t> > listReceived; list<pair<CTxDestination, int64_t> > listSent; wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount); if (wtx.GetDepthInMainChain() >= nMinDepth && wtx.GetBlocksToMaturity() == 0) { BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listReceived) nBalance += r.second; } BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listSent) nBalance -= r.second; nBalance -= allFee; } return ValueFromAmount(nBalance); } accountingDeprecationCheck(); string strAccount = AccountFromValue(params[0]); int64_t nBalance = GetAccountBalance(strAccount, nMinDepth); return ValueFromAmount(nBalance); } Value movecmd(const Array& params, bool fHelp) { if (fHelp || params.size() < 3 || params.size() > 5) throw runtime_error( "move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n" "Move from one account in your wallet to another."); accountingDeprecationCheck(); string strFrom = AccountFromValue(params[0]); string strTo = AccountFromValue(params[1]); int64_t nAmount = AmountFromValue(params[2]); if (params.size() > 3) // unused parameter, used to be nMinDepth, keep type-checking it though (void)params[3].get_int(); string strComment; if (params.size() > 4) strComment = params[4].get_str(); CWalletDB walletdb(pwalletMain->strWalletFile); if (!walletdb.TxnBegin()) throw JSONRPCError(RPC_DATABASE_ERROR, "database error"); int64_t nNow = GetAdjustedTime(); // Debit CAccountingEntry debit; debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb); debit.strAccount = strFrom; debit.nCreditDebit = -nAmount; debit.nTime = nNow; debit.strOtherAccount = strTo; debit.strComment = strComment; walletdb.WriteAccountingEntry(debit); // Credit CAccountingEntry credit; credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb); credit.strAccount = strTo; credit.nCreditDebit = nAmount; credit.nTime = nNow; credit.strOtherAccount = strFrom; credit.strComment = strComment; walletdb.WriteAccountingEntry(credit); if (!walletdb.TxnCommit()) throw JSONRPCError(RPC_DATABASE_ERROR, "database error"); return true; } Value sendfrom(const Array& params, bool fHelp) { if (fHelp || params.size() < 3 || params.size() > 6) throw runtime_error( "sendfrom <fromaccount> <tobitalphaaddress> <amount> [minconf=1] [comment] [comment-to]\n" "<amount> is a real and is rounded to the nearest 0.000001" + HelpRequiringPassphrase()); string strAccount = AccountFromValue(params[0]); CBitcoinAddress address(params[1].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid BitAlpha address"); int64_t nAmount = AmountFromValue(params[2]); int nMinDepth = 1; if (params.size() > 3) nMinDepth = params[3].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty()) wtx.mapValue["comment"] = params[4].get_str(); if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty()) wtx.mapValue["to"] = params[5].get_str(); EnsureWalletIsUnlocked(); // Check funds int64_t nBalance = GetAccountBalance(strAccount, nMinDepth); if (nAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); // Send string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); if (strError != "") throw JSONRPCError(RPC_WALLET_ERROR, strError); return wtx.GetHash().GetHex(); } Value sendmany(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) throw runtime_error( "sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n" "amounts are double-precision floating point numbers" + HelpRequiringPassphrase()); string strAccount = AccountFromValue(params[0]); Object sendTo = params[1].get_obj(); int nMinDepth = 1; if (params.size() > 2) nMinDepth = params[2].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()) wtx.mapValue["comment"] = params[3].get_str(); set<CBitcoinAddress> setAddress; vector<pair<CScript, int64_t> > vecSend; int64_t totalAmount = 0; BOOST_FOREACH(const Pair& s, sendTo) { CBitcoinAddress address(s.name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid BitAlpha address: ")+s.name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_); setAddress.insert(address); CScript scriptPubKey; scriptPubKey.SetDestination(address.Get()); int64_t nAmount = AmountFromValue(s.value_); totalAmount += nAmount; vecSend.push_back(make_pair(scriptPubKey, nAmount)); } EnsureWalletIsUnlocked(); // Check funds int64_t nBalance = GetAccountBalance(strAccount, nMinDepth); if (totalAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); // Send CReserveKey keyChange(pwalletMain); int64_t nFeeRequired = 0; bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired); if (!fCreated) { if (totalAmount + nFeeRequired > pwalletMain->GetBalance()) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds"); throw JSONRPCError(RPC_WALLET_ERROR, "Transaction creation failed"); } if (!pwalletMain->CommitTransaction(wtx, keyChange)) throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed"); return wtx.GetHash().GetHex(); } Value addmultisigaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) { string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n" "Add a nrequired-to-sign multisignature address to the wallet\"\n" "each key is a BitAlpha address or hex-encoded public key\n" "If [account] is specified, assign address to [account]."; throw runtime_error(msg); } int nRequired = params[0].get_int(); const Array& keys = params[1].get_array(); string strAccount; if (params.size() > 2) strAccount = AccountFromValue(params[2]); // Gather public keys if (nRequired < 1) throw runtime_error("a multisignature address must require at least one key to redeem"); if ((int)keys.size() < nRequired) throw runtime_error( strprintf("not enough keys supplied " "(got %"PRIszu" keys, but need at least %d to redeem)", keys.size(), nRequired)); std::vector<CPubKey> pubkeys; pubkeys.resize(keys.size()); for (unsigned int i = 0; i < keys.size(); i++) { const std::string& ks = keys[i].get_str(); // Case 1: Bitcoin address and we have full public key: CBitcoinAddress address(ks); if (pwalletMain && address.IsValid()) { CKeyID keyID; if (!address.GetKeyID(keyID)) throw runtime_error( strprintf("%s does not refer to a key",ks)); CPubKey vchPubKey; if (!pwalletMain->GetPubKey(keyID, vchPubKey)) throw runtime_error( strprintf("no full public key for address %s",ks)); if (!vchPubKey.IsFullyValid()) throw runtime_error(" Invalid public key: "+ks); pubkeys[i] = vchPubKey; } // Case 2: hex public key else if (IsHex(ks)) { CPubKey vchPubKey(ParseHex(ks)); if (!vchPubKey.IsFullyValid()) throw runtime_error(" Invalid public key: "+ks); pubkeys[i] = vchPubKey; } else { throw runtime_error(" Invalid public key: "+ks); } } // Construct using pay-to-script-hash: CScript inner; inner.SetMultisig(nRequired, pubkeys); CScriptID innerID = inner.GetID(); if (!pwalletMain->AddCScript(inner)) throw runtime_error("AddCScript() failed"); pwalletMain->SetAddressBookName(innerID, strAccount); return CBitcoinAddress(innerID).ToString(); } Value addredeemscript(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) { string msg = "addredeemscript <redeemScript> [account]\n" "Add a P2SH address with a specified redeemScript to the wallet.\n" "If [account] is specified, assign address to [account]."; throw runtime_error(msg); } string strAccount; if (params.size() > 1) strAccount = AccountFromValue(params[1]); // Construct using pay-to-script-hash: vector<unsigned char> innerData = ParseHexV(params[0], "redeemScript"); CScript inner(innerData.begin(), innerData.end()); CScriptID innerID = inner.GetID(); if (!pwalletMain->AddCScript(inner)) throw runtime_error("AddCScript() failed"); pwalletMain->SetAddressBookName(innerID, strAccount); return CBitcoinAddress(innerID).ToString(); } struct tallyitem { int64_t nAmount; int nConf; tallyitem() { nAmount = 0; nConf = std::numeric_limits<int>::max(); } }; Value ListReceived(const Array& params, bool fByAccounts) { // Minimum confirmations int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); // Whether to include empty accounts bool fIncludeEmpty = false; if (params.size() > 1) fIncludeEmpty = params[1].get_bool(); // Tally map<CBitcoinAddress, tallyitem> mapTally; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || wtx.IsCoinStake() || !IsFinalTx(wtx)) continue; int nDepth = wtx.GetDepthInMainChain(); if (nDepth < nMinDepth) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address)) continue; tallyitem& item = mapTally[address]; item.nAmount += txout.nValue; item.nConf = min(item.nConf, nDepth); } } // Reply Array ret; map<string, tallyitem> mapAccountTally; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strAccount = item.second; map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address); if (it == mapTally.end() && !fIncludeEmpty) continue; int64_t nAmount = 0; int nConf = std::numeric_limits<int>::max(); if (it != mapTally.end()) { nAmount = (*it).second.nAmount; nConf = (*it).second.nConf; } if (fByAccounts) { tallyitem& item = mapAccountTally[strAccount]; item.nAmount += nAmount; item.nConf = min(item.nConf, nConf); } else { Object obj; obj.push_back(Pair("address", address.ToString())); obj.push_back(Pair("account", strAccount)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); ret.push_back(obj); } } if (fByAccounts) { for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it) { int64_t nAmount = (*it).second.nAmount; int nConf = (*it).second.nConf; Object obj; obj.push_back(Pair("account", (*it).first)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); ret.push_back(obj); } } return ret; } Value listreceivedbyaddress(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "listreceivedbyaddress [minconf=1] [includeempty=false]\n" "[minconf] is the minimum number of confirmations before payments are included.\n" "[includeempty] whether to include addresses that haven't received any payments.\n" "Returns an array of objects containing:\n" " \"address\" : receiving address\n" " \"account\" : the account of the receiving address\n" " \"amount\" : total amount received by the address\n" " \"confirmations\" : number of confirmations of the most recent transaction included"); return ListReceived(params, false); } Value listreceivedbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "listreceivedbyaccount [minconf=1] [includeempty=false]\n" "[minconf] is the minimum number of confirmations before payments are included.\n" "[includeempty] whether to include accounts that haven't received any payments.\n" "Returns an array of objects containing:\n" " \"account\" : the account of the receiving addresses\n" " \"amount\" : total amount received by addresses with this account\n" " \"confirmations\" : number of confirmations of the most recent transaction included"); accountingDeprecationCheck(); return ListReceived(params, true); } static void MaybePushAddress(Object & entry, const CTxDestination &dest) { CBitcoinAddress addr; if (addr.Set(dest)) entry.push_back(Pair("address", addr.ToString())); } void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret) { int64_t nFee; string strSentAccount; list<pair<CTxDestination, int64_t> > listReceived; list<pair<CTxDestination, int64_t> > listSent; wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount); bool fAllAccounts = (strAccount == string("*")); // Sent if ((!wtx.IsCoinStake()) && (!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount)) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& s, listSent) { Object entry; entry.push_back(Pair("account", strSentAccount)); MaybePushAddress(entry, s.first); entry.push_back(Pair("category", "send")); entry.push_back(Pair("amount", ValueFromAmount(-s.second))); entry.push_back(Pair("fee", ValueFromAmount(-nFee))); if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } } // Received if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth) { bool stop = false; BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& r, listReceived) { string account; if (pwalletMain->mapAddressBook.count(r.first)) account = pwalletMain->mapAddressBook[r.first]; if (fAllAccounts || (account == strAccount)) { Object entry; entry.push_back(Pair("account", account)); MaybePushAddress(entry, r.first); if (wtx.IsCoinBase() || wtx.IsCoinStake()) { if (wtx.GetDepthInMainChain() < 1) entry.push_back(Pair("category", "orphan")); else if (wtx.GetBlocksToMaturity() > 0) entry.push_back(Pair("category", "immature")); else entry.push_back(Pair("category", "generate")); } else { entry.push_back(Pair("category", "receive")); } if (!wtx.IsCoinStake()) entry.push_back(Pair("amount", ValueFromAmount(r.second))); else { entry.push_back(Pair("amount", ValueFromAmount(-nFee))); stop = true; // only one coinstake output } if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } if (stop) break; } } } void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret) { bool fAllAccounts = (strAccount == string("*")); if (fAllAccounts || acentry.strAccount == strAccount) { Object entry; entry.push_back(Pair("account", acentry.strAccount)); entry.push_back(Pair("category", "move")); entry.push_back(Pair("time", (int64_t)acentry.nTime)); entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit))); entry.push_back(Pair("otheraccount", acentry.strOtherAccount)); entry.push_back(Pair("comment", acentry.strComment)); ret.push_back(entry); } } Value listtransactions(const Array& params, bool fHelp) { if (fHelp || params.size() > 3) throw runtime_error( "listtransactions [account] [count=10] [from=0]\n" "Returns up to [count] most recent transactions skipping the first [from] transactions for account [account]."); string strAccount = "*"; if (params.size() > 0) strAccount = params[0].get_str(); int nCount = 10; if (params.size() > 1) nCount = params[1].get_int(); int nFrom = 0; if (params.size() > 2) nFrom = params[2].get_int(); if (nCount < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count"); if (nFrom < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from"); Array ret; std::list<CAccountingEntry> acentries; CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount); // iterate backwards until we have nCount items to return: for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) { CWalletTx *const pwtx = (*it).second.first; if (pwtx != 0) ListTransactions(*pwtx, strAccount, 0, true, ret); CAccountingEntry *const pacentry = (*it).second.second; if (pacentry != 0) AcentryToJSON(*pacentry, strAccount, ret); if ((int)ret.size() >= (nCount+nFrom)) break; } // ret is newest to oldest if (nFrom > (int)ret.size()) nFrom = ret.size(); if ((nFrom + nCount) > (int)ret.size()) nCount = ret.size() - nFrom; Array::iterator first = ret.begin(); std::advance(first, nFrom); Array::iterator last = ret.begin(); std::advance(last, nFrom+nCount); if (last != ret.end()) ret.erase(last, ret.end()); if (first != ret.begin()) ret.erase(ret.begin(), first); std::reverse(ret.begin(), ret.end()); // Return oldest to newest return ret; } Value listaccounts(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "listaccounts [minconf=1]\n" "Returns Object that has account names as keys, account balances as values."); accountingDeprecationCheck(); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); map<string, int64_t> mapAccountBalances; BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) { if (IsMine(*pwalletMain, entry.first)) // This address belongs to me mapAccountBalances[entry.second] = 0; } for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; int64_t nFee; string strSentAccount; list<pair<CTxDestination, int64_t> > listReceived; list<pair<CTxDestination, int64_t> > listSent; int nDepth = wtx.GetDepthInMainChain(); if (nDepth < 0) continue; wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount); mapAccountBalances[strSentAccount] -= nFee; BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& s, listSent) mapAccountBalances[strSentAccount] -= s.second; if (nDepth >= nMinDepth && wtx.GetBlocksToMaturity() == 0) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& r, listReceived) if (pwalletMain->mapAddressBook.count(r.first)) mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second; else mapAccountBalances[""] += r.second; } } list<CAccountingEntry> acentries; CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries); BOOST_FOREACH(const CAccountingEntry& entry, acentries) mapAccountBalances[entry.strAccount] += entry.nCreditDebit; Object ret; BOOST_FOREACH(const PAIRTYPE(string, int64_t)& accountBalance, mapAccountBalances) { ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second))); } return ret; } Value listsinceblock(const Array& params, bool fHelp) { if (fHelp) throw runtime_error( "listsinceblock [blockhash] [target-confirmations]\n" "Get all transactions in blocks since block [blockhash], or all transactions if omitted"); CBlockIndex *pindex = NULL; int target_confirms = 1; if (params.size() > 0) { uint256 blockId = 0; blockId.SetHex(params[0].get_str()); pindex = CBlockLocator(blockId).GetBlockIndex(); } if (params.size() > 1) { target_confirms = params[1].get_int(); if (target_confirms < 1) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); } int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1; Array transactions; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++) { CWalletTx tx = (*it).second; if (depth == -1 || tx.GetDepthInMainChain() < depth) ListTransactions(tx, "*", 0, true, transactions); } uint256 lastblock; if (target_confirms == 1) { lastblock = hashBestChain; } else { int target_height = pindexBest->nHeight + 1 - target_confirms; CBlockIndex *block; for (block = pindexBest; block && block->nHeight > target_height; block = block->pprev) { } lastblock = block ? block->GetBlockHash() : 0; } Object ret; ret.push_back(Pair("transactions", transactions)); ret.push_back(Pair("lastblock", lastblock.GetHex())); return ret; } Value gettransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "gettransaction <txid>\n" "Get detailed information about <txid>"); uint256 hash; hash.SetHex(params[0].get_str()); Object entry; if (pwalletMain->mapWallet.count(hash)) { const CWalletTx& wtx = pwalletMain->mapWallet[hash]; TxToJSON(wtx, 0, entry); int64_t nCredit = wtx.GetCredit(); int64_t nDebit = wtx.GetDebit(); int64_t nNet = nCredit - nDebit; int64_t nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0); entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee))); if (wtx.IsFromMe()) entry.push_back(Pair("fee", ValueFromAmount(nFee))); WalletTxToJSON(wtx, entry); Array details; ListTransactions(pwalletMain->mapWallet[hash], "*", 0, false, details); entry.push_back(Pair("details", details)); } else { CTransaction tx; uint256 hashBlock = 0; if (GetTransaction(hash, tx, hashBlock)) { TxToJSON(tx, 0, entry); if (hashBlock == 0) entry.push_back(Pair("confirmations", 0)); else { entry.push_back(Pair("blockhash", hashBlock.GetHex())); map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight)); else entry.push_back(Pair("confirmations", 0)); } } } else throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction"); } return entry; } Value backupwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "backupwallet <destination>\n" "Safely copies wallet.dat to destination, which can be a directory or a path with filename."); string strDest = params[0].get_str(); if (!BackupWallet(*pwalletMain, strDest)) throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!"); return Value::null; } Value keypoolrefill(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "keypoolrefill [new-size]\n" "Fills the keypool." + HelpRequiringPassphrase()); unsigned int nSize = max(GetArg("-keypool", 100), (int64_t)0); if (params.size() > 0) { if (params[0].get_int() < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size"); nSize = (unsigned int) params[0].get_int(); } EnsureWalletIsUnlocked(); pwalletMain->TopUpKeyPool(nSize); if (pwalletMain->GetKeyPoolSize() < nSize) throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool."); return Value::null; } static void LockWallet(CWallet* pWallet) { LOCK(cs_nWalletUnlockTime); nWalletUnlockTime = 0; pWallet->Lock(); } Value walletpassphrase(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 3)) throw runtime_error( "walletpassphrase <passphrase> <timeout> [stakingonly]\n" "Stores the wallet decryption key in memory for <timeout> seconds.\n" "if [stakingonly] is true sending functions are disabled."); if (fHelp) return true; if (!fServer) throw JSONRPCError(RPC_SERVER_NOT_STARTED, "Error: RPC server was not started, use server=1 to change this."); if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called."); // Note that the walletpassphrase is stored in params[0] which is not mlock()ed SecureString strWalletPass; strWalletPass.reserve(100); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() > 0) { if (!pwalletMain->Unlock(strWalletPass)) throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); } else throw runtime_error( "walletpassphrase <passphrase> <timeout>\n" "Stores the wallet decryption key in memory for <timeout> seconds."); pwalletMain->TopUpKeyPool(); int64_t nSleepTime = params[1].get_int64(); LOCK(cs_nWalletUnlockTime); nWalletUnlockTime = GetTime() + nSleepTime; RPCRunLater("lockwallet", boost::bind(LockWallet, pwalletMain), nSleepTime); // ppcoin: if user OS account compromised prevent trivial sendmoney commands if (params.size() > 2) fWalletUnlockStakingOnly = params[2].get_bool(); else fWalletUnlockStakingOnly = false; return Value::null; } Value walletpassphrasechange(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2)) throw runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called."); // TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strOldWalletPass; strOldWalletPass.reserve(100); strOldWalletPass = params[0].get_str().c_str(); SecureString strNewWalletPass; strNewWalletPass.reserve(100); strNewWalletPass = params[1].get_str().c_str(); if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1) throw runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass)) throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); return Value::null; } Value walletlock(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0)) throw runtime_error( "walletlock\n" "Removes the wallet encryption key from memory, locking the wallet.\n" "After calling this method, you will need to call walletpassphrase again\n" "before being able to call any methods which require the wallet to be unlocked."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called."); { LOCK(cs_nWalletUnlockTime); pwalletMain->Lock(); nWalletUnlockTime = 0; } return Value::null; } Value encryptwallet(const Array& params, bool fHelp) { if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1)) throw runtime_error( "encryptwallet <passphrase>\n" "Encrypts the wallet with <passphrase>."); if (fHelp) return true; if (pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called."); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strWalletPass; strWalletPass.reserve(100); strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() < 1) throw runtime_error( "encryptwallet <passphrase>\n" "Encrypts the wallet with <passphrase>."); if (!pwalletMain->EncryptWallet(strWalletPass)) throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet."); // BDB seems to have a bad habit of writing old data into // slack space in .dat files; that is bad if the old data is // unencrypted private keys. So: StartShutdown(); return "wallet encrypted; BitAlpha server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup."; } // ppcoin: reserve balance from being staked for network protection Value reservebalance(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "reservebalance [<reserve> [amount]]\n" "<reserve> is true or false to turn balance reserve on or off.\n" "<amount> is a real and rounded to cent.\n" "Set reserve amount not participating in network protection.\n" "If no parameters provided current setting is printed.\n"); if (params.size() > 0) { bool fReserve = params[0].get_bool(); if (fReserve) { if (params.size() == 1) throw runtime_error("must provide amount to reserve balance.\n"); int64_t nAmount = AmountFromValue(params[1]); nAmount = (nAmount / CENT) * CENT; // round to cent if (nAmount < 0) throw runtime_error("amount cannot be negative.\n"); nReserveBalance = nAmount; } else { if (params.size() > 1) throw runtime_error("cannot specify amount to turn off reserve.\n"); nReserveBalance = 0; } } Object result; result.push_back(Pair("reserve", (nReserveBalance > 0))); result.push_back(Pair("amount", ValueFromAmount(nReserveBalance))); return result; } // ppcoin: check wallet integrity Value checkwallet(const Array& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "checkwallet\n" "Check wallet for integrity.\n"); int nMismatchSpent; int64_t nBalanceInQuestion; pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion, true); Object result; if (nMismatchSpent == 0) result.push_back(Pair("wallet check passed", true)); else { result.push_back(Pair("mismatched spent coins", nMismatchSpent)); result.push_back(Pair("amount in question", ValueFromAmount(nBalanceInQuestion))); } return result; } // ppcoin: repair wallet Value repairwallet(const Array& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "repairwallet\n" "Repair wallet if checkwallet reports any problem.\n"); int nMismatchSpent; int64_t nBalanceInQuestion; pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion); Object result; if (nMismatchSpent == 0) result.push_back(Pair("wallet check passed", true)); else { result.push_back(Pair("mismatched spent coins", nMismatchSpent)); result.push_back(Pair("amount affected by repair", ValueFromAmount(nBalanceInQuestion))); } return result; } // NovaCoin: resend unconfirmed wallet transactions Value resendtx(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "resendtx\n" "Re-send unconfirmed transactions.\n" ); ResendWalletTransactions(true); return Value::null; } // ppcoin: make a public-private key pair Value makekeypair(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "makekeypair [prefix]\n" "Make a public/private key pair.\n" "[prefix] is optional preferred prefix for the public key.\n"); string strPrefix = ""; if (params.size() > 0) strPrefix = params[0].get_str(); CKey key; key.MakeNewKey(false); CPrivKey vchPrivKey = key.GetPrivKey(); Object result; result.push_back(Pair("PrivateKey", HexStr<CPrivKey::iterator>(vchPrivKey.begin(), vchPrivKey.end()))); result.push_back(Pair("PublicKey", HexStr(key.GetPubKey()))); return result; } Value settxfee(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1 || AmountFromValue(params[0]) < MIN_TX_FEE) throw runtime_error( "settxfee <amount>\n" "<amount> is a real and is rounded to the nearest 0.01"); nTransactionFee = AmountFromValue(params[0]); nTransactionFee = (nTransactionFee / CENT) * CENT; // round to cent return true; }
[ "doxtyphon@hotmail.com" ]
doxtyphon@hotmail.com
450a65248ed95e3f7f80780b9f36c8a5ab5e907a
009cca46aed9599d633441b044987ae78b60685a
/include/QweakSimBeamLineMessenger.hh
755a2ee4a5ef16d430c2c763cdd7f95ca282730c
[]
no_license
cipriangal/QweakG4DD
0de40f6c2693021db44916e03d8d55703aa37387
5c8f55be4ba0ec3a3898a40c4e1ff8eb42c550ad
refs/heads/master
2021-01-23T10:29:53.163237
2018-06-25T19:03:24
2018-06-25T19:03:24
29,534,503
0
4
null
2017-03-27T21:06:14
2015-01-20T14:45:37
C++
UTF-8
C++
false
false
1,674
hh
//============================================================================= // // --------------------------- // | Doxygen File Information | // --------------------------- /** \file QweakSimBeamLineMessenger.hh $Revision: 1.2 $ $Date: 2011/10/19 12:44 $ \author Peiqing Wang */ //============================================================================= // //============================================================================= // // --------------------------- // | Doxygen Class Information | // --------------------------- /** \class QweakSimBeamLineMessenger \brief Placeholder for a long explaination */ //============================================================================= //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... #ifndef QweakSimBeamLineMessenger_h #define QweakSimBeamLineMessenger_h 1 //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... // user includes #include "QweakSimMessengerDeclaration.hh" // user classes class QweakSimBeamLine; //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... class QweakSimBeamLineMessenger: public G4UImessenger { public: QweakSimBeamLineMessenger(QweakSimBeamLine*); ~QweakSimBeamLineMessenger(); void SetNewValue(G4UIcommand*, G4String); private: QweakSimBeamLine* myBeamLine; G4UIdirectory* BeamLineDir; G4UIcmdWithAString* BeamLineMatCmd; G4UIcmdWithADoubleAndUnit* BeamLineZPosCmd; }; //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... #endif
[ "ciprian@dochia.local" ]
ciprian@dochia.local
c301f3baf8877e6b96c708d87ca0ad0e212be1fd
ed4ab37b6d8bb37ac2c513f530f8a1151b5e950b
/wpstat3d-105/BWP.cpp
7d32b2f9751863e9f2f8eed9f02ba45537f89ae1
[]
no_license
Bots-United/joebotxp
f8b66040325098fe921cdb1354e8265f2c97f1a1
8834237de0fa24447d95d0b300a23e6818cafe61
refs/heads/master
2020-04-25T14:44:13.797982
2019-02-27T05:50:41
2019-02-27T05:50:41
172,851,898
0
0
null
null
null
null
UTF-8
C++
false
false
9,028
cpp
// BWP.cpp: implementation of the CBWP class. // ////////////////////////////////////////////////////////////////////// #include <math.h> #include "BWP.h" #include <iostream> using namespace std; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// #include "Line.h" #include "Cube.h" extern CObject **Objects; extern long lObjects; extern float rD; extern bool g_bshowbwp; CBWPNode::CBWPNode() { m_bLeaf = true; m_pParent = 0; m_ppChildren[0] = m_ppChildren[1] = 0; m_fBorder = 0; m_iPartComp = 0; } CBWPNode::~CBWPNode(){ } CBWP::CBWP(){ m_pHead = 0; } CBWP::~CBWP(){ reset(); } void CBWP::addWaypoint(CWaypoint *pWP){ if(m_pHead){ CBWPNode *pNode = 0; int i, iComp = -1; // component to divide this partition by Vector VDiff; pNode = traceNode(pWP->m_VOrigin); VDiff = pWP->m_VOrigin - pNode->m_pWaypoint->m_VOrigin; if(VDiff.length() == 0) // don't add identical waypoints return; int iNot=-1; if(pNode->m_pParent){ iNot = pNode->m_pParent->m_iPartComp; } iNot = -1; for(i=0; i < 2; i++) if((iComp == -1&& i != iNot) || (fabs(VDiff[i]) > fabs(VDiff[iComp]) && i != iNot)) iComp = i; cout << iComp << " "; pNode->m_fBorder = pNode->m_pWaypoint->m_VOrigin[iComp] + VDiff[iComp] / 2.f; pNode->m_iPartComp = iComp; pNode->m_ppChildren[0] = new CBWPNode; pNode->m_ppChildren[1] = new CBWPNode; pNode->m_ppChildren[0]->m_pParent = pNode; pNode->m_ppChildren[1]->m_pParent = pNode; if(pWP->m_VOrigin[iComp] < pNode->m_fBorder){ pNode->m_ppChildren[0]->m_pWaypoint = pWP; pNode->m_ppChildren[1]->m_pWaypoint = pNode->m_pWaypoint; } else{ pNode->m_ppChildren[0]->m_pWaypoint = pNode->m_pWaypoint; pNode->m_ppChildren[1]->m_pWaypoint = pWP; } pNode->m_pWaypoint = 0; pNode->m_bLeaf = false; /*{ Objects[lObjects] = new CLine; if(iComp == 0){ ((CLine *)Objects[lObjects])->x1 = pNode->m_fBorder/1000; ((CLine *)Objects[lObjects])->y1 = -4; ((CLine *)Objects[lObjects])->z1 = 0; ((CLine *)Objects[lObjects])->x2 = pNode->m_fBorder/1000; ((CLine *)Objects[lObjects])->y2 = 4; ((CLine *)Objects[lObjects])->z2 = 0; } else if(iComp == 1){ ((CLine *)Objects[lObjects])->y1 = pNode->m_fBorder/1000; ((CLine *)Objects[lObjects])->x1 = -4; ((CLine *)Objects[lObjects])->z1 = 0; ((CLine *)Objects[lObjects])->y2 = pNode->m_fBorder/1000; ((CLine *)Objects[lObjects])->x2 = 4; ((CLine *)Objects[lObjects])->z2 = 0; } else{ ((CLine *)Objects[lObjects])->z1 = pNode->m_fBorder/1000; ((CLine *)Objects[lObjects])->x1 = -4; ((CLine *)Objects[lObjects])->y1 = 0; ((CLine *)Objects[lObjects])->z2 = pNode->m_fBorder/1000; ((CLine *)Objects[lObjects])->x2 = 4; ((CLine *)Objects[lObjects])->y2 = 0; } ((CLine *)Objects[lObjects])->r = .0f; ((CLine *)Objects[lObjects])->g = .9f; ((CLine *)Objects[lObjects])->b = .0f; lObjects++; }*/ } else{ m_pHead = new CBWPNode; m_pHead->m_bLeaf = true; m_pHead->m_pWaypoint = pWP; } } CBWPNode *CBWP::traceNode(Vector &VVec){ CBWPNode *pNode = m_pHead; while(/*pNode && */!pNode->m_bLeaf){ if(g_bshowbwp){ float fl,fr; Objects[lObjects] = new CLine; if(pNode->m_iPartComp == 0){ getBorders(pNode,1,fl,fr); ((CLine *)Objects[lObjects])->x1 = pNode->m_fBorder/1000.f; ((CLine *)Objects[lObjects])->y1 = fl/1000.f; ((CLine *)Objects[lObjects])->z1 = 0; ((CLine *)Objects[lObjects])->x2 = pNode->m_fBorder/1000.f; ((CLine *)Objects[lObjects])->y2 = fr/1000.f; ((CLine *)Objects[lObjects])->z2 = 0; } else if(pNode->m_iPartComp == 1){ getBorders(pNode,0,fl,fr); ((CLine *)Objects[lObjects])->y1 = pNode->m_fBorder/1000.f; ((CLine *)Objects[lObjects])->x1 = fl/1000.f; ((CLine *)Objects[lObjects])->z1 = 0; ((CLine *)Objects[lObjects])->y2 = pNode->m_fBorder/1000.f; ((CLine *)Objects[lObjects])->x2 = fr/1000.f; ((CLine *)Objects[lObjects])->z2 = 0; } else{ getBorders(pNode,0,fl,fr); ((CLine *)Objects[lObjects])->z1 = pNode->m_fBorder/1000.f; ((CLine *)Objects[lObjects])->x1 = fl/1000.f; ((CLine *)Objects[lObjects])->y1 = 0; ((CLine *)Objects[lObjects])->z2 = pNode->m_fBorder/1000.f; ((CLine *)Objects[lObjects])->x2 = fr/1000.f; ((CLine *)Objects[lObjects])->y2 = 0; } ((CLine *)Objects[lObjects])->r = .0f; ((CLine *)Objects[lObjects])->g = .0f; ((CLine *)Objects[lObjects])->b = 1.f; lObjects++; } pNode = pNode->m_ppChildren[VVec[pNode->m_iPartComp] >= pNode->m_fBorder]; } if(g_bshowbwp){ Vector V1,V2; getBorders(pNode,0,V1.x,V2.x); getBorders(pNode,1,V1.y,V2.y); //getBorders(pNode,3,V1.z,V2.z); V1.z = V2.z = 0; Objects[lObjects] = new CLine; ((CLine *)Objects[lObjects])->x1 = V1.x/1000; ((CLine *)Objects[lObjects])->y1 = V1.y/1000; ((CLine *)Objects[lObjects])->z1 = V1.z/1000; ((CLine *)Objects[lObjects])->x2 = V2.x/1000; ((CLine *)Objects[lObjects])->y2 = V1.y/1000; ((CLine *)Objects[lObjects])->z2 = V1.z/1000; ((CLine *)Objects[lObjects])->r = .0f; ((CLine *)Objects[lObjects])->g = .9f; ((CLine *)Objects[lObjects])->b = .0f; lObjects++; Objects[lObjects] = new CLine; ((CLine *)Objects[lObjects])->x1 = V2.x/1000; ((CLine *)Objects[lObjects])->y1 = V1.y/1000; ((CLine *)Objects[lObjects])->z1 = V1.z/1000; ((CLine *)Objects[lObjects])->x2 = V2.x/1000; ((CLine *)Objects[lObjects])->y2 = V2.y/1000; ((CLine *)Objects[lObjects])->z2 = V1.z/1000; ((CLine *)Objects[lObjects])->r = .0f; ((CLine *)Objects[lObjects])->g = .9f; ((CLine *)Objects[lObjects])->b = .0f; lObjects++; Objects[lObjects] = new CLine; ((CLine *)Objects[lObjects])->x1 = V2.x/1000; ((CLine *)Objects[lObjects])->y1 = V2.y/1000; ((CLine *)Objects[lObjects])->z1 = V1.z/1000; ((CLine *)Objects[lObjects])->x2 = V1.x/1000; ((CLine *)Objects[lObjects])->y2 = V2.y/1000; ((CLine *)Objects[lObjects])->z2 = V1.z/1000; ((CLine *)Objects[lObjects])->r = .0f; ((CLine *)Objects[lObjects])->g = .9f; ((CLine *)Objects[lObjects])->b = .0f; lObjects++; Objects[lObjects] = new CLine; ((CLine *)Objects[lObjects])->x1 = V1.x/1000; ((CLine *)Objects[lObjects])->y1 = V2.y/1000; ((CLine *)Objects[lObjects])->z1 = V1.z/1000; ((CLine *)Objects[lObjects])->x2 = V1.x/1000; ((CLine *)Objects[lObjects])->y2 = V1.y/1000; ((CLine *)Objects[lObjects])->z2 = V1.z/1000; ((CLine *)Objects[lObjects])->r = .0f; ((CLine *)Objects[lObjects])->g = .9f; ((CLine *)Objects[lObjects])->b = .0f; lObjects++; Objects[lObjects] = new CLine; ((CLine *)Objects[lObjects])->x1 = V1.x/1000; ((CLine *)Objects[lObjects])->y1 = V1.y/1000; ((CLine *)Objects[lObjects])->z1 = V1.z/1000; ((CLine *)Objects[lObjects])->x2 = V2.x/1000; ((CLine *)Objects[lObjects])->y2 = V2.y/1000; ((CLine *)Objects[lObjects])->z2 = V1.z/1000; ((CLine *)Objects[lObjects])->r = .0f; ((CLine *)Objects[lObjects])->g = .9f; ((CLine *)Objects[lObjects])->b = .0f; lObjects++; Objects[lObjects] = new CLine; ((CLine *)Objects[lObjects])->x1 = V2.x/1000; ((CLine *)Objects[lObjects])->y1 = V1.y/1000; ((CLine *)Objects[lObjects])->z1 = V1.z/1000; ((CLine *)Objects[lObjects])->x2 = V1.x/1000; ((CLine *)Objects[lObjects])->y2 = V2.y/1000; ((CLine *)Objects[lObjects])->z2 = V1.z/1000; ((CLine *)Objects[lObjects])->r = .0f; ((CLine *)Objects[lObjects])->g = .9f; ((CLine *)Objects[lObjects])->b = .0f; lObjects++; } return pNode; } void CBWP::removeChildren(CBWPNode *pRemove){ if(pRemove->m_ppChildren[0]){ removeChildren(pRemove->m_ppChildren[0]); } if(pRemove->m_ppChildren[1]){ removeChildren(pRemove->m_ppChildren[1]); } delete pRemove->m_ppChildren[0]; pRemove->m_ppChildren[0] = 0; delete pRemove->m_ppChildren[1]; pRemove->m_ppChildren[1] = 0; } void CBWP::reset(void){ removeChildren(m_pHead); delete m_pHead; m_pHead = 0; } void CBWP::getBorders(CBWPNode *pNode,int iComp,float &fLeft,float &fRight){ bool bLeft = false; bool bRight= false; fRight = 4096; fLeft = -4096; CBWPNode *pIterNode = pNode,*pLastNode; while(!(bLeft&&bRight)){ pLastNode = pIterNode; pIterNode = pIterNode->m_pParent; if(!pIterNode) break; if(pIterNode->m_iPartComp == iComp){ if(pIterNode->m_ppChildren[1] == pLastNode){ if(!bLeft){ bLeft = true; fLeft = pIterNode->m_fBorder; } } else{ if(!bRight){ bRight = true; fRight = pIterNode->m_fBorder; } } } } }
[ "weimingzhi@baidu.com" ]
weimingzhi@baidu.com
1841340339114deb23af7711e77569fc04d8ce1b
21ca9a722eaa16d8eacb79e0ab39dffc3d4174e9
/plcl/iplugindocument_impl.cpp
12eabdb4a839a4d8fa634a655a57146b1a831413
[]
no_license
zhangmingmovidius/ekc
be9c68624ccdf95d743e61492e3f274d17b7cf5e
887bbaccee7ee3de58734894441a619f8654a962
refs/heads/master
2021-05-27T11:22:35.773702
2014-12-08T11:15:35
2014-12-08T11:15:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,620
cpp
// Copyright (C) 2012 Yuri Agafonov // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "stdafx.h" #define WIN32_LEAN_AND_MEAN #define INC_OLE2 #include "iplugindocument_impl.h" #include "ipluginpage_impl.h" #include "itextpage_impl.h" #include "impl_exception_helper.hpp" IPluginDocumentImpl::IPluginDocumentImpl(plcl::Doc *doc_) : doc(doc_) {} IPluginDocumentImpl::~IPluginDocumentImpl() {} STDMETHODIMP IPluginDocumentImpl::get_PageCount(DWORD *v) { try { if (!v) return E_INVALIDARG; *v = static_cast<DWORD>(doc->PageCount()); return S_OK; } CATCH_EXCEPTION("IPluginDocumentImpl::get_PageCount()") } STDMETHODIMP IPluginDocumentImpl::GetPage(DWORD zero_based_page_number, IPluginPage **r) { try { if ((!r) || (static_cast<unsigned int>(zero_based_page_number) >= doc->PageCount())) return E_INVALIDARG; plcl::Page *page(0); if (!doc->GetPage(static_cast<unsigned int>(zero_based_page_number), &page)) return E_FAIL; ScopedComPtr<IPluginPage> page_ptr; plcl::TextPage *text_page = dynamic_cast<plcl::TextPage*>(page); if (text_page) { page_ptr = new ITextPageImpl(text_page); } else { page_ptr = new IPluginPageImpl(page); } *r = page_ptr.Detach(); return S_OK; } CATCH_EXCEPTION("IPluginDocumentImpl::GetPage()") }
[ "hatc.ogtuae@gmail.com" ]
hatc.ogtuae@gmail.com
9fb86054165ebe6a450e3a2917a240e3dc0db58b
e83b6e642da3f5dc481f6ed1d165484125ac4640
/lib/IR/EntryPoint.cpp
3f40fcd11f693a4201ebde42a114f8ad044eff4d
[ "NCSA", "LicenseRef-scancode-unknown-license-reference" ]
permissive
maziyang08/LLAIR
3a863d37562d36a53a3c72dd62b0675e4f6d1691
e92ca3a0e32ad9c1652fecb18692b61480f002a6
refs/heads/master
2020-03-18T03:28:29.370183
2018-04-25T21:14:55
2018-04-25T21:14:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
986
cpp
#include <llair/IR/EntryPoint.h> #include <llair/IR/Module.h> namespace llvm { template<> void SymbolTableListTraits<llair::EntryPoint>::addNodeToList(llair::EntryPoint *entry_point) { auto owner = getListOwner(); entry_point->setModule(owner); } template<> void SymbolTableListTraits<llair::EntryPoint>::removeNodeFromList(llair::EntryPoint *entry_point) { entry_point->setModule(nullptr); } } namespace llair { EntryPoint * EntryPoint::Create(EntryPoint::Type type, llvm::Function * function, Module *module) { return new EntryPoint(type, function, module); } EntryPoint::EntryPoint(EntryPoint::Type type, llvm::Function *function, Module *module) : d_module(module) , d_function(function) , d_type(type) { if (module) { module->getEntryPointList().push_back(this); } } void EntryPoint::setModule(Module *module) { d_module = module; } llvm::StringRef EntryPoint::getName() const { return d_function? d_function->getName() : llvm::StringRef(); } }
[ "alex.betts@gmail.com" ]
alex.betts@gmail.com
5aec4de8ed1a2205deae337995c17ef068063d66
359dc84bea9721c0802361bf482663799f043679
/CheckBalancedParanthesis.cpp
12226f856ad17fb3be7bdcbc2999917827ecd78b
[]
no_license
KanakJain/DSA
108772c988272e3fa4392cb5bb223d9e7c05951d
6c8308cd4dc98be3697593d71ec1cba2a478e38f
refs/heads/master
2020-04-02T13:21:27.445487
2018-10-24T09:56:41
2018-10-24T09:56:41
154,477,883
0
0
null
null
null
null
UTF-8
C++
false
false
573
cpp
#include <iostream> #include <stack> #include <cstring> using namespace std; bool CheckBalancedParanthesis(char c[], int n){ stack<char> S; for (int i=0; i<n; i++){ if(c[i] == '(' || c[i] == '[' || c[i] == '{'){ S.push(c[i]); } else if(c[i] == ')' || c[i] == ']' || c[i] == '}'){ if(S.empty()){ return false; } else{ S.pop(); } } } if(S.empty()){ return true; } else return false; } int main(){ char c[70]; cout<<"enter the expression"; cin>>c; cout<<CheckBalancedParanthesis(c, strlen(c)); }
[ "noreply@github.com" ]
noreply@github.com
7879f871acacc99cfc0f01047cecafeae3d0a885
54e8cbc8fd50b6330cc859695a3909226aeb3718
/src/Point.cpp
8f31b7ce7b8b038109d63f35d9739b690fc278c4
[]
no_license
astraub2/Fight-Or-Flight-Game
6cb65cd512ca15b5895df7f54a0e5b36abdea2da
24edb09d9afe5d78bece933354629328d949d64e
refs/heads/master
2021-01-22T20:45:26.915998
2017-03-17T21:24:09
2017-03-17T21:24:09
85,357,830
0
0
null
null
null
null
UTF-8
C++
false
false
248
cpp
#include "Point.hpp" Point::Point(int x, int y) : x(x), y(y) { } Point::~Point(){} int Point::getX() { return this->x; } int Point::getY() { return this->y; } void Point::setX(int newX) { x = newX; } void Point::setY(int newY) { y = newY; }
[ "spargete@uoregon.edu" ]
spargete@uoregon.edu
2e596bf6ee087db61983ec3308c3b75b6efe5143
1ac667dcb0e08a94f150bf1cbbb724f743820a89
/sc2d/src/core/os/stacktrace.cpp
81a2b1fee311373cdc73e73cc9515d791f6a71b2
[ "MIT" ]
permissive
NovaSurfer/scarecrow2d
2dde91c2e7167c935521c809a5bab1228464424e
3f877c082a8e0206edb3d899e18616c7d16b0e6f
refs/heads/master
2023-01-10T15:47:43.498299
2022-10-09T20:34:04
2022-10-09T20:34:04
131,281,610
2
0
MIT
2020-03-14T22:05:57
2018-04-27T10:22:05
C++
UTF-8
C++
false
false
3,257
cpp
/* * Copyright (c) 2009-2017, Farooq Mela * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "stacktrace.h" #include "core/compiler.h" #if defined(COMPILER_CLANG) || defined(COMPILER_GCC) # include <cxxabi.h> // for __cxa_demangle # include <dlfcn.h> // for dladdr # include <execinfo.h> // for backtrace #elif defined(COMPILER_MVC) //#include <DbgHelp.h> #endif #include <cstdio> #include <cstdlib> #include <sstream> #include <string> // This function produces a stack backtrace with demangled function & method names. const char* Backtrace(int skip = 1) { #if defined(COMPILER_CLANG) || defined(COMPILER_GCC) void* callstack[128]; const int nMaxFrames = sizeof(callstack) / sizeof(callstack[0]); char buf[1024]; int nFrames = backtrace(callstack, nMaxFrames); char** symbols = backtrace_symbols(callstack, nFrames); std::ostringstream trace_buf; for(int i = skip; i < nFrames; i++) { printf("%s\n", symbols[i]); Dl_info info; if(dladdr(callstack[i], &info) && info.dli_sname) { char* demangled = nullptr; int status = -1; if(info.dli_sname[0] == '_') demangled = abi::__cxa_demangle(info.dli_sname, nullptr, nullptr, &status); snprintf(buf, sizeof(buf), "%-3d %*p %s + %zd\n", i, int(2 + sizeof(void*) * 2), callstack[i], status == 0 ? demangled : info.dli_sname == nullptr ? symbols[i] : info.dli_sname, (char*)callstack[i] - (char*)info.dli_saddr); free(demangled); } else { snprintf(buf, sizeof(buf), "%-3d %*p %s\n", i, int(2 + sizeof(void*) * 2), callstack[i], symbols[i]); } trace_buf << buf; } free(symbols); return trace_buf.str().c_str(); #elif defined(COMPILER_MVC) return nullptr; #endif }
[ "tribar.ge@gmail.com" ]
tribar.ge@gmail.com
1b141b643956bee3ad7cd22412abde2504e96ceb
775a3fc6e96d50b2f2782d92be72bdc6170f22b7
/Arcade/Intro/46-elections-winners.cpp
8bf6891d609e3ccaecfc40e1ba09670cb6a7262c
[]
no_license
son2005/CoFi
3f9e4ef1778c6e246199cae7a69bbb0b08e2567f
d76ba175f240d0018f879a636c0c91fc413e0d6f
refs/heads/master
2021-06-02T14:01:06.322261
2021-02-06T16:03:31
2021-02-06T16:03:31
94,472,532
1
0
null
null
null
null
UTF-8
C++
false
false
413
cpp
// https://codefights.com/arcade/intro/level-10/8RiRRM3yvbuAd3MNg int electionsWinners(std::vector<int> votes, int k) { int maxVote = *std::max_element(votes.begin(), votes.end()); int counter = 0, counterSame = 0; for(auto &&i:votes) { if(k==0 && i == maxVote) counterSame++; else if(i+k > maxVote) counter++; } if(k==0) return counterSame == 1 ? 1 : 0; return counter; }
[ "tranbaoson2005@gmail.com" ]
tranbaoson2005@gmail.com