hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
4aa46507f58ef6450874fac86c3b690a4d8c866d
497
cpp
C++
lib/duden/FsdFile.cpp
nonwill/lsd2dsl
00e2a9832666dff03667b07815d73fab3fa8378e
[ "MIT" ]
66
2015-01-17T16:57:38.000Z
2022-02-06T15:29:54.000Z
lib/duden/FsdFile.cpp
nonwill/lsd2dsl
00e2a9832666dff03667b07815d73fab3fa8378e
[ "MIT" ]
19
2015-02-08T15:35:12.000Z
2022-01-26T10:46:11.000Z
lib/duden/FsdFile.cpp
nongeneric/lsd2dsl
4bf92b42b1ae47eee8e0b71bc04224dc037bd549
[ "MIT" ]
18
2015-03-23T07:06:07.000Z
2022-01-15T21:03:04.000Z
#include "FsdFile.h" #include <limits> namespace duden { FsdFile::FsdFile(std::shared_ptr<dictlsd::IRandomAccessStream> stream) : _stream(stream) {} void FsdFile::read(uint32_t plainOffset, uint32_t size, std::vector<char>& output) { output.resize(size); std::fill(begin(output), end(output), 0); _stream->seek(plainOffset); _stream->readSome(&output[0], size); } unsigned FsdFile::decodedSize() const { return std::numeric_limits<unsigned>::max(); } } // namespace duden
24.85
91
0.704225
[ "vector" ]
4aaaa6aaf0b10e20f96a003a81405a276b1195d2
1,016
cpp
C++
Others/1143-longest-common-subsequence.cpp
wandsX/LeetCodeExperience
8502e6e8ce911045f45f0075bcf3ee751a4558c7
[ "MIT" ]
null
null
null
Others/1143-longest-common-subsequence.cpp
wandsX/LeetCodeExperience
8502e6e8ce911045f45f0075bcf3ee751a4558c7
[ "MIT" ]
null
null
null
Others/1143-longest-common-subsequence.cpp
wandsX/LeetCodeExperience
8502e6e8ce911045f45f0075bcf3ee751a4558c7
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; //leetcode submit region begin(Prohibit modification and deletion) class Solution { public: int longestCommonSubsequence(string text1, string text2) { int m = text1.length(); int n = text2.length(); // dp[i][j] 表示text1[0:i] 和 text2[0:j]的最长公共子序列的长度 std::vector<std::vector<int>> dp( m + 1, std::vector(n, 0)); for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (text1[i - 1] == text2[j - 1]) { dp[i][j] = dp[i - 1][j - 1] + 1; } else { dp[i][j] = std::max(dp[i][j - 1], dp[i - 1][j]); } } } return dp[m][n]; } }; //leetcode submit region end(Prohibit modification and deletion)
26.051282
72
0.397638
[ "vector" ]
4ab7f1d42c0e8705b682d8389ed65bee3ced431c
2,723
cpp
C++
rede/admitanceCalc.cpp
BigsonLvrocha/NeuralPowerFlow
3d64078b5d1053cd521318229b69592acab6582a
[ "MIT" ]
null
null
null
rede/admitanceCalc.cpp
BigsonLvrocha/NeuralPowerFlow
3d64078b5d1053cd521318229b69592acab6582a
[ "MIT" ]
null
null
null
rede/admitanceCalc.cpp
BigsonLvrocha/NeuralPowerFlow
3d64078b5d1053cd521318229b69592acab6582a
[ "MIT" ]
null
null
null
/** * @brief Implements methods for admitance calculation of power network * * @file admitanceCalc.cpp * @author Luiz Victor Linhares Rocha * @date 2018-09-22 * @copyright 2018 Luiz Victor Linhares Rocha */ #include <iostream> #include "barra.hpp" #include "branch.hpp" #include "powerNet.hpp" #include "admitanceCalc.hpp" #include "../util/complexutils.h" namespace neuralFlux { /** * @brief gets only on part of the sum of calculation of admitance for the same bar * * @param branch the branch object * @return complexo result */ complexo AdmitanceCalc::getAdmitanceKkPartial(const BranchPtr& branch) { double modTrafo = complexModulo2(branch->getTrafo()); if (branch->isBranchOn()) { return modTrafo*(branch->getYkm()+complexo(0, branch->getBshkm())); } return 0; } /** * @brief * * @param branch * @return complexo */ complexo AdmitanceCalc::getAdmitanceMmPartial(const BranchPtr& branch) { if (branch->isBranchOn()) return branch->getYkm()+complexo(0, branch->getBshkm()); return 0; } complexo AdmitanceCalc::getAdmitanceKm(const BranchPtr& branch) { if (branch->isBranchOn()) return -branch->getA()*branch->getYkm()*complexCis(-branch->getPhi()); return 0; } complexo AdmitanceCalc::getAdmitanceMk(const BranchPtr& branch) { if (branch->isBranchOn()) return -branch->getA()*branch->getYkm()*complexCis( branch->getPhi()); return 0; } complexo AdmitanceCalc::getAdmitanceKk(const BarPtr& bar) { complexo admitance = complexo(0, bar->getBsh()); for (size_t i = 0, n = bar->getNConnections(); i < n; i++) { if (bar->getConnection(i)->getK() == bar) { admitance += getAdmitanceKkPartial(bar->getConnection(i)); } else { admitance += getAdmitanceMmPartial(bar->getConnection(i)); } } return admitance; } Eigen::MatrixXcd AdmitanceCalc::getMatrix(const PowerNetPtr& net) { const size_t nBars = net->getNBars(); Eigen::MatrixXcd Y; Y.setZero(nBars, nBars); for (size_t i = 0 ; i < nBars ; i++) { BarPtr bar = net->getBarByIndex(i); Y(i, i) = getAdmitanceKk(bar); for (size_t j = i+1 ; j < nBars ; j++) { try { BranchPtr branch = net->getBranchByIndex(i, j); if (branch->getK() == bar) { Y(i, j) = getAdmitanceKm(branch); Y(j, i) = getAdmitanceMk(branch); } else { Y(i, j) = getAdmitanceMk(branch); Y(j, i) = getAdmitanceKm(branch); } } catch (std::exception e) { } } } return Y; } } // namespace neuralFlux
28.663158
83
0.602277
[ "object" ]
3860032bf9652b8a0c5a3dee1d97dcf890d8fa8d
6,831
cpp
C++
StepClearpath.cpp
ctsuu/clear-path-servo-in-ROS
1783d72ea28871de11395a24a0fa27061dc6ae04
[ "MIT" ]
2
2019-01-14T08:11:14.000Z
2019-06-14T10:57:14.000Z
StepClearpath.cpp
ctsuu/clear-path-servo-in-ROS
1783d72ea28871de11395a24a0fa27061dc6ae04
[ "MIT" ]
null
null
null
StepClearpath.cpp
ctsuu/clear-path-servo-in-ROS
1783d72ea28871de11395a24a0fa27061dc6ae04
[ "MIT" ]
null
null
null
/* StepClearpath.h - Library for interfacing with Clearpath motors using an Arduino- Version 1 Teknic 2014 Brendan Flosenzier This library is free software; you can redistribute it and/or modify it. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ /* A StepClearpath is activated by creating an instance of the StepClearpath class. There can several instances of StepClearpath however each must be attached to different pins. This class is used in conjuntion with the StepController class, and is related to the PulseClearpath class. All functions available in the PulseClearpath class, are available in addition to Functions defined here. Note: Each attached motor must have its direction/B pin connected to one of pins 8-13 in order to work with The StepController object. Other devices can be connected to pins 8-13 as well The unique functions for a step motor are: StepClearpath - default constructor for initializing the motor stopMove() - Interupts the current move, the motor may abruptly stop calcSteps() - Internal Function used by StepController to calculate how many pulses to send to each motor setMaxVel() - sets the maximum veloctiy setMaxAccel() - sets the acceleration commandDone() - returns wheter or not there is a valid current command disable() - disables the motor */ #include "Arduino.h" #include "StepClearpath.h" /* This is an internal Function used by StepController to calculate how many pulses to send to each motor. It tracks the current command, as well as how many steps have been sent, and calculates how many steps to send in the next ISR. */ int StepClearpath::calcSteps() { _TX++;//increment time if(!_enabled) return 0; // Process current move state. switch(_moveStateX){ case 3: // IdleState state, executed only once. if(_commandX == 0) //If no/finished command/, do nothing set everything to 0 { _PX=0; _VX=0; _OPX=0; _TX=0; _TX1=0; _TX2=0; _TX3=0; _BurstX=0; } else { // Compute Move parameters _ZX = _commandX<<_bitshift; _ZX2 = abs(_ZX>>1); if(_ZX > 0) _AXS = _AXMX; else _AXS = -_AXMX; _AX = _AXS; // Do immediate move if half move length <= maximum acceleration. if(_ZX2 <= _AXMX) { _AX = 0; _VX = 0; _PX = _ZX; _moveStateX = 3; //Set to Move Idle _commandX=0; //Zero command break; } // Otherwise, execute move and go to Phase1 _PX = _PX + _VX;// + (_AX>>1); _VX = _VX + _AX; _moveStateX = 1; } break; case 1: //Phase 1 first half of move // Execute move _PX = _PX + _VX + (_AX>>1); _VX = _VX + _AX; // Check position. if(abs(_PX) >= _ZX2) { // If half move reached, compute time parameters and go to PXhase2 if(_flag) //This makes sure you go one step past half in order to make sure Phase 2 goes well { if(_TX1 == 0) { _TX1 = _TX; } if(_TX2 == 0) { _TX2 = _TX; } _AX = -_AX; //Set deccelleration _TX3 = (_TX2<<1) - _TX1; //compute time params _TAUX = _TX2<<1; _moveStateX = 2; //Start Phase 2 } _flag=true; } else { // Otherwise, check velocity. if(labs(_VX) >= _VMX) { // If maximum velocity reached, compute TX1 and set AX = 0, and _VX=_VMX. if(_TX1 == 0) { _AX = 0; _TX1 = _TX; if(_VX > 0) _VX=_VMX; else _VX=-_VMX; } } } break; case 2: //Phase 2 2nd half of move // Execute move _PX = _PX + _VX + (_AX>>1); _VX = _VX + _AX; // Check time. if(_TX >= _TX3) { // If beyond TX3, wait for done condition. _AX = -_AXS; if((_TX > _TAUX) || (labs(_PX) > labs(_ZX)) || (_VX*_AX > 0)) { // If done, enforce final position. _AX = 0; _VX = 0; _PX = _ZX; _moveStateX = 3; _commandX=0; } } break; } // Compute burst value _BurstX = (_PX - _OPX)>>_bitshift; // Update accumulated integer position _OPX += (long)(_BurstX)<<_bitshift; //check which direction, and incement absPosition if(_direction) _absPosition+=_BurstX; else _absPosition-=_BurstX; return _BurstX; } /* This is the default constructor. This intializes the variables. */ StepClearpath::StepClearpath() { _moveStateX=3; _Apin=0; _Bpin=0; _Epin=0; _Hpin=0; _enabled=false; _VMX=0; _AXMX=0; _PX=0; _OPX=0; _VX=0; _AX=0; _TX=0; _TX1=0; _TX2=0; _TX3=0; _TAUX=0; _flag=0; _AXS=0; _ZX=0; _ZX2=0; _commandX=0; _bitshift=10; _BurstX=0; _absPosition=0; } /* This function clears the current move, and puts the motor in a move idle state, without disableing it, or clearing the position. This may cause an abrupt stop. */ void StepClearpath::stopMove() { _PX=0; _VX=0; _OPX=0; _TX=0; _TX1=0; _TX2=0; _TX3=0; _BurstX=0; _moveStateX = 3; _commandX=0; } /* This function sets the velocity in Counts/sec assuming the ISR frequency is 2kHz. The maximum value for velMax is 100,000, the minimum is 2 */ void StepClearpath::setMaxVel(long velMax) { int n = velMax/2000; if(n<51) _VMX=(velMax*(1<<_bitshift))/2000; else _VMX=50*(1<<_bitshift); } /* This function sets the acceleration in Counts/sec/sec assuming the ISR frequency is 2kHz. The maximum value for accelMax is 2,000,000, the minimum is 4,000 */ void StepClearpath::setMaxAccel(long accelMax) { _AXMX=(accelMax*(1<<_bitshift))/4000000; } /* This function is a debugging function */ long StepClearpath::Movestate() { return _moveStateX; } /* This function is a debugging function */ long StepClearpath::test() { return _moveStateX; } /* This function returns true if there is no current command It returns false if there is a current command */ boolean StepClearpath::commandDone() { if(_commandX==0) return true; else return false; } /* This function returns zeros out the current command, and digitally writes the enable pin LOW If the motor was not attached with an enable pin, then it just zeros the command */ void StepClearpath::disable() { if(_Epin!=0) digitalWrite(_Epin,LOW); _PX=0; _enabled=false; _VX=0; _OPX=0; _TX=0; _TX1=0; _TX2=0; _TX3=0; _BurstX=0; _moveStateX = 3; _commandX=0; }
23
112
0.615576
[ "object" ]
3867e0513a6a189b2ecc8daad15dd0d79eeffcc2
2,014
cpp
C++
source/ff.data/source/value_vector.cpp
spadapet/ff_game_library
f1bf00f90adde66c2c2aa35b109fe61b8d2c6352
[ "MIT" ]
null
null
null
source/ff.data/source/value_vector.cpp
spadapet/ff_game_library
f1bf00f90adde66c2c2aa35b109fe61b8d2c6352
[ "MIT" ]
null
null
null
source/ff.data/source/value_vector.cpp
spadapet/ff_game_library
f1bf00f90adde66c2c2aa35b109fe61b8d2c6352
[ "MIT" ]
null
null
null
#include "pch.h" #include "value_vector.h" ff::value_ptr ff::type::value_vector_type::try_convert_from(const value* other) const { if (other->can_have_indexed_children()) { ff::value_vector vec; vec.reserve(other->index_child_count()); for (size_t i = 0; i < other->index_child_count(); i++) { vec.push_back(other->index_child(i)); } return ff::value::create<ff::value_vector>(std::move(vec)); } return nullptr; } bool ff::type::value_vector_type::can_have_indexed_children() const { return true; } ff::value_ptr ff::type::value_vector_type::index_child(const value* val, size_t index) const { const ff::value_vector& values = val->get<std::vector<value_ptr>>(); return index < values.size() ? values[index] : nullptr; } size_t ff::type::value_vector_type::index_child_count(const value* val) const { return val->get<ff::value_vector>().size(); } ff::value_ptr ff::type::value_vector_type::load(reader_base& reader) const { size_t size; if (ff::load(reader, size)) { ff::value_vector vec; vec.reserve(size); for (size_t i = 0; i < size; i++) { value_ptr child = ff::value::load_typed(reader); if (!child) { assert(false); return nullptr; } vec.push_back(std::move(child)); } return ff::value::create<ff::value_vector>(std::move(vec)); } assert(false); return nullptr; } bool ff::type::value_vector_type::save(const value* val, writer_base& writer) const { ff::value_vector src = val->get<ff::value_vector>(); size_t size = src.size(); if (ff::save(writer, size)) { for (const value_ptr& child : src) { if (!child->save_typed(writer)) { assert(false); return false; } } return true; } assert(false); return false; }
23.418605
92
0.575968
[ "vector" ]
387bfa0c8bac62d4921faa28a688511cb3a7cfc4
916
hpp
C++
cpp/include/cg3/manager/strategy.hpp
tychota/cg3-path-tracer
548519121cacb01a4be835c0bece21238b56f92b
[ "Beerware" ]
null
null
null
cpp/include/cg3/manager/strategy.hpp
tychota/cg3-path-tracer
548519121cacb01a4be835c0bece21238b56f92b
[ "Beerware" ]
null
null
null
cpp/include/cg3/manager/strategy.hpp
tychota/cg3-path-tracer
548519121cacb01a4be835c0bece21238b56f92b
[ "Beerware" ]
null
null
null
# pragma once # include "cg3/manager/tile.hpp" class Strategy { public: Strategy( tiny_vec< std::size_t, 2 > subdivisions , std::size_t samples_per_pixel , Tile::sampling_type subsampling = Tile::SAMPLE_RANDOM ) : _subdivisions( subdivisions ) , _samples_per_pixel( samples_per_pixel ) , _subpixel_sampling( subsampling ) {} virtual std::vector< Tile > create_render_tiles( tiny_vec< std::size_t, 2 > resolution ); virtual std::vector< Tile > create_target_tiles( tiny_vec< std::size_t, 2 > resolution ); virtual std::vector< Tile > create_tile_field( tiny_vec< std::size_t, 2 > resolution, size_t const samples_per_pixel, real_type const weight ); protected: tiny_vec< std::size_t, 2 > _subdivisions; std::size_t _samples_per_pixel; Tile::sampling_type _subpixel_sampling; };
32.714286
148
0.655022
[ "vector" ]
387cfb2428d00e442c49d7cb5db7e5e1e887e044
2,381
cpp
C++
Interview Puzzles/Pascal's Triangle or Binomial.cpp
TiwariAnil/Algorithmic_Puzzles
13a6b2ed8e8fd0176b9b58c073b2e9847e7ba774
[ "MIT" ]
null
null
null
Interview Puzzles/Pascal's Triangle or Binomial.cpp
TiwariAnil/Algorithmic_Puzzles
13a6b2ed8e8fd0176b9b58c073b2e9847e7ba774
[ "MIT" ]
null
null
null
Interview Puzzles/Pascal's Triangle or Binomial.cpp
TiwariAnil/Algorithmic_Puzzles
13a6b2ed8e8fd0176b9b58c073b2e9847e7ba774
[ "MIT" ]
null
null
null
#include<vector> #include<stack> #include<set> #include<map> #include<queue> #include<deque> #include<string> #include<iostream> #include<algorithm> #include<cstring> #include<cassert> #include<cstdlib> #include<cstdio> #include<cmath> #include<string> #include<stdio.h> using namespace std; #define s(n) scanf("%d",&n) #define sl(n) scanf("%lld",&n) #define sf(n) scanf("%lf",&n) #define ss(n) scanf("%s",n) #define p(n) printf("%d",n) #define pl(n) printf("%lld",n) #define pf(n) printf("%lf",n) #define ps(n) printf("%s",n) #define maX(a,b) ((a)>(b)?(a):(b)) #define miN(a,b) ((a)<(b)?(a):(b)) #define abS(x) ((x)<0?-(x):(x)) #define FOR(i,a,b) for(int i=a;i<b;i++) #define REP(i,n) FOR(i,0,n) #define mp make_pair #define pb push_back #define fill(a,v) memset(a,v,sizeof a) typedef long long LL; typedef pair<int,int> PII; typedef pair<LL,LL> PLL; typedef pair<int,PII> TRI; typedef vector<int> VI; typedef vector<LL> VL; typedef vector<PII> VII; typedef vector<PLL> VLL; typedef vector<TRI> VT; typedef vector<VI> VVI; typedef vector<VL> VVL; typedef vector<VII> VVII; typedef vector<VLL> VVLL; typedef vector<VT> VVT; void debugarr(int * arr,int n) { cout<<"["; for(int i=0;i<n;i++) cout<<arr[i]<<" "; cout<<"]"<<endl; } /* Tiwari's code */ int a[11][10]; int n; int solve() { int k; FOR(i,0,n+2) a[0][i]=i,a[i][1]=1; ///* FOR(i,1,n) { k=i; for(int j=2;j<n+1 && k>=0;j++,k--) if(k==0) a[k][j]=a[k][j-1]+1; else a[k][j]=a[k][j-1]+a[k-1][j]; } // */ FOR(i,0,n+1) cout<<"1 "; cout<<endl; FOR(i,0,n) { FOR(j,1,n+2) { if(i+j<2*(n-2)) cout<<a[i][j]<<" "; } cout<<endl; } return 1; } bool input() { s(n); return true; } int main() { int T=1; FOR(i,0,n) FOR(j,1,n) a[i][j]=0; //s(T); for(int testnum=1;testnum<=T;testnum++) { if(!input()) break; solve(); printf("\n"); } return 0; }
19.516393
52
0.457791
[ "vector" ]
387d7dc162934c5d07ae9f50d99ccd8f48d1af9a
8,943
cpp
C++
src/icebox/icebox/plugins/heapsan.cpp
IMULMUL/icebox
60586590472d7816645fa1f087b45c1ed08d794b
[ "MIT" ]
null
null
null
src/icebox/icebox/plugins/heapsan.cpp
IMULMUL/icebox
60586590472d7816645fa1f087b45c1ed08d794b
[ "MIT" ]
null
null
null
src/icebox/icebox/plugins/heapsan.cpp
IMULMUL/icebox
60586590472d7816645fa1f087b45c1ed08d794b
[ "MIT" ]
null
null
null
#include "heapsan.hpp" #define FDP_MODULE "heapsan" #include "core.hpp" #include "log.hpp" #include "nt/nt.hpp" #include "tracer/heaps.gen.hpp" #include "utils/hash.hpp" #include "utils/utils.hpp" #include <map> #include <unordered_map> #include <unordered_set> namespace { struct realloc_t { thread_t thread; nt::PVOID HeapHandle; }; inline bool operator==(const realloc_t& a, const realloc_t& b) { return a.thread.id == b.thread.id && a.HeapHandle == b.HeapHandle; } struct heap_t { nt::PVOID HeapHandle; nt::PVOID BaseAddress; }; inline bool operator==(const heap_t& a, const heap_t& b) { return a.HeapHandle == b.HeapHandle && a.BaseAddress == b.BaseAddress; } } namespace std { template <> struct hash<realloc_t> { size_t operator()(const realloc_t& arg) const { size_t seed = 0; ::hash::combine(seed, arg.thread.id, arg.HeapHandle); return seed; } }; template <> struct hash<heap_t> { size_t operator()(const heap_t& arg) const { size_t seed = 0; ::hash::combine(seed, arg.HeapHandle, arg.BaseAddress); return seed; } }; } // namespace std namespace { using Reallocs = std::unordered_set<realloc_t>; using Heaps = std::unordered_set<heap_t>; using Data = plugins::HeapSan::Data; constexpr size_t ptr_prolog = 0x20; constexpr size_t ptr_epilog = 0x20; } struct plugins::HeapSan::Data { Data(core::Core& core, proc_t target); core::Core& core_; nt::heaps tracer_; Reallocs reallocs_; Heaps heaps_; proc_t target_; }; Data::Data(core::Core& core, proc_t target) : core_(core) , tracer_(core, "ntdll") , target_(target) { } plugins::HeapSan::~HeapSan() = default; namespace { void on_RtlpAllocateHeapInternal(Data& d, nt::PVOID HeapHandle, nt::SIZE_T Size) { const auto thread = threads::current(d.core_); if(!thread) return; const auto it = d.reallocs_.find(realloc_t{*thread, HeapHandle}); if(it != d.reallocs_.end()) return; const auto ok = functions::write_arg(d.core_, 1, {ptr_prolog + Size + ptr_epilog}); if(!ok) return; auto* pdata = &d; functions::break_on_return(d.core_, "return RtlpAllocateHeapInternal", [=] { auto& d = *pdata; const auto ptr = registers::read(d.core_, reg_e::rax); if(!ptr) return; const auto new_ptr = ptr_prolog + ptr; const auto ok = registers::write(d.core_, reg_e::rax, new_ptr); if(!ok) return; d.heaps_.emplace(heap_t{HeapHandle, new_ptr}); }); } void on_RtlFreeHeap(Data& d, nt::PVOID HeapHandle, nt::ULONG /*Flags*/, nt::PVOID BaseAddress) { const auto it = d.heaps_.find(heap_t{HeapHandle, BaseAddress}); if(it == d.heaps_.end()) return; functions::write_arg(d.core_, 2, {BaseAddress - ptr_prolog}); d.heaps_.erase(it); } void on_RtlSizeHeap(Data& d, nt::PVOID HeapHandle, nt::ULONG /*Flags*/, nt::PVOID BaseAddress) { const auto it = d.heaps_.find(heap_t{HeapHandle, BaseAddress}); if(it == d.heaps_.end()) return; const auto ok = functions::write_arg(d.core_, 2, {BaseAddress - ptr_prolog}); if(!ok) return; const auto* pdata = &d; functions::break_on_return(d.core_, "return RtlSizeHeap", [=] { const auto& d = *pdata; const auto size = registers::read(d.core_, reg_e::rax); if(!size) return; registers::write(d.core_, reg_e::rax, size - ptr_prolog - ptr_epilog); }); } void on_RtlGetUserInfoHeap(Data& d, nt::PVOID HeapHandle, nt::ULONG /*Flags*/, nt::PVOID BaseAddress) { const auto it = d.heaps_.find(heap_t{HeapHandle, BaseAddress}); if(it == d.heaps_.end()) return; functions::write_arg(d.core_, 2, {BaseAddress - ptr_prolog}); } void on_RtlSetUserValueHeap(Data& d, nt::PVOID HeapHandle, nt::ULONG /*Flags*/, nt::PVOID BaseAddress) { const auto it = d.heaps_.find(heap_t{HeapHandle, BaseAddress}); if(it == d.heaps_.end()) return; functions::write_arg(d.core_, 2, {BaseAddress - ptr_prolog}); } void realloc_unknown_pointer(Data& d, nt::PVOID HeapHandle, nt::ULONG /*Flags*/, nt::PVOID /*BaseAddress*/, nt::ULONG /*Size*/) { const auto thread = threads::current(d.core_); if(!thread) return; // disable alloc hooks during this call d.reallocs_.insert(realloc_t{*thread, HeapHandle}); auto* pdata = &d; functions::break_on_return(d.core_, "return RtlpReAllocateHeapInternal unknown", [=] { auto& d = *pdata; d.reallocs_.erase(realloc_t{*thread, HeapHandle}); }); } void on_RtlpReAllocateHeapInternal(Data& d, nt::PVOID HeapHandle, nt::ULONG Flags, nt::PVOID BaseAddress, nt::ULONG Size) { if(!BaseAddress) return; const auto it = d.heaps_.find(heap_t{HeapHandle, BaseAddress}); if(it == d.heaps_.end()) return realloc_unknown_pointer(d, HeapHandle, Flags, BaseAddress, Size); const auto thread = threads::current(d.core_); if(!thread) return; // tweak back pointer auto ok = functions::write_arg(d.core_, 2, {BaseAddress - ptr_prolog}); if(!ok) return; // tweak size up ok = functions::write_arg(d.core_, 3, {ptr_prolog + Size + ptr_epilog}); if(!ok) return; // disable alloc hooks during this call d.reallocs_.insert(realloc_t{*thread, HeapHandle}); // remove pointer from heap because it can be freed with original value d.heaps_.erase(it); auto* pdata = &d; functions::break_on_return(d.core_, "return RtlpReAllocateHeapInternal known", [=] { auto& d = *pdata; d.reallocs_.erase(realloc_t{*thread, HeapHandle}); const auto ptr = registers::read(d.core_, reg_e::rax); if(!ptr) return; // store new pointer which always have prolog const auto new_ptr = ptr + ptr_prolog; d.heaps_.emplace(heap_t{HeapHandle, new_ptr}); registers::write(d.core_, reg_e::rax, new_ptr); }); } void get_callstack(Data& d) { if(true) return; auto callers = std::vector<callstacks::caller_t>(128); const auto n = callstacks::read(d.core_, &callers[0], callers.size(), d.target_); for(size_t i = 0; i < n; ++i) { const auto addr = callers[i].addr; const auto symbol = symbols::string(d.core_, d.target_, addr); LOG(INFO, "%-3" PRIx64 " - 0x%" PRIx64 "- %s", i, addr, symbol.data()); } } } plugins::HeapSan::HeapSan(core::Core& core, proc_t target) : d_(std::make_unique<Data>(core, target)) { const auto& d = *d_; d.tracer_.register_RtlpAllocateHeapInternal(d.target_, [=](nt::PVOID HeapHandle, nt::SIZE_T Size) { get_callstack(*d_); on_RtlpAllocateHeapInternal(*d_, HeapHandle, Size); return 0; }); d.tracer_.register_RtlFreeHeap(d.target_, [=](nt::PVOID HeapHandle, nt::ULONG Flags, nt::PVOID BaseAddress) { get_callstack(*d_); on_RtlFreeHeap(*d_, HeapHandle, Flags, BaseAddress); return 0; }); d.tracer_.register_RtlSizeHeap(d.target_, [=](nt::PVOID HeapHandle, nt::ULONG Flags, nt::PVOID BaseAddress) { get_callstack(*d_); on_RtlSizeHeap(*d_, HeapHandle, Flags, BaseAddress); return 0; }); d.tracer_.register_RtlGetUserInfoHeap(d.target_, [=](nt::PVOID HeapHandle, nt::ULONG Flags, nt::PVOID BaseAddress, nt::PVOID /*UserValue*/, nt::PULONG /*UserFlags*/) { get_callstack(*d_); on_RtlGetUserInfoHeap(*d_, HeapHandle, Flags, BaseAddress); return 0; }); d.tracer_.register_RtlSetUserValueHeap(d.target_, [=](nt::PVOID HeapHandle, nt::ULONG Flags, nt::PVOID BaseAddress, nt::PVOID /*UserValue*/) { get_callstack(*d_); on_RtlSetUserValueHeap(*d_, HeapHandle, Flags, BaseAddress); return 0; }); d.tracer_.register_RtlpReAllocateHeapInternal(d.target_, [=](nt::PVOID HeapHandle, nt::ULONG Flags, nt::PVOID BaseAddress, nt::ULONG Size) { get_callstack(*d_); on_RtlpReAllocateHeapInternal(*d_, HeapHandle, Flags, BaseAddress, Size); return 0; }); }
30.111111
169
0.58146
[ "vector" ]
387e15a8cd5e51f9161ea6ec80a75dc6dbaba59a
2,582
cpp
C++
src/common/utils/utils.cpp
intel/oneccl
b7d66de16e17f88caffd7c6df4cd5e12b266af84
[ "Apache-2.0" ]
26
2019-11-18T09:45:28.000Z
2020-03-02T17:00:24.000Z
src/common/utils/utils.cpp
intel/oneccl
b7d66de16e17f88caffd7c6df4cd5e12b266af84
[ "Apache-2.0" ]
8
2020-02-05T20:34:23.000Z
2020-02-21T22:26:22.000Z
src/common/utils/utils.cpp
intel/oneccl
b7d66de16e17f88caffd7c6df4cd5e12b266af84
[ "Apache-2.0" ]
9
2019-11-21T16:58:47.000Z
2020-02-26T15:40:04.000Z
/* Copyright 2016-2020 Intel Corporation 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 "common/log/log.hpp" #include "common/utils/utils.hpp" namespace ccl { namespace utils { size_t get_ptr_diff(const void* ptr1, const void* ptr2) { return static_cast<const char*>(ptr2) - static_cast<const char*>(ptr1); } size_t pof2(size_t number) { size_t last_bit_mask = ((size_t)1 << (8 * sizeof(size_t) - 1)); if (number & last_bit_mask) { return last_bit_mask; } size_t pof2 = 1; while (pof2 <= number) { pof2 <<= 1; } pof2 >>= 1; return pof2; } size_t aligned_sz(size_t size, size_t alignment) { return ((size % alignment) == 0) ? size : ((size / alignment) + 1) * alignment; } std::string get_substring_between_delims(std::string& full_str, const std::string& start_delim, const std::string& stop_delim) { auto first_delim_pos = full_str.find(start_delim); auto end_pos_of_first_delim = first_delim_pos + start_delim.length(); auto last_delim_pos = full_str.find(stop_delim); CCL_THROW_IF_NOT(last_delim_pos > first_delim_pos, "incorrect delim positions: {first delim: ", first_delim_pos, ", last delim: ", last_delim_pos, "}"); return full_str.substr(end_pos_of_first_delim, last_delim_pos - end_pos_of_first_delim); } void str_to_array(const std::string& input_str, std::string delimiter, std::vector<std::string>& result) { size_t last = 0; size_t next = 0; while ((next = input_str.find(delimiter, last)) != std::string::npos) { auto substr = input_str.substr(last, next - last); CCL_THROW_IF_NOT(substr.size() != 0, "unexpected string size: ", substr.size()); result.push_back(input_str.substr(last, next - last)); last = next + 1; } result.push_back(input_str.substr(last)); } } // namespace utils } // namespace ccl
33.532468
92
0.63904
[ "vector" ]
38958a2dcbf3366342d8f69bafb36b5451f682b7
551
cpp
C++
src/processor.cpp
h-arieff/SystemMonitor
64db2d76832b3a0c15f6481ad49ec363d828dbcd
[ "MIT" ]
null
null
null
src/processor.cpp
h-arieff/SystemMonitor
64db2d76832b3a0c15f6481ad49ec363d828dbcd
[ "MIT" ]
null
null
null
src/processor.cpp
h-arieff/SystemMonitor
64db2d76832b3a0c15f6481ad49ec363d828dbcd
[ "MIT" ]
null
null
null
#include "processor.h" #include "linux_parser.h" #include <string> #include <vector> #include <numeric> #include <iostream> // TODO: Return the aggregate CPU utilization float Processor::Utilization() { //from the link provided to roseta code std::vector<unsigned long> r=LinuxParser::CpuUtilization(); unsigned long tt=std::accumulate(r.begin(), r.end(), 0ll); unsigned long idle=r[3]; unsigned long i_d=idle-prev_idle; unsigned long t_d=tt-prev_total; prev_idle=idle; prev_total=tt; return (1.0-(float)i_d/t_d); }
29
63
0.704174
[ "vector" ]
38b554dc89a613647bddb8c7b32d7dbe3ab6db57
25,084
hpp
C++
cpp-projects/exvr-designer/data/connector.hpp
FlorianLance/exvr
4d210780737479e9576c90e9c80391c958787f44
[ "MIT" ]
null
null
null
cpp-projects/exvr-designer/data/connector.hpp
FlorianLance/exvr
4d210780737479e9576c90e9c80391c958787f44
[ "MIT" ]
null
null
null
cpp-projects/exvr-designer/data/connector.hpp
FlorianLance/exvr
4d210780737479e9576c90e9c80391c958787f44
[ "MIT" ]
null
null
null
/*********************************************************************************** ** exvr-designer ** ** MIT License ** ** Copyright (c) [2018] [Florian Lance][EPFL-LNCO] ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** ** of this software and associated documentation files (the "Software"), to deal ** ** in the Software without restriction, including without limitation the rights ** ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ** ** copies of the Software, and to permit persons to whom the Software is ** ** furnished to do so, subject to the following conditions: ** ** ** ** The above copyright notice and this permission notice shall be included in all ** ** copies or substantial portions of the Software. ** ** ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ** ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ** ** SOFTWARE. ** ************************************************************************************/ #pragma once // qt-utility #include "data/argument.hpp" // local #include "connection_node.hpp" namespace tool::ex { struct Connector; using ConnectorUP = std::unique_ptr<Connector>; struct Connector{ // # Connector categories enum class Category : int { Convertor=0, Function, Generator, Operator, Component, Action, Flow, Link, Event, Display, Resource, Legacy, SizeEnum }; using Name = std::string_view; using C = Category; using TCategory = std::tuple<Category, Name>; static constexpr TupleArray<Category::SizeEnum, TCategory> categories ={{ TCategory {C::Action, "Action"sv }, {C::Convertor, "Convertor"sv }, {C::Display, "Display"sv }, {C::Event, "Event"sv }, {C::Flow, "Flow"sv }, {C::Function, "Function"sv }, {C::Generator, "Generator"sv }, {C::Link, "Link"sv }, {C::Operator, "Operator"sv }, {C::Component, "Component"sv }, {C::Resource, "Resource"sv }, {C::Legacy, "Legacy"sv }, }}; static auto get_name(C c) { return categories.at<0,1>(c); } static auto all_categories() { return categories.tuple_column<0>(); } static auto all_categories_name() { return categories.tuple_column<1>(); } static auto get_category_from_name(Name n) { return categories.optional_at<1,0>(n); } // Connectors types enum class Type : int { Component, // Component Boolean, Integer,Real, String, Vector3, Transform, Id_any, String_any, // Generator Reals_to_vec2, Reals_to_vec3, Vec2_to_reals, Vec3_to_reals, String_list_to_id_any, Transform_to_vectors, Vectors_to_transform,// Convertor Curve_x, Logger, // Display Decimal_trigonometry, Decimal_counter, Delay, Variable_delay, // Function Binary_operation, Decimal_operation, String_operation, // Operator Pass_value_trigger, Conditional_trigger, Pass_values, Conditional_gate, Check_id, Check_str, // Link Filter_keyboard_button, Check_joypad_button, Check_joypad_axis, Check_mouse_button, Check_keyboard_button, // Event Next, Previous, Stop, Pause, Next_with_name, Next_with_cond, Previous_with_name, Previous_with_cond, Force_component_config, // Action Time, Start_routine, Stop_routine, Update_routine, Pre_update_routine, Post_update_routine, Routine_condition,// Flow Image_resource,Text_resource, // Resource SizeEnum}; using T = Type; using Caption = std::string_view; using TType = std::tuple<Type,Name,Caption>; static constexpr TupleArray<Type::SizeEnum,TType> types ={{ TType // # Action {T::Next, "Next"sv, "Next routine"sv}, {T::Next_with_cond, "NextElementWithCond"sv, "Next element with cond"sv}, {T::Next_with_name, "NextElementWithName"sv, "Next element with name"sv}, {T::Previous, "Previous"sv, "Previous routine"sv}, {T::Previous_with_name, "PreviousElementWithName"sv, "Previous element with name"sv}, {T::Previous_with_cond, "PreviousElementWithCond"sv, "Previous element with cond"sv}, {T::Force_component_config, "ForceComponentConfig"sv, "Force component config"sv}, {T::Stop, "Stop"sv, "Stop experiment"sv}, {T::Pause, "PauseAction"sv, "Pause experiment"sv}, // # Convertors {T::Reals_to_vec2, "RealsToVector2"sv, "To vec2"sv}, {T::Vec2_to_reals, "Vector2ToReals"sv, "From vec2"sv}, {T::Reals_to_vec3, "RealsToVector3"sv, "To vec3"sv}, {T::Vec3_to_reals, "Vector3ToReals"sv, "From vec3"sv}, {T::String_list_to_id_any, "StringListToIdAny"sv, "String list to id any"sv}, {T::Transform_to_vectors, "TransformToVectors"sv, "Transform to vectors"sv}, {T::Vectors_to_transform, "VectorsToTransform"sv, "Vectors to transform"sv}, // # Display {T::Curve_x, "CurveX"sv, "Curve X"sv}, {T::Logger, "Logger"sv, "Logger"sv}, // # Event {T::Check_keyboard_button, "CheckKeyboardButton"sv, "Check keyboard button"sv}, {T::Filter_keyboard_button, "FilterKeyboardButton"sv, "Filter keyboard button"sv}, {T::Check_joypad_button, "CheckJoypadButton"sv, "Check joypad button"sv}, {T::Check_joypad_axis, "CheckJoypadAxis"sv, "Check joypad axis"sv}, {T::Check_mouse_button, "CheckMouseButton"sv, "Check mouse button"sv}, // # Flow {T::Time, "Time"sv, "Time"sv}, {T::Start_routine, "StartRoutine"sv, "Start routine"sv}, {T::Stop_routine, "StopRoutine"sv, "Stop routine"sv}, {T::Pre_update_routine, "PreUpdateRoutine"sv, "Pre-update routine"sv}, {T::Update_routine, "UpdateRoutine"sv, "Update routine"sv}, {T::Post_update_routine, "PostUpdateRoutine"sv, "Post-update routine"sv}, {T::Routine_condition, "RoutineCondition"sv, "Routine condition from id"sv}, // # Function {T::Decimal_trigonometry, "DecimalTrigonometry"sv, "Trigonometry"sv}, {T::Decimal_counter, "DecimalCounter"sv, "Counter"sv}, {T::Delay, "Delay"sv, "Delay"sv}, {T::Variable_delay, "VariableDelay"sv, "Variable delay"sv}, // # Generator {T::Boolean, "Boolean"sv, "Boolean"sv}, {T::Integer, "Integer"sv, "Integer"sv}, {T::Real, "Real"sv, "Real"sv}, {T::String, "String"sv, "String"sv}, {T::Vector3, "Vector3"sv, "Vector3"sv}, {T::Transform, "Transform"sv, "Transform"sv}, {T::Id_any, "IdAny"sv, "Id any"sv}, {T::String_any, "StringAny"sv, "String any"sv}, // # Link {T::Pass_values, "PassValues"sv, "Pass values"sv}, {T::Pass_value_trigger, "PassValueTrigger"sv, "Pass value trigger"sv}, {T::Conditional_trigger, "ConditionalTrigger"sv, "Conditional trigger"sv}, {T::Conditional_gate, "ConditionalGate"sv, "Conditional gate"sv}, {T::Check_id, "CheckId"sv, "Check id any"sv}, {T::Check_str, "CheckStr"sv, "Check string any"sv}, // # Operator {T::Decimal_operation, "DecimalOperation"sv, "Decimal operation"sv}, {T::Binary_operation, "BinaryOperation"sv, "Binary operation"sv}, {T::String_operation, "StringOperation"sv, "String operation"sv}, // # Resource {T::Image_resource, "ImageResource"sv, "Image resource"sv}, {T::Text_resource, "TextResource"sv, "Text resource"sv}, // # Component {T::Component, "-"sv, "-"sv}, }}; static auto get_type_from_name(Name n) { return types.optional_at<1,0>(n); } static auto get_type_from_caption(Caption c) { return types.optional_at<2,0>(c); } static auto get_name(Type t) { return types.at<0,1>(t); } static auto get_caption(Type t) { return types.at<0,2>(t); } enum class Priority : int { Low=0, Medium, Hight }; struct Text{ const std::string_view name; const std::string_view caption; }; static constexpr int maxInputConnection = 10; static constexpr int maxOutputConnection = 10; struct IO{ unsigned int inNb; std_a1<ConnectionNode::Type,maxInputConnection> inTypes; unsigned int outNb; std_a1<ConnectionNode::Type,maxOutputConnection> outTypes; }; struct IO2{ constexpr IO2(std_a1<ConnectionNode::Type,maxInputConnection> in, std_a1<ConnectionNode::Type,maxOutputConnection> out): inTypes(in), outTypes(out),inNb(in.size()),outNb(out.size()){ } std_a1<ConnectionNode::Type,maxInputConnection> inTypes; std_a1<ConnectionNode::Type,maxOutputConnection> outTypes; size_t inNb; size_t outNb; }; struct Style{ bool captionVisibility; std_a1<bool, maxInputConnection> inPortsVisibility; std_a1<bool, maxOutputConnection> outPortsVisibility; }; enum class Interactivity{ Interactive,Locked }; enum class WidgetMode{ Focus, Popup }; using Inter = size_t; using P = Priority; using Te = Text; using S = Style; using I = Interactivity; using WM = WidgetMode; using CNT = ConnectionNode::Type; static constexpr auto t_void = CNT::void_t; static constexpr auto t_bool = CNT::boolean_t; static constexpr auto t_int = CNT::integer_t; static constexpr auto t_float = CNT::float_t; static constexpr auto t_real = CNT::real_t; static constexpr auto t_vec2 = CNT::vector2_t; static constexpr auto t_vec3 = CNT::vector3_t; static constexpr auto t_transform = CNT::transform_t; static constexpr auto t_str = CNT::string_t; static constexpr auto t_img = CNT::image_t; static constexpr auto t_str_l = CNT::string_list_t; static constexpr auto t_real_l = CNT::real_list_t; static constexpr auto t_any = CNT::any_t; static constexpr auto t_id_any = CNT::id_any_t; static constexpr auto t_str_any = CNT::string_any_t; static constexpr auto t_dec = CNT::decimal_t; static constexpr auto t_plot = CNT::plot_t; static constexpr auto t_variant = CNT::variant_t; static constexpr auto t_joy_but_s = CNT::joypad_button_event_t; static constexpr auto t_joy_ax_s = CNT::joypad_axis_event_t; static constexpr auto t_key_but_s = CNT::keyboard_button_event_t; static constexpr auto t_mou_but_s = CNT::mouse_button_event_t; static constexpr auto L = P::Low; static constexpr auto M = P::Medium; static constexpr auto H = P::Hight; static constexpr auto v = true; static constexpr auto i = false; static constexpr auto LO = I::Locked; static constexpr auto IN = I::Interactive; static constexpr auto FO = WM::Focus; static constexpr auto PO = WM::Popup; using TConnector = std::tuple< Type, Category, P, IO, Style, I, WM, Inter>; static constexpr TupleArray<Type::SizeEnum,TConnector> connectors ={{ TConnector // # Component {T::Component, C::Component, M, {0,{}, 0,{}}, {i,{}, {}}, LO, FO, 0}, // # Convertor {T::Reals_to_vec2, C::Convertor, M, {2,{t_real,t_real}, 1,{t_vec2}}, {v,{v,v}, {v}}, LO, FO, 0}, {T::Vec2_to_reals, C::Convertor, M, {1,{t_vec2}, 2,{t_real,t_real}}, {v,{v}, {v,v}}, LO, FO, 0}, {T::Reals_to_vec3, C::Convertor, M, {3,{t_real,t_real,t_real}, 1,{t_vec3}}, {v,{v,v,v}, {v}}, LO, FO, 0}, {T::Vec3_to_reals, C::Convertor, M, {1,{t_vec3}, 3,{t_real,t_real,t_real}}, {v,{v}, {v,v,v}}, LO, FO, 0}, {T::String_list_to_id_any, C::Convertor, M, {1,{t_str_l}, 1,{t_id_any}}, {v,{v}, {v,}}, LO, FO, 0}, {T::Transform_to_vectors, C::Convertor, M, {1,{t_transform}, 3,{t_vec3,t_vec3,t_vec3}}, {v,{v}, {v,v,v}}, LO, FO, 0}, {T::Vectors_to_transform, C::Convertor, M, {3,{t_vec3,t_vec3,t_vec3}, 1,{t_transform}}, {v,{v,v,v}, {v}}, LO, FO, 0}, // # Display {T::Curve_x, C::Display, M, {1,{t_real_l}, 0,{}}, {v,{v}, {}}, IN, PO, 0}, {T::Logger, C::Display, M, {1,{t_any}, 0,{}}, {v,{v}, {}}, LO, FO, 0}, // # Function {T::Decimal_trigonometry, C::Function, M, {1,{t_dec}, 1,{t_dec}}, {v,{v}, {v}}, IN, FO, 1}, {T::Decimal_counter, C::Function, M, {3,{t_dec,t_dec,t_void}, 1,{t_dec}}, {v,{v,v,v}, {v}}, LO, FO, 1}, {T::Delay, C::Function, M, {1,{t_any}, 1,{t_any}}, {v,{v}, {v}}, IN, FO, 1}, {T::Variable_delay, C::Function, M, {2,{t_plot,t_any}, 1,{t_any}}, {v,{v}, {v}}, IN, FO, 1}, // # Generator {T::Boolean, C::Generator, M, {2,{t_bool,t_void}, 1,{t_bool}}, {v,{v,v}, {v}}, IN, FO, 1}, {T::Integer, C::Generator, M, {1,{t_int}, 1,{t_int}}, {v,{v}, {v}}, IN, FO, 1}, {T::Real, C::Generator, M, {1,{t_real}, 1,{t_real}}, {v,{v}, {v}}, IN, FO, 1}, {T::String, C::Generator, M, {1,{t_str}, 1,{t_str}}, {v,{v}, {v}}, IN, FO, 1}, {T::Vector3, C::Generator, M, {1,{t_vec3}, 1,{t_vec3}}, {v,{v}, {v}}, IN, FO, 1}, {T::Transform, C::Generator, M, {1,{t_transform}, 1,{t_transform}}, {v,{v}, {v}}, IN, PO, 1}, {T::Id_any, C::Generator, M, {1,{t_any}, 1,{t_id_any}}, {v,{v}, {v}}, IN, FO, 1}, {T::String_any, C::Generator, M, {1,{t_any}, 1,{t_str_any}}, {v,{v}, {v}}, IN, FO, 1}, // # Operator {T::Decimal_operation, C::Operator, M, {2,{t_dec,t_dec}, 1,{t_variant}}, {v,{v,v}, {v}}, IN, FO, 1}, {T::Binary_operation, C::Operator, M, {2,{t_bool,t_bool}, 1,{t_bool}}, {v,{v,v}, {v}}, IN, FO, 1}, {T::String_operation, C::Operator, M, {2,{t_str,t_str}, 1,{t_variant}}, {v,{v,v}, {v}}, IN, FO, 1}, // # Link {T::Check_id, C::Link, M, {1,{t_id_any}, 1,{t_any}}, {v,{v}, {v}}, IN, FO, 1}, {T::Check_str, C::Link, M, {1,{t_str_any}, 1,{t_any}}, {v,{v}, {v}}, IN, FO, 1}, {T::Pass_values, C::Link, M, {4,{t_any,t_any,t_any,t_any}, 1,{t_any}}, {v,{v,v,v,v}, {v}}, LO, FO, 1}, {T::Pass_value_trigger, C::Link, M, {2,{t_any, t_void}, 1,{t_any}}, {v,{v,v}, {v}}, LO, FO, 1}, {T::Conditional_trigger, C::Link, M, {1,{t_bool}, 1,{t_void}}, {v,{v}, {v}}, LO, FO, 1}, {T::Conditional_gate, C::Link, M, {2,{t_any, t_bool}, 1,{t_any}}, {v,{v,v}, {v}}, IN, FO, 1}, // # Event {T::Check_keyboard_button, C::Event, M, {1,{t_key_but_s}, 3,{t_real,t_real,t_real}}, {v,{v}, {v,v,v}}, IN, FO, 1}, {T::Filter_keyboard_button, C::Event, M, {1,{t_key_but_s}, 1,{t_key_but_s}}, {v,{v}, {v}}, IN, FO, 1}, {T::Check_joypad_button, C::Event, M, {1,{t_joy_but_s}, 3,{t_real,t_real,t_real}}, {v,{v}, {v,v,v}}, IN, FO, 1}, {T::Check_joypad_axis, C::Event, M, {1,{t_joy_ax_s}, 2,{t_float,t_real}}, {v,{v}, {v,v}}, IN, FO, 1}, {T::Check_mouse_button, C::Event, M, {1,{t_mou_but_s}, 3,{t_real,t_real,t_real}}, {v,{v}, {v,v,v}}, IN, FO, 1}, // # Action {T::Next, C::Action, M, {1,{t_void}, 0,{}}, {v,{v}, {}}, LO, FO, 0}, {T::Next_with_name, C::Action, M, {1,{t_void}, 0,{}}, {v,{v}, {}}, IN, FO, 0}, {T::Next_with_cond, C::Action, M, {1,{t_void}, 0,{}}, {v,{v}, {}}, IN, FO, 0}, {T::Previous, C::Action, M, {1,{t_void}, 0,{}}, {v,{v}, {}}, LO, FO, 0}, {T::Previous_with_name, C::Action, M, {1,{t_void}, 0,{}}, {v,{v}, {}}, IN, FO, 0}, {T::Previous_with_cond, C::Action, M, {1,{t_void}, 0,{}}, {v,{v}, {}}, IN, FO, 0}, {T::Stop, C::Action, M, {1,{t_void}, 0,{}}, {v,{v}, {}}, LO, FO, 0}, {T::Pause, C::Action, M, {1,{t_void}, 0,{}}, {v,{v}, {}}, LO, FO, 0}, {T::Force_component_config, C::Action, M, {1,{t_void}, 0,{}}, {v,{v}, {}}, IN, FO, 0}, // # Flow {T::Time, C::Flow, H, {1,{t_void}, 1,{t_real}}, {v,{v}, {v}}, IN, FO, 1}, {T::Start_routine, C::Flow, H, {0,{}, 5,{t_str, t_str, t_int, t_int, t_real}}, {v,{}, {v,v,v,v,v}}, LO, FO, 0}, {T::Stop_routine, C::Flow, H, {0,{}, 2,{t_str, t_str}}, {v,{}, {v,v}}, LO, FO, 0}, {T::Pre_update_routine, C::Flow, H, {0,{}, 1,{t_real}}, {v,{}, {v}}, LO, FO, 0}, {T::Update_routine, C::Flow, H, {0,{}, 1,{t_real}}, {v,{}, {v}}, LO, FO, 0}, {T::Post_update_routine, C::Flow, H, {0,{}, 1,{t_real}}, {v,{}, {v}}, LO, FO, 0}, {T::Routine_condition, C::Flow, H, {1,{t_int}, 1,{t_str}}, {v,{v}, {v}}, IN, FO, 1}, // # Resource {T::Image_resource, C::Resource, M, {1,{t_str}, 1,{t_img}}, {v,{v}, {v}}, LO, FO, 1}, {T::Text_resource, C::Resource, M, {1,{t_str}, 1,{t_str}}, {v,{v}, {v}}, LO, FO, 1}, }}; template<Category c> static size_t connectors_count() { return connectors.count_equal<1>(c); } static auto all_types() { return connectors.tuple_column<0>(); } template<Category c> static std::vector<Type> types_with_category() { return connectors.elements_matching_columns_values<1,0>(c); } static auto get_category(Type t) { return connectors.at<0,1>(t); } static auto get_io(Type t) { return connectors.at<0,3>(t); } static auto get_caption_visibility(Type t) { return connectors.at<0,4>(t).captionVisibility; } static auto get_in_port_visibility(Type t, size_t index) { return connectors.at<0,4>(t).inPortsVisibility[index]; } static auto get_out_port_visibility(Type t, size_t index) { return connectors.at<0,4>(t).outPortsVisibility[index]; } static auto get_interactivity(Type t) { return connectors.at<0,5>(t); } static auto get_widget_mode(Type t) { return connectors.at<0,6>(t); } static auto get_inter_number(Type t) { return connectors.at<0,7>(t); } explicit Connector(ConnectorKey id, Type t, QString n, QPointF p) : key(IdKey::Type::Connector, id.v), name(n), pos(p), type(t){ } explicit Connector(ConnectorKey id, Type t, QString n, QPointF p, Arg a) : key(IdKey::Type::Connector, id.v), name(n), pos(p), arg(a), type(t){ } static ConnectorUP copy_with_new_element_id(const Connector &connectorToCopy); inline QString to_string() const{return QSL("Connector(") % name % QSL("|") % QString::number(key()) % QSL(")");} IdKey key; QString name; QPointF pos; Arg arg; bool inputValidity = true; Type type; QSize size; // TO REMOVE bool selected = false; }; static bool operator<(const ConnectorUP &l, const ConnectorUP &r){ if(l->key() == r->key()){ return false; } return true; } static bool operator==(const ConnectorUP &l, const ConnectorUP &r){ return !(l < r) && !(r < l); } }
57.53211
162
0.45244
[ "vector", "transform" ]
38bb26842d991fb1289d113450eba3e26d42af0e
1,863
cpp
C++
src/main.cpp
matt-harvey/swx
e7b10fe7d4bf0bd6581ceada53ad14b08bc1d852
[ "Apache-2.0" ]
7
2017-10-08T08:08:25.000Z
2020-04-27T09:25:00.000Z
src/main.cpp
matt-harvey/swx
e7b10fe7d4bf0bd6581ceada53ad14b08bc1d852
[ "Apache-2.0" ]
null
null
null
src/main.cpp
matt-harvey/swx
e7b10fe7d4bf0bd6581ceada53ad14b08bc1d852
[ "Apache-2.0" ]
1
2020-04-27T09:24:42.000Z
2020-04-27T09:24:42.000Z
/* * Copyright 2014, 2017 Matthew Harvey * * 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 "application.hpp" #include "config.hpp" #include "info.hpp" #include "stream_utilities.hpp" #include <cassert> #include <cstdlib> #include <iostream> #include <stdexcept> #include <string> #include <utility> #include <vector> using std::cerr; using std::cout; using std::endl; using std::move; using std::runtime_error; using std::string; using std::vector; using swx::Application; using swx::enable_exceptions; using swx::Config; using swx::Info; int main(int argc, char** argv) { try { enable_exceptions(cout); if (argc < 2) { cerr << "Command not provided.\n" << Application::directions_to_get_help() << endl; return EXIT_FAILURE; } assert (argc >= 2); vector<string> const args(argv + 2, argv + argc); auto const config_path = Info::home_dir() + "/.swxrc"; // non-portable Config const config(config_path); Application const application(move(config)); return application.process_command(argv[1], args); } catch (runtime_error& e) { cerr << "Error: " << e.what() << endl; return EXIT_FAILURE; } catch (...) { // Ensure stack is fully unwound. throw; } }
26.614286
79
0.648953
[ "vector" ]
38bcb3980c968a279196e9a9b5c67deb11ad8d23
6,107
cpp
C++
urdf_transform/src/AlignRotationAxis.cpp
JenniferBuehler/urdf_tools
548ddd4fb8865ee6a08921ce8436c39069f14692
[ "BSD-3-Clause" ]
6
2017-01-17T01:55:39.000Z
2020-04-24T02:03:30.000Z
urdf_transform/src/AlignRotationAxis.cpp
JenniferBuehler/urdf_tools
548ddd4fb8865ee6a08921ce8436c39069f14692
[ "BSD-3-Clause" ]
10
2016-06-16T19:38:38.000Z
2020-12-11T12:13:05.000Z
urdf_transform/src/AlignRotationAxis.cpp
JenniferBuehler/urdf_tools
548ddd4fb8865ee6a08921ce8436c39069f14692
[ "BSD-3-Clause" ]
7
2017-12-12T17:21:19.000Z
2021-02-10T05:51:25.000Z
/** * <ORGANIZATION> = Jennifer Buehler * <COPYRIGHT HOLDER> = Jennifer Buehler * * Copyright (c) 2016 Jennifer Buehler * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <ORGANIZATION> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> 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 <Eigen/Core> #include <Eigen/Geometry> #include <ros/ros.h> #include <urdf_traverser/Functions.h> #include <urdf_traverser/Helpers.h> #include <urdf_traverser/UrdfTraverser.h> #include <urdf_transform/AlignRotationAxis.h> using urdf_traverser::UrdfTraverser; using urdf_traverser::RecursionParams; /** * \brief Recursion parameters with one 3D vector * \author Jennifer Buehler */ class Vector3RecursionParams: public RecursionParams { public: typedef baselib_binding::shared_ptr<Vector3RecursionParams>::type Ptr; Vector3RecursionParams(): RecursionParams() {} Vector3RecursionParams(const Eigen::Vector3d& _vec): RecursionParams(), vec(_vec) {} Vector3RecursionParams(const Vector3RecursionParams& o): RecursionParams(o), vec(o.vec) {} virtual ~Vector3RecursionParams() {} // Result set Eigen::Vector3d vec; }; /** * Recursion method to be used with traverseTreeTopDown() and recursion parameters * of type *Vector3RecursionParams*. * * Re-arranges the joint-transform of the recursion link's *parent joint*, along with * the link's visual/collision/intertial rotations, such that all joints rotate around the axis * given in the recursion parameters vector. */ int allRotationsToAxisCB(urdf_traverser::RecursionParamsPtr& p) { urdf_traverser::LinkPtr link = p->getLink(); if (!link) { ROS_ERROR("allRotationsToAxis: NULL link passed"); return -1; } Vector3RecursionParams::Ptr param = baselib_binding_ns::dynamic_pointer_cast<Vector3RecursionParams>(p); if (!param) { ROS_ERROR("Wrong recursion parameter type"); return -1; } urdf_traverser::JointPtr joint = link->parent_joint; if (!joint) { ROS_INFO_STREAM("allRotationsToAxis: Joint for link " << link->name << " is NULL, so this must be the root joint"); return 1; } Eigen::Vector3d axis = param->vec; Eigen::Quaterniond alignAxis; if (urdf_traverser::jointTransformForAxis(joint, axis, alignAxis)) { Eigen::Vector3d rotAxis(joint->axis.x, joint->axis.y, joint->axis.z); // ROS_INFO_STREAM("Transforming axis "<<rotAxis<<" for joint "<<joint->name<<" with transform "<<urdf_traverser::EigenTransform(alignAxis)); urdf_traverser::applyTransform(joint, urdf_traverser::EigenTransform(alignAxis), false); // the link has to receive the inverse transform, so it stays at the original position Eigen::Quaterniond alignAxisInv = alignAxis.inverse(); urdf_traverser::applyTransform(link, urdf_traverser::EigenTransform(alignAxisInv), true); // we also have to fix the child joint's (1st order child joints) transform // to correct for this transformation. for (std::vector<urdf_traverser::JointPtr>::iterator pj = link->child_joints.begin(); pj != link->child_joints.end(); pj++) { urdf_traverser::applyTransform(*pj, urdf_traverser::EigenTransform(alignAxisInv), true); } // finally, set the rotation axis to the target joint->axis.x = axis.x(); joint->axis.y = axis.y(); joint->axis.z = axis.z(); } // all good, indicate that recursion can continue return 1; } bool urdf_transform::allRotationsToAxis(UrdfTraverser& traverser, const std::string& fromLink, const Eigen::Vector3d& axis) { // ROS_INFO_STREAM("### Transforming all rotations starting from "<<fromLinkName<<" to axis "<<axis); std::string startLink = fromLink; if (startLink.empty()) { startLink = traverser.getRootLinkName(); } urdf_traverser::LinkPtr startLink_ = traverser.getLink(startLink); if (!startLink_) { ROS_ERROR("Link %s does not exist", startLink.c_str()); return false; } Vector3RecursionParams * vp = new Vector3RecursionParams(axis); urdf_traverser::RecursionParamsPtr p(vp); // traverse top-down, but don't include the link itself, as the method allRotationsToAxis() // operates on the links parent joints. int travRet = traverser.traverseTreeTopDown(startLink, boost::bind(&allRotationsToAxisCB, _1), p, false); if (travRet <= 0) { ROS_ERROR("Recursion to align all rotation axes failed"); return false; } return true; }
37.931677
149
0.691174
[ "geometry", "vector", "transform", "3d" ]
38bfe318c6066b39ee0b67d0853efccbb5880186
10,233
cpp
C++
Database/Scheduler/SharedWorklistScheduler.cpp
gunaprsd/cavalia
a408c75fa349f3c6f45c929734437647a0c023c5
[ "Apache-2.0" ]
null
null
null
Database/Scheduler/SharedWorklistScheduler.cpp
gunaprsd/cavalia
a408c75fa349f3c6f45c929734437647a0c023c5
[ "Apache-2.0" ]
null
null
null
Database/Scheduler/SharedWorklistScheduler.cpp
gunaprsd/cavalia
a408c75fa349f3c6f45c929734437647a0c023c5
[ "Apache-2.0" ]
null
null
null
#include "SharedWorklistScheduler.h" #include "../Executor/ConcurrentExecutor.h" using namespace Cavalia; using namespace Cavalia::Database; void SharedWorklistScheduler::Initialize(const size_t& thread_id) { std::vector<ParamBatch*>* execution_batches = new std::vector<ParamBatch*>(); std::vector<ParamBatch*>* input_batches = redirector_ptr_->GetParameterBatches(thread_id); for (size_t i = 0; i < input_batches->size(); ++i) { ParamBatch *tuple_batch = input_batches->at(i); // copy to local memory. ParamBatch *execution_batch = new ParamBatch(gParamBatchSize); for (size_t j = 0; j < tuple_batch->size(); ++j) { TxnParam *entry = tuple_batch->get(j); // copy each parameter. CharArray str; entry->Serialize(str); TxnParam* new_tuple = executor_->DeserializeParam(entry->type_, str); execution_batch->push_back(new_tuple); str.Clear(); delete entry; entry = NULL; } (*execution_batches).push_back(execution_batch); delete tuple_batch; tuple_batch = NULL; } raw_batches_[thread_id] = execution_batches; } void SharedWorklistScheduler::SynchronizeBatchExecution(const size_t& thread_id) { BEGIN_BATCH_SYNC_TIME_MEASURE(thread_id); int next_batch_idx = current_batch_idx_.load() + 1; lock_.lock(); waiting_threads_.push_back(thread_id); if(waiting_threads_.size() == thread_count_) { waiting_threads_.clear(); current_batch_idx_.fetch_add(1); } lock_.unlock(); while(current_batch_idx_.load() < next_batch_idx); END_BATCH_SYNC_TIME_MEASURE(thread_id); } void SharedWorklistScheduler::ThreadRun() { BEGIN_PARTITIONING_TIME_MEASURE(0); size_t num_batches = raw_batches_[0]->size(); for(int batch_idx = 0; batch_idx < num_batches; batch_idx++) { #if defined(SELECTIVE_CC) batches_.push_back(DoDataBasedPartition(batch_idx)); #else batches_.push_back(DoSimplePartition(batch_idx)); #endif } END_PARTITIONING_TIME_MEASURE(0); std::cout << "done with scheduler initial run..." << std::endl; executor_->is_scheduler_ready_ = true; } SimpleConcurrentWorklist* SharedWorklistScheduler::DoSimplePartition(int batch_idx) { //each batch_idx corresponds to a concurrent-worklist SimpleConcurrentWorklist* wl = new SimpleConcurrentWorklist(); for(int i = 0; i < thread_count_; i++) { //each thread has a part of the super-batch ParamBatch* thread_param_batch = (*raw_batches_[i])[batch_idx]; if(thread_param_batch != NULL) { int size = thread_param_batch->size(); for(int j = 0; j < size; ) { ParamBatch* atomic_batch = new ParamBatch(MAX_ATOMIC_BATCH_SIZE); for(int k = 0; k < MAX_ATOMIC_BATCH_SIZE && j < size; k++) { atomic_batch->push_back(thread_param_batch->get(j)); j++; } wl->Add(atomic_batch); } delete thread_param_batch; } } return wl; } SimpleConcurrentWorklist* SharedWorklistScheduler::DoDataBasedPartition(int batch_idx) { std::unordered_set<TxnParam*> clusters; ReadWriteSet batch_rw_set; /* Step 1: Create singleton clusters and build read-write sets of txn */ for(int i = 0; i < thread_count_; i++) { ParamBatch* thread_param_batch = (*raw_batches_[i])[batch_idx]; if(thread_param_batch != NULL) { int size = thread_param_batch->size(); for(int j = 0; j < size; j++) { TxnParam* txn = thread_param_batch->get(j); txn->BuildReadWriteSet(batch_rw_set); clusters.insert(txn); } delete thread_param_batch; } } size_t num_txns = clusters.size(); size_t num_items = batch_rw_set.lookup_.size(); size_t num_contention_items = 0; double average_contention = 0.0, contention_ratio = 0.0; std::unordered_set<BatchAccessInfo*> interesting_items; size_t max_progress = 0; /* Step 2: Collect all interesting data items. Interesting data items are those that are accessed by more than one transaction */ for(auto iter = batch_rw_set.lookup_.begin(); iter != batch_rw_set.lookup_.end(); iter++) { BatchAccessInfo* info = iter->second; size_t size = info->txns_.size(); if(size > 1 && size < MAX_ATOMIC_BATCH_SIZE) { interesting_items.insert(info); max_progress = std::max(max_progress, info->txns_.size()); } else if(size == 1) { info->avoid_cc_ = true; } else if(size >= MAX_ATOMIC_BATCH_SIZE) { num_contention_items++; average_contention += size; } } /* Step 3: Iteratively cluster txns grouped by data items from the interesting_items set. Progress indicator ensures that the loop terminates. We look at every data item only once and merge them if the size constraints are satisfied */ size_t progress = 2; std::vector<BatchAccessInfo*> targets; while(progress <= max_progress) { //collect target items for this round for(auto iter = interesting_items.begin(); iter != interesting_items.end(); iter++) { BatchAccessInfo* info = (*iter); if(info->txns_.size() <= progress) { targets.push_back(*iter); } } //for each target item, try to merge them into a cluster for(auto iter = targets.begin(); iter != targets.end(); iter++) { BatchAccessInfo* info = *iter; //find resulting cluster size, if we merge clusters of this data item size_t resulting_cluster_size = 0; for(auto txn_iter = info->txns_.begin(); txn_iter != info->txns_.end(); txn_iter++) { TxnParam* txn = *txn_iter; if(txn->data_ != NULL) { resulting_cluster_size += ((ClusterInfo*)txn->data_)->GetSize(); } else { resulting_cluster_size++; } } if(resulting_cluster_size < MAX_ATOMIC_BATCH_SIZE) { while(info->txns_.size() > 1) { auto iter = info->txns_.begin(); auto t1 = *iter; iter++; auto t2 = *iter; auto merged = ClusterInfo::Merge(t1, t2); if(merged == t1) { clusters.erase(t2); } else { clusters.erase(t1); } } info->avoid_cc_ = true; interesting_items.erase(info); } else { //remove from interesting items so that we don't get it again average_contention += resulting_cluster_size; interesting_items.erase(info); num_contention_items++; } } progress++; } #if defined(DYNAMIC_CC) ConcurrencyControlType type; if(num_contention_items > 0) { average_contention /= num_contention_items; contention_ratio = (double)num_contention_items / (double)num_items; if(contention_ratio < 0.2 && average_contention < 25) { type = CC_OCC; std::cout << "batch idx : " << batch_idx << " cc : OCC" << std::endl; } else { type = CC_LOCK_WAIT; std::cout << "batch idx : " << batch_idx << " cc : 2PL" << std::endl; } } else { type = CC_OCC; std::cout << "batch idx : " << batch_idx <<" cc : OCC" << std::endl; } #endif /* Step 4: now we use the produced clusters to partition the super-batch into atomic-batches of size atmost MAX_ATOMIC_BATCH_SIZE. Here we greedily fill the buckets. We can do slightly better by sorting and distributing appropriately*/ //int num_atomic_batches = (num_txns / MAX_ATOMIC_BATCH_SIZE) + 1; SimpleConcurrentWorklist* wl = new SimpleConcurrentWorklist(); ParamBatch* current_batch = new ParamBatch(MAX_ATOMIC_BATCH_SIZE); size_t current_batch_size = 0; for(auto iter = clusters.begin(); iter != clusters.end(); iter++) { TxnParam* param = *iter; size_t size_of_cluster = param->data_ == NULL ? 1 : ((ClusterInfo*)param->data_)->GetSize(); bool can_add_in_same_batch = (current_batch_size + size_of_cluster) < MAX_ATOMIC_BATCH_SIZE; if(!can_add_in_same_batch) { #if defined(DYNAMIC_CC) current_batch->cc_type_ = type; #endif wl->Add(current_batch); current_batch = new ParamBatch(MAX_ATOMIC_BATCH_SIZE); current_batch_size = 0; } if(param->data_ == NULL) { current_batch->push_back(param); current_batch_size++; } else { ClusterInfo* info = (ClusterInfo*)param->data_; for(auto txn_iter = info->members_.begin(); txn_iter != info->members_.end(); txn_iter++) { current_batch->push_back(*iter); current_batch_size++; } delete info; } } //adding last batch #if defined(DYNAMIC_CC) current_batch->cc_type_ = type; #endif wl->Add(current_batch); return wl; } ParamBatch* SharedWorklistScheduler::GetNextBatch(const size_t& thread_id) { int current_batch_idx = current_batch_idx_.load(); if(current_batch_idx < batches_.size()) { //current super-batch is active : try getting from current super-batch ParamBatch* batch = batches_[current_batch_idx]->GetNext(); if(batch != NULL) { return batch; } else { SynchronizeBatchExecution(thread_id); return GetNextBatch(thread_id); } } else { return NULL; } } bool compare_degree(BatchAccessInfo* info1, BatchAccessInfo* info2) { return info1->txns_.size() < info2->txns_.size(); }
39.206897
103
0.594156
[ "vector" ]
38c5e33577fd0fa1018e9f76d8daeb1b097c3adb
6,796
hpp
C++
libcaf_io/caf/io/network/test_multiplexer.hpp
samanbarghi/actor-framework
9fb82f556760e1004e27fb4d303499b603a3fc19
[ "BSL-1.0", "BSD-3-Clause" ]
2
2020-08-25T15:22:08.000Z
2021-03-05T16:29:24.000Z
libcaf_io/caf/io/network/test_multiplexer.hpp
wujsy/actor-framework
9fb82f556760e1004e27fb4d303499b603a3fc19
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
libcaf_io/caf/io/network/test_multiplexer.hpp
wujsy/actor-framework
9fb82f556760e1004e27fb4d303499b603a3fc19
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2016 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_IO_NETWORK_TEST_MULTIPLEXER_HPP #define CAF_IO_NETWORK_TEST_MULTIPLEXER_HPP #include "caf/io/receive_policy.hpp" #include "caf/io/abstract_broker.hpp" #include "caf/io/network/multiplexer.hpp" namespace caf { namespace io { namespace network { class test_multiplexer : public multiplexer { public: explicit test_multiplexer(actor_system* sys); ~test_multiplexer() override; expected<connection_handle> new_tcp_scribe(const std::string& host, uint16_t port_hint) override; expected<void> assign_tcp_scribe(abstract_broker* ptr, connection_handle hdl) override; connection_handle add_tcp_scribe(abstract_broker*, native_socket) override; expected<connection_handle> add_tcp_scribe(abstract_broker* ptr, const std::string& host, uint16_t desired_port) override; expected<std::pair<accept_handle, uint16_t>> new_tcp_doorman(uint16_t desired_port, const char*, bool) override; expected<void> assign_tcp_doorman(abstract_broker* ptr, accept_handle hdl) override; accept_handle add_tcp_doorman(abstract_broker*, native_socket) override; expected<std::pair<accept_handle, uint16_t>> add_tcp_doorman(abstract_broker* ptr, uint16_t prt, const char* in, bool reuse_addr) override; supervisor_ptr make_supervisor() override; void run() override; void provide_scribe(std::string host, uint16_t desired_port, connection_handle hdl); void provide_acceptor(uint16_t desired_port, accept_handle hdl); /// A buffer storing bytes. using buffer_type = std::vector<char>; /// Models pending data on the network, i.e., the network /// input buffer usually managed by the operating system. buffer_type& virtual_network_buffer(connection_handle hdl); /// Returns the output buffer of the scribe identified by `hdl`. buffer_type& output_buffer(connection_handle hdl); /// Returns the input buffer of the scribe identified by `hdl`. buffer_type& input_buffer(connection_handle hdl); /// Returns the configured read policy of the scribe identified by `hdl`. receive_policy::config& read_config(connection_handle hdl); /// Returns whether the scribe identified by `hdl` receives write ACKs. bool& ack_writes(connection_handle hdl); /// Returns `true` if this handle has been closed /// for reading, `false` otherwise. bool& stopped_reading(connection_handle hdl); /// Returns `true` if this handle is inactive, otherwise `false`. bool& passive_mode(connection_handle hdl); intrusive_ptr<scribe>& impl_ptr(connection_handle hdl); uint16_t& port(accept_handle hdl); /// Returns `true` if this handle has been closed /// for reading, `false` otherwise. bool& stopped_reading(accept_handle hdl); /// Returns `true` if this handle is inactive, otherwise `false`. bool& passive_mode(accept_handle hdl); intrusive_ptr<doorman>& impl_ptr(accept_handle hdl); /// Stores `hdl` as a pending connection for `src`. void add_pending_connect(accept_handle src, connection_handle hdl); using pending_connects_map = std::unordered_multimap<accept_handle, connection_handle>; pending_connects_map& pending_connects(); using pending_scribes_map = std::map<std::pair<std::string, uint16_t>, connection_handle>; bool has_pending_scribe(std::string x, uint16_t y); /// Accepts a pending connect on `hdl`. bool accept_connection(accept_handle hdl); /// Reads data from the external input buffer until /// the configured read policy no longer allows receiving. void read_data(connection_handle hdl); /// Appends `buf` to the virtual network buffer of `hdl` /// and calls `read_data(hdl)` afterwards. void virtual_send(connection_handle hdl, const buffer_type& buf); /// Waits until a `runnable` is available and executes it. void exec_runnable(); /// Returns `true` if a `runnable` was available, `false` otherwise. bool try_exec_runnable(); /// Executes all pending `runnable` objects. void flush_runnables(); protected: void exec_later(resumable* ptr) override; private: using resumable_ptr = intrusive_ptr<resumable>; void exec(resumable_ptr& ptr); using guard_type = std::unique_lock<std::mutex>; struct scribe_data { buffer_type xbuf; buffer_type rd_buf; buffer_type wr_buf; receive_policy::config recv_conf; bool stopped_reading = false; bool passive_mode = false; intrusive_ptr<scribe> ptr; bool ack_writes = false; }; struct doorman_data { uint16_t port; bool stopped_reading = false; bool passive_mode = false; intrusive_ptr<doorman> ptr; }; // guards resumables_ and scribes_ std::mutex mx_; std::condition_variable cv_; std::list<resumable_ptr> resumables_; pending_scribes_map scribes_; std::unordered_map<uint16_t, accept_handle> doormen_; std::unordered_map<connection_handle, scribe_data> scribe_data_; std::unordered_map<accept_handle, doorman_data> doorman_data_; pending_connects_map pending_connects_; }; } // namespace network } // namespace io } // namespace caf #endif // CAF_IO_NETWORK_TEST_MULTIPLEXER_HPP
36.537634
86
0.623014
[ "vector" ]
38c5e3de0a20706fdd4143637a8019d8c465f634
3,713
cpp
C++
src/renderer/raytracer/raytracer_renderer.cpp
KsEv13/CGGD
ac02e41077777d1fa80d6110120ea1053e67f622
[ "CC-BY-3.0", "Cube", "MIT" ]
null
null
null
src/renderer/raytracer/raytracer_renderer.cpp
KsEv13/CGGD
ac02e41077777d1fa80d6110120ea1053e67f622
[ "CC-BY-3.0", "Cube", "MIT" ]
null
null
null
src/renderer/raytracer/raytracer_renderer.cpp
KsEv13/CGGD
ac02e41077777d1fa80d6110120ea1053e67f622
[ "CC-BY-3.0", "Cube", "MIT" ]
null
null
null
#include "raytracer_renderer.h" #include "utils/resource_utils.h" #include <iostream> void cg::renderer::ray_tracing_renderer::init() { model = std::make_shared<cg::world::model>(); model->load_obj(settings->model_path); camera = std::make_shared<cg::world::camera>(); camera->set_width(static_cast<float>(settings->width)); camera->set_height(static_cast<float>(settings->height)); camera->set_position(float3{ settings->camera_position[0], settings->camera_position[1], settings->camera_position[2], }); camera->set_theta(settings->camera_theta); camera->set_phi(settings->camera_phi); camera->set_angle_of_view(settings->camera_angle_of_view); camera->set_z_near(settings->camera_z_near); camera->set_z_far(settings->camera_z_far); render_target = std::make_shared<cg::resource<cg::unsigned_color>>( settings->width, settings->height ); raytracer = std::make_shared<cg::renderer::raytracer<cg::vertex, cg::unsigned_color>>(); raytracer->set_render_target(render_target); raytracer->set_viewport(settings->width, settings->height); raytracer->set_vertex_buffers(model->get_vertex_buffers()); raytracer->set_index_buffers(model->get_index_buffers()); lights.push_back({ float3{ 0, 1.58f, -0.03f }, float3{ 0.78f, 0.78f, 0.78f }, }); shadow_raytracer = std::make_shared<cg::renderer::raytracer<cg::vertex, cg::unsigned_color>>(); } void cg::renderer::ray_tracing_renderer::destroy() {} void cg::renderer::ray_tracing_renderer::update() {} void cg::renderer::ray_tracing_renderer::render() { raytracer->clear_render_target({ 0, 0, 0 }); raytracer->miss_shader = [](const ray& ray) { payload payload{}; payload.color = { 0.0f, 0.0f, (ray.direction.y + 1.0f) * 0.5f }; return payload; }; std::random_device random_device; std::mt19937 rng(random_device()); std::uniform_real_distribution<float> uniform_distribution(-1.0f, 1.0f); raytracer->closest_hit_shader = [&](const ray& ray, payload& payload, const triangle<cg::vertex>& triangle, size_t depth) { float3 position = ray.position + ray.direction * payload.t; float3 normal = normalize( payload.bary.x * triangle.na + payload.bary.y * triangle.nb + payload.bary.z * triangle.nc ); float3 result_color = { 0.0f, 0.0f, 0.0f }; for (auto& light : lights) { cg::renderer::ray to_light(position, light.position - position); auto shadow_payload = shadow_raytracer->trace_ray( to_light, 1, length(light.position - position) ); if (shadow_payload.t >= 0.0f) { continue; } result_color += triangle.diffuse * (light.color / 2) * std::max( dot(normal, to_light.direction), 0.0f ); } payload.color = cg::color::from_float3(result_color); return payload; }; raytracer->build_acceleration_structure(); shadow_raytracer->miss_shader = [](const ray& ray) { payload payload{}; payload.t = -1.0f; return payload; }; shadow_raytracer->any_hit_shader = []( const ray& ray, payload& payload, const triangle<cg::vertex>& triangle) { return payload; }; shadow_raytracer->acceleration_structures = raytracer->acceleration_structures; auto start = std::chrono::high_resolution_clock::now(); raytracer->ray_generation( camera->get_position(), camera->get_direction(), camera->get_right(), camera->get_up(), settings->raytracing_depth, settings->accumulation_num ); auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<float, std::milli> raytracing_duration = end - start; std::cout << "Raytracing took " << raytracing_duration.count() << " ms" << std::endl; cg::utils::save_resource(*render_target, settings->result_path); }
28.128788
96
0.70132
[ "render", "model" ]
38d141b8b7cae900cef204e7bcb5defebdcca13c
326
hpp
C++
3/picture.hpp
j00st/cpse2
f541d9097d1db064974d71f816cf49ecae30c6f8
[ "MIT" ]
null
null
null
3/picture.hpp
j00st/cpse2
f541d9097d1db064974d71f816cf49ecae30c6f8
[ "MIT" ]
null
null
null
3/picture.hpp
j00st/cpse2
f541d9097d1db064974d71f816cf49ecae30c6f8
[ "MIT" ]
null
null
null
#ifndef _PICTURE_HPP #define _PICTURE_HPP #include <SFML/Graphics.hpp> #include "entity.hpp" class picture : public entity { private: std::string path; sf::Texture image; sf::RectangleShape shape; public: picture(sf::Vector2f position, std::string path); std::string print() override; }; #endif
14.818182
53
0.687117
[ "shape" ]
38d1e17de61546bc9f0317f9c3f3dc5adbe75727
3,573
cpp
C++
module/eagle2bookshelf/PadsASCII2bookshelf.cpp
sethhillbrand/SA-PCB
5403d495f4478861fa61592481342820046e4dcd
[ "BSD-3-Clause" ]
1
2020-09-23T05:07:16.000Z
2020-09-23T05:07:16.000Z
module/eagle2bookshelf/PadsASCII2bookshelf.cpp
sethhillbrand/SA-PCB
5403d495f4478861fa61592481342820046e4dcd
[ "BSD-3-Clause" ]
1
2019-07-18T19:23:12.000Z
2019-07-18T19:23:12.000Z
module/eagle2bookshelf/PadsASCII2bookshelf.cpp
sethhillbrand/SA-PCB
5403d495f4478861fa61592481342820046e4dcd
[ "BSD-3-Clause" ]
2
2019-07-18T19:11:05.000Z
2019-07-30T06:04:26.000Z
#include <iostream> #include <fstream> #include <vector> #include <sstream> #include <string> #include <map> struct pin { std::string m_name; }; struct net { std::vector<pin> m_pins; }; size_t tokenlize(std::string &str, std::vector<std::string> *token) { std::stringstream ss(str); std::string s; while (ss>>s) { token->push_back(s); } return token->size(); } int main(int argc, char *argv[]) { std::ifstream MGfile; MGfile.open(argv[1], std::ifstream::in); std::string in; std::vector <net> nets; std::vector <pin> pins; std::map <std::string, int> mod; bool flag = false; while (MGfile >> in) { if(in == "*SIGNAL*" && flag == 0) { flag = 1; } if(in == "*SIGNAL*") { net n; while(std::getline(MGfile, in)) { if(in == "") break; std::vector<std::string> token; size_t size = tokenlize(in,&token); if (size == 2) { for (size_t i = 0; i < size; ++i) { pin p; std::stringstream _name(token[i]); std::string s; std::getline(_name, s, '.'); p.m_name = s; mod.insert(std::pair<std::string, int>(s,0)); n.m_pins.push_back(p); pins.push_back(p); } } } nets.push_back(n); } } std::ofstream netFile; std::string netFileName = "temp.nets"; std::cout << netFileName << " writing...\n"; netFile.open(netFileName, std::ios::out); netFile << "UCLA nets 1.0" << std::endl; netFile << std::endl; netFile << "#Created :" << std::endl; netFile << "#Created by :" << std::endl; netFile << std::endl; netFile << "NumNets : " << nets.size()-1 << std::endl; netFile << "NumPins : " << pins.size() << std::endl; netFile << std::endl; for (size_t i = 1; i < nets.size(); ++i) { netFile << "NetDegree : " << nets[i].m_pins.size() << std::endl; for (size_t j = 0; j < nets[i].m_pins.size(); ++j) netFile << " " << nets[i].m_pins[j].m_name << " B : 0.0 0.0\n";// << nets[i].m_pins[j].m_x << " " << nets[i].m_pins[j].m_y << std::endl; } netFile.close(); std::ofstream nodeFile; std::string nodeFileName = "temp.nodes"; std::cout << nodeFileName << " writing...\n"; nodeFile.open(nodeFileName, std::ios::out); nodeFile << "UCLA nodes 1.0" << std::endl; nodeFile << std::endl; nodeFile << "#Created :" << std::endl; nodeFile << "#Created by :" << std::endl; nodeFile << std::endl; nodeFile << "NumNodes : " << mod.size() << std::endl; nodeFile << "NumTerminals : 0 " << std::endl; nodeFile << std::endl; for (std::map<std::string,int>::iterator it=mod.begin(); it!=mod.end(); ++it) { nodeFile << it->first << " 10 10\n"; } nodeFile.close(); std::ofstream plFile; std::string plFileName = "temp.pl"; std::cout << plFileName << " writing...\n"; plFile.open(plFileName, std::ios::out); plFile << "UCLA pl 1.0" << std::endl; plFile << std::endl; plFile << "#Created :" << std::endl; plFile << "#Created by :" << std::endl; plFile << std::endl; for (std::map<std::string,int>::iterator it=mod.begin(); it!=mod.end(); ++it) { plFile << it->first << " 0.0 0.0 : N\n"; } plFile.close(); /* std::ofstream wtsFile; std::string wtsFileName = "temp.wts"; std::cout << wtsFileName << " writing...\n"; wtsFile.open(wtsFileName, std::ios::out); wtsFile << "UCLA wts 1.0" << std::endl; wtsFile << std::endl; wtsFile << "#Created :" << std::endl; wtsFile << "#Created by :" << std::endl; wtsFile << std::endl; for (size_t i = 1; i < nets.size(); ++i) { wtsFile << nets[i].m_name << " 1" << std::endl; } wtsFile.close();*/ return 0; }
23.201299
150
0.563952
[ "vector" ]
38d2d3fc6f70e7eb6bc89a88c92d74f2d49bbe6b
2,860
hpp
C++
src/snoise.hpp
RedErr404/cprocessing
ab8ef25ea3e4bcd915f9c086b649696866ea77ca
[ "BSD-2-Clause" ]
12
2015-01-12T07:43:22.000Z
2022-03-08T06:43:20.000Z
src/snoise.hpp
RedErr404/cprocessing
ab8ef25ea3e4bcd915f9c086b649696866ea77ca
[ "BSD-2-Clause" ]
null
null
null
src/snoise.hpp
RedErr404/cprocessing
ab8ef25ea3e4bcd915f9c086b649696866ea77ca
[ "BSD-2-Clause" ]
7
2015-02-09T15:44:10.000Z
2019-07-07T11:48:10.000Z
#ifndef SIMPLEXNOISE_HPP_ #define SIMPLEXNOISE_HPP_ namespace cprocessing { class SimplexNoise { private: static double SQRT3; static double SQRT5; /** * Skewing and unskewing factors for 2D, 3D and 4D, some of them * pre-multiplied. */ static double F2; static double G2; static double G22; static double F3; static double G3; static double F4; static double G4; static double G42; static double G43; static double G44; /** * Gradient vectors (pointing to mid points of all edges of a unit * cube) */ static int grad3[][3]; static int grad4[][4]; /** * Permutation table */ static int p[]; /** * To remove the need for index wrapping, double the permutation table * length */ static int perm[512]; static int permMod12[512]; /** * A lookup table to traverse the simplex around a given point in 4D. * Details can be found where this table is used, in the 4D noise method. */ static int simplex[][4]; inline double dot(int g[], double x, double y); inline double dot(int g[], double x, double y, double z); inline double dot(int g[], double x, double y, double z, double w); inline int fastfloor(double x); public: SimplexNoise(); double noise(double x, double y); double noise(double x, double y, double z); double noise(double x, double y, double z, double w); }; /*!Calculates one dimensional simplex noise * @param x any number * @return value between -1 and 1*/ double snoise(double x); /*!Calculates two dimensional simplex noise * @param x any number * @param y any number * @return value between -1 and 1*/ double snoise(double x, double y); /*!Calculates three dimensional simplex noise * @param x any number * @param y any number * @param z any number * @return value between -1 and 1*/ double snoise(double x, double y, double z); /*!Calculates four dimensional simplex noise * @param x any number * @param y any number * @param z any number * @param k any number * @return value between -1 and 1*/ double snoise(double x, double y, double z, double k); } #endif
33.647059
89
0.501748
[ "3d" ]
38e4da9b19edaf38e81709ab44d20abfe252eb73
41,026
cpp
C++
dev/Code/CryEngine/CryAISystem/AIActions.cpp
crazyskateface/lumberyard
164512f8d415d6bdf37e195af319ffe5f96a8f0b
[ "AML" ]
5
2018-08-17T21:05:55.000Z
2021-04-17T10:48:26.000Z
dev/Code/CryEngine/CryAISystem/AIActions.cpp
JulianoCristian/Lumberyard-3
dc523dd780f3cd1874251181b7cf6848b8db9959
[ "AML" ]
null
null
null
dev/Code/CryEngine/CryAISystem/AIActions.cpp
JulianoCristian/Lumberyard-3
dc523dd780f3cd1874251181b7cf6848b8db9959
[ "AML" ]
5
2017-12-05T16:36:00.000Z
2021-04-27T06:33:54.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #include "StdAfx.h" #include <ISystem.h> #include <ICryPak.h> #include <IEntitySystem.h> #include <IEntity.h> #include "CAISystem.h" #include "PipeUser.h" #include "AIActions.h" #include "AIActor.h" #include "AIBubblesSystem/IAIBubblesSystem.h" /////////////////////////////////////////////////// // CAIAction /////////////////////////////////////////////////// bool CAIAction::TraverseAndValidateAction(EntityId idOfUser) const { assert(m_pFlowGraph.get() != NULL); if (!m_pFlowGraph) { return false; } // - for all EFLN_AIACTION_START nodes in the flow graph: // - flood the graph between that EFLN_AIACTION_START node and the terminating EFLN_AIACTION_END node // - inspect the encountered nodes for being compatible when being run in the context of an IAIAction (read: AISequence nodes must not appear inside an AIAction due to some GoalOp-related weirdness) IFlowNodeIteratorPtr nodeIterator = m_pFlowGraph->CreateNodeIterator(); TFlowNodeId nodeId; while (IFlowNodeData* data = nodeIterator->Next(nodeId)) { SFlowNodeConfig config; data->GetConfiguration(config); if (config.GetTypeFlags() & EFLN_AIACTION_START) { std::deque<TFlowNodeId> nodesToVisit; std::set<TFlowNodeId> examinedNodes; nodesToVisit.push_back(nodeId); while (!nodesToVisit.empty()) { nodeId = nodesToVisit.front(); // compatibility check: AISequence nodes are _not_ allowed IFlowNodeData* nodeData = m_pFlowGraph->GetNodeData(nodeId); assert(nodeData); nodeData->GetConfiguration(config); if (config.GetTypeFlags() & EFLN_AISEQUENCE_ACTION) { stack_string message; message.Format("AI Action contains a flownode not supported by the AI Action system : %s", m_pFlowGraph->GetNodeTypeName(nodeId)); AIQueueBubbleMessage("AI Action - Flownode not supported", idOfUser, message, eBNS_LogWarning | eBNS_Balloon | eBNS_BlockingPopup); return false; } nodesToVisit.pop_front(); examinedNodes.insert(nodeId); // visit neighbors IFlowEdgeIteratorPtr edgeIter = m_pFlowGraph->CreateEdgeIterator(); IFlowEdgeIterator::Edge edge; while (edgeIter->Next(edge)) { if (edge.fromNodeId != nodeId) { continue; } IFlowNodeData* dataOfDestinationNode = m_pFlowGraph->GetNodeData(edge.toNodeId); assert(dataOfDestinationNode); SFlowNodeConfig configOfDestinationNode; dataOfDestinationNode->GetConfiguration(configOfDestinationNode); if (configOfDestinationNode.GetTypeFlags() & EFLN_AIACTION_END) { continue; // hit the terminating action node } if (examinedNodes.find(edge.toNodeId) != examinedNodes.end()) { continue; // examined this node already (can happen if being pointed to by more than one node) } nodesToVisit.push_back(edge.toNodeId); } } } } return true; } /////////////////////////////////////////////////// // CAnimationAction /////////////////////////////////////////////////// // returns the goal pipe which executes this AI Action IGoalPipe* CAnimationAction::GetGoalPipe() const { // create the goal pipe here IGoalPipe* pPipe = gAIEnv.pPipeManager->CreateGoalPipe(string(bSignaledAnimation ? "$$" : "@") + sAnimationName, CPipeManager::SilentlyReplaceDuplicate); GoalParameters params; IGoalPipe::EGroupType grouped(IGoalPipe::eGT_NOGROUP); if (bExactPositioning) { if (iApproachStance != -1) { params.fValue = (float)iApproachStance; pPipe->PushGoal(eGO_BODYPOS, false, grouped, params); params.fValue = 0; grouped = IGoalPipe::eGT_GROUPWITHPREV; } if (fApproachSpeed != -1) { params.fValue = fApproachSpeed; params.nValue = 0; pPipe->PushGoal(eGO_RUN, false, grouped, params); params.fValue = 0; params.nValue = 0; grouped = IGoalPipe::eGT_GROUPWITHPREV; } params.str = "refpoint"; pPipe->PushGoal(eGO_LOCATE, false, grouped, params); params.str.clear(); params.bValue = bSignaledAnimation; params.str = sAnimationName; params.vPos.x = fStartWidth; params.vPos.y = fDirectionTolerance; params.vPos.z = fStartArcAngle; params.vPosAux = vApproachPos; params.nValue = bAutoTarget ? 1 : 0; pPipe->PushGoal(eGO_ANIMTARGET, false, IGoalPipe::eGT_GROUPWITHPREV, params); params.bValue = false; params.str.clear(); params.vPos.zero(); params.nValue = 0; params.str = "animtarget"; pPipe->PushGoal(eGO_LOCATE, false, IGoalPipe::eGT_GROUPWITHPREV, params); params.str.clear(); params.fValue = 1.5f; // end distance params.fValueAux = 1.0f; // end accuracy params.nValue = AILASTOPRES_USE | AI_STOP_ON_ANIMATION_START; pPipe->PushGoal(eGO_APPROACH, true, IGoalPipe::eGT_GROUPWITHPREV, params); params.fValue = 0; params.fValueAux = 0; params.nValue = 0; params.fValue = 0; params.nValue = BRANCH_ALWAYS; params.nValueAux = 2; pPipe->PushGoal(eGO_BRANCH, false, IGoalPipe::eGT_NOGROUP, params); params.nValue = 0; params.nValueAux = 0; params.nValueAux = 1; params.str = "CANCEL_CURRENT"; params.nValue = 0; pPipe->PushGoal(eGO_SIGNAL, true, IGoalPipe::eGT_NOGROUP, params); params.nValueAux = 0; params.str.clear(); params.nValue = 0; params.fValue = 0; params.nValue = BRANCH_ALWAYS; params.nValueAux = 1; pPipe->PushGoal(eGO_BRANCH, false, IGoalPipe::eGT_NOGROUP, params); params.nValue = 0; params.nValueAux = 0; params.nValueAux = 1; params.str = "OnAnimTargetReached"; params.nValue = 0; pPipe->PushGoal(eGO_SIGNAL, true, IGoalPipe::eGT_NOGROUP, params); params.nValueAux = 0; params.str.clear(); params.nValue = 0; } else { params.nValue = bSignaledAnimation ? AIANIM_SIGNAL : AIANIM_ACTION; params.str = sAnimationName; pPipe->PushGoal(eGO_ANIMATION, false, IGoalPipe::eGT_NOGROUP, params); params.bValue = false; params.str.clear(); } return pPipe; } /////////////////////////////////////////////////// // CActiveAction represents single active CAIAction or CAnimationAction /////////////////////////////////////////////////// void CActiveAction::EndAction() { // end action only if it isn't canceled already if (m_iThreshold >= 0 && !m_bDeleted) { m_bDeleted = true; // modify the states if (!m_nextUserState.empty()) { gAIEnv.pSmartObjectManager->ModifySmartObjectStates(m_pUserEntity, m_nextUserState); m_nextUserState.clear(); } if (m_pObjectEntity && !m_nextObjectState.empty()) { gAIEnv.pSmartObjectManager->ModifySmartObjectStates(m_pObjectEntity, m_nextObjectState); m_nextObjectState.clear(); } this->NotifyListeners(ActionEnd); } } void CActiveAction::CancelAction() { // cancel action only if it isn't ended already if (!m_bDeleted && m_iThreshold >= 0) { m_iThreshold = -1; // modify the states if (!m_canceledUserState.empty()) { gAIEnv.pSmartObjectManager->ModifySmartObjectStates(m_pUserEntity, m_canceledUserState); m_canceledUserState.clear(); } if (m_pObjectEntity && !m_canceledObjectState.empty()) { gAIEnv.pSmartObjectManager->ModifySmartObjectStates(m_pObjectEntity, m_canceledObjectState); m_canceledObjectState.clear(); } } this->NotifyListeners(ActionCancel); } bool CActiveAction::AbortAction() { // abort action only if it isn't aborted, ended or canceled already if (m_bDeleted || m_iThreshold < 0) { return false; } IAIObject* pUser = m_pUserEntity->GetAI(); if (m_pFlowGraph) { CPipeUser* pPipeUser = pUser ? pUser->CastToCPipeUser() : NULL; if (pPipeUser) { // enumerate nodes and make all AI:ActionAbort nodes RegularlyUpdated bool bHasAbort = false; int idNode = 0; TFlowNodeTypeId nodeTypeId; TFlowNodeTypeId actionAbortTypeId = gEnv->pFlowSystem->GetTypeId("AI:ActionAbort"); while ((nodeTypeId = m_pFlowGraph->GetNodeTypeId(idNode)) != InvalidFlowNodeTypeId) { if (nodeTypeId == actionAbortTypeId) { m_pFlowGraph->SetRegularlyUpdated(idNode, true); bHasAbort = true; } ++idNode; } if (bHasAbort) { pPipeUser->AbortActionPipe(m_idGoalPipe); return true; } } } CancelAction(); return false; } bool CActiveAction::operator == (const CActiveAction& other) const { return // (MATT) More thorough equality testing was needed. Can we get rid of this entirely? {2008/07/28} m_idGoalPipe == other.m_idGoalPipe && m_pFlowGraph == other.m_pFlowGraph && m_pUserEntity == other.m_pUserEntity && m_pObjectEntity == other.m_pObjectEntity && m_SuspendCounter == other.m_SuspendCounter && m_sAnimationName == other.m_sAnimationName && m_vAnimationPos == other.m_vAnimationPos && m_vAnimationDir == other.m_vAnimationDir; } /////////////////////////////////////////////////// // CAIActionManager keeps track of all AIActions /////////////////////////////////////////////////// CAIActionManager::CAIActionManager() { if (gEnv->pEntitySystem) { gEnv->pEntitySystem->GetIEntityPoolManager()->AddListener(this, "ActionManager", IEntityPoolListener::EntityReturningToPool); } } CAIActionManager::~CAIActionManager() { if (gEnv->pEntitySystem) { gEnv->pEntitySystem->GetIEntityPoolManager()->RemoveListener(this); } Reset(); m_ActionsLib.clear(); } // suspends all active AI Actions in which the entity is involved // it's safe to pass pEntity == NULL int CAIActionManager::SuspendActionsOnEntity(IEntity* pEntity, int goalPipeId, const IAIAction* pAction, bool bHighPriority, int& numHigherPriority) { // count how many actions are suspended so we can prevent execution of too many actions at same time int count = 0; numHigherPriority = 0; if (pEntity) { // if entity is registered as CPipeUser... IAIObject* pAI = pEntity->GetAI(); if (pAI) { CPipeUser* pPipeUser = pAI->CastToCPipeUser(); if (pPipeUser) { GetAISystem()->Record(pAI, IAIRecordable::E_ACTIONSUSPEND, ""); // insert the pipe IGoalPipe* pPipe = pAction->GetGoalPipe(); if (pPipe) { pPipe = pPipeUser->InsertSubPipe(bHighPriority ? AIGOALPIPE_HIGHPRIORITY : 0, pPipe->GetName(), NILREF, goalPipeId); if (pPipe != NULL && ((CGoalPipe*)pPipe)->GetSubpipe() == NULL) { pPipeUser->SetRefPointPos(pAction->GetAnimationPos(), pAction->GetAnimationDir()); } } else { pPipe = pPipeUser->InsertSubPipe(bHighPriority ? AIGOALPIPE_HIGHPRIORITY : 0, "_action_", NILREF, goalPipeId); if (!pPipe) { // create the goal pipe here GoalParameters params; pPipe = gAIEnv.pPipeManager->CreateGoalPipe("_action_", CPipeManager::SilentlyReplaceDuplicate); params.fValue = 0.1f; pPipe->PushGoal(eGO_TIMEOUT, true, IGoalPipe::eGT_NOGROUP, params); params.fValue = 0; params.nValue = BRANCH_ALWAYS; params.nValueAux = -1; pPipe->PushGoal(eGO_BRANCH, true, IGoalPipe::eGT_NOGROUP, params); // try to insert the pipe now once again pPipe = pPipeUser->InsertSubPipe(bHighPriority ? AIGOALPIPE_HIGHPRIORITY : 0, "_action_", NILREF, goalPipeId); } } // pPipe might be NULL if the puppet is dead if (!pPipe) { return 100; } numHigherPriority = ((CGoalPipe*)pPipe)->CountSubpipes(); // set debug name string name("["); if (bHighPriority) { name += '!'; } const char* szName = pAction->GetName(); if (!szName) { name += pPipe->GetName(); } else { name += szName; } name += ']'; pPipe->SetDebugName(name); // and watch it pPipeUser->RegisterGoalPipeListener(this, goalPipeId, "CAIActionManager::SuspendActionsOnEntity"); } else // if ( CAIPlayer* pAIPlayer = pAI->CastToCAIPlayer() ) { if (pAction->GetFlowGraph() == NULL) { pAI->GetProxy()->PlayAnimationAction(pAction, goalPipeId); } } } TActiveActions::iterator it, itEnd = m_ActiveActions.end(); for (it = m_ActiveActions.begin(); it != itEnd; ++it) { if (it->m_pUserEntity == pEntity /*|| it->m_pObjectEntity == pEntity*/) { if (bHighPriority == true || it->m_bHighPriority == false) { if (!it->m_SuspendCounter) { IFlowGraph* pGraph = it->GetFlowGraph(); if (pGraph) { pGraph->SetSuspended(true); } } ++it->m_SuspendCounter; } ++count; } } } // returns the number of active actions return count + 1; } // resumes all active AI Actions in which the entity is involved // (resuming depends on it how many times it was suspended) // note: it's safe to pass pEntity == NULL void CAIActionManager::ResumeActionsOnEntity(IEntity* pEntity, int goalPipeId) { if (pEntity) { if (goalPipeId) { // if entity is registered as CPipeUser... IAIObject* pAI = pEntity->GetAI(); if (pAI) { CPipeUser* pPipeUser = pAI->CastToCPipeUser(); if (pPipeUser) { GetAISystem()->Record(pAI, IAIRecordable::E_ACTIONRESUME, ""); // ...stop watching it... pPipeUser->UnRegisterGoalPipeListener(this, goalPipeId); // ...remove "_action_" goal pipe pPipeUser->RemoveSubPipe(goalPipeId); } } } TActiveActions::iterator it, itEnd = m_ActiveActions.end(); for (it = m_ActiveActions.begin(); it != itEnd; ++it) { if (it->m_pUserEntity == pEntity /*|| it->m_pObjectEntity == pEntity*/) { --it->m_SuspendCounter; if (!it->m_SuspendCounter) { IFlowGraph* pGraph = it->GetFlowGraph(); if (pGraph) { pGraph->SetSuspended(false); } } } } } } // aborts specific AI Action (specified by goalPipeId) or all AI Actions (goalPipeId == 0) in which pEntity is a user void CAIActionManager::AbortAIAction(IEntity* pEntity, int goalPipeId /*=0*/) { AIAssert(pEntity); if (!pEntity) { return; } TActiveActions::iterator it, itEnd = m_ActiveActions.end(); for (it = m_ActiveActions.begin(); it != itEnd; ++it) { if ((goalPipeId || !it->m_bHighPriority) && it->m_pUserEntity == pEntity) { if (!goalPipeId || goalPipeId == it->m_idGoalPipe) { it->AbortAction(); } } } } // finishes specific AI Action (specified by goalPipeId) for the pEntity as a user void CAIActionManager::FinishAIAction(IEntity* pEntity, int goalPipeId) { AIAssert(pEntity); if (!pEntity) { return; } TActiveActions::iterator it, itEnd = m_ActiveActions.end(); for (it = m_ActiveActions.begin(); it != itEnd; ++it) { if (it->m_pUserEntity == pEntity && goalPipeId == it->m_idGoalPipe) { it->EndAction(); break; } } } // implementation of IGoalPipeListener void CAIActionManager::OnGoalPipeEvent(IPipeUser* pPipeUser, EGoalPipeEvent event, int goalPipeId, bool& unregisterListenerAfterEvent) { TActiveActions::iterator it, itEnd = m_ActiveActions.end(); for (it = m_ActiveActions.begin(); it != itEnd; ++it) { CActiveAction& action = *it; if (action.m_idGoalPipe == goalPipeId) { if (event == ePN_Deselected) { action.CancelAction(); break; } if (!action.GetFlowGraph()) { // additional stuff for animations actions if (event == ePN_Resumed) { // restore reference point pPipeUser->SetRefPointPos(action.GetAnimationPos(), action.GetAnimationDir()); break; } else if (event == ePN_Finished) { action.EndAction(); break; } } } } } // stops all active actions void CAIActionManager::Reset() { TActiveActions::iterator it, itEnd = m_ActiveActions.end(); for (it = m_ActiveActions.begin(); it != itEnd; ++it) { CActiveAction& action = *it; if (action.GetFlowGraph()) { action.GetFlowGraph()->SetAIAction(0); } if (action.GetUserEntity()) { IAIObject* pAI = action.GetUserEntity()->GetAI(); if (pAI) { CPipeUser* pPipeUser = pAI->CastToCPipeUser(); if (pPipeUser) { pPipeUser->UnRegisterGoalPipeListener(this, action.m_idGoalPipe); } } } } m_ActiveActions.clear(); } // returns an existing AI Action by its name specified in the rule // or creates a new temp. action for playing the animation specified in the rule IAIAction* CAIActionManager::GetAIAction(const CCondition* pRule) { IAIAction* pResult = NULL; if (pRule->sAction.empty()) { return NULL; } if (pRule->eActionType == eAT_AnimationSignal || pRule->eActionType == eAT_AnimationAction || pRule->eActionType == eAT_PriorityAnimationSignal || pRule->eActionType == eAT_PriorityAnimationAction) { if (pRule->sAnimationHelper.empty()) { pResult = new CAnimationAction(pRule->sAction, pRule->eActionType == eAT_AnimationSignal || pRule->eActionType == eAT_PriorityAnimationSignal); } else { pResult = new CAnimationAction( pRule->sAction, pRule->eActionType == eAT_AnimationSignal || pRule->eActionType == eAT_PriorityAnimationSignal, pRule->fApproachSpeed, pRule->iApproachStance, pRule->fStartWidth, pRule->fDirectionTolerance, pRule->fStartArcAngle); } } else if (pRule->eActionType == eAT_Action || pRule->eActionType == eAT_PriorityAction) { pResult = GetAIAction(pRule->sAction); } return pResult; } // returns an existing AI Action from the library or NULL if not found IAIAction* CAIActionManager::GetAIAction(const char* sName) { if (!sName || !*sName) { return NULL; } TActionsLib::iterator it = m_ActionsLib.find(CONST_TEMP_STRING(sName)); if (it != m_ActionsLib.end()) { return &it->second; } else { return NULL; } } // returns an existing AI Action by its index in the library or NULL index is out of range IAIAction* CAIActionManager::GetAIAction(size_t index) { if (index >= m_ActionsLib.size()) { return NULL; } TActionsLib::iterator it = m_ActionsLib.begin(); while (index--) { ++it; } return &it->second; } // adds an AI Action in the list of active actions void CAIActionManager::ExecuteAIAction(const IAIAction* pAction, IEntity* pUser, IEntity* pObject, int maxAlertness, int goalPipeId, const char* userState, const char* objectState, const char* userCanceledState, const char* objectCanceledState, IAIAction::IAIActionListener* pListener) { AIAssert(pAction); AIAssert(pUser); AIAssert(pObject); pAction->TraverseAndValidateAction(pUser->GetId()); IAIObject* pAI = pUser->GetAI(); if (GetAISystem()->IsRecording(pAI, IAIRecordable::E_ACTIONSTART)) { string str(pAction->GetName()); str += " on entity "; str += pObject->GetName(); GetAISystem()->Record(pAI, IAIRecordable::E_ACTIONSTART, str); } // don't execute the action if the user is dead const bool isAIDisabled = pAI ? !pAI->IsEnabled() : false; if (isAIDisabled) { if (!pAction->GetFlowGraph()) { delete pAction; } return; } // allocate an goal pipe id if not specified if (!goalPipeId) { goalPipeId = GetAISystem()->AllocGoalPipeId(); } // create a clone of the flow graph IFlowGraphPtr pFlowGraph = NULL; if (IFlowGraph* pActionFlowGraph = pAction->GetFlowGraph()) { pFlowGraph = pActionFlowGraph->Clone(); } // suspend all actions executing on the User or the Object int suspendCounter = 0; int numActions = SuspendActionsOnEntity(pUser, goalPipeId, pAction, maxAlertness >= 100, suspendCounter); if (numActions == 100) { // can't select the goal pipe if (!pAction->GetFlowGraph()) { delete pAction; } return; } // Tell entity about action start GetAISystem()->SendSignal(SIGNALFILTER_SENDER, 1, "OnActionStart", pAI); if (pFlowGraph) { // create active action and add it to the list CActiveAction action; action.m_pFlowGraph = pFlowGraph; action.m_Name = pAction->GetName(); action.m_pUserEntity = pUser; action.m_pObjectEntity = pObject; action.m_SuspendCounter = suspendCounter; action.m_idGoalPipe = goalPipeId; action.m_iThreshold = numActions > 10 ? -1 : maxAlertness % 100; // cancel this action if there are already 10 actions executing action.m_nextUserState = userState; action.m_nextObjectState = objectState; action.m_canceledUserState = userCanceledState; action.m_canceledObjectState = objectCanceledState; action.m_bDeleted = false; action.m_bHighPriority = maxAlertness >= 100; m_ActiveActions.push_front(action); if (pListener) { m_ActiveActions.front().RegisterListener(pListener, "ListenerFlowGraphAction"); pListener->OnActionEvent(IAIAction::ActionStart); } // the User will be first graph entity. if (pUser) { pFlowGraph->SetGraphEntity(FlowEntityId(pUser->GetId()), 0); } // the Object will be second graph entity. if (pObject) { pFlowGraph->SetGraphEntity(FlowEntityId(pObject->GetId()), 1); } // initialize the graph pFlowGraph->InitializeValues(); pFlowGraph->SetAIAction(&m_ActiveActions.front()); if (action.m_SuspendCounter > 0) { pFlowGraph->SetSuspended(true); } } else { // create active action and add it to the list CActiveAction action; action.m_pFlowGraph = NULL; action.m_Name = pAction->GetName(); action.m_pUserEntity = pUser; action.m_pObjectEntity = pObject; action.m_SuspendCounter = suspendCounter; action.m_idGoalPipe = goalPipeId; action.m_iThreshold = numActions > 10 ? -1 : maxAlertness % 100; // cancel this action if there are already 10 actions executing action.m_nextUserState = userState; action.m_nextObjectState = objectState; action.m_canceledUserState = userCanceledState; action.m_canceledObjectState = objectCanceledState; action.m_bDeleted = false; action.m_bSignaledAnimation = pAction->IsSignaledAnimation(); action.m_bExactPositioning = pAction->IsExactPositioning(); action.m_sAnimationName = pAction->GetAnimationName(); action.m_bHighPriority = maxAlertness >= 100; action.m_vAnimationPos = pAction->GetAnimationPos(); action.m_vAnimationDir = pAction->GetAnimationDir(); action.m_vApproachPos = pAction->GetApproachPos(); action.m_bAutoTarget = pAction->IsUsingAutoAssetAlignment(); action.m_fStartWidth = pAction->GetStartWidth(); action.m_fStartArcAngle = pAction->GetStartArcAngle(); action.m_fDirectionTolerance = pAction->GetDirectionTolerance(); m_ActiveActions.push_front(action); if (pListener) { m_ActiveActions.front().RegisterListener(pListener, "ListenerAction"); pListener->OnActionEvent(IAIAction::ActionStart); } // delete temp. action delete pAction; } } void CAIActionManager::ExecuteAIAction(const char* sActionName, IEntity* pUser, IEntity* pObject, int maxAlertness, int goalPipeId, IAIAction::IAIActionListener* pListener) { string str(sActionName); str += ",\"\",\"\",\"\",\"\","; int i = str.find(',', 0); int j = str.find('\"', i + 2); int k = str.find('\"', j + 3); int l = str.find('\"', k + 3); int m = str.find('\"', l + 3); IAIAction* pAction = GetAIAction(str.substr(0, i)); if (pAction) { ExecuteAIAction(pAction, pUser, pObject, maxAlertness, goalPipeId, str.substr(i + 2, j - i - 2), str.substr(j + 3, k - j - 3), str.substr(k + 3, l - k - 3), str.substr(l + 3, m - l - 3), pListener); } else { AIError("Entity '%s' requested execution of undefined AI Action '%s' [Design bug]", pUser ? pUser->GetName() : "<NULL>", sActionName); } } // removes deleted AI Action from the list of active actions void CAIActionManager::Update() { FUNCTION_PROFILER(gEnv->pSystem, PROFILE_AI) TActiveActions::iterator it = m_ActiveActions.begin(); while (it != m_ActiveActions.end()) { CActiveAction& action = *it; if (!action.m_pUserEntity) { // the action is already deleted just remove it from the list m_ActiveActions.erase(it++); continue; } ++it; if (action.m_bDeleted) { AILogComment("AIAction '%s' with '%s' and '%s' ended.\n", action.GetName(), action.m_pUserEntity->GetName(), action.m_pObjectEntity->GetName()); ActionDone(action); } else { IAIObject* pAI = action.m_pUserEntity->GetAI(); if (pAI) { CAIActor* pActor = pAI->CastToCAIActor(); IAIActorProxy* pProxy = pActor ? pActor->GetProxy() : NULL; int alertness = pProxy ? pProxy->GetAlertnessState() : 0; if (alertness > action.m_iThreshold) { if (action.m_iThreshold < 0) { AILogComment("AIAction '%s' with '%s' and '%s' cancelled\n", action.GetName(), action.m_pUserEntity->GetName(), action.m_pObjectEntity->GetName()); ActionDone(action); } else { AILogComment("AIAction '%s' with '%s' and '%s' aborted\n", action.GetName(), action.m_pUserEntity->GetName(), action.m_pObjectEntity->GetName()); action.AbortAction(); } } } else if (action.m_iThreshold < 0) { // action was canceled AILogComment("AIAction '%s' with '%s' and '%s' cancelled\n", action.GetName(), action.m_pUserEntity->GetName(), action.m_pObjectEntity->GetName()); ActionDone(action); } } } } // marks AI Action from the list of active actions as deleted void CAIActionManager::ActionDone(CActiveAction& action, bool bRemoveAction /*= true*/) { IAIObject* pAI = action.m_pUserEntity->GetAI(); if (GetAISystem()->IsRecording(pAI, IAIRecordable::E_ACTIONEND)) { string str(action.GetName()); str += " on entity "; str += action.m_pObjectEntity->GetName(); GetAISystem()->Record(pAI, IAIRecordable::E_ACTIONEND, str); } // remove the pointer to this action in the flow graph IFlowGraph* pFlowGraph = action.GetFlowGraph(); if (pFlowGraph) { pFlowGraph->SetAIAction(NULL); } // make a copy before removing CActiveAction copy = action; // find the action in the list of active actions if (bRemoveAction) { m_ActiveActions.remove(copy); } // resume last suspended action executing on the User or the Object ResumeActionsOnEntity(copy.m_pUserEntity, copy.m_idGoalPipe); // notify the current behavior script that action was finished if (pAI) { CAIActor* pAIActor = pAI->CastToCAIActor(); if (pAIActor) { IAISignalExtraData* pData = GetAISystem()->CreateSignalExtraData(); pData->SetObjectName(copy.GetName()); pData->nID = copy.m_pObjectEntity->GetId(); pData->iValue = copy.m_bDeleted ? 1 : 0; // if m_bDeleted is true it means the action was succeeded pAIActor->SetSignal(10, "OnActionDone", NULL, pData, gAIEnv.SignalCRCs.m_nOnActionDone); if (CPipeUser* pPipeUser = pAIActor->CastToCPipeUser()) { pPipeUser->SetLastActionStatus(copy.m_bDeleted); // if m_bDeleted is true it means the action was succeeded } } } // if it was deleted it also means that it was succesfully finished if (copy.m_bDeleted) { if (!copy.m_nextUserState.empty()) { gAIEnv.pSmartObjectManager->ModifySmartObjectStates(copy.m_pUserEntity, copy.m_nextUserState); } if (copy.m_pObjectEntity && !copy.m_nextObjectState.empty()) { gAIEnv.pSmartObjectManager->ModifySmartObjectStates(copy.m_pObjectEntity, copy.m_nextObjectState); } } else { if (!copy.m_canceledUserState.empty()) { gAIEnv.pSmartObjectManager->ModifySmartObjectStates(copy.m_pUserEntity, copy.m_canceledUserState); } if (copy.m_pObjectEntity && !copy.m_canceledObjectState.empty()) { gAIEnv.pSmartObjectManager->ModifySmartObjectStates(copy.m_pObjectEntity, copy.m_canceledObjectState); } } // if ( copy.m_pUserEntity != copy.m_pObjectEntity ) // ResumeActionsOnEntity( copy.m_pObjectEntity ); // Tell entity about action end GetAISystem()->SendSignal(SIGNALFILTER_SENDER, 1, "OnActionEnd", pAI); } #undef LoadLibrary // loads the library of AI Action Flow Graphs void CAIActionManager::LoadLibrary(const char* sPath) { m_ActiveActions.clear(); // don't delete all actions - only those which are added or modified will be reloaded //m_ActionsLib.clear(); string path(sPath); ICryPak* pCryPak = gEnv->pCryPak; _finddata_t fd; string filename; path.TrimRight("/\\"); string search = path + "/*.xml"; intptr_t handle = pCryPak->FindFirst(search.c_str(), &fd); if (handle != -1) { do { filename = path; filename += "/"; filename += fd.name; XmlNodeRef root = GetISystem()->LoadXmlFromFile(filename); if (root) { if (gEnv->pFlowSystem) { filename = PathUtil::GetFileName(filename); CAIAction& action = m_ActionsLib[ filename ]; // this creates a new entry in m_ActionsLib if (!action.m_pFlowGraph) { action.m_Name = filename; action.m_pFlowGraph = gEnv->pFlowSystem->CreateFlowGraph(); action.m_pFlowGraph->SetSuspended(true); action.m_pFlowGraph->SetAIAction(&action); action.m_pFlowGraph->SerializeXML(root, true); } } } } while (pCryPak->FindNext(handle, &fd) >= 0); pCryPak->FindClose(handle); } } //------------------------------------------------------------------------------------------------------------------------ void CAIActionManager::OnEntityReturningToPool(EntityId entityId, IEntity* pEntity) { assert(pEntity); //When entities return to the pool, the actions can't be serialized into the entity's bookmark. So the action will get canceled on the next frame, // but the AI if it is pulled back from the bookmark will not be aware. -Morgan 03/01/2011 OnEntityRemove(pEntity); } // notification sent by smart objects system void CAIActionManager::OnEntityRemove(IEntity* pEntity) { // bool bFound = false; TActiveActions::iterator it, itEnd = m_ActiveActions.end(); for (it = m_ActiveActions.begin(); it != itEnd; ++it) { CActiveAction& action = *it; if (pEntity == action.GetUserEntity() || pEntity == action.GetObjectEntity()) { action.CancelAction(); // bFound = true; AILogComment("AIAction '%s' with '%s' and '%s' canceled because '%s' was deleted.\n", action.GetName(), action.m_pUserEntity->GetName(), action.m_pObjectEntity->GetName(), pEntity->GetName()); ActionDone(action, false); action.OnEntityRemove(); } } // calling Update() from here causes a crash if the entity gets deleted while the action flow graph is being updated // if ( bFound ) // { // // Update() will remove canceled actions // Update(); // } } void CAIActionManager::Serialize(TSerialize ser) { if (ser.BeginOptionalGroup("AIActionManager", true)) { int numActiveActions = m_ActiveActions.size(); ser.Value("numActiveActions", numActiveActions); if (ser.IsReading()) { Reset(); while (numActiveActions--) { m_ActiveActions.push_back(CActiveAction()); } } TActiveActions::iterator it, itEnd = m_ActiveActions.end(); for (it = m_ActiveActions.begin(); it != itEnd; ++it) { it->Serialize(ser); } ser.EndGroup(); //AIActionManager } } void CAIActionManager::ReloadActions() { CTimeValue t1 = gEnv->pTimer->GetAsyncTime(); AIAssert(gEnv->pEntitySystem); if (gAIEnv.pSmartObjectManager) { LoadLibrary(AI_ACTIONS_PATH); } CTimeValue t2 = gEnv->pTimer->GetAsyncTime(); AILogComment("All AI Actions reloaded in %g mSec.", (t2 - t1).GetMilliSeconds()); } void CActiveAction::Serialize(TSerialize ser) { ser.BeginGroup("ActiveAction"); { ser.Value("m_Name", m_Name); EntityId userId = m_pUserEntity && !ser.IsReading() ? m_pUserEntity->GetId() : 0; ser.Value("userId", userId); if (ser.IsReading()) { m_pUserEntity = gEnv->pEntitySystem->GetEntity(userId); } EntityId objectId = m_pObjectEntity && !ser.IsReading() ? m_pObjectEntity->GetId() : 0; ser.Value("objectId", objectId); if (ser.IsReading()) { m_pObjectEntity = gEnv->pEntitySystem->GetEntity(objectId); } ser.Value("m_SuspendCounter", m_SuspendCounter); ser.Value("m_idGoalPipe", m_idGoalPipe); if (m_idGoalPipe && ser.IsReading()) { IAIObject* pAI = m_pUserEntity ? m_pUserEntity->GetAI() : NULL; AIAssert(pAI); if (pAI) { CPipeUser* pPipeUser = pAI->CastToCPipeUser(); if (pPipeUser) { pPipeUser->RegisterGoalPipeListener(gAIEnv.pAIActionManager, m_idGoalPipe, "CActiveAction::Serialize"); CGoalPipe* pPipe = pPipeUser->GetCurrentGoalPipe(); while (pPipe) { if (pPipe->GetEventId() == m_idGoalPipe) { pPipe->SetDebugName((m_bHighPriority ? "[" : "[!") + m_Name + ']'); break; } pPipe = pPipe->GetSubpipe(); } } } } ser.Value("m_iThreshold", m_iThreshold); ser.Value("m_nextUserState", m_nextUserState); ser.Value("m_nextObjectState", m_nextObjectState); ser.Value("m_canceledUserState", m_canceledUserState); ser.Value("m_canceledObjectState", m_canceledObjectState); ser.Value("m_bDeleted", m_bDeleted); ser.Value("m_bHighPriority", m_bHighPriority); ser.Value("m_bSignaledAnimation", m_bSignaledAnimation); ser.Value("m_bExactPositioning", m_bExactPositioning); ser.Value("m_sAnimationName", m_sAnimationName); ser.Value("m_vAnimationPos", m_vAnimationPos); ser.Value("m_vAnimationDir", m_vAnimationDir); ser.Value("m_vApproachPos", m_vApproachPos); ser.Value("m_bAutoTarget", m_bAutoTarget); ser.Value("m_fStartWidth", m_fStartWidth); ser.Value("m_fStartArcAngle", m_fStartArcAngle); ser.Value("m_fDirectionTolerance", m_fDirectionTolerance); if (ser.BeginOptionalGroup("m_pFlowGraph", m_pFlowGraph != NULL)) { if (ser.IsReading()) { IAIAction* pAction = gAIEnv.pAIActionManager->GetAIAction(m_Name); AIAssert(pAction); if (pAction) { m_pFlowGraph = pAction->GetFlowGraph()->Clone(); } if (m_pFlowGraph) { m_pFlowGraph->SetAIAction(this); } } if (m_pFlowGraph) { m_pFlowGraph->SetGraphEntity(FlowEntityId(userId), 0); m_pFlowGraph->SetGraphEntity(FlowEntityId(objectId), 1); m_pFlowGraph->Serialize(ser); } ser.EndGroup(); //m_pFlowGraph } } ser.EndGroup(); }
34.388935
202
0.568371
[ "object" ]
38e6ba694b493c956ed722ebdee672cc058ca0cc
10,638
cc
C++
services/python/mojo_url_redirector/mojo_url_redirector_apptest.cc
zbowling/mojo
4d2ed40dc2390ca98a6fea0580e840535878f11c
[ "BSD-3-Clause" ]
1
2020-04-28T14:35:10.000Z
2020-04-28T14:35:10.000Z
services/python/mojo_url_redirector/mojo_url_redirector_apptest.cc
zbowling/mojo
4d2ed40dc2390ca98a6fea0580e840535878f11c
[ "BSD-3-Clause" ]
null
null
null
services/python/mojo_url_redirector/mojo_url_redirector_apptest.cc
zbowling/mojo
4d2ed40dc2390ca98a6fea0580e840535878f11c
[ "BSD-3-Clause" ]
1
2020-04-28T14:35:11.000Z
2020-04-28T14:35:11.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/bind.h" #include "base/logging.h" #include "base/run_loop.h" #include "base/strings/string_split.h" #include "base/strings/stringprintf.h" #include "mojo/data_pipe_utils/data_pipe_utils.h" #include "mojo/public/cpp/application/application_impl.h" #include "mojo/public/cpp/application/application_test_base.h" #include "mojo/services/http_server/cpp/http_server_util.h" #include "mojo/services/http_server/interfaces/http_server.mojom.h" #include "mojo/services/http_server/interfaces/http_server_factory.mojom.h" #include "mojo/services/network/interfaces/net_address.mojom.h" #include "mojo/services/network/interfaces/network_service.mojom.h" #include "mojo/services/network/interfaces/url_loader.mojom.h" namespace mojo_url_redirector { namespace { const std::string kPlatform1 = "platform1"; const std::string kPlatform2 = "platform2"; const std::string kKnownAppName = "spinning_cube.mojo"; const std::string kMissingAppName = "missing_app.mojo"; const std::string kGoogleStorageBaseURL = "https://storage.googleapis.com/"; std::string LocationOfAppOnPlatform(const std::string& platform, const std::string& app) { return platform + "-" + app; } void CheckRedirectorResponse(uint32 expected_http_status, std::string expected_redirect, mojo::URLResponsePtr response) { // Break out of the nested runloop that the test started running after // starting the request that is now complete. base::MessageLoop::current()->Quit(); EXPECT_FALSE(response->error); EXPECT_EQ(expected_http_status, response->status_code); std::string response_body; mojo::common::BlockingCopyToString(response->body.Pass(), &response_body); EXPECT_EQ("", response_body); if (expected_http_status != 302) return; // Check that the response contains a header redirecting to the expected // location. bool found_redirect_header = false; EXPECT_FALSE(response->headers.is_null()); for (size_t i = 0; i < response->headers.size(); i++) { const auto& header = response->headers[i]; if (header->name == "location" && header->value == expected_redirect) { found_redirect_header = true; break; } } EXPECT_TRUE(found_redirect_header); } } // namespace class MojoUrlRedirectorApplicationTest : public mojo::test::ApplicationTestBase, public http_server::HttpHandler { public: MojoUrlRedirectorApplicationTest() : ApplicationTestBase(), binding_(this), redirector_port_(0), redirector_registered_(false) {} ~MojoUrlRedirectorApplicationTest() override {} protected: // ApplicationTestBase: void SetUp() override { ApplicationTestBase::SetUp(); // Obtain the port that the redirector is at and the port that we should // spin up the app location files server at. uint16_t app_location_files_port = 0; for (const std::string& arg : application_impl()->args()) { if (arg.find("--redirector_port") != std::string::npos) { sscanf(arg.c_str(), "--redirector_port=%hu", &redirector_port_); } else if (arg.find("--app_location_files_port") != std::string::npos) { sscanf(arg.c_str(), "--app_location_files_port=%hu", &app_location_files_port); } } DCHECK(redirector_port_); DCHECK(app_location_files_port); // Spin up the app location files server. http_server::HttpHandlerPtr location_files_handler; binding_.Bind(GetProxy(&location_files_handler)); http_server::HttpServerFactoryPtr http_server_factory; application_impl()->ConnectToService("mojo:http_server", &http_server_factory); mojo::NetAddressPtr location_files_server_addr(mojo::NetAddress::New()); location_files_server_addr->family = mojo::NetAddressFamily::IPV4; location_files_server_addr->ipv4 = mojo::NetAddressIPv4::New(); location_files_server_addr->ipv4->addr.resize(4); location_files_server_addr->ipv4->addr[0] = 0; location_files_server_addr->ipv4->addr[1] = 0; location_files_server_addr->ipv4->addr[2] = 0; location_files_server_addr->ipv4->addr[3] = 0; location_files_server_addr->ipv4->port = app_location_files_port; http_server_factory->CreateHttpServer( GetProxy(&location_files_server_).Pass(), location_files_server_addr.Pass()); location_files_server_->SetHandler( "/.*", location_files_handler.Pass(), base::Bind(&MojoUrlRedirectorApplicationTest::OnAddedHandler, base::Unretained(this))); location_files_server_.WaitForIncomingResponse(); // Connect to the redirector and wait until it registers itself as a // handler with the server on |redirector_port_|. application_impl()->ConnectToApplication("mojo:mojo_url_redirector"); application_impl()->ConnectToService("mojo:network_service", &network_service_); WaitForRedirectorRegistration(); } void TestRedirectForKnownApp(const std::string& platform, const std::string& app); mojo::Binding<http_server::HttpHandler> binding_; mojo::NetworkServicePtr network_service_; uint16_t redirector_port_; bool redirector_registered_; private: // HttpHandler: void HandleRequest( http_server::HttpRequestPtr request, const mojo::Callback<void(http_server::HttpResponsePtr)>& callback) override; void WaitForRedirectorRegistration(); void CheckRedirectorRegistered(mojo::URLResponsePtr response); void OnAddedHandler(bool result); http_server::HttpServerPtr location_files_server_; MOJO_DISALLOW_COPY_AND_ASSIGN(MojoUrlRedirectorApplicationTest); }; void MojoUrlRedirectorApplicationTest::OnAddedHandler(bool result) { CHECK(result); } // Handles requests for app location files. void MojoUrlRedirectorApplicationTest::HandleRequest( http_server::HttpRequestPtr request, const mojo::Callback<void(http_server::HttpResponsePtr)>& callback) { // The relative url should be of the form "/<platform>/<app>_location". std::vector<std::string> url_components; base::SplitString(request->relative_url, '/', &url_components); ASSERT_EQ(3u, url_components.size()); std::string requested_platform = url_components[1]; EXPECT_TRUE(requested_platform == kPlatform1 || requested_platform == kPlatform2); std::string location_file_basename = url_components[2]; std::string known_app_location_file = kKnownAppName + "_location"; std::string missing_app_location_file = kMissingAppName + "_location"; EXPECT_TRUE(location_file_basename == known_app_location_file || location_file_basename == missing_app_location_file); if (location_file_basename == missing_app_location_file) { callback.Run(http_server::CreateHttpResponse(404, "")); return; } std::string app_location = LocationOfAppOnPlatform(requested_platform, kKnownAppName); callback.Run(http_server::CreateHttpResponse(200, app_location)); } void MojoUrlRedirectorApplicationTest::WaitForRedirectorRegistration() { while (!redirector_registered_) { mojo::URLLoaderPtr url_loader; network_service_->CreateURLLoader(GetProxy(&url_loader)); mojo::URLRequestPtr url_request = mojo::URLRequest::New(); url_request->url = base::StringPrintf("http://localhost:%u/test", redirector_port_); url_loader->Start(url_request.Pass(), base::Bind( &MojoUrlRedirectorApplicationTest::CheckRedirectorRegistered, base::Unretained(this))); ASSERT_TRUE(url_loader.WaitForIncomingResponse()); } } void MojoUrlRedirectorApplicationTest::CheckRedirectorRegistered( mojo::URLResponsePtr response) { if (response->error) { // The server at |redirector_port_| has not yet been spun up. return; } if (response->status_code == 404) { // The redirector has not yet been registered as a handler. return; } redirector_registered_ = true; } void MojoUrlRedirectorApplicationTest::TestRedirectForKnownApp( const std::string& platform, const std::string& app) { mojo::URLLoaderPtr url_loader; network_service_->CreateURLLoader(GetProxy(&url_loader)); mojo::URLRequestPtr url_request = mojo::URLRequest::New(); url_request->url = base::StringPrintf("http://localhost:%u/%s/%s", redirector_port_, platform.c_str(), app.c_str()); std::string app_location = kGoogleStorageBaseURL + LocationOfAppOnPlatform(platform, app); url_loader->Start(url_request.Pass(), base::Bind(&CheckRedirectorResponse, 302, app_location)); base::RunLoop run_loop; run_loop.Run(); } // TODO(blundell): This test is flaky. // https://github.com/domokit/mojo/issues/115 TEST_F(MojoUrlRedirectorApplicationTest, DISABLED_MalformedRequest) { mojo::URLLoaderPtr url_loader; network_service_->CreateURLLoader(GetProxy(&url_loader)); mojo::URLRequestPtr url_request = mojo::URLRequest::New(); url_request->url = base::StringPrintf("http://localhost:%u/test", redirector_port_); url_loader->Start(url_request.Pass(), base::Bind(&CheckRedirectorResponse, 400, "")); base::RunLoop run_loop; run_loop.Run(); } // TODO(blundell): This test is flaky. // https://github.com/domokit/mojo/issues/115 TEST_F(MojoUrlRedirectorApplicationTest, DISABLED_RequestForMissingApp) { mojo::URLLoaderPtr url_loader; network_service_->CreateURLLoader(GetProxy(&url_loader)); mojo::URLRequestPtr url_request = mojo::URLRequest::New(); url_request->url = base::StringPrintf("http://localhost:%u/%s/%s", redirector_port_, kPlatform1.c_str(), kMissingAppName.c_str()); url_loader->Start(url_request.Pass(), base::Bind(&CheckRedirectorResponse, 404, "")); base::RunLoop run_loop; run_loop.Run(); } // TODO(blundell): This test is flaky. // https://github.com/domokit/mojo/issues/115 TEST_F(MojoUrlRedirectorApplicationTest, DISABLED_RequestForKnownApp) { TestRedirectForKnownApp(kPlatform1, kKnownAppName); TestRedirectForKnownApp(kPlatform2, kKnownAppName); } } // namespace mojo_url_redirector
38.266187
78
0.704832
[ "vector" ]
38ee07b14f11b1d8074dce539eba8115de98d782
1,382
cpp
C++
src/3d/geometry/transform_test.cpp
wkrzemien/j-pet-mlem
4ed746f3fe79890e4141158cd49d1869938105de
[ "Apache-2.0" ]
null
null
null
src/3d/geometry/transform_test.cpp
wkrzemien/j-pet-mlem
4ed746f3fe79890e4141158cd49d1869938105de
[ "Apache-2.0" ]
5
2018-08-08T08:26:04.000Z
2020-05-13T13:33:39.000Z
src/3d/geometry/transform_test.cpp
wkrzemien/j-pet-mlem
4ed746f3fe79890e4141158cd49d1869938105de
[ "Apache-2.0" ]
5
2018-06-04T21:04:29.000Z
2021-07-03T14:19:39.000Z
#include "util/test.h" #include "3d/geometry/ray.h" #include "3d/geometry/point.h" #include "3d/geometry/transform.h" #include "common/types.h" using Vector = PET3D::Vector<F>; using Point = PET3D::Point<F>; TEST_CASE("3d/transform") { SECTION("vector/rotation/1") { Vector src(0.1f, 0.2f, 0.3f); auto dest = rotate(src, F(M_PI / 3.0), Vector(0, 0, 1.0)); CHECK(dest == VApprox(Vector(-0.123205080757, 0.186602540378, 0.3))); } SECTION("Vector/rotation/2") { Vector src(0.1f, 0.2f, 0.3f); auto dest = rotate(src, F(M_PI / 3.0), Vector(.2, .4, 1).normalized()); CHECK(dest == VApprox(Vector(0.02008778013, 0.198289443268, 0.316666666667))); } SECTION("point/rotation/1") { Point src(0.1f, 0.2f, 0.3f); auto dest = rotate(src, F(M_PI / 3.0), Vector(0, 0, 1.0)); CHECK(dest == VApprox(Point(-0.123205080757, 0.186602540378, 0.3))); } SECTION("point/rotation/2") { Point src(0.1f, 0.2f, 0.3f); auto dest = rotate(src, F(M_PI / 3.0), Vector(.2, .4, 1).normalized()); CHECK(dest == VApprox(Point(0.02008778013, 0.198289443268, 0.316666666667))); } SECTION("point/rotation/2") { Point src(0.1f, 0.2f, 0.3f); auto dest = rotate( src, F(M_PI / 3.0), Vector(.2, .4, 1).normalized(), Point(0.2, .4, .7)); CHECK(dest == VApprox(Point(0.139956, 0.200855, 0.291667))); } }
26.075472
80
0.600579
[ "geometry", "vector", "transform", "3d" ]
38efc4c1faaf59f21ca5b541dd25bc43b57b03ad
462
cpp
C++
codetop/Leetcode121.cpp
Aged-cat/interview_codehub
0d915934a8d89a10943ef3e0ba8e528948433578
[ "MIT" ]
2
2021-09-06T06:47:34.000Z
2022-02-21T04:43:23.000Z
codetop/Leetcode121.cpp
Aged-cat/interview_codehub
0d915934a8d89a10943ef3e0ba8e528948433578
[ "MIT" ]
null
null
null
codetop/Leetcode121.cpp
Aged-cat/interview_codehub
0d915934a8d89a10943ef3e0ba8e528948433578
[ "MIT" ]
null
null
null
#include<iostream> #include<string> #include<map> #include<string.h> #include<vector> #include<algorithm> #include<sstream> #include<climits> using namespace std; int maxProfit(vector<int>& prices) { int preMin=prices[0]; int maxPro=INT32_MIN; for(int i=1;i<prices.size();++i) { int curPro=prices[i]-preMin; maxPro=max(curPro,maxPro); preMin=min(prices[i],preMin); } if(maxPro<0) return 0; return maxPro; }
17.769231
37
0.649351
[ "vector" ]
38f4c37734066eb065e03450ef248e561eb669f9
12,293
hpp
C++
include/puffinn/prefixmap.hpp
mvesterli/puffinn
cefac8aac93f983d82da09953ac990433df0b179
[ "MIT" ]
49
2019-06-28T08:00:35.000Z
2021-10-31T16:01:26.000Z
include/puffinn/prefixmap.hpp
mvesterli/puffinn
cefac8aac93f983d82da09953ac990433df0b179
[ "MIT" ]
7
2019-08-26T07:58:28.000Z
2021-06-07T10:55:08.000Z
include/puffinn/prefixmap.hpp
mvesterli/puffinn
cefac8aac93f983d82da09953ac990433df0b179
[ "MIT" ]
7
2019-08-20T13:50:55.000Z
2022-02-15T10:16:52.000Z
#pragma once #include "puffinn/dataset.hpp" #include "puffinn/hash_source/hash_source.hpp" #include "puffinn/typedefs.hpp" #include "puffinn/performance.hpp" #include <algorithm> #include <cstdint> #include <functional> #include <istream> #include <ostream> #include <utility> #include <vector> namespace puffinn { // A query stores the hash, the current prefix as well as which segment in the map that has // already been searched. struct PrefixMapQuery { // The prefix of the query hash. LshDatatype hash; // Mask used to reduce hashes to the considered prefix. LshDatatype prefix_mask; // The index of the first and one past the last vector in the referenced hashes that share // the searched prefix. uint_fast32_t prefix_start; uint_fast32_t prefix_end; // Construct a query with the hashes precomputed. // // The main purpose is to avoid hashing multiple times. // A reference to the list of hashes is also stored to be able to find the next segment // in the map to process. PrefixMapQuery( LshDatatype hash, const std::vector<LshDatatype>& hashes, uint32_t prefix_index_start, uint32_t prefix_index_end ) : hash(hash) { // given indices are just hints to where it lies between prefix_start = prefix_index_start; prefix_end = prefix_index_end; // inspired by databasearchitects.blogspot.com/2015/09/trying-to-speed-up-binary-search.html uint_fast32_t half = prefix_end-prefix_start; while (half != 0) { half /= 2; uint_fast32_t mid = prefix_start+half; prefix_start = (hashes[mid] < hash ? (mid+1) : prefix_start); } // Initially set to empty segment of index just above the prefix. prefix_end = prefix_start; prefix_mask = 0xffffffff; } }; const static int SEGMENT_SIZE = 12; // A PrefixMap stores all inserted values in sorted order by their hash codes. // // This allows querying all values that share a common prefix. The length of the prefix // can be decreased to look at a larger set of values. When the prefix is decreased, // previously queried values are not queried again. template <typename T> class PrefixMap { using HashedVecIdx = std::pair<uint32_t, LshDatatype>; // Number of bits to precompute locations in the stored vector for. const static int PREFIX_INDEX_BITS = 13; // contents std::vector<uint32_t> indices; std::vector<LshDatatype> hashes; // Scratch space for use when rebuilding. The length and capacity is set to 0 otherwise. std::vector<HashedVecIdx> rebuilding_data; // Length of the hash values used. unsigned int hash_length; std::unique_ptr<Hash> hash_function; // index of the first value with each prefix. // If there is no such value, it is the first higher prefix instead. // Used as a hint for the binary search. uint32_t prefix_index[(1 << PREFIX_INDEX_BITS)+1] = {0}; public: // Construct a new prefix map over the specified dataset using the given hash functions. PrefixMap(std::unique_ptr<Hash> hash, unsigned int hash_length) : hash_length(hash_length), hash_function(std::move(hash)) { // Ensure that the map can be queried even if nothing is inserted. rebuild(); } PrefixMap(std::istream& in, HashSource<T>& source) { size_t len; in.read(reinterpret_cast<char*>(&len), sizeof(size_t)); indices.resize(len); hashes.resize(len); if (len != 0) { in.read(reinterpret_cast<char*>(&indices[0]), len*sizeof(uint32_t)); in.read(reinterpret_cast<char*>(&hashes[0]), len*sizeof(LshDatatype)); } size_t rebuilding_len; in.read(reinterpret_cast<char*>(&rebuilding_len), sizeof(size_t)); rebuilding_data.resize(rebuilding_len); if (rebuilding_len != 0) { in.read( reinterpret_cast<char*>(&rebuilding_data[0]), rebuilding_len*sizeof(HashedVecIdx)); } in.read(reinterpret_cast<char*>(&hash_length), sizeof(unsigned int)); hash_function = source.deserialize_hash(in); in.read( reinterpret_cast<char*>(&prefix_index[0]), ((1 << PREFIX_INDEX_BITS)+1)*sizeof(uint32_t)); } void serialize(std::ostream& out) const { size_t len = indices.size(); out.write(reinterpret_cast<const char*>(&len), sizeof(size_t)); if (len != 0) { out.write(reinterpret_cast<const char*>(&indices[0]), len*sizeof(uint32_t)); out.write(reinterpret_cast<const char*>(&hashes[0]), len*sizeof(LshDatatype)); } size_t rebuilding_len = rebuilding_data.size(); out.write(reinterpret_cast<const char*>(&rebuilding_len), sizeof(size_t)); if (rebuilding_len != 0) { out.write( reinterpret_cast<const char*>(&rebuilding_data[0]), rebuilding_len*sizeof(HashedVecIdx)); } out.write(reinterpret_cast<const char*>(&hash_length), sizeof(unsigned int)); hash_function->serialize(out); out.write(reinterpret_cast<const char*>( &prefix_index), ((1 << PREFIX_INDEX_BITS)+1)*sizeof(uint32_t)); } // Add a vector to be included next time rebuild is called. // Expects that the hash source was last reset with that vector. void insert(uint32_t idx, HashSourceState* hash_state) { rebuilding_data.push_back({ idx, (*hash_function)(hash_state) }); } // Reserve the correct amount of memory before inserting. void reserve(size_t size) { if (hashes.size() == 0) { rebuilding_data.reserve(size); } else { rebuilding_data.reserve(size-(hashes.size()-2*SEGMENT_SIZE)); } } void rebuild() { // A value whose prefix will never match that of a query vector, as long as less than 32 // hash bits are used. static const LshDatatype IMPOSSIBLE_PREFIX = 0xffffffff; rebuilding_data.reserve(hashes.size()+rebuilding_data.size()); if (hashes.size() != 0) { // Move data to temporary vector for sorting. for (size_t i=SEGMENT_SIZE; i < hashes.size()-SEGMENT_SIZE; i++) { rebuilding_data.push_back({ indices[i], hashes[i] }); } } std::sort( rebuilding_data.begin(), rebuilding_data.end(), [](HashedVecIdx& a, HashedVecIdx& b) { return a.second < b.second; } ); std::vector<LshDatatype> new_hashes; new_hashes.reserve(rebuilding_data.size()+2*SEGMENT_SIZE); std::vector<uint32_t> new_indices; new_indices.reserve(rebuilding_data.size()+2*SEGMENT_SIZE); // Pad with SEGMENT_SIZE values on each size to remove need for bounds check. for (int i=0; i < SEGMENT_SIZE; i++) { new_hashes.push_back(IMPOSSIBLE_PREFIX); new_indices.push_back(0); } for (auto v : rebuilding_data) { new_indices.push_back(v.first); new_hashes.push_back(v.second); } for (int i=0; i < SEGMENT_SIZE; i++) { new_hashes.push_back(IMPOSSIBLE_PREFIX); new_indices.push_back(0); } hashes = std::move(new_hashes); indices = std::move(new_indices); // Build prefix_index data structure. // Index of the first occurence of the prefix uint32_t idx = 0; for (unsigned int prefix=0; prefix < (1u << PREFIX_INDEX_BITS); prefix++) { while ( idx < rebuilding_data.size() && (hashes[SEGMENT_SIZE+idx] >> (hash_length-PREFIX_INDEX_BITS)) < prefix ) { idx++; } prefix_index[prefix] = SEGMENT_SIZE+idx; } prefix_index[1 << PREFIX_INDEX_BITS] = SEGMENT_SIZE+rebuilding_data.size(); rebuilding_data.clear(); rebuilding_data.shrink_to_fit(); } // Construct a query object to search for the nearest neighbors of the given vector. PrefixMapQuery create_query(HashSourceState* hash_state) const { g_performance_metrics.start_timer(Computation::Hashing); auto hash = (*hash_function)(hash_state); g_performance_metrics.store_time(Computation::Hashing); g_performance_metrics.start_timer(Computation::CreateQuery); auto prefix = hash >> (hash_length-PREFIX_INDEX_BITS); PrefixMapQuery res( hash, hashes, prefix_index[prefix], prefix_index[prefix+1]); g_performance_metrics.store_time(Computation::CreateQuery); return res; } // Reduce the length of the prefix by one and retrieve the range of indices that should // be considered next. // Assumes that everything in the current prefix is already searched. This is not true // in the first iteration, but will be after there has been a search each way. // As most queries need multiple iterations, this should not be a problem. std::pair<const uint32_t*, const uint32_t*> get_next_range(PrefixMapQuery& query) const { auto prev_mask = (query.prefix_mask >> 1); auto removed_bit = prev_mask & (-prev_mask); // Least significant bit // The value of the removed bit. // If a 0-bit is removed, search upwards, otherwise downwards. // (Since we need to include all values with 1-bits, which are above) // In the first iteration, where no bit is removed, this is 0. auto bit_value = query.hash & removed_bit; auto hash_prefix = (query.hash & query.prefix_mask); if (bit_value == 0) { auto next_idx = query.prefix_end; auto start_idx = next_idx; while ((hashes[next_idx] & query.prefix_mask) == hash_prefix) { next_idx += SEGMENT_SIZE; } auto end_idx = next_idx; if (end_idx >= indices.size()-SEGMENT_SIZE) { // Adjust the range so that no values in the padding are checked // However, next time the padding is reached it would cause end_idx < start_idx end_idx = std::max(start_idx, end_idx-SEGMENT_SIZE); } query.prefix_mask <<= 1; return std::make_pair(&indices[start_idx], &indices[end_idx]); } else { auto next_idx = query.prefix_start-1; auto end_idx = next_idx+1; while ((hashes[next_idx] & query.prefix_mask) == hash_prefix) { next_idx -= SEGMENT_SIZE; } auto start_idx = next_idx+1; if (start_idx < SEGMENT_SIZE) { start_idx = std::min(end_idx, start_idx+SEGMENT_SIZE); } query.prefix_mask <<= 1; return std::make_pair(&indices[start_idx], &indices[end_idx]); } } static uint64_t memory_usage(size_t size, uint64_t function_size) { size = size+2*SEGMENT_SIZE; return sizeof(PrefixMap) + size*sizeof(uint32_t) + size*sizeof(LshDatatype) + function_size; } }; }
42.389655
104
0.575612
[ "object", "vector" ]
ac029fc8af3b4ed03a85826f3a06d2e8a1ffb36a
1,545
cpp
C++
nurbs++-3.0.11/nurbs++-3.0.11/nurbs/d_nurbsS.cpp
Ophien/H-GM-Humanoid-Robot-Real-Time-Trajectory-Manipulator
febe9e0f6b55a7eb25f1bf83fb9f6bc896bf9323
[ "MIT" ]
null
null
null
nurbs++-3.0.11/nurbs++-3.0.11/nurbs/d_nurbsS.cpp
Ophien/H-GM-Humanoid-Robot-Real-Time-Trajectory-Manipulator
febe9e0f6b55a7eb25f1bf83fb9f6bc896bf9323
[ "MIT" ]
null
null
null
nurbs++-3.0.11/nurbs++-3.0.11/nurbs/d_nurbsS.cpp
Ophien/H-GM-Humanoid-Robot-Real-Time-Trajectory-Manipulator
febe9e0f6b55a7eb25f1bf83fb9f6bc896bf9323
[ "MIT" ]
null
null
null
#include "nurbsS.cpp" namespace PLib { #ifdef NO_IMPLICIT_TEMPLATES // double instantiation template class NurbsSurface<double,3> ; template void gordonSurface(NurbsCurveArray<double,3>& lU, NurbsCurveArray<double,3>& lV, const Matrix< Point_nD<double,3> >& intersections, NurbsSurface<double,3>& gS); template int surfMeshParams(const Matrix< Point_nD<double,3> >& Q, Vector<double>& uk, Vector<double>& vl); template int surfMeshParamsH(const Matrix< HPoint_nD<double,3> >& Q, Vector<double>& uk, Vector<double>& vl); template int surfMeshParamsClosedU(const Matrix< Point_nD<double,3> >& Q, Vector<double>& uk, Vector<double>& vl, int degU); template int surfMeshParamsClosedUH(const Matrix< HPoint_nD<double,3> >& Q, Vector<double>& uk, Vector<double>& vl, int degU); template void globalSurfInterpXY(const Matrix< Point_nD<double,3> >& Q, int pU, int pV, NurbsSurface<double,3>& S); template void globalSurfInterpXY(const Matrix< Point_nD<double,3> >& Q, int pU, int pV, NurbsSurface<double,3>& S, const Vector<double>& uk, const Vector<double>& vk); template void globalSurfApprox(const Matrix< Point_nD<double,3> >& Q, int pU, int pV, NurbsSurface<double,3>& S, double error); template void projectToLine(const Point_nD<double,3>& S, const Point_nD<double,3>& Trj, const Point_nD<double,3>& pnt, Point_nD<double,3>& p) ; template void wrapPointMatrix(const Matrix< Point_nD<double,3> >& Q, int d, int dir, Matrix< Point_nD<double,3> >& Qw); template class OpAreaFcn<double,3> ; template class OpAreaAuxFcn<double,3> ; #endif }
51.5
169
0.750809
[ "vector" ]
f19d407ed3a80815271f40ce4333e79555f81fde
1,230
hpp
C++
PSE/include/base_flow.hpp
srharris91/OrrSommerfeld_Squire
92a1dcdc8e982238c7ed8f287622293f9cc60e73
[ "MIT" ]
null
null
null
PSE/include/base_flow.hpp
srharris91/OrrSommerfeld_Squire
92a1dcdc8e982238c7ed8f287622293f9cc60e73
[ "MIT" ]
null
null
null
PSE/include/base_flow.hpp
srharris91/OrrSommerfeld_Squire
92a1dcdc8e982238c7ed8f287622293f9cc60e73
[ "MIT" ]
1
2020-09-25T15:09:43.000Z
2020-09-25T15:09:43.000Z
#ifndef BASE_FLOW_H #define BASE_FLOW_H #include <petscksp.h> namespace PSE { /** * \brief set plane channel flow velocity variables U, U' and U'' * \usage use this once to set the vectors with the velocity of plane channel flow (max u=1) * \return 0 if successful */ int base_flow( PetscScalar U[], ///< [out] velocity along channel axis PetscScalar Uy[], ///< [out] first derivative of velocity const PetscScalar y[], ///< [in] input y vector (usually linspace(-1,1,n) const PetscInt &n ///< [in] size of vectors ); /** * \brief set plane channel flow velocity variables U, U' and U'' * \usage use this once to set the vectors with the velocity of plane channel flow (max u=1) * \return 0 if successful */ int base_flow( Mat &U, ///< [out] velocity along channel axis (uninitialized) Mat &Uy, ///< [out] first derivative of velocity (uninitialized) const PetscScalar y[], ///< [in] input y vector (usually linspace(-1,1,n) const PetscInt &n ///< [in] size of vectors ); } #endif
39.677419
96
0.558537
[ "vector" ]
f1a051412ca14ca41879ce31c938a600fec619d4
3,076
cpp
C++
libraries/scripts/data_gen/cor_mruby_cor_mruby_interface_inc.cpp
rmake/cor-engine
d8920325db490d19dc8c116ab8e9620fe55e9975
[ "MIT" ]
4
2015-01-13T09:55:02.000Z
2016-09-10T03:42:23.000Z
libraries/scripts/data_gen/cor_mruby_cor_mruby_interface_inc.cpp
rmake/cor-engine
d8920325db490d19dc8c116ab8e9620fe55e9975
[ "MIT" ]
null
null
null
libraries/scripts/data_gen/cor_mruby_cor_mruby_interface_inc.cpp
rmake/cor-engine
d8920325db490d19dc8c116ab8e9620fe55e9975
[ "MIT" ]
2
2015-01-22T02:30:29.000Z
2021-05-10T06:56:49.000Z
#undef __SSE__ #define BOOST_VARIANT_HPP #include "../../cor_type/sources/basic_types.h" #include "../../cor_type/sources/collision/collision_2d.h" #include "../../cor_type/sources/collision/collision_2d_tmpl.h" #include "../../cor_type/sources/cor_type.h" #include "../../cor_type/sources/math/matrix4x4.h" #include "../../cor_type/sources/math/matrix4x4_tmpl.h" #include "../../cor_type/sources/math/vector2.h" #include "../../cor_type/sources/math/vector2_tmpl.h" #include "../../cor_type/sources/math/vector3.h" #include "../../cor_type/sources/math/vector3_tmpl.h" #include "../../cor_type/sources/math/vector4.h" #include "../../cor_type/sources/math/vector4_tmpl.h" #include "../../cor_type/sources/primitive/box.h" #include "../../cor_type/sources/primitive/box_tmpl.h" #include "../../cor_type/sources/primitive/o_box.h" #include "../../cor_type/sources/primitive/o_box_tmpl.h" #include "../../cor_type/sources/primitive/o_sphere.h" #include "../../cor_type/sources/primitive/o_sphere_tmpl.h" #include "../../cor_type/sources/primitive/sphere.h" #include "../../cor_type/sources/primitive/sphere_tmpl.h" #include "../../cor_data_structure/sources/ai/cost_grid_space.h" #include "../../cor_data_structure/sources/ai/cost_grid_space_tmpl.h" #include "../../cor_data_structure/sources/ai/priority_queue.h" #include "../../cor_data_structure/sources/ai/priority_queue_tmpl.h" #include "../../cor_data_structure/sources/ai/stack_decoder.h" #include "../../cor_data_structure/sources/ai/stack_decoder_tmpl.h" #include "../../cor_data_structure/sources/array_pool.h" #include "../../cor_data_structure/sources/array_pool_tmpl.h" #include "../../cor_data_structure/sources/basic/shared_ptr_table.h" #include "../../cor_data_structure/sources/geometry/r_tree_pool.h" #include "../../cor_data_structure/sources/geometry/r_tree_pool_tmpl.h" #include "../../cor_data_structure/sources/geometry/uniform_grid.h" #include "../../cor_data_structure/sources/geometry/uniform_grid_tmpl.h" #include "../../cor_data_structure/sources/tree_pool.h" #include "../../cor_data_structure/sources/tree_pool_tmpl.h" #include "../../cor_algorithm/sources/bit_operation.h" #include "../../cor_algorithm/sources/bit_operation_tmpl.h" #include "../../cor_algorithm/sources/utilities.h" #include "../../cor_algorithm/sources/utilities_tmpl.h" #include "../../cor_system/sources/allocation_monitor.h" #include "../../cor_system/sources/cor_crypt.h" #include "../../cor_system/sources/cor_time.h" #include "../../cor_system/sources/job_queue.h" #include "../../cor_system/sources/logger.h" #include "../../cor_system/sources/parallel_processor.h" #include "../../cor_system/sources/thread_pool.h" #include "../../cor_mruby_interface/sources/basic_bind.h" #include "../../cor_mruby_interface/sources/mruby_array.h" #include "../../cor_mruby_interface/sources/mruby_array_tmpl.h" #include "../../cor_mruby_interface/sources/mruby_experimental.h" #include "../../cor_mruby_interface/sources/mruby_ref_container.h" #include "../../cor_mruby_interface/sources/mruby_state.h" #undef RELATIVE #undef ABSOLUTE
53.964912
72
0.75
[ "geometry" ]
f1a6a93f124b9a7115bd0d757bd6d86fc9e229c8
5,846
cpp
C++
iotvideo/src/v20191126/model/SystemType.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
iotvideo/src/v20191126/model/SystemType.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
iotvideo/src/v20191126/model/SystemType.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/iotvideo/v20191126/model/SystemType.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Iotvideo::V20191126::Model; using namespace std; SystemType::SystemType() : m_androidHasBeenSet(false), m_linuxHasBeenSet(false), m_liteOsHasBeenSet(false) { } CoreInternalOutcome SystemType::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("Android") && !value["Android"].IsNull()) { if (!value["Android"].IsArray()) return CoreInternalOutcome(Core::Error("response `SystemType.Android` is not array type")); const rapidjson::Value &tmpValue = value["Android"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { OsData item; CoreInternalOutcome outcome = item.Deserialize(*itr); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_android.push_back(item); } m_androidHasBeenSet = true; } if (value.HasMember("Linux") && !value["Linux"].IsNull()) { if (!value["Linux"].IsArray()) return CoreInternalOutcome(Core::Error("response `SystemType.Linux` is not array type")); const rapidjson::Value &tmpValue = value["Linux"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { OsData item; CoreInternalOutcome outcome = item.Deserialize(*itr); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_linux.push_back(item); } m_linuxHasBeenSet = true; } if (value.HasMember("LiteOs") && !value["LiteOs"].IsNull()) { if (!value["LiteOs"].IsArray()) return CoreInternalOutcome(Core::Error("response `SystemType.LiteOs` is not array type")); const rapidjson::Value &tmpValue = value["LiteOs"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { OsData item; CoreInternalOutcome outcome = item.Deserialize(*itr); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_liteOs.push_back(item); } m_liteOsHasBeenSet = true; } return CoreInternalOutcome(true); } void SystemType::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_androidHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Android"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); int i=0; for (auto itr = m_android.begin(); itr != m_android.end(); ++itr, ++i) { value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator); (*itr).ToJsonObject(value[key.c_str()][i], allocator); } } if (m_linuxHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Linux"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); int i=0; for (auto itr = m_linux.begin(); itr != m_linux.end(); ++itr, ++i) { value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator); (*itr).ToJsonObject(value[key.c_str()][i], allocator); } } if (m_liteOsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "LiteOs"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); int i=0; for (auto itr = m_liteOs.begin(); itr != m_liteOs.end(); ++itr, ++i) { value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator); (*itr).ToJsonObject(value[key.c_str()][i], allocator); } } } vector<OsData> SystemType::GetAndroid() const { return m_android; } void SystemType::SetAndroid(const vector<OsData>& _android) { m_android = _android; m_androidHasBeenSet = true; } bool SystemType::AndroidHasBeenSet() const { return m_androidHasBeenSet; } vector<OsData> SystemType::GetLinux() const { return m_linux; } void SystemType::SetLinux(const vector<OsData>& _linux) { m_linux = _linux; m_linuxHasBeenSet = true; } bool SystemType::LinuxHasBeenSet() const { return m_linuxHasBeenSet; } vector<OsData> SystemType::GetLiteOs() const { return m_liteOs; } void SystemType::SetLiteOs(const vector<OsData>& _liteOs) { m_liteOs = _liteOs; m_liteOsHasBeenSet = true; } bool SystemType::LiteOsHasBeenSet() const { return m_liteOsHasBeenSet; }
29.525253
107
0.625556
[ "vector", "model" ]
f1ac955a9381aad629d1e8973cbab7e327ea10d6
362
cpp
C++
chap12/Page473_weak_ptr.cpp
sjbarigye/CPP_Primer
d9d31a73a45ca46909bae104804fc9503ab242f2
[ "Apache-2.0" ]
50
2016-01-08T14:28:53.000Z
2022-01-21T12:55:00.000Z
chap12/Page473_weak_ptr.cpp
sjbarigye/CPP_Primer
d9d31a73a45ca46909bae104804fc9503ab242f2
[ "Apache-2.0" ]
2
2017-06-05T16:45:20.000Z
2021-04-17T13:39:24.000Z
chap12/Page473_weak_ptr.cpp
sjbarigye/CPP_Primer
d9d31a73a45ca46909bae104804fc9503ab242f2
[ "Apache-2.0" ]
18
2016-08-17T15:23:51.000Z
2022-03-26T18:08:43.000Z
#include <memory> using std::make_shared; using std::shared_ptr; using std::weak_ptr; int main() { shared_ptr<int> sp = make_shared<int>(42); weak_ptr<int> wp(sp); if(shared_ptr<int> np = wp.lock()) //true if np is not null, an artful way to use condition {// inside if, np shares its object with sp // do something } return 0; }
24.133333
95
0.643646
[ "object" ]
f1b1e3661e46ac342439a159a93a1788a5399a0c
1,814
cpp
C++
test/LogFileHelperTest.cpp
rock-cpp/new_rock_replay
bc24c181b589533037e626b9361597bf1bf1170f
[ "BSD-3-Clause" ]
null
null
null
test/LogFileHelperTest.cpp
rock-cpp/new_rock_replay
bc24c181b589533037e626b9361597bf1bf1170f
[ "BSD-3-Clause" ]
null
null
null
test/LogFileHelperTest.cpp
rock-cpp/new_rock_replay
bc24c181b589533037e626b9361597bf1bf1170f
[ "BSD-3-Clause" ]
null
null
null
#include "LogFileHelper.hpp" #include "FileLocationHandler.hpp" #include <boost/test/unit_test.hpp> #include <iostream> const std::string logFolder = getLogFilePath(); void testParser(const std::vector<std::string>& args, uint64_t size) { auto fileNames = LogFileHelper::parseFileNames(args); BOOST_TEST(fileNames.size() == size); } void testStreamSplit(const std::string& input, const std::string& firstPart, const std::string& secondPart) { const auto namePair = LogFileHelper::splitStreamName(input); BOOST_TEST(namePair.first == firstPart); BOOST_TEST(namePair.second == secondPart); } BOOST_AUTO_TEST_CASE(TestLogfileParserFilenames) { std::vector<std::string> cmdLineArgs = {logFolder + "trajectory_follower_Logger.0.log", "non_existing"}; testParser(cmdLineArgs, 1); } BOOST_AUTO_TEST_CASE(TestLogfileParserFolder) { std::vector<std::string> cmdLineArgs = {logFolder}; testParser(cmdLineArgs, 4); } BOOST_AUTO_TEST_CASE(TestLogfileParserEmpty) { std::vector<std::string> cmdLineArgs = {""}; testParser(cmdLineArgs, 0); } BOOST_AUTO_TEST_CASE(TestStreamNameSplitSingleDot) { const std::string first = "trajectory_follower"; const std::string second = "my_port"; testStreamSplit(first + "." + second, first, second); } BOOST_AUTO_TEST_CASE(TestStreamNameSplitMultiDot) { const std::string first = "trajectory_follower.my_port"; const std::string second = "my_member"; testStreamSplit(first + "." + second, first, second); } BOOST_AUTO_TEST_CASE(TestStreamNameSplitSlash) { const std::string first = "trajectory_follower.my_port/nested"; const std::string second = "my_member"; testStreamSplit(first + "." + second, first, second); } BOOST_AUTO_TEST_CASE(TestStreamNameEmpty) { testStreamSplit("", "", ""); }
25.549296
108
0.729879
[ "vector" ]
f1b202403f195dbf84642852606f10ee1700a8f9
999
cpp
C++
BOJ_solve/14412.cpp
python-programmer1512/Code_of_gunwookim
e72e6724fb9ee6ccf2e1064583956fa954ba0282
[ "MIT" ]
4
2021-01-27T11:51:30.000Z
2021-01-30T17:02:55.000Z
BOJ_solve/14412.cpp
python-programmer1512/Code_of_gunwookim
e72e6724fb9ee6ccf2e1064583956fa954ba0282
[ "MIT" ]
null
null
null
BOJ_solve/14412.cpp
python-programmer1512/Code_of_gunwookim
e72e6724fb9ee6ccf2e1064583956fa954ba0282
[ "MIT" ]
5
2021-01-27T11:46:12.000Z
2021-05-06T05:37:47.000Z
#include <bits/stdc++.h> #define x first #define y second #define pb push_back #define all(v) v.begin(),v.end() #pragma gcc optimize("O3") #pragma gcc optimize("Ofast") #pragma gcc optimize("unroll-loops") using namespace std; const int INF = 1e9; const long long llINF = 1e18; //long long mod; typedef long long ll; typedef long double ld; typedef pair <int,int> pi; typedef pair <ll,ll> pl; typedef vector <int> vec; typedef vector <pi> vecpi; typedef long long ll; int n,m,a[1005][1005]; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cin >> n >> m; for(int i = 1;i <= m;i++) { int x,y; cin >> x >> y; a[x][y] = a[y][x] = 1; } for(int i = 2;i <= n;i++) { if(!a[1][i]) { for(int j = 1;j <= n;j++) { if(i == j) continue; if(a[i][j]) a[i][j] = a[j][i] = 0; else a[i][j] = a[j][i] = 1; } } } for(int i = 1;i <= n;i++) { int cnt = 0; for(int j = 1;j <= n;j++) cnt += a[i][j]; if(cnt != n-1) { cout << "NE"; return 0; } } cout << "DA"; }
21.255319
46
0.551552
[ "vector" ]
f1b6cb060b76ba7d0832ac016b701da5637f9920
4,938
cpp
C++
rootex/vendor/Rlottie/rlottie/example/lottieperf.cpp
ChronicallySerious/Rootex
bf2a0997b6aa5be84dbfc0e7826c31ff693ca0f1
[ "MIT" ]
166
2019-06-19T19:51:45.000Z
2022-03-24T13:03:29.000Z
rootex/vendor/Rlottie/rlottie/example/lottieperf.cpp
rahil627/Rootex
44f827d469bddc7167b34dedf80d7a8b984fdf20
[ "MIT" ]
312
2019-06-13T19:39:25.000Z
2022-03-02T18:37:22.000Z
rootex/vendor/Rlottie/rlottie/example/lottieperf.cpp
rahil627/Rootex
44f827d469bddc7167b34dedf80d7a8b984fdf20
[ "MIT" ]
23
2019-10-04T11:02:21.000Z
2021-12-24T16:34:52.000Z
#include <memory> #include <vector> #include <dirent.h> #include <algorithm> #include <chrono> #include <iostream> #include <cstring> #include <rlottie.h> static bool isJsonFile(const char *filename) { const char *dot = strrchr(filename, '.'); if(!dot || dot == filename) return false; return !strcmp(dot + 1, "json"); } static std::vector<std::string> jsonFiles(const std::string &dirName) { DIR *d; struct dirent *dir; std::vector<std::string> result; d = opendir(dirName.c_str()); if (d) { while ((dir = readdir(d)) != NULL) { if (isJsonFile(dir->d_name)) result.push_back(dirName + dir->d_name); } closedir(d); } std::sort(result.begin(), result.end(), [](auto & a, auto &b){return a < b;}); return result; } class Renderer { public: explicit Renderer(const std::string& filename) { _animation = rlottie::Animation::loadFromFile(filename); _frames = _animation->totalFrame(); _buffer = std::make_unique<uint32_t[]>(100 * 100); _surface = rlottie::Surface(_buffer.get(), 100, 100, 100 * 4); } void render() { if (_cur >= _frames) _cur = 0; _animation->renderSync(_cur++, _surface); } void renderAsync() { if (_cur >= _frames) _cur = 0; _future = _animation->render(_cur++, _surface); } void get() { if (_future.valid()) _future.get(); } private: std::unique_ptr<uint32_t[]> _buffer; std::unique_ptr<rlottie::Animation> _animation; size_t _frames{0}; size_t _cur{0}; rlottie::Surface _surface; std::future<rlottie::Surface> _future; }; class PerfTest { public: explicit PerfTest(size_t resourceCount, size_t iterations): _resourceCount(resourceCount), _iterations(iterations) { _resourceList = jsonFiles(std::string(DEMO_DIR)); } void test(bool async) { setup(); std::cout<<" Test Started : .... \n"; auto start = std::chrono::high_resolution_clock::now(); benchmark(async); std::chrono::duration<double> secs = std::chrono::high_resolution_clock::now() - start; std::chrono::duration<double, std::milli> millisecs = secs; std::cout<< " Test Finished.\n"; std::cout<< " \nPerformance Report: \n\n"; std::cout<< " \t Resource Rendered per Frame : "<< _resourceCount <<"\n"; std::cout<< " \t Render Buffer Size : (100 X 100) \n"; std::cout<< " \t Render Mode : "<< (async ? "Async" : "Sync")<<"\n"; std::cout<< " \t Total Frames Rendered : "<< _iterations<<"\n"; std::cout<< " \t Total Render Time : "<< secs.count()<<"sec\n"; std::cout<< " \t Avrage Time per Resource : "<< millisecs.count() / (_iterations * _resourceCount)<<"ms\n"; std::cout<< " \t Avrage Time Per Frame : "<< millisecs.count() / _iterations <<"ms\n"; std::cout<< " \t FPS : "<< _iterations / secs.count() <<"fps\n\n"; } private: void setup() { for (auto i = 0u; i < _resourceCount; i++) { auto index = i % _resourceList.size(); _renderers.push_back(std::make_unique<Renderer>(_resourceList[index])); } } void benchmark(bool async) { for (auto i = 0u; i < _iterations; i++) { if (async) { for (const auto &e : _renderers) e->renderAsync(); for (const auto &e : _renderers) e->get(); } else { for (const auto &e : _renderers) e->render(); } } } private: size_t _resourceCount; size_t _iterations; std::vector<std::string> _resourceList; std::vector<std::unique_ptr<Renderer>> _renderers; }; static int help() { std::cout<<"\nUsage : ./perf [--sync] [-c] [resource count] [-i] [iteration count] \n"; std::cout<<"\nExample : ./perf -c 50 -i 100 \n"; std::cout<<"\n\t runs perf test for 100 iterations. renders 50 resource per iteration\n\n"; return 0; } int main(int argc, char ** argv) { bool async = true; size_t resourceCount = 250; size_t iterations = 500; auto index = 0; while (index < argc) { const char* option = argv[index]; index++; if (!strcmp(option,"--help") || !strcmp(option,"-h")) { return help(); } else if (!strcmp(option,"--sync")) { async = false; } else if (!strcmp(option,"-c")) { resourceCount = (index < argc) ? atoi(argv[index]) : resourceCount; index++; } else if (!strcmp(option,"-i")) { iterations = (index < argc) ? atoi(argv[index]) : iterations; index++; } } PerfTest obj(resourceCount, iterations); obj.test(async); return 0; }
30.670807
118
0.548198
[ "render", "vector" ]
f1b9324d2beb7fa0ff462f1613525509c1010cf4
1,665
hpp
C++
src/profiling/ProfilingConnectionDumpToFileDecorator.hpp
sahilbandar/armnn
249950645b7bc0593582182097c7e2f1d6d97442
[ "MIT" ]
856
2018-03-09T17:26:23.000Z
2022-03-24T21:31:33.000Z
src/profiling/ProfilingConnectionDumpToFileDecorator.hpp
Elm8116/armnn
e571cde8411803aec545b1070ed677e481f46f3f
[ "MIT" ]
623
2018-03-13T04:40:42.000Z
2022-03-31T09:45:17.000Z
src/profiling/ProfilingConnectionDumpToFileDecorator.hpp
Elm8116/armnn
e571cde8411803aec545b1070ed677e481f46f3f
[ "MIT" ]
284
2018-03-09T23:05:28.000Z
2022-03-29T14:42:28.000Z
// // Copyright © 2019 Arm Ltd and Contributors. All rights reserved. // SPDX-License-Identifier: MIT // #pragma once #include "IProfilingConnection.hpp" #include "ProfilingUtils.hpp" #include <Runtime.hpp> #include <armnn/Optional.hpp> #include <fstream> #include <memory> #include <string> #include <vector> namespace armnn { namespace profiling { class ProfilingConnectionDumpToFileDecorator : public IProfilingConnection { public: ProfilingConnectionDumpToFileDecorator(std::unique_ptr<IProfilingConnection> connection, const IRuntime::CreationOptions::ExternalProfilingOptions& options, bool ignoreFailures = false); ~ProfilingConnectionDumpToFileDecorator(); bool IsOpen() const override; void Close() override; bool WritePacket(const unsigned char* buffer, uint32_t length) override; arm::pipe::Packet ReadPacket(uint32_t timeout) override; private: bool OpenIncomingDumpFile(); bool OpenOutgoingDumpFile(); void DumpIncomingToFile(const arm::pipe::Packet& packet); bool DumpOutgoingToFile(const unsigned char* buffer, uint32_t length); void Fail(const std::string& errorMessage); std::unique_ptr<IProfilingConnection> m_Connection; IRuntime::CreationOptions::ExternalProfilingOptions m_Options; std::ofstream m_IncomingDumpFileStream; std::ofstream m_OutgoingDumpFileStream; bool m_IgnoreFileErrors; }; } // namespace profiling } // namespace armnn
26.015625
110
0.663664
[ "vector" ]
f1c075d558b32da69445cf7e73aa849061800b62
13,460
cpp
C++
VehiclePhysicsSim/src/Track.cpp
lbowes/A-Level-Computer-Science-NEA
0dd3f15a0b22a6622a962381089e8353c330680f
[ "MIT" ]
3
2019-09-07T02:05:47.000Z
2019-12-11T08:53:44.000Z
VehiclePhysicsSim/src/Track.cpp
lbowes/vehicle-dynamics-simulation
0dd3f15a0b22a6622a962381089e8353c330680f
[ "MIT" ]
null
null
null
VehiclePhysicsSim/src/Track.cpp
lbowes/vehicle-dynamics-simulation
0dd3f15a0b22a6622a962381089e8353c330680f
[ "MIT" ]
null
null
null
#include "Track.h" #define CIRCULAR_TRACK 0 #define COMPLEX_TRACK 1 #define SQUARE_TRACK 0 #define ALMOST_SQUARE_TRACK 0 #define P_SHAPED_TRACK 0 namespace External { Track::Track(const unsigned int terrainSize_heightSamples) : /* Called by Terrain::Terrain * Prepares the class for runHeights and runSurfaceTypes to be called, by running a pilot version of the track generation algorithm */ mTerrainSize_heightSamples(terrainSize_heightSamples) { mTempSurfaceTypes.resize(pow(terrainSize_heightSamples - 1, 2) * 2); addAllPoints(); runPilotVersion(); mSizeLimit = (mTerrainSize_heightSamples - 1) - (2 * mTerrainBorderPadding) - mWidth; mPilotToMainScaleFactor = mSizeLimit / std::max(mPilotResults.mShapeDimensions.x, mPilotResults.mShapeDimensions.y); updateStartingPosition(); } void Track::runHeights(std::vector<double>& previousLayerHeights) /* Called by Terrain::generateHeightData * Adds the track shape to the terrain height buffer passed in */ { const int terrainSize = sqrt(previousLayerHeights.size()), halfTerrainSize = 0.5 * terrainSize; int currentX = 0, currentZ = 0, lastX = 0, lastZ = 0; double currentAngle = 0.0; glm::dvec2 positionTracker = mStartPosition, currentDirection = mStartDirection; //Iterate over the shape of the track by taking small steps along a changing direction vector for (unsigned int i = 0; i < mNumSamplesOverTotal; i++) { //Look up the angle of the 2D direction vector, clockwise from the -Z axis, at the current position on the track currentAngle = lookUpAngleAtPercent_graph((double)i / (double)mNumSamplesOverTotal); //Create a direction (unit) vector using this angle currentDirection = normalize(glm::rotate(mStartDirection, glm::radians(currentAngle))); //Take a step along the vector positionTracker += currentDirection * mPilotToMainScaleFactor; //If the track could sit inside the terrain at our position after taking this step... if ( positionTracker.x > (-halfTerrainSize - 0.5 * mWidth) && positionTracker.x < (halfTerrainSize + 0.5 * mWidth) && positionTracker.y >(-halfTerrainSize - 0.5 * mWidth) && positionTracker.y < (halfTerrainSize + 0.5 * mWidth)) { //...then find the terrain square that our current position lies within currentX = floor(positionTracker.x); currentZ = floor(positionTracker.y); //If this is different to the previous square... if (currentX != lastX || currentZ != lastZ) { //...then imprint/'stamp' a circle with the track width as its diameter around this point and continue imprintCircle(previousLayerHeights, currentX, currentZ); lastX = currentX; lastZ = currentZ; } } else continue; } } void Track::runSurfaceTypes(std::vector<unsigned char>& previousLayerSurfaceTypes) /* Called by Terrain::generateSurfaceTypeData * Sets the terrain surface types for the track */ { //To avoid unnecessarily iterating over the track twice, mTempSurfaceTypes is filled DURING the height iteration and then //just copied into previousLayerSurfaceTypes here. previousLayerSurfaceTypes = mTempSurfaceTypes; } void Track::addAllPoints() /* Called by Track::Track * Defines the shape of a continuous loop (independent of position, orientation or scale) */ { //The angle of the tangent to the track (clockwise from the starting direction) is a function of the percentage along the track. //Points are added to a graph of this function, and linear interpolation between them is used to make it continuous. mPoints_graph.push_back(glm::dvec2(0.0, 0.0)); //Multiple track shapes were used during testing, but 'COMPLEX_TRACK' is the final version used //in the application #if COMPLEX_TRACK double pi = glm::pi<double>(), total = 0.0, L = 6.0 + (21.0 / 2.0) * pi; total += 0.5 * pi; addPoint_graph(total / L, 90.0); //b total += 3.0; addPoint_graph(total / L, 90.0); //c total += (3.0 / 2.0) * pi; addPoint_graph(total / L, 180.0); //d total += pi; addPoint_graph(total / L, 270.0); //e total += 0.5 * pi; addPoint_graph(total / L, 360.0); //f total += pi; addPoint_graph(total / L, 270.0); //g total += 0.5 * pi; addPoint_graph(total / L, 180.0); //h total += 0.5 * pi; addPoint_graph(total / L, 90.0); //i total += 0.5 * pi; addPoint_graph(total / L, 180.0); //j total += 3; addPoint_graph(total / L, 180.0); //k total += 0.5 * pi; addPoint_graph(total / L, 270.0); //l total += 0.5 * pi; addPoint_graph(total / L, 360.0); //m total += (3.0 / 2.0) * pi; addPoint_graph(total / L, 270.0); //n total += 0.5 * pi; addPoint_graph(total / L, 360.0); //o total += pi; addPoint_graph(total / L, 90.0); //p #endif #if P_SHAPED_TRACK addPoint_graph(0.242597, 180); addPoint_graph(0.485194, 0); addPoint_graph(0.588155, 0); addPoint_graph(0.588155, 270); addPoint_graph(0.897039, 270); addPoint_graph(0.897039, 180); addPoint_graph(1, 180); #endif #if ALMOST_SQUARE_TRACK addPoint_graph(0.25, 0); addPoint_graph(0.25, 90); addPoint_graph(0.375, 90); addPoint_graph(0.375, 180); addPoint_graph(0.5, 180); addPoint_graph(0.5, 90); addPoint_graph(0.625, 90); addPoint_graph(0.625, 180); addPoint_graph(0.75, 180); addPoint_graph(0.75, 270); addPoint_graph(1, 270); #endif #if SQUARE_TRACK addPoint_graph(0.25, 0.0); addPoint_graph(0.25, 90.0); addPoint_graph(0.5, 90.0); addPoint_graph(0.5, 180.0); addPoint_graph(0.75, 180.0); addPoint_graph(0.75, 270.0); addPoint_graph(1.0, 270.0); #endif mPoints_graph.push_back(glm::dvec2(1.0, 360.0)); } void Track::addPoint_graph(double percent, double angle) /* Called by Track::addAllPoints */ { if (percent >= 0.0 && percent <= 1.0 && angle >= 0.0 && angle <= 360.0) mPoints_graph.push_back(glm::dvec2(percent, angle)); else printf("ERROR: Point out of bounds: (%g, %g)\n", percent, angle); } double Track::lookUpAngleAtPercent_graph(double percent) /* Called by * - Track::runPilotVersion * - Track::runHeights * Input: a percentage along the track, given between 0.0 and 1.0 * Output: the angle of the tangent to the track at this percentage */ { //Lower and upper bounds for interpolation are both points on the graph glm::dvec2 behind, ahead; //Make sure that the track wraps round if (percent < 0.0) percent += 1.0; if (percent > 1.0) percent -= 1.0; //Iterate over all points on the percentage-angle graph for (unsigned int i = 0; i < mPoints_graph.size(); i++) { //If there's a point on the graph with the exact target percentage... if (mPoints_graph[i].x == percent) { //... then no interpolation is required, and this can be returned directly. unsigned int latest = 0; //Just check that there aren't any other more recent points with the same coordinate for (unsigned int j = i; j < mPoints_graph.size(); j++) { if (mPoints_graph[j].x == percent) latest = j; } return mPoints_graph[latest].y; } //Just overshot the target point else if (mPoints_graph[i].x > percent) { //The point behind the current position behind = mPoints_graph[i - 1]; //The point ahead of the current position ahead = mPoints_graph[i]; //Handle the fact that 0 degrees is the same as 360 degrees if (behind.y == 360.0 && (360.0 - ahead.y >= 180.0)) behind.y = 0.0; else if (ahead.y == 360.0 && (360.0 - behind.y >= 180.0) && (behind.y != 0.0)) ahead.y = 0.0; //Interpolate between points to return the answer return behind.y + (ahead.y - behind.y) * ((percent - behind.x) / (ahead.x - behind.x)); } } } void Track::imprintCircle(std::vector<double>& toImprintHeights, int centreX, int centreZ) /* Called by Track::runHeights * Imprints a circle with a diameter of mWidth, and centre (centreX, centreZ) in the terrain height data */ { const int halfTerrainSize = floor(mTerrainSize_heightSamples * 0.5), circleRadius = floor(0.5 * mWidth); //X and Z need to be integer coordinates within the bounds of the heights array int targetX = 0, targetZ = 0, currentHeightIndex = 0; double distToCircleCentre = 0.0, //The distance from the current point to the centre of the circle circleWeighting = 0.0, //A value between 0.0 and 1.0 describing the depth of the 'bowl' shape at a point newHeight = 0.0; //Used to store the new height being added to the terrain //Iterate over a square of points around (centreX, centreZ) for (int x = -circleRadius; x <= circleRadius; x++) { for (int z = -circleRadius; z <= circleRadius; z++) { //Calculate the distance of the current point to the centre of the circle distToCircleCentre = sqrt(pow(x, 2.0) + pow(z, 2.0)); //If this distance is greater than the radius, then the point is outside the circle if (distToCircleCentre > circleRadius) continue; //Otherwise, establish where the target point is on the terrain (given the position of the centre, //and the position of the point relative to the centre). targetX = centreX + x; targetZ = centreZ + z; //Use these values to get the index into the height array of this point currentHeightIndex = (targetX + halfTerrainSize) * mTerrainSize_heightSamples + (targetZ + halfTerrainSize); //Check that this point is actually within the terrain if (targetX >= -halfTerrainSize && targetX <= halfTerrainSize && targetZ >= -halfTerrainSize && targetZ <= halfTerrainSize) { //This line is used to give the track a 'bowl' like shape, by calculating a depth based on the distance to the centre of the circle circleWeighting = (1.0 - pow(distToCircleCentre / circleRadius, 3.0)); newHeight = circleWeighting * -mMaxDepth; //Avoids a shape issue with overlapping circles if (newHeight < toImprintHeights[currentHeightIndex]) toImprintHeights[currentHeightIndex] = newHeight; //Lastly, modify the surface types to represent the track mTempSurfaceTypes[2 * (currentHeightIndex - halfTerrainSize - targetX)] = TerrainType::TARMAC; mTempSurfaceTypes[2 * (currentHeightIndex - halfTerrainSize - targetX) + 1] = TerrainType::TARMAC; } } } } void Track::runPilotVersion() /* Called by Track::Track * Iterates over the track shape once to determine various parameters required before the full iteration is completed, * like the bounds of shape, its dimensions and a */ { //Used to store values during the iteration double percent = 0.0, currentAngle = 0.0; glm::dvec2 direction = mStartDirection, displacementTracker = glm::dvec2(0.0); //Iterate round the shape with a given number of samples for (unsigned int i = 0; i < mNumSamplesOverTotal; i++) { //The the current percentage round the track, between 0.0 and 1.0 percent = (double)i / (double)mNumSamplesOverTotal; currentAngle = lookUpAngleAtPercent_graph(percent); direction = normalize(glm::rotate(mStartDirection, glm::radians(currentAngle))); displacementTracker += direction; //The track shape's bounding rectangle grows as the track covers more area if (displacementTracker.x < mPilotResults.mLowerBoundDisplacement.x) mPilotResults.mLowerBoundDisplacement.x = displacementTracker.x; else if (displacementTracker.x > mPilotResults.mUpperBoundDisplacement.x) mPilotResults.mUpperBoundDisplacement.x = displacementTracker.x; if (displacementTracker.y < mPilotResults.mLowerBoundDisplacement.y) mPilotResults.mLowerBoundDisplacement.y = displacementTracker.y; else if (displacementTracker.y > mPilotResults.mUpperBoundDisplacement.y) mPilotResults.mUpperBoundDisplacement.y = displacementTracker.y; } mPilotResults.mShapeDimensions = mPilotResults.mUpperBoundDisplacement - mPilotResults.mLowerBoundDisplacement; } void Track::updateStartingPosition() /* Called by Track::Track * Calculates the starting position of the track, for the full iteration, given the results obtained by the pilot run. * This accounts for the track dimensions, width, and mTerrainBorderPadding (the space that should always be left * clear of the track at the edges of the terrain). */ { //Occurs on both axes double terrainSize_units = mTerrainSize_heightSamples - 1, completePadding = mTerrainBorderPadding + 0.5 * mWidth; //Scale the results of the pilot run to match the size that the full track should cover glm::dvec2 lowerBound = mPilotResults.mLowerBoundDisplacement * mPilotToMainScaleFactor, upperBound = mPilotResults.mUpperBoundDisplacement * mPilotToMainScaleFactor, dimensions = mPilotResults.mShapeDimensions * mPilotToMainScaleFactor; //Calculate a starting position for the track that allows its bounding rectangle to fit within that of the terrain (square) if (mPilotResults.shapeIsLandscape()) { mStartPosition.x = completePadding + abs(lowerBound.x); mStartPosition.y = completePadding + abs(lowerBound.y) + 0.5 * (terrainSize_units - (completePadding * 2.0) - dimensions.y); } else { mStartPosition.x = completePadding + abs(lowerBound.x) + 0.5 * (terrainSize_units - (completePadding * 2.0) - dimensions.x); mStartPosition.y = completePadding + abs(lowerBound.y); } mStartPosition -= glm::dvec2(0.5 * terrainSize_units); } }
34.336735
136
0.699034
[ "shape", "vector" ]
f1c33f29cfd7960e4ab05bf939d8248f36e69a56
3,225
cpp
C++
ivmpServer/apiDialog.cpp
WuskieFTW1113/IV-MP-T4
ec4f193c90d23e07e6200dcb061ec8773be6bedc
[ "MIT" ]
2
2021-07-18T17:37:32.000Z
2021-08-04T12:33:51.000Z
ivmpServer/apiDialog.cpp
VittorioC97/IV-MP-T4
ec4f193c90d23e07e6200dcb061ec8773be6bedc
[ "MIT" ]
1
2022-02-22T03:26:50.000Z
2022-02-22T03:26:50.000Z
ivmpServer/apiDialog.cpp
WuskieFTW1113/IV-MP-T4
ec4f193c90d23e07e6200dcb061ec8773be6bedc
[ "MIT" ]
5
2021-06-17T06:41:00.000Z
2022-02-17T09:37:40.000Z
#include "API/apiDialog.h" #include "networkManager.h" #include <map> #include "players.h" #include "API/apiPlayerEvents.h" #include "dialogManager.h" #include "../SharedDefines/packetsIds.h" #if linux #define _strdup strdup #endif struct dialogRowInternal { std::string data; int customId; }; struct dialogListInternal { apiDialog::dialogList* list; RakNet::BitStream* b; std::vector<dialogRowInternal> rows; }; std::map<unsigned int, dialogListInternal> dialogLists; apiDialog::dialogList::dialogList(unsigned int id, char* windowName, unsigned int columns) { this->id = id; this->windowName = _strdup(windowName); this->columns = columns; this->headers = "n"; this->btnNames[0] = "Ok", this->btnNames[1] = "Cancel"; } apiDialog::dialogList::~dialogList(){} void apiDialog::dialogList::setColumnsHeaders(const char* s) { this->headers = _strdup(s); } void apiDialog::dialogList::setBtnNames(const char* b1, const char* b2) { this->btnNames[0] = _strdup(b1); this->btnNames[1] = _strdup(b2); } void apiDialog::dialogList::addRow(const char* s, int customId) { dialogRowInternal r; r.customId = customId, r.data = s; dialogLists.at(this->id).rows.push_back(r); } void apiDialog::dialogList::clearRows() { dialogLists.at(this->id).rows.clear(); } void apiDialog::dialogList::save() { RakNet::RakString s; s.Clear(); RakNet::BitStream* b = dialogLists.at(this->id).b; b->Reset(); std::vector<dialogRowInternal>& v = dialogLists.at(this->id).rows; size_t rows = v.size(); b->Write((MessageID)IVMP); b->Write(DRAW_DIALOG_LIST); b->Write(this->id); s = std::string(this->windowName).c_str(); b->Write(s); s = std::string(this->headers).c_str(); b->Write(s); for(size_t i = 0; i < 2; i++) { s = std::string(btnNames[i]).c_str(); b->Write(s); } b->Write(this->columns); b->Write(rows); for(size_t i = 0; i < rows; i++) { s = v[i].data.c_str(); b->Write(s); b->Write(v[i].customId); } } bool apiDialog::addNew(unsigned int id, char* windowName, unsigned int columns) { dialogListInternal di; di.list = new dialogList(id, windowName, columns); di.b = new RakNet::BitStream; dialogLists.insert(std::make_pair(id, di)); return true; } void apiDialog::remove(int id) { delete dialogLists.at(id).list; delete dialogLists.at(id).b; dialogLists.erase(id); } bool apiDialog::isValid(int id) { return dialogLists.find(id) != dialogLists.end(); } apiDialog::dialogList* apiDialog::get(int id) { return dialogLists.at(id).list; } RakNet::BitStream* dialogManager::getList(unsigned int id) { return dialogLists.at(id).b; } apiPlayerEvents::pDialogListResponse lResponse = 0; void apiPlayerEvents::registerPlayerDialogListResponse(pDialogListResponse f) { lResponse = f; } void dialogManager::listResponse(networkManager::connection* con, RakNet::BitStream &bsIn) { if(lResponse == 0) //why bother { return; } if(!players::isPlayer(con->packet->guid.g)) { return; } unsigned int dialogId; bsIn.Read(dialogId); if(dialogLists.find(dialogId) == dialogLists.end()) { return; } int btn, row, custom = -1; bsIn.Read(btn); bsIn.Read(row); bsIn.Read(custom); lResponse(players::getPlayer(con->packet->guid.g).id, dialogId, btn, row, custom); }
20.15625
90
0.697054
[ "vector" ]
f1caec92a7a0320cc49e8da978cbdb25f032d313
4,493
cpp
C++
D-Squared-Engine/source/Library.Shared/XmlParseMaster.cpp
stropheum/D_Square_Engine
4e607f7cd6f5e7ffd9dc5207dc2b29ad6c4fa5b1
[ "MIT" ]
null
null
null
D-Squared-Engine/source/Library.Shared/XmlParseMaster.cpp
stropheum/D_Square_Engine
4e607f7cd6f5e7ffd9dc5207dc2b29ad6c4fa5b1
[ "MIT" ]
null
null
null
D-Squared-Engine/source/Library.Shared/XmlParseMaster.cpp
stropheum/D_Square_Engine
4e607f7cd6f5e7ffd9dc5207dc2b29ad6c4fa5b1
[ "MIT" ]
null
null
null
#include "pch.h" #include "XmlParseMaster.h" using namespace std; namespace Library { RTTI_DEFINITIONS(XmlParseMaster::SharedData); XmlParseMaster::XmlParseMaster(SharedData* const sharedData) : m_xmlParser(XML_ParserCreate(nullptr)), m_activeFileName(""), m_sharedData(sharedData), m_depth(0), m_clonedInstance(false), m_helpersAreInitialized(false) { XML_SetUserData(m_xmlParser, m_sharedData); XML_SetElementHandler(m_xmlParser, StartElementHandler, EndElementHandler); XML_SetCharacterDataHandler(m_xmlParser, CharDataHandler); } XmlParseMaster::~XmlParseMaster() { if (m_clonedInstance) { delete m_sharedData; for (uint32_t i = 0; i < m_helpers.Size(); i++) { delete m_helpers[i]; } m_helpers.Clear(); } XML_ParserFree(m_xmlParser); } XmlParseMaster* XmlParseMaster::Clone() const { XmlParseMaster* newParseMaster = new XmlParseMaster(m_sharedData->Clone()); newParseMaster->m_clonedInstance = true; newParseMaster->m_activeFileName = m_activeFileName; for (uint32_t i = 0; i < m_helpers.Size(); i++) { newParseMaster->m_helpers.PushBack(m_helpers[i]->Clone()); } return newParseMaster; } void XmlParseMaster::AddHelper(IXmlParseHelper& helper) { m_helpers.PushBack(&helper); } void XmlParseMaster::RemoveHelper(IXmlParseHelper& helper) { m_helpers.Remove(&helper); } void XmlParseMaster::Parse(char* const xmlData, const uint32_t& length, const bool endOfFile) { HandleHelperInitialization(); XML_Parse(m_xmlParser, xmlData, length, endOfFile); } void XmlParseMaster::ParseFromFile(const string& fileName) { HandleHelperInitialization(); m_activeFileName = fileName; ifstream input; input.open(fileName, ios::binary); input.seekg(0, ios::end); int32_t length = static_cast<int32_t>(input.tellg()); input.seekg(ios::beg); char* buffer = new char[length]; input.read(buffer, length); input.close(); Parse(buffer, length, true); delete[] buffer; } const string& XmlParseMaster::GetFileName() const { return m_activeFileName; } void XmlParseMaster::SetSharedData(SharedData* const sharedData) { m_sharedData = sharedData; } XmlParseMaster::SharedData* XmlParseMaster::GetSharedData() const { return m_sharedData; } void XmlParseMaster::StartElementHandler(void* userData, const XML_Char* name, const XML_Char** atts) { SharedData* data = static_cast<SharedData*>(userData); HashMap<string, string> attributes; for (uint32_t i = 0; atts[i]; i += 2) { string key = atts[i]; string value = atts[i + 1]; attributes[key] = value; } Vector<IXmlParseHelper*>& helpers = data->GetXmlParseMaster()->m_helpers; for (uint32_t i = 0; i < helpers.Size(); i++) { if (helpers[i]->StartElementHandler(*data, name, attributes)) { break; } } data->IncrementDepth(); } void XmlParseMaster::EndElementHandler(void* userData, const XML_Char* name) { SharedData* data = static_cast<SharedData*>(userData); Vector<IXmlParseHelper*>& helpers = data->GetXmlParseMaster()->m_helpers; for (uint32_t i = 0; i < helpers.Size(); i++) { if (helpers[i]->EndElementHandler(*data, name)) { break; } } data->DecrementDepth(); } void XmlParseMaster::CharDataHandler(void* userData, const XML_Char* s, int len) { SharedData* data = static_cast<SharedData*>(userData); UNREFERENCED_PARAMETER(data); UNREFERENCED_PARAMETER(s); UNREFERENCED_PARAMETER(len); } void XmlParseMaster::HandleHelperInitialization() { if (!m_helpersAreInitialized) { for (uint32_t i = 0; i < m_helpers.Size(); i++) { // Initialize all Parse helpers so they reflect the correct Parse master m_helpers[i]->Initialize(this); } m_helpersAreInitialized = true; } } }
27.396341
105
0.597819
[ "vector" ]
f1d77dabe635008a2465875a320d25b5a6e90c42
12,607
cpp
C++
src/Athena_Blocks.cpp
wparad/athena_blocks
e66a84f4a22fce0ce6d8f7ba6be3c5750dcf7e19
[ "MIT" ]
1
2015-08-04T23:36:28.000Z
2015-08-04T23:36:28.000Z
src/Athena_Blocks.cpp
wparad/athena_blocks
e66a84f4a22fce0ce6d8f7ba6be3c5750dcf7e19
[ "MIT" ]
null
null
null
src/Athena_Blocks.cpp
wparad/athena_blocks
e66a84f4a22fce0ce6d8f7ba6be3c5750dcf7e19
[ "MIT" ]
null
null
null
//============================================================================ // Name : Athena_Blocks.cpp // Author : Warren Parad // Version : v1.0 // Date : 9/25/2012 // Copyright : Copy at your own risk // Description : Hello World in C++, Ansi-style /*IMPORTANT DETAILS: * * Answer: 806844323190414 * Runtime: 88.091 [fastest time] * Computer Specs: hp laptop * xubuntu (ubuntu linux 10.04) * GCC 4.4.3 (x86_44) * CPU: AMD Turion II Ultra Dual-Core Mobile M620 * Freq: 800 MHz * L2 Cache: 1024 * RAM: 3GB (but ran the program with 2899MiB free) * Motherboard Host Bridge: * AMD K10 * HP Company Device 3638 * * Three compiler flags can be set to see interesting information about the program as it runs //run in Debug mode switch #define _DEBUG 0 //see execution running time #define _CHECK_EXEC_TIME 0 //change this to show error messages instead of just seeing a "0" output on failure #define _SHOW_ERRORS 0 */ /* *Your niece was given a set of blocks for her birthday, and she has decided to build a panel using 3”×1” and 4.5”×1" blocks. For structural integrity, the spaces between the blocks must not line up in adjacent rows. For example, the 13.5”×3” panel below is unacceptable, because some of the spaces between the blocks in the first two rows line up (as indicated by the dotted line). There are 2 ways in which to build a 7.5”×1” panel, 2 ways to build a 7.5”×2” panel, 4 ways to build a 12”×3” panel, and 7958 ways to build a 27”×5” panel. How many different ways are there for your niece to build a 48”×10” panel? The answer will fit in a 64-bit integer. Write a program to calculate the answer. The program should be non-interactive and run as a single-line command which takes two command-line arguments, width and height, in that order. Given any width between 3 and 48 that is a multiple of 0.5, inclusive, and any height that is an integer between 1 and 10, inclusive, your program should calculate the number of valid ways there are to build a wall of those dimensions. Your program’s output should simply be the solution as a number, with no line-breaks or white spaces. Your program will be judged on how fast it runs and how clearly the code is written. We will be running your program as well as reading the source code, so anything you can do to make this process easier would be appreciated. Send the source code and let us know the value that your program computes, your program’s running time, and the kind of machine on which you ran it. */ //============================================================================ #include <iostream> #include <fstream> #include <stdlib.h> #include <sstream> #include <cmath> #include <vector> #include <sys/time.h> //run in Debug mode switch #define _DEBUG 0 #define _CHECK_EXEC_TIME 0 //change this to show error messages #define _SHOW_ERRORS 0 #define MATRIX_MAX_D1 3329 #define MATRIX_MAX_D2 48 using namespace std; //struct to cache permutations and where the cracks are in a line struct line{ unsigned int cracks; long long perm[10]; }; //global counter to keep track of the permutations for height 1 // normally i would never use a global outside of OOP, but I wanted to see if this would make a difference in // performance. unsigned short counter = 0; unsigned long long wallPermutations(int,int,short,short (*)[MATRIX_MAX_D2],line*); void linePermutations(int,unsigned int,line*); bool overlapCrack(int, int,int); void printLine(int,int); int main(int argc, char *argv[]) { #if _DEBUG|_CHECK_EXEC_TIME timeval t1, t2; double execTime = 0; gettimeofday(&t1, NULL); // for(int i = 0; i < argc; i++) cout <<"arg "<<i<<": "<<argv[i]<< endl; //validate command line parameters #endif #if _SHOW_ERRORS if(argc != 3){ cout << "Wall Permutations takes 2 arguments." << endl; return 1; } double decimal = 0; //validate width double width = 0.0; int intWidth = 0; istringstream wstr(argv[1]); if(!(wstr >> width)) { cout << "The width is not a valid value.: " << width <<"."<< endl; return 1; } //even if it is a valid double, it might not be a valid width else if(fmod(width*2/3.,1) != 0){ cout << "No wall for that width can be made from 3\" and 4.5\" bricks." << endl; return 1; } else { decimal = fmod(width,1); if(width < 3 || width > 48 || (decimal != 0 && decimal != .5)){ cout << "The width is not a valid number." << endl; return 1; } } //MUST use for <int> math, this makes everything simpler including the use of an int for binary operations intWidth = int(width*2/3.); //validate height double height = 0; istringstream hstr(argv[2]); if(!(hstr >> height)) { cout << "The height is not a valid value: " << height <<"."<< endl; return 1; } else if( height < 1 || height > 10 || height != int(height)){ cout << "The height is not a valid number." << endl; return 1; } #else //begin do not show errors if(argc != 3){ cout<<"0"<<endl; return 1; } double decimal = 0; //validate width double width = 0.0; int intWidth = 0; istringstream wstr(argv[1]); if(!(wstr >> width)) { cout<<"0"<<endl; return 1; } //even if it is a valid double, it might not be a valid width else if(fmod(width*2/3.,1) != 0){ cout<<"0"<<endl; return 1; } else { decimal = fmod(width,1); if(width < 3 || width > 48 || (decimal != 0 && decimal != .5)){ cout<<"0"<<endl; return 1; } } //MUST use for <int> math, this makes everything simpler including the use of an int for binary operations intWidth = int(width*2/3.); //validate height double height = 0; istringstream hstr(argv[2]); if(!(hstr >> height)) { cout<<"0"<<endl; return 1; } else if( height < 1 || height > 10 || height != int(height)){ cout<<"0"<<endl; return 1; } //end do not show errors #endif //max number of possible permutations for a line at a specific width line* permLines = new line[MATRIX_MAX_D1]; //generate line array linePermutations(intWidth,1,permLines); /*Max calculated no overlapping lines for the same position in a wall. * Normally this would never be done, but it is here for 3 reasons: * 1) A width of 48 perfectly reduces to 32 bits in this program preventing a wider line from being * calculated, therefore making this assumption. * 2) To create a lookup table due to computer resources this array again has to be limited, so the smallest * size was chosen. * 3) Without a lookup table, the program execution time is too expensive, something on the order of 3329^10 * computations. */ short (*allowedLines)[MATRIX_MAX_D2] = new short[MATRIX_MAX_D1+1][MATRIX_MAX_D2]; #if _DEBUG gettimeofday(&t2, NULL); execTime = (t2.tv_sec - t1.tv_sec) * 1000.0; execTime += (t2.tv_usec - t1.tv_usec) / 1000.0; cout << "time: " << execTime << endl; #endif //populate which lines can be next to each other if for each line there is another that can be adjacent // then allowedLines[first line+1][count] = second line+1 and // allowedLines[second line+1][second count] = first line+1 //the reason the +1 are in there is to allow a "NULL" at 0 and recognize this fact without negative numbers int next = 0; //compile time determination allowed pre-initialization and causes ln2Next to be 0 in 0ms. short *ln2Next = new short[MATRIX_MAX_D1]; for(unsigned short ln = 0; ln < counter ; ++ln) { next = 0; for(unsigned short ln2 = ln+1; ln2 < counter; ++ln2){ if(!overlapCrack(permLines[ln].cracks,permLines[ln2].cracks,intWidth)){ allowedLines[ln+1][next++] = ln2+1; allowedLines[ln2+1][ln2Next[ln2]++] = ln+1; } } //uncomment line to visually see what a height 1 permutation line looks like #if _DEBUG printLine(permLines[ln].cracks,intWidth); #endif } #if _DEBUG|_CHECK_EXEC_TIME gettimeofday(&t2, NULL); execTime = (t2.tv_sec - t1.tv_sec) * 1000.0; execTime += (t2.tv_usec - t1.tv_usec) / 1000.0; cout << "time: " << execTime << endl; #endif //**************************// //Run the wal permutations cout<< wallPermutations(intWidth,(int)height,-1,allowedLines,permLines) << endl; delete[] allowedLines; #if _DEBUG|_CHECK_EXEC_TIME gettimeofday(&t2, NULL); execTime = (t2.tv_sec - t1.tv_sec) * 1000.0; execTime += (t2.tv_usec - t1.tv_usec) / 1000.0; cout << "time: " << execTime << endl; #endif return 0; } //comput wall permutations from available lines unsigned long long wallPermutations(int width, int height,short index, short (*allowedLines)[MATRIX_MAX_D2],line* permLines){ #if _DEBUG // cout<<index<<":"<<height<<":"<<endl; #endif unsigned long long tmp = 0; short line = 0; if(height < 1) return 0; //no height no possible permutations unsigned long long total = 0; //force for height =1 either the counter for real height 1, or recursive. If recursive grab total from the array // generated by the main inlined double for loop highlighted above. if(height == 1){ if(index == -1) return counter; tmp = permLines[index].perm[0]; if(tmp != 0) return tmp; for(unsigned short ln = 0; ln < MATRIX_MAX_D2;++ln){ if(allowedLines[index+1][ln] == 0) break; ++tmp; } permLines[index].perm[0] = tmp; return tmp; } //index == -1 means the first pass we have no restrictions, we also know height != 1, so we dont have to worry about anything. if(index == -1) { //for the first row there are no restrictions, assume any of the possible lines can be there for(unsigned short ln = 0; ln < counter; ++ln){ total+= wallPermutations(width,height-1,ln,allowedLines,permLines); } return total; } //its not the bottom row or the first row because index == -1 and height == 1 have already taken care of those tmp = 0; for(unsigned short ln = 0; ln < MATRIX_MAX_D2;++ln){ //for each possible line check to see if it can come next line = allowedLines[index+1][ln]; //no more allowed lines remaining, we can reset and adjust back a level if(line == 0) return total; //CACHING tmp = permLines[line-1].perm[height-1]; //tmp = 0 //turn on/off caching lowest level performance enhancement; if(tmp == 0) { //recursive call for next row tmp=wallPermutations(width,height-1,line-1,allowedLines,permLines); permLines[line-1].perm[height - 1] = tmp; } //END CACHING total += tmp; } //return the number of permutations there are for the current line * the number of wallPermuation // for everything below considering this restriction return total; } /* * This is going to get complicated really fast to maintain performance. I want to use bits to represent the * location of cracks. then using the bitwise & we and equivalence to 0 we are going to check if a block can * be next to another one. * Since the bricks are 3 and 4.5 and the max length of the wall is 48 lets instead do this problem by 2/3 * so bricks 2 and 3 and wall length of 32, since the crack at 0 and 32 does not count and there is no brick * of length 1, we cannot have cracks at 1 or 31 which leaves 2 through 30 or 29 possible cracks. This value * will fit in a variable of length 32 easily. */ void linePermutations(int width,unsigned int curLine, line* permLines){ if(width == 2 ) { permLines[counter++].cracks = curLine; return; } else if(width == 3){ //line up the last three block size with the the last 2 block size permLines[counter++].cracks = (curLine << 1); return; } else if(width <= 1) return; else { //we want to add this _ _| linePermutations(width-2,(curLine<<2)|1,permLines); //we want to add this _ _ _| linePermutations(width-3,(curLine<<3)|1,permLines); } } /*returns if 2 brick patterns will have overlapping cracks, this is a simple bit-wise & because of how the lines * were determined. intWidth is required to remove the place holder at the MSB. * */ bool overlapCrack(int lineA, int lineB,int intWidth){ // return (lineA & lineB) & (0b0111111111111111111111111111111 >> (32-intWidth)); return (lineA & lineB) > (1 <<(intWidth -2)); } //Visually will print a line given a line in the <int> format generated from a height 1 wall and specified intWidth. void printLine(int line,int intWidth){ if(line == 0) return; //if we had added back one more space to the int to take the full 32 we could use a -1 instead of -2, //but its the same for(int A = intWidth - 2; A>=0 ; A--){ if((line >> A & 1) == 1) cout<<" _"; else cout << " _"; } cout<< " _" << endl; for(int A = intWidth - 2; A>=0 ; A--){ if((line >> A & 1) == 1) cout<<"|_"; else cout << " _"; } cout<< " _|" << endl; }
36.123209
127
0.673911
[ "vector" ]
f1d8922dca2bac40d82b0159ea59366f756f16d5
5,285
cpp
C++
src/interface/uiFloatingButtonLayer.cpp
santaclose/noose
e963138b81f380ca0f46369941cf65c4349bd4fb
[ "Apache-2.0" ]
8
2021-01-31T11:30:05.000Z
2021-09-01T07:48:34.000Z
src/interface/uiFloatingButtonLayer.cpp
santaclose/noose
e963138b81f380ca0f46369941cf65c4349bd4fb
[ "Apache-2.0" ]
4
2021-09-01T08:17:18.000Z
2021-09-24T22:32:24.000Z
src/interface/uiFloatingButtonLayer.cpp
santaclose/noose
e963138b81f380ca0f46369941cf65c4349bd4fb
[ "Apache-2.0" ]
1
2021-09-01T07:49:58.000Z
2021-09-01T07:49:58.000Z
#include "uiFloatingButtonLayer.h" #include <pathUtils.h> #include <vector> #include <iostream> #include "uiData.h" #include <math/nooseMath.h> #include <math/vectorOperators.h> #define BUTTON_RADIUS 0.46f // uv space #define BUTTON_COLOR 0x5a5a5aff #define BUTTON_SIZE 50 #define MARGIN 18 namespace uiFloatingButtonLayer { bool active = true; sf::RenderWindow* renderWindow; const sf::Vector2i* mouseScreenPosPointer; sf::Shader genericShader; std::vector<FloatingButton> buttons; } void uiFloatingButtonLayer::updatButtonElementPositions(FloatingButton& fb) { if (fb.pos == ButtonPosition::BottomLeft || fb.pos == ButtonPosition::TopLeft) { fb.va[0].position.x = fb.va[1].position.x = MARGIN; fb.va[2].position.x = fb.va[3].position.x = MARGIN + BUTTON_SIZE; } else { fb.va[0].position.x = fb.va[1].position.x = renderWindow->getSize().x - BUTTON_SIZE - MARGIN; fb.va[2].position.x = fb.va[3].position.x = renderWindow->getSize().x - MARGIN; } if (fb.pos == ButtonPosition::TopLeft || fb.pos == ButtonPosition::TopRight) { fb.va[0].position.y = fb.va[3].position.y = MARGIN; fb.va[1].position.y = fb.va[2].position.y = MARGIN + BUTTON_SIZE; } else { fb.va[0].position.y = fb.va[3].position.y = renderWindow->getSize().y - BUTTON_SIZE - MARGIN; fb.va[1].position.y = fb.va[2].position.y = renderWindow->getSize().y - MARGIN; } if (fb.text != nullptr) fb.text->setPosition( MARGIN + BUTTON_SIZE / 2.0 - fb.text->getLocalBounds().width / 2.0, renderWindow->getSize().y - MARGIN - BUTTON_SIZE / 2.0 - fb.text->getLocalBounds().height / 1.2); } void uiFloatingButtonLayer::initialize(sf::RenderWindow& window, const sf::Vector2i* mouseScreenPosPointer) { renderWindow = &window; uiFloatingButtonLayer::mouseScreenPosPointer = mouseScreenPosPointer; if (!genericShader.loadFromFile(pathUtils::getAssetsDirectory() + "shaders/floatingButton.shader", sf::Shader::Fragment)) std::cout << "[UI] Failed to load floating button shader\n"; genericShader.setUniform("radius", BUTTON_RADIUS); } void uiFloatingButtonLayer::addButton(ButtonPosition position, const std::string& customShaderPath) { addButton(position, '\0', &customShaderPath); } void uiFloatingButtonLayer::addButton(ButtonPosition position, char symbol, const std::string* customShaderPath) { buttons.emplace_back(); buttons.back().pos = position; if (customShaderPath == nullptr) { buttons.back().customShader = nullptr; buttons.back().text = new sf::Text(sf::String(symbol), uiData::font, 30); } else { buttons.back().text = nullptr; buttons.back().customShader = new sf::Shader(); if (!buttons.back().customShader->loadFromFile(pathUtils::getAssetsDirectory() + *customShaderPath, sf::Shader::Fragment)) std::cout << "[UI] Failed to load floating button shader\n"; buttons.back().customShader->setUniform("radius", BUTTON_RADIUS); } buttons.back().va = sf::VertexArray(sf::Quads, 4); // set vertex colors buttons.back().va[0].color = buttons.back().va[1].color = buttons.back().va[2].color = buttons.back().va[3].color = sf::Color(BUTTON_COLOR); // set texture coordinates buttons.back().va[0].texCoords.x = buttons.back().va[1].texCoords.x = buttons.back().va[0].texCoords.y = buttons.back().va[3].texCoords.y = 0.0; buttons.back().va[2].texCoords.x = buttons.back().va[3].texCoords.x = buttons.back().va[1].texCoords.y = buttons.back().va[2].texCoords.y = 1.0; updatButtonElementPositions(buttons.back()); } void uiFloatingButtonLayer::draw() { if (!active) return; sf::FloatRect visibleArea(0, 0, renderWindow->getSize().x, renderWindow->getSize().y); renderWindow->setView(sf::View(visibleArea)); for (const FloatingButton& fb : buttons) { if (fb.customShader != nullptr) { renderWindow->draw(fb.va, fb.customShader); } else { renderWindow->draw(fb.va, &genericShader); renderWindow->draw(*fb.text); } } } sf::Vector2f uiFloatingButtonLayer::getButtonCenterCoords(ButtonPosition pos) { sf::Vector2f res = { 0.0f, 0.0f }; if (pos == ButtonPosition::BottomLeft || pos == ButtonPosition::TopLeft) res.x = MARGIN + BUTTON_SIZE * 0.5f; else res.x = renderWindow->getSize().x - MARGIN - BUTTON_SIZE * 0.5f; if (pos == ButtonPosition::TopLeft || pos == ButtonPosition::TopRight) res.y = MARGIN + BUTTON_SIZE * 0.5f; else res.y = renderWindow->getSize().y - MARGIN - BUTTON_SIZE * 0.5f; return res; } void uiFloatingButtonLayer::terminate() { for (FloatingButton& button : buttons) { if (button.customShader != nullptr) delete button.customShader; else delete button.text; } } uiFloatingButtonLayer::ButtonPosition uiFloatingButtonLayer::onPollEvent(const sf::Event& e) { switch (e.type) { case sf::Event::Resized: for (FloatingButton& fb : buttons) updatButtonElementPositions(fb); break; case sf::Event::MouseButtonPressed: { if (e.mouseButton.button != sf::Mouse::Left || !active) break; for (const FloatingButton& fb : buttons) { sf::Vector2f mousePosInUVSpace = (sf::Vector2f(mouseScreenPosPointer->x, mouseScreenPosPointer->y) - fb.va[0].position) / BUTTON_SIZE; if (nooseMath::distance(sf::Vector2f(0.5, 0.5), mousePosInUVSpace) < BUTTON_RADIUS) return fb.pos; } break; } } return ButtonPosition::None; }
31.088235
145
0.705014
[ "vector" ]
f1ea7f702c6c7a18d90322f25069f20f6a55e042
935
cpp
C++
API/GameEngineContents/KillCountUI.cpp
hooony1324/Portfolio
5be1b439d53dcc861b4e06ec69bad53f3bd05ab5
[ "MIT" ]
null
null
null
API/GameEngineContents/KillCountUI.cpp
hooony1324/Portfolio
5be1b439d53dcc861b4e06ec69bad53f3bd05ab5
[ "MIT" ]
null
null
null
API/GameEngineContents/KillCountUI.cpp
hooony1324/Portfolio
5be1b439d53dcc861b4e06ec69bad53f3bd05ab5
[ "MIT" ]
null
null
null
#include "KillCountUI.h" #include <GameEngine/GameEngine.h> #include <GameEngineBase/GameEngineWindow.h> #include <GameEngine/GameEngineImageManager.h> #include <GameEngine/GameEngineRenderer.h> #include "GameInfo.h" KillCountUI::KillCountUI() { } KillCountUI::~KillCountUI() { } void KillCountUI::Start() { SetPosition(float4{GameEngineWindow::GetScale().Half().x, 0 } + float4{410, 45}); SetScale(float4{60, 30}); GameEngineRenderer* Renderer_ = CreateRenderer("SkullToken.bmp"); Renderer_->CameraEffectOff(); TextFont_.Load("../Resources/PlayUI/KO.ttf"); NextLevelOff(); } void KillCountUI::Update() { } void KillCountUI::Render() { std::string KillCount = std::to_string(GameInfo::GetPlayerInfo()->KillCount_); int StrLength = static_cast<int>(KillCount.length()) - 1; int Space = 8 * StrLength; TextFont_.Draw(KillCount, { GetPosition().x - 22 - Space, GetPosition().y - 11}, RGB(255, 255, 255), 23, 800); }
22.261905
111
0.721925
[ "render" ]
f1ebda26dd37ff179e96c600ed1eeee001c44de6
16,182
cpp
C++
data/QuadriFlow/src/dedge.cpp
hjwdzh/TextureNet
f3515537909ffb4ab04694b91109b535bb5c85d5
[ "MIT" ]
89
2019-03-30T03:59:25.000Z
2021-08-25T05:16:51.000Z
data/QuadriFlow/src/dedge.cpp
jtpils/TextureNet
f3515537909ffb4ab04694b91109b535bb5c85d5
[ "MIT" ]
1
2019-06-29T11:21:11.000Z
2019-07-12T04:09:41.000Z
data/QuadriFlow/src/dedge.cpp
jtpils/TextureNet
f3515537909ffb4ab04694b91109b535bb5c85d5
[ "MIT" ]
12
2019-04-12T01:20:44.000Z
2020-07-12T16:10:33.000Z
#include "dedge.hpp" #include "config.hpp" #include <atomic> #include <fstream> #include <iostream> #include <set> #include <vector> #include "compare-key.hpp" #ifdef WITH_TBB #include "tbb_common.h" #endif inline int dedge_prev(int e, int deg) { return (e % deg == 0u) ? e + (deg - 1) : e - 1; } inline bool atomicCompareAndExchange(volatile int* v, uint32_t newValue, int oldValue) { #if defined(_WIN32) return _InterlockedCompareExchange(reinterpret_cast<volatile long*>(v), (long)newValue, (long)oldValue) == (long)oldValue; #else return __sync_bool_compare_and_swap(v, oldValue, newValue); #endif } #undef max #undef min bool compute_direct_graph(MatrixXd& V, MatrixXi& F, VectorXi& V2E, VectorXi& E2E, VectorXi& boundary, VectorXi& nonManifold) { V2E.resize(V.cols()); V2E.setConstant(INVALID); uint32_t deg = F.rows(); std::vector<std::pair<uint32_t, uint32_t>> tmp(F.size()); #ifdef WITH_TBB tbb::parallel_for( tbb::blocked_range<uint32_t>(0u, (uint32_t)F.cols(), GRAIN_SIZE), [&](const tbb::blocked_range<uint32_t>& range) { for (uint32_t f = range.begin(); f != range.end(); ++f) { for (uint32_t i = 0; i < deg; ++i) { uint32_t idx_cur = F(i, f), idx_next = F((i + 1) % deg, f), edge_id = deg * f + i; if (idx_cur >= V.cols() || idx_next >= V.cols()) throw std::runtime_error( "Mesh data contains an out-of-bounds vertex reference!"); if (idx_cur == idx_next) continue; tmp[edge_id] = std::make_pair(idx_next, INVALID); if (!atomicCompareAndExchange(&V2E[idx_cur], edge_id, INVALID)) { uint32_t idx = V2E[idx_cur]; while (!atomicCompareAndExchange((int*)&tmp[idx].second, edge_id, INVALID)) idx = tmp[idx].second; } } } }); #else for (int f = 0; f < F.cols(); ++f) { for (unsigned int i = 0; i < deg; ++i) { unsigned int idx_cur = F(i, f), idx_next = F((i + 1) % deg, f), edge_id = deg * f + i; if (idx_cur >= V.cols() || idx_next >= V.cols()) throw std::runtime_error("Mesh data contains an out-of-bounds vertex reference!"); if (idx_cur == idx_next) continue; tmp[edge_id] = std::make_pair(idx_next, -1); if (V2E[idx_cur] == -1) V2E[idx_cur] = edge_id; else { unsigned int idx = V2E[idx_cur]; while (tmp[idx].second != -1) { idx = tmp[idx].second; } tmp[idx].second = edge_id; } } } #endif nonManifold.resize(V.cols()); nonManifold.setConstant(false); E2E.resize(F.cols() * deg); E2E.setConstant(INVALID); #ifdef WITH_OMP #pragma omp parallel for #endif for (int f = 0; f < F.cols(); ++f) { for (uint32_t i = 0; i < deg; ++i) { uint32_t idx_cur = F(i, f), idx_next = F((i + 1) % deg, f), edge_id_cur = deg * f + i; if (idx_cur == idx_next) continue; uint32_t it = V2E[idx_next], edge_id_opp = INVALID; while (it != INVALID) { if (tmp[it].first == idx_cur) { if (edge_id_opp == INVALID) { edge_id_opp = it; } else { nonManifold[idx_cur] = true; nonManifold[idx_next] = true; edge_id_opp = INVALID; break; } } it = tmp[it].second; } if (edge_id_opp != INVALID && edge_id_cur < edge_id_opp) { E2E[edge_id_cur] = edge_id_opp; E2E[edge_id_opp] = edge_id_cur; } } } std::atomic<uint32_t> nonManifoldCounter(0), boundaryCounter(0), isolatedCounter(0); boundary.resize(V.cols()); boundary.setConstant(false); /* Detect boundary regions of the mesh and adjust vertex->edge pointers*/ #ifdef WITH_OMP #pragma omp parallel for #endif for (int i = 0; i < V.cols(); ++i) { uint32_t edge = V2E[i]; if (edge == INVALID) { isolatedCounter++; continue; } if (nonManifold[i]) { nonManifoldCounter++; V2E[i] = INVALID; continue; } /* Walk backwards to the first boundary edge (if any) */ uint32_t start = edge, v2e = INVALID; do { v2e = std::min(v2e, edge); uint32_t prevEdge = E2E[dedge_prev(edge, deg)]; if (prevEdge == INVALID) { /* Reached boundary -- update the vertex->edge link */ v2e = edge; boundary[i] = true; boundaryCounter++; break; } edge = prevEdge; } while (edge != start); V2E[i] = v2e; } #ifdef LOG_OUTPUT printf("counter triangle %d %d\n", (int)boundaryCounter, (int)nonManifoldCounter); #endif return true; std::vector<std::vector<int> > vert_to_edges(V2E.size()); for (int i = 0; i < F.cols(); ++i) { for (int j = 0; j < 3; ++j) { int v = F(j, i); vert_to_edges[v].push_back(i * 3 + j); } } std::vector<int> colors(F.cols() * 3, -1); bool update = false; int num_v = V.cols(); std::map<int, int> new_vertices; for (int i = 0; i < vert_to_edges.size(); ++i) { int num_color = 0; for (int j = 0; j < vert_to_edges[i].size(); ++j) { int deid0 = vert_to_edges[i][j]; if (colors[deid0] == -1) { int deid = deid0; do { colors[deid] = num_color; if (num_color != 0) F(deid%3, deid/3) = num_v; deid = deid / 3 * 3 + (deid + 2) % 3; deid = E2E[deid]; } while (deid != deid0); num_color += 1; if (num_color > 1) { update = true; new_vertices[num_v] = i; num_v += 1; } } } } if (update) { V.conservativeResize(3, num_v); for (auto& p : new_vertices) { V.col(p.first) = V.col(p.second); } return false; } return true; } void compute_direct_graph_quad(std::vector<Vector3d>& V, std::vector<Vector4i>& F, std::vector<int>& V2E, std::vector<int>& E2E, VectorXi& boundary, VectorXi& nonManifold) { V2E.clear(); E2E.clear(); boundary = VectorXi(); nonManifold = VectorXi(); V2E.resize(V.size(), INVALID); uint32_t deg = 4; std::vector<std::pair<uint32_t, uint32_t>> tmp(F.size() * deg); #ifdef WITH_TBB tbb::parallel_for( tbb::blocked_range<uint32_t>(0u, (uint32_t)F.size(), GRAIN_SIZE), [&](const tbb::blocked_range<uint32_t>& range) { for (uint32_t f = range.begin(); f != range.end(); ++f) { for (uint32_t i = 0; i < deg; ++i) { uint32_t idx_cur = F[f][i], idx_next = F[f][(i + 1) % deg], edge_id = deg * f + i; if (idx_cur >= V.cols() || idx_next >= V.cols()) throw std::runtime_error( "Mesh data contains an out-of-bounds vertex reference!"); if (idx_cur == idx_next) continue; tmp[edge_id] = std::make_pair(idx_next, INVALID); if (!atomicCompareAndExchange(&V2E[idx_cur], edge_id, INVALID)) { uint32_t idx = V2E[idx_cur]; while (!atomicCompareAndExchange((int*)&tmp[idx].second, edge_id, INVALID)) idx = tmp[idx].second; } } } }); #else for (int f = 0; f < F.size(); ++f) { for (unsigned int i = 0; i < deg; ++i) { unsigned int idx_cur = F[f][i], idx_next = F[f][(i + 1) % deg], edge_id = deg * f + i; if (idx_cur >= V.size() || idx_next >= V.size()) throw std::runtime_error("Mesh data contains an out-of-bounds vertex reference!"); if (idx_cur == idx_next) continue; tmp[edge_id] = std::make_pair(idx_next, -1); if (V2E[idx_cur] == -1) { V2E[idx_cur] = edge_id; } else { unsigned int idx = V2E[idx_cur]; while (tmp[idx].second != -1) { idx = tmp[idx].second; } tmp[idx].second = edge_id; } } } #endif nonManifold.resize(V.size()); nonManifold.setConstant(false); E2E.resize(F.size() * deg, INVALID); #ifdef WITH_OMP #pragma omp parallel for #endif for (int f = 0; f < F.size(); ++f) { for (uint32_t i = 0; i < deg; ++i) { uint32_t idx_cur = F[f][i], idx_next = F[f][(i + 1) % deg], edge_id_cur = deg * f + i; if (idx_cur == idx_next) continue; uint32_t it = V2E[idx_next], edge_id_opp = INVALID; while (it != INVALID) { if (tmp[it].first == idx_cur) { if (edge_id_opp == INVALID) { edge_id_opp = it; } else { nonManifold[idx_cur] = true; nonManifold[idx_next] = true; edge_id_opp = INVALID; break; } } it = tmp[it].second; } if (edge_id_opp != INVALID && edge_id_cur < edge_id_opp) { E2E[edge_id_cur] = edge_id_opp; E2E[edge_id_opp] = edge_id_cur; } } } std::atomic<uint32_t> nonManifoldCounter(0), boundaryCounter(0), isolatedCounter(0); boundary.resize(V.size()); boundary.setConstant(false); /* Detect boundary regions of the mesh and adjust vertex->edge pointers*/ #ifdef WITH_OMP #pragma omp parallel for #endif for (int i = 0; i < V.size(); ++i) { uint32_t edge = V2E[i]; if (edge == INVALID) { isolatedCounter++; continue; } if (nonManifold[i]) { nonManifoldCounter++; V2E[i] = INVALID; continue; } /* Walk backwards to the first boundary edge (if any) */ uint32_t start = edge, v2e = INVALID; do { v2e = std::min(v2e, edge); uint32_t prevEdge = E2E[dedge_prev(edge, deg)]; if (prevEdge == INVALID) { /* Reached boundary -- update the vertex->edge link */ v2e = edge; boundary[i] = true; boundaryCounter++; break; } edge = prevEdge; } while (edge != start); V2E[i] = v2e; } #ifdef LOG_OUTPUT printf("counter %d %d\n", (int)boundaryCounter, (int)nonManifoldCounter); #endif } void remove_nonmanifold(std::vector<Vector4i>& F, std::vector<Vector3d>& V) { typedef std::pair<uint32_t, uint32_t> Edge; int degree = 4; std::map<uint32_t, std::map<uint32_t, std::pair<uint32_t, uint32_t>>> irregular; std::vector<std::set<int>> E(V.size()); std::vector<std::set<int>> VF(V.size()); auto kill_face_single = [&](uint32_t f) { if (F[f][0] == INVALID) return; for (int i = 0; i < degree; ++i) E[F[f][i]].erase(F[f][(i + 1) % degree]); F[f].setConstant(INVALID); }; auto kill_face = [&](uint32_t f) { if (degree == 4 && F[f][2] == F[f][3]) { auto it = irregular.find(F[f][2]); if (it != irregular.end()) { for (auto& item : it->second) { kill_face_single(item.second.second); } } } kill_face_single(f); }; uint32_t nm_edge = 0, nm_vert = 0; for (uint32_t f = 0; f < (uint32_t)F.size(); ++f) { if (F[f][0] == INVALID) continue; if (degree == 4 && F[f][2] == F[f][3]) { /* Special handling of irregular faces */ irregular[F[f][2]][F[f][0]] = std::make_pair(F[f][1], f); continue; } bool nonmanifold = false; for (uint32_t e = 0; e < degree; ++e) { uint32_t v0 = F[f][e], v1 = F[f][(e + 1) % degree], v2 = F[f][(e + 2) % degree]; if (E[v0].find(v1) != E[v0].end() || (degree == 4 && E[v0].find(v2) != E[v0].end())) nonmanifold = true; } if (nonmanifold) { nm_edge++; F[f].setConstant(INVALID); continue; } for (uint32_t e = 0; e < degree; ++e) { uint32_t v0 = F[f][e], v1 = F[f][(e + 1) % degree], v2 = F[f][(e + 2) % degree]; E[v0].insert(v1); if (degree == 4) E[v0].insert(v2); VF[v0].insert(f); } } std::vector<Edge> edges; for (auto item : irregular) { bool nonmanifold = false; auto face = item.second; edges.clear(); uint32_t cur = face.begin()->first, stop = cur; while (true) { uint32_t pred = cur; cur = face[cur].first; uint32_t next = face[cur].first, it = 0; while (true) { ++it; if (next == pred) break; if (E[cur].find(next) != E[cur].end() && it == 1) nonmanifold = true; edges.push_back(Edge(cur, next)); next = face[next].first; } if (cur == stop) break; } if (nonmanifold) { nm_edge++; for (auto& i : item.second) F[i.second.second].setConstant(INVALID); continue; } else { for (auto e : edges) { E[e.first].insert(e.second); for (auto e2 : face) VF[e.first].insert(e2.second.second); } } } /* Check vertices */ std::set<uint32_t> v_marked, v_unmarked, f_adjacent; std::function<void(uint32_t)> dfs = [&](uint32_t i) { v_marked.insert(i); v_unmarked.erase(i); for (uint32_t f : VF[i]) { if (f_adjacent.find(f) == f_adjacent.end()) /* if not part of adjacent face */ continue; for (uint32_t j = 0; j < degree; ++j) { uint32_t k = F[f][j]; if (v_unmarked.find(k) == v_unmarked.end() || /* if not unmarked OR */ v_marked.find(k) != v_marked.end()) /* if already marked */ continue; dfs(k); } } }; for (uint32_t i = 0; i < (uint32_t)V.size(); ++i) { v_marked.clear(); v_unmarked.clear(); f_adjacent.clear(); for (uint32_t f : VF[i]) { if (F[f][0] == INVALID) continue; for (uint32_t k = 0; k < degree; ++k) v_unmarked.insert(F[f][k]); f_adjacent.insert(f); } if (v_unmarked.empty()) continue; v_marked.insert(i); v_unmarked.erase(i); dfs(*v_unmarked.begin()); if (v_unmarked.size() > 0) { nm_vert++; for (uint32_t f : f_adjacent) kill_face(f); } } if (nm_vert > 0 || nm_edge > 0) { std::cout << "Non-manifold elements: vertices=" << nm_vert << ", edges=" << nm_edge << std::endl; } uint32_t nFaces = 0, nFacesOrig = F.size(); for (uint32_t f = 0; f < (uint32_t)F.size(); ++f) { if (F[f][0] == INVALID) continue; if (nFaces != f) { F[nFaces] = F[f]; } ++nFaces; } if (nFacesOrig != nFaces) { F.resize(nFaces); std::cout << "Faces reduced from " << nFacesOrig << " -> " << nFaces << std::endl; } }
33.433884
173
0.476579
[ "mesh", "vector" ]
f1ecdbf126c59918d736d6e1a6191b65947c5db8
3,479
cpp
C++
cameras/environment.cpp
cathook/rendering_final_proj
d0c147b563d6949839983bf38317c81367e2ed4c
[ "BSD-2-Clause" ]
3
2020-12-09T00:03:29.000Z
2021-07-03T13:31:41.000Z
cameras/environment.cpp
piwell/CS348B-pbrt
147a9a3ef55cfcb0a1ad0132c63d1ac2f928418f
[ "BSD-2-Clause" ]
null
null
null
cameras/environment.cpp
piwell/CS348B-pbrt
147a9a3ef55cfcb0a1ad0132c63d1ac2f928418f
[ "BSD-2-Clause" ]
1
2020-11-28T12:33:24.000Z
2020-11-28T12:33:24.000Z
/* pbrt source code Copyright(c) 1998-2012 Matt Pharr and Greg Humphreys. This file is part of pbrt. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // cameras/environment.cpp* #include "stdafx.h" #include "cameras/environment.h" #include "paramset.h" #include "sampler.h" // EnvironmentCamera Method Definitions float EnvironmentCamera::GenerateRay(const CameraSample &sample, Ray *ray) const { // Compute environment camera ray direction float theta = M_PI * sample.imageY / film->yResolution; float phi = 2 * M_PI * sample.imageX / film->xResolution; Vector dir(sinf(theta) * cosf(phi), cosf(theta), sinf(theta) * sinf(phi)); *ray = Ray(Point(0,0,0), dir, 0.f, INFINITY, sample.time); CameraToWorld(*ray, ray); return 1.f; } EnvironmentCamera *CreateEnvironmentCamera(const ParamSet &params, const AnimatedTransform &cam2world, Film *film) { // Extract common camera parameters from _ParamSet_ 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); swap(shutterclose, shutteropen); } float lensradius = params.FindOneFloat("lensradius", 0.f); float focaldistance = params.FindOneFloat("focaldistance", 1e30f); float frame = params.FindOneFloat("frameaspectratio", float(film->xResolution)/float(film->yResolution)); float screen[4]; if (frame > 1.f) { screen[0] = -frame; screen[1] = frame; screen[2] = -1.f; screen[3] = 1.f; } else { screen[0] = -1.f; screen[1] = 1.f; screen[2] = -1.f / frame; screen[3] = 1.f / frame; } int swi; const float *sw = params.FindFloat("screenwindow", &swi); if (sw && swi == 4) memcpy(screen, sw, 4*sizeof(float)); (void) lensradius; // don't need this (void) focaldistance; // don't need this return new EnvironmentCamera(cam2world, shutteropen, shutterclose, film); }
38.655556
79
0.68008
[ "vector" ]
f1edc62bbe0a011f35d40dece0ff284d29844276
4,710
cpp
C++
src/qt/bitcoinamountfield.cpp
lachesis/bitcoin
5c5d310a0a94ec00d08c52637d38f3344a6e2c6f
[ "MIT" ]
2
2017-10-01T04:19:51.000Z
2021-09-03T01:23:54.000Z
src/qt/bitcoinamountfield.cpp
Lolcust/Tenebrix-QT
822bf1ac9be041cfb608183d2d5c9ab8a7b212f9
[ "MIT" ]
null
null
null
src/qt/bitcoinamountfield.cpp
Lolcust/Tenebrix-QT
822bf1ac9be041cfb608183d2d5c9ab8a7b212f9
[ "MIT" ]
null
null
null
#include "bitcoinamountfield.h" #include "qvalidatedlineedit.h" #include "qvaluecombobox.h" #include "bitcoinunits.h" #include <QLabel> #include <QLineEdit> #include <QRegExpValidator> #include <QHBoxLayout> #include <QKeyEvent> #include <QComboBox> BitcoinAmountField::BitcoinAmountField(QWidget *parent): QWidget(parent), amount(0), decimals(0), currentUnit(-1) { amount = new QValidatedLineEdit(this); amount->setValidator(new QRegExpValidator(QRegExp("[0-9]*"), this)); amount->setAlignment(Qt::AlignRight|Qt::AlignVCenter); amount->installEventFilter(this); amount->setMaximumWidth(75); decimals = new QValidatedLineEdit(this); decimals->setValidator(new QRegExpValidator(QRegExp("[0-9]+"), this)); decimals->setAlignment(Qt::AlignLeft|Qt::AlignVCenter); decimals->setMaximumWidth(75); QHBoxLayout *layout = new QHBoxLayout(this); layout->setSpacing(0); layout->addWidget(amount); layout->addWidget(new QLabel(QString("<b>.</b>"))); layout->addWidget(decimals); unit = new QValueComboBox(this); unit->setModel(new BitcoinUnits(this)); layout->addWidget(unit); layout->addStretch(1); layout->setContentsMargins(0,0,0,0); setLayout(layout); setFocusPolicy(Qt::TabFocus); setFocusProxy(amount); // If one if the widgets changes, the combined content changes as well connect(amount, SIGNAL(textChanged(QString)), this, SIGNAL(textChanged())); connect(decimals, SIGNAL(textChanged(QString)), this, SIGNAL(textChanged())); connect(unit, SIGNAL(currentIndexChanged(int)), this, SLOT(unitChanged(int))); // Set default based on configuration unitChanged(unit->currentIndex()); } void BitcoinAmountField::setText(const QString &text) { const QStringList parts = text.split(QString(".")); if(parts.size() == 2) { amount->setText(parts[0]); decimals->setText(parts[1]); } else { amount->setText(QString()); decimals->setText(QString()); } } void BitcoinAmountField::clear() { amount->clear(); decimals->clear(); unit->setCurrentIndex(0); } bool BitcoinAmountField::validate() { bool valid = true; if(decimals->text().isEmpty()) { decimals->setValid(false); valid = false; } if(!BitcoinUnits::parse(currentUnit, text(), 0)) { setValid(false); valid = false; } return valid; } void BitcoinAmountField::setValid(bool valid) { amount->setValid(valid); decimals->setValid(valid); } QString BitcoinAmountField::text() const { if(decimals->text().isEmpty() && amount->text().isEmpty()) { return QString(); } return amount->text() + QString(".") + decimals->text(); } // Intercept '.' and ',' keys, if pressed focus a specified widget bool BitcoinAmountField::eventFilter(QObject *object, QEvent *event) { Q_UNUSED(object); if(event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if(keyEvent->key() == Qt::Key_Period || keyEvent->key() == Qt::Key_Comma) { decimals->setFocus(); decimals->selectAll(); } } return false; } QWidget *BitcoinAmountField::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, amount); QWidget::setTabOrder(amount, decimals); return decimals; } qint64 BitcoinAmountField::value(bool *valid_out) const { qint64 val_out = 0; bool valid = BitcoinUnits::parse(currentUnit, text(), &val_out); if(valid_out) { *valid_out = valid; } return val_out; } void BitcoinAmountField::setValue(qint64 value) { setText(BitcoinUnits::format(currentUnit, value)); } void BitcoinAmountField::unitChanged(int idx) { // Use description tooltip for current unit for the combobox unit->setToolTip(unit->itemData(idx, Qt::ToolTipRole).toString()); // Determine new unit ID int newUnit = unit->itemData(idx, BitcoinUnits::UnitRole).toInt(); // Parse current value and convert to new unit bool valid = false; qint64 currentValue = value(&valid); currentUnit = newUnit; // Set max length after retrieving the value, to prevent truncation amount->setMaxLength(BitcoinUnits::amountDigits(currentUnit)); decimals->setMaxLength(BitcoinUnits::decimals(currentUnit)); if(valid) { // If value was valid, re-place it in the widget with the new unit setValue(currentValue); } else { // If current value is invalid, just clear field setText(""); } setValid(true); } void BitcoinAmountField::setDisplayUnit(int newUnit) { unit->setValue(newUnit); }
26.312849
82
0.661783
[ "object" ]
f1f280f8943b8b082cb0d813a01d222066fe4662
1,204
cpp
C++
Regex/Problem24/main.cpp
zsef123/ModernCppChallengeStudy
058c0a6c5e41758f53336e554f29b497c9881fae
[ "MIT" ]
null
null
null
Regex/Problem24/main.cpp
zsef123/ModernCppChallengeStudy
058c0a6c5e41758f53336e554f29b497c9881fae
[ "MIT" ]
null
null
null
Regex/Problem24/main.cpp
zsef123/ModernCppChallengeStudy
058c0a6c5e41758f53336e554f29b497c9881fae
[ "MIT" ]
null
null
null
#include <gsl/gsl> #include <vector> #include <string> #include <iostream> #include <boost/algorithm/string.hpp> /* String to binary conversion Write a function that, given a string containing hexadecimal digits as the input argument, returns a vector of 8-bit integers that represent the numerical deserialization of the string content. Th following are examples: Input: "BAADF00D"or "baadF00D", output: {0xBA, 0xAD, 0xF0, 0x0D} Input "010203040506", output: {1, 2, 3, 4, 5, 6} */ auto str2hex(std::string &input) { const char *ptr = input.c_str(); char buf[3] = {0}; std::vector<std::string> output; size_t max = input.length(); for (size_t i = 0; i < max - 1; i += 2) { if (ptr[i] < '9' && ptr[i+1] < '9'){ output.push_back(std::string(1, ptr[i + 1])); } else { output.push_back(std::string("0x") + boost::algorithm::to_upper_copy(std::string(ptr + i, 2))); } } return output; } int main(int argc, char* argv[]) { std::string a = "BAADF00D"; std::string b = "baadF00D"; std::string c = "010203040506"; auto z = str2hex(a); for (auto x : z) std::cout << x << ", "; return 0; }
28
107
0.60299
[ "vector" ]
f1f8e8b0fc7357bfa364b9526addd07f1d1d7981
789
cpp
C++
JAL/PAT/Advanced/1028.cpp
webturing/CPlusPlus
6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f
[ "AFL-2.0" ]
14
2018-06-21T14:41:26.000Z
2021-12-19T14:43:51.000Z
JAL/PAT/Advanced/1028.cpp
webturing/CPlusPlus
6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f
[ "AFL-2.0" ]
null
null
null
JAL/PAT/Advanced/1028.cpp
webturing/CPlusPlus
6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f
[ "AFL-2.0" ]
2
2020-04-20T11:16:53.000Z
2021-01-02T15:58:35.000Z
#include<bits/stdc++.h> using namespace std; template<typename T = int> T read(){ T x; cin >> x; return x; } struct Node { int score; string id,name; }; int main(){ int n = read(), c = read(); vector<Node>v(n); for(auto &i: v){ i.id = read<string>(); i.name = read<string>(); i.score = read(); } if(c == 1){ sort(v.begin(), v.end(), [](Node a, Node b)->bool{ return a.id < b.id; }); }else if(c == 2){ sort(v.begin(), v.end(), [](Node a, Node b)->bool{ if(a.name != b.name) return a.name < b.name; return a.id < b.id; }); }else{ sort(v.begin(), v.end(), [](Node a, Node b)->bool{ if(a.score != b.score) return a.score < b.score; return a.id < b.id; }); } for(auto i: v){ cout << i.id << ' ' << i.name << ' ' << i.score << endl; } }
18.785714
58
0.515843
[ "vector" ]
f1f9edacbb5ae5aa215f999debe5c34b746ae29a
4,420
cpp
C++
src/GLES/FCGLMesh.cpp
mslinklater/FC
d00e2e56a982cd7c85c7de18ac0449bf43d8025e
[ "MIT" ]
null
null
null
src/GLES/FCGLMesh.cpp
mslinklater/FC
d00e2e56a982cd7c85c7de18ac0449bf43d8025e
[ "MIT" ]
null
null
null
src/GLES/FCGLMesh.cpp
mslinklater/FC
d00e2e56a982cd7c85c7de18ac0449bf43d8025e
[ "MIT" ]
2
2015-04-13T10:07:14.000Z
2019-05-16T11:14:18.000Z
/* Copyright (C) 2011-2012 by Martin Linklater Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Shared/Graphics/FCGraphics.h" #include "FCGLMesh.h" #include "FCGLShaderManager.h" FCGLMesh::FCGLMesh( std::string shaderName, GLenum primitiveType ) : m_pParentModel(0) , m_vertexBufferStride(0) , m_numVertices(0) , m_numTriangles(0) , m_numEdges(0) , m_sizeVertexBuffer(0) , m_pVertexBuffer(0) , m_sizeIndexBuffer(0) , m_pIndexBuffer(0) , m_vertexBufferHandle(0) , m_indexBufferHandle(0) , m_fixedUp(false) , m_primitiveType(primitiveType) { // m_shaderProgram = FCGLShaderManager::Instance()->Program( shaderName ); // m_vertexBufferStride = m_shaderProgram->Stride(); } FCGLMesh::~FCGLMesh() { FCglDeleteBuffers(1, &m_indexBufferHandle); FCglDeleteBuffers(1, &m_vertexBufferHandle); if (m_pIndexBuffer) { free( m_pIndexBuffer ); } if (m_pVertexBuffer) { free( m_pVertexBuffer ); } } void FCGLMesh::SetNumVertices( uint32_t numVertices ) { FC_ASSERT( m_vertexBufferStride ); FC_ASSERT_MSG( m_numVertices == 0, "numVertices already set - cannot do twice" ); FC_ASSERT_MSG( m_numVertices < 65535, "Cannot cope with meshes with more than 65535 verts yet"); m_numVertices = numVertices; m_sizeVertexBuffer = m_numVertices * m_vertexBufferStride; m_pVertexBuffer = malloc( m_sizeVertexBuffer ); } void FCGLMesh::SetNumTriangles( uint32_t numTriangles ) { if( m_primitiveType == GL_TRIANGLES ) { FC_ASSERT_MSG( m_numTriangles == 0, "numTriangles already set - cannot do twice"); m_numTriangles = numTriangles; m_sizeIndexBuffer = m_numTriangles * 3 * sizeof(uint16_t); m_pIndexBuffer = (uint16_t*)malloc( m_sizeIndexBuffer ); } } void FCGLMesh::SetNumEdges( uint32_t numEdges ) { if( m_primitiveType == GL_LINES ) { FC_ASSERT_MSG( m_numEdges == 0, "numEdges already set - cannot do twice"); m_numEdges = numEdges; m_sizeIndexBuffer = m_numEdges * 2 * sizeof(uint16_t); m_pIndexBuffer = (uint16_t*)malloc( m_sizeIndexBuffer ); } } void FCGLMesh::Render() { if (!m_fixedUp) { FixUpBuffers(); } m_shaderProgram->Use(); FCglBindBuffer( GL_ELEMENT_ARRAY_BUFFER, m_indexBufferHandle ); FCglBindBuffer( GL_ARRAY_BUFFER, m_vertexBufferHandle ); m_shaderProgram->BindUniformsWithMesh( this ); m_shaderProgram->BindAttributes(); #if defined (FC_DEBUG) m_shaderProgram->Validate(); #endif switch (m_primitiveType) { case GL_TRIANGLES: FCglDrawElements( GL_TRIANGLES, m_numTriangles * 3, GL_UNSIGNED_SHORT, 0 ); break; case GL_LINES: FCglDrawElements( GL_LINES, m_numEdges * 2, GL_UNSIGNED_SHORT, 0 ); break; default: FC_HALT; break; } } void FCGLMesh::FixUpBuffers() { FC_ASSERT( !m_fixedUp ); // build VBOs FCglGenBuffers( 1, &m_vertexBufferHandle); FCglBindBuffer( GL_ARRAY_BUFFER, m_vertexBufferHandle ); FCglBufferData( GL_ARRAY_BUFFER, m_sizeVertexBuffer, m_pVertexBuffer, GL_STATIC_DRAW ); FCglGenBuffers( 1, &m_indexBufferHandle ); FCglBindBuffer( GL_ELEMENT_ARRAY_BUFFER, m_indexBufferHandle ); FCglBufferData( GL_ELEMENT_ARRAY_BUFFER, m_sizeIndexBuffer, m_pIndexBuffer, GL_STATIC_DRAW ); // release working memory if( m_pVertexBuffer ) { free( m_pVertexBuffer ); m_pVertexBuffer = 0; } if( m_pIndexBuffer ) { free( m_pIndexBuffer ); m_pIndexBuffer = 0; } m_fixedUp = true; } uint16_t* FCGLMesh::PIndexBufferAtIndex( uint16_t index ) { return m_pIndexBuffer + index; }
27.116564
97
0.755204
[ "render" ]
f1fc9b839cc0c7552376eafc87809e3fbcbbf4b1
49,476
cc
C++
ash/wm/desks/templates/desks_templates_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-11-16T13:10:29.000Z
2021-11-16T13:10:29.000Z
ash/wm/desks/templates/desks_templates_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
ash/wm/desks/templates/desks_templates_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2021 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 <string> #include "ash/constants/app_types.h" #include "ash/constants/ash_features.h" #include "ash/constants/ash_pref_names.h" #include "ash/public/cpp/desk_template.h" #include "ash/public/cpp/rounded_image_view.h" #include "ash/session/session_controller_impl.h" #include "ash/shell.h" #include "ash/style/button_style.h" #include "ash/wm/desks/desk_mini_view.h" #include "ash/wm/desks/desks_bar_view.h" #include "ash/wm/desks/desks_test_util.h" #include "ash/wm/desks/expanded_desks_bar_button.h" #include "ash/wm/desks/templates/desks_templates_dialog_controller.h" #include "ash/wm/desks/templates/desks_templates_grid_view.h" #include "ash/wm/desks/templates/desks_templates_icon_container.h" #include "ash/wm/desks/templates/desks_templates_icon_view.h" #include "ash/wm/desks/templates/desks_templates_item_view.h" #include "ash/wm/desks/templates/desks_templates_presenter.h" #include "ash/wm/desks/zero_state_button.h" #include "ash/wm/mru_window_tracker.h" #include "ash/wm/overview/overview_grid.h" #include "ash/wm/overview/overview_highlight_controller.h" #include "ash/wm/overview/overview_session.h" #include "ash/wm/overview/overview_test_base.h" #include "ash/wm/overview/overview_test_util.h" #include "ash/wm/tablet_mode/tablet_mode_controller.h" #include "base/callback_helpers.h" #include "base/guid.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/test/bind.h" #include "base/test/scoped_feature_list.h" #include "base/time/time.h" #include "components/app_restore/app_launch_info.h" #include "components/app_restore/window_info.h" #include "components/prefs/pref_service.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/window.h" #include "ui/compositor/layer.h" #include "ui/events/test/event_generator.h" #include "ui/views/controls/label.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/window/dialog_delegate.h" namespace ash { // Wrapper for DesksTemplatesPresenter that exposes internal state to test // functions. class DesksTemplatesPresenterTestApi { public: explicit DesksTemplatesPresenterTestApi(DesksTemplatesPresenter* presenter) : presenter_(presenter) { DCHECK(presenter_); } DesksTemplatesPresenterTestApi(const DesksTemplatesPresenterTestApi&) = delete; DesksTemplatesPresenterTestApi& operator=( const DesksTemplatesPresenterTestApi&) = delete; ~DesksTemplatesPresenterTestApi() = default; void SetOnUpdateUiClosure(base::OnceClosure closure) { DCHECK(!presenter_->on_update_ui_closure_for_testing_); presenter_->on_update_ui_closure_for_testing_ = std::move(closure); } private: DesksTemplatesPresenter* const presenter_; }; // Wrapper for DesksTemplatesGridView that exposes internal state to test // functions. class DesksTemplatesGridViewTestApi { public: explicit DesksTemplatesGridViewTestApi( const DesksTemplatesGridView* grid_view) : grid_view_(grid_view) { DCHECK(grid_view_); } DesksTemplatesGridViewTestApi(const DesksTemplatesGridViewTestApi&) = delete; DesksTemplatesGridViewTestApi& operator=( const DesksTemplatesGridViewTestApi&) = delete; ~DesksTemplatesGridViewTestApi() = default; const std::vector<DesksTemplatesItemView*>& grid_items() const { return grid_view_->grid_items_; } private: const DesksTemplatesGridView* grid_view_; }; // Wrapper for DesksTemplatesItemView that exposes internal state to test // functions. class DesksTemplatesItemViewTestApi { public: explicit DesksTemplatesItemViewTestApi( const DesksTemplatesItemView* item_view) : item_view_(item_view) { DCHECK(item_view_); } DesksTemplatesItemViewTestApi(const DesksTemplatesItemViewTestApi&) = delete; DesksTemplatesItemViewTestApi& operator=( const DesksTemplatesItemViewTestApi&) = delete; ~DesksTemplatesItemViewTestApi() = default; const views::Textfield* name_view() const { return item_view_->name_view_; } const views::Label* time_view() const { return item_view_->time_view_; } const CloseButton* delete_button() const { return item_view_->delete_button_; } const PillButton* launch_button() const { return item_view_->launch_button_; } const base::GUID uuid() const { return item_view_->uuid_; } const std::vector<DesksTemplatesIconView*>& icon_views() const { return item_view_->icon_container_view_->icon_views_; } private: const DesksTemplatesItemView* item_view_; }; // Wrapper for DesksTemplatesIconView that exposes internal state to test // functions. class DesksTemplatesIconViewTestApi { public: explicit DesksTemplatesIconViewTestApi( const DesksTemplatesIconView* desks_templates_icon_view) : desks_templates_icon_view_(desks_templates_icon_view) { DCHECK(desks_templates_icon_view_); } DesksTemplatesIconViewTestApi(const DesksTemplatesIconViewTestApi&) = delete; DesksTemplatesIconViewTestApi& operator=( const DesksTemplatesIconViewTestApi&) = delete; ~DesksTemplatesIconViewTestApi() = default; const views::Label* count_label() const { return desks_templates_icon_view_->count_label_; } const RoundedImageView* icon_view() const { return desks_templates_icon_view_->icon_view_; } const DesksTemplatesIconView* desks_templates_icon_view() const { return desks_templates_icon_view_; } private: const DesksTemplatesIconView* desks_templates_icon_view_; }; class DesksTemplatesTest : public OverviewTestBase { public: DesksTemplatesTest() = default; DesksTemplatesTest(const DesksTemplatesTest&) = delete; DesksTemplatesTest& operator=(const DesksTemplatesTest&) = delete; ~DesksTemplatesTest() override = default; // Adds an entry to the desks model directly without capturing a desk. Allows // for testing the names and times of the UI directly. void AddEntry(const base::GUID& uuid, const std::string& name, base::Time created_time, std::unique_ptr<app_restore::RestoreData> restore_data = std::make_unique<app_restore::RestoreData>()) { auto desk_template = std::make_unique<DeskTemplate>( uuid.AsLowercaseString(), DeskTemplateSource::kUser, name, created_time); desk_template->set_desk_restore_data(std::move(restore_data)); AddEntry(std::move(desk_template)); } // Adds a captured desk entry to the desks model. void AddEntry(std::unique_ptr<DeskTemplate> desk_template) { base::RunLoop loop; desk_model()->AddOrUpdateEntry( std::move(desk_template), base::BindLambdaForTesting( [&](desks_storage::DeskModel::AddOrUpdateEntryStatus status) { EXPECT_EQ(desks_storage::DeskModel::AddOrUpdateEntryStatus::kOk, status); loop.Quit(); })); loop.Run(); } // Creates an app_restore::RestoreData object with `num_windows.size()` apps, // where the ith app has `num_windows[i]` windows. The windows // activation index is its creation order. std::unique_ptr<app_restore::RestoreData> CreateRestoreData( std::vector<int> num_windows) { auto restore_data = std::make_unique<app_restore::RestoreData>(); int32_t activation_index_counter = 0; for (size_t i = 0; i < num_windows.size(); ++i) { const std::string app_id = base::NumberToString(i); for (int32_t window_id = 0; window_id < num_windows[i]; ++window_id) { restore_data->AddAppLaunchInfo( std::make_unique<app_restore::AppLaunchInfo>(app_id, window_id)); app_restore::WindowInfo window_info; window_info.activation_index = absl::make_optional<int32_t>(activation_index_counter++); restore_data->ModifyWindowInfo(app_id, window_id, window_info); } } return restore_data; } // Return the `grid_item_index`th DesksTemplatesItemView from the first // OverviewGrid in `GetOverviewGridList()`. DesksTemplatesItemView* GetItemViewFromOverviewGrid(int grid_item_index) { views::Widget* grid_widget = GetOverviewGridList().front()->desks_templates_grid_widget(); DCHECK(grid_widget); const DesksTemplatesGridView* templates_grid_view = static_cast<DesksTemplatesGridView*>(grid_widget->GetContentsView()); DCHECK(templates_grid_view); std::vector<DesksTemplatesItemView*> grid_items = DesksTemplatesGridViewTestApi(templates_grid_view).grid_items(); DesksTemplatesItemView* item_view = grid_items.at(grid_item_index); DCHECK(item_view); return item_view; } // Gets the current list of template entries from the desk model directly // without updating the UI. const std::vector<DeskTemplate*> GetAllEntries() { std::vector<DeskTemplate*> templates; base::RunLoop loop; desk_model()->GetAllEntries(base::BindLambdaForTesting( [&](desks_storage::DeskModel::GetAllEntriesStatus status, std::vector<DeskTemplate*> entries) { EXPECT_EQ(desks_storage::DeskModel::GetAllEntriesStatus::kOk, status); templates = entries; loop.Quit(); })); loop.Run(); return templates; } // Deletes an entry to the desks model directly without interacting with the // UI. void DeleteEntry(const base::GUID& uuid) { base::RunLoop loop; desk_model()->DeleteEntry( uuid.AsLowercaseString(), base::BindLambdaForTesting( [&](desks_storage::DeskModel::DeleteEntryStatus status) { loop.Quit(); })); loop.Run(); } // A lot of the UI relies on calling into the local desk data manager to // update, which sends callbacks via posting tasks. Call `WaitForUI()` if // testing a piece of the UI which calls into the desk model. void WaitForUI() { auto* overview_session = GetOverviewSession(); DCHECK(overview_session); base::RunLoop run_loop; DesksTemplatesPresenterTestApi( overview_session->desks_templates_presenter()) .SetOnUpdateUiClosure(run_loop.QuitClosure()); run_loop.Run(); } views::View* GetDesksTemplatesButtonForRoot(aura::Window* root_window, bool zero_state) { auto* overview_session = GetOverviewSession(); if (!overview_session) return nullptr; const auto* overview_grid = overview_session->GetGridWithRootWindow(root_window); // May be null in tablet mode. const auto* desks_bar_view = overview_grid->desks_bar_view(); if (!desks_bar_view) return nullptr; if (zero_state) return desks_bar_view->zero_state_desks_templates_button(); return desks_bar_view->expanded_state_desks_templates_button(); } views::Widget* GetSaveDeskAsTemplateButtonForRoot(aura::Window* root_window) { auto* overview_session = GetOverviewSession(); if (!overview_session) return nullptr; const auto* overview_grid = overview_session->GetGridWithRootWindow(root_window); return overview_grid->save_desk_as_template_widget_.get(); } // Shows the desks templates grid by emulating a click on the templates // button. It is required to have at least one entry in the desk model for the // button to be visible and clickable. void ShowDesksTemplatesGrids() { auto* root_window = Shell::GetPrimaryRootWindow(); auto* zero_button = GetDesksTemplatesButtonForRoot(root_window, /*zero_state=*/true); auto* expanded_button = GetDesksTemplatesButtonForRoot(root_window, /*zero_state=*/false); ASSERT_TRUE(zero_button); ASSERT_TRUE(expanded_button); ASSERT_TRUE(zero_button->GetVisible() || expanded_button->GetVisible()); if (zero_button->GetVisible()) ClickOnView(zero_button); else ClickOnView(expanded_button); } // Helper function for attempting to delete a template based on its uuid. Also // checks if the grid item count is as expected before deleting. This function // assumes we are already in overview mode and viewing the desks templates // grid. void DeleteTemplate(const base::GUID uuid, const size_t expected_current_item_count, bool expect_template_exists = true) { auto& grid_list = GetOverviewGridList(); views::Widget* grid_widget = grid_list[0]->desks_templates_grid_widget(); ASSERT_TRUE(grid_widget); const DesksTemplatesGridView* templates_grid_view = static_cast<DesksTemplatesGridView*>(grid_widget->GetContentsView()); ASSERT_TRUE(templates_grid_view); std::vector<DesksTemplatesItemView*> grid_items = DesksTemplatesGridViewTestApi(templates_grid_view).grid_items(); // Check the current grid item count. ASSERT_EQ(expected_current_item_count, grid_items.size()); auto iter = std::find_if(grid_items.cbegin(), grid_items.cend(), [&](const DesksTemplatesItemView* v) { return DesksTemplatesItemViewTestApi(v).uuid() == uuid; }); if (!expect_template_exists) { ASSERT_EQ(grid_items.end(), iter); return; } ASSERT_NE(grid_items.end(), iter); ClickOnView(DesksTemplatesItemViewTestApi(*iter).delete_button()); // Clicking on the delete button should bring up the delete dialog. ASSERT_TRUE(Shell::IsSystemModalWindowOpen()); // Click the delete button on the delete dialog. Show delete dialog and // select accept. auto* dialog_controller = DesksTemplatesDialogController::Get(); auto* dialog_delegate = dialog_controller->dialog_widget() ->widget_delegate() ->AsDialogDelegate(); dialog_delegate->AcceptDialog(); WaitForUI(); } // Open overview mode if we're not in overview mode yet, and then show the // desks templates grid. void OpenOverviewAndShowTemplatesGrid() { if (!GetOverviewSession()) { ToggleOverview(); WaitForUI(); } ShowDesksTemplatesGrids(); WaitForUI(); } void ClickOnView(const views::View* view) { DCHECK(view); const gfx::Point view_center = view->GetBoundsInScreen().CenterPoint(); auto* event_generator = GetEventGenerator(); event_generator->MoveMouseTo(view_center); DCHECK(view->GetVisible()); event_generator->ClickLeftButton(); } const std::vector<std::unique_ptr<OverviewGrid>>& GetOverviewGridList() { auto* overview_session = GetOverviewSession(); DCHECK(overview_session); return overview_session->grid_list(); } OverviewHighlightableView* GetHighlightedView() { return OverviewHighlightController::TestApi( GetOverviewSession()->highlight_controller()) .GetHighlightView(); } // Opens overview mode and then clicks the save template button. This should // save a new desk template and open the desks templates grid. void OpenOverviewAndSaveTemplate(aura::Window* root) { if (!GetOverviewSession()) { ToggleOverview(); WaitForUI(); } auto* save_template = GetSaveDeskAsTemplateButtonForRoot(root); ASSERT_TRUE(save_template->IsVisible()); ClickOnView(save_template->GetContentsView()); WaitForUI(); for (auto& overview_grid : GetOverviewGridList()) ASSERT_TRUE(overview_grid->IsShowingDesksTemplatesGrid()); } // OverviewTestBase: void SetUp() override { scoped_feature_list_.InitAndEnableFeature(features::kDesksTemplates); OverviewTestBase::SetUp(); } private: base::test::ScopedFeatureList scoped_feature_list_; }; // Tests the helpers `AddEntry()` and `DeleteEntry()`, which will be used in // different tests. TEST_F(DesksTemplatesTest, AddDeleteEntry) { const base::GUID expected_uuid = base::GUID::GenerateRandomV4(); const std::string expected_name = "desk name"; base::Time expected_time = base::Time::Now(); AddEntry(expected_uuid, expected_name, expected_time); std::vector<DeskTemplate*> entries = GetAllEntries(); ASSERT_EQ(1ul, entries.size()); EXPECT_EQ(expected_uuid, entries[0]->uuid()); EXPECT_EQ(base::UTF8ToUTF16(expected_name), entries[0]->template_name()); EXPECT_EQ(expected_time, entries[0]->created_time()); DeleteEntry(expected_uuid); EXPECT_EQ(0ul, desk_model()->GetEntryCount()); } // Tests the desks templates button visibility in clamshell mode. TEST_F(DesksTemplatesTest, DesksTemplatesButtonVisibilityClamshell) { // Helper function to verify which of the desks templates buttons are // currently shown. auto verify_button_visibilities = [this](bool zero_state_shown, bool expanded_state_shown, const std::string& trace_string) { SCOPED_TRACE(trace_string); for (auto* root_window : Shell::GetAllRootWindows()) { auto* zero_button = GetDesksTemplatesButtonForRoot(root_window, /*zero_state=*/true); auto* expanded_button = GetDesksTemplatesButtonForRoot(root_window, /*zero_state=*/false); ASSERT_TRUE(zero_button); ASSERT_TRUE(expanded_button); EXPECT_EQ(zero_state_shown, zero_button->GetVisible()); EXPECT_EQ(expanded_state_shown, expanded_button->GetVisible()); } }; // The templates button should appear on all root windows. UpdateDisplay("800x700,801+0-800x700"); ASSERT_EQ(2u, Shell::GetAllRootWindows().size()); // There are no entries initially, so the none of the desks templates buttons // are visible. ToggleOverview(); WaitForUI(); verify_button_visibilities(/*zero_state_shown=*/false, /*expanded_state_shown=*/false, /*trace_string=*/"one-desk-zero-entries"); // Exit overview and add an entry. ToggleOverview(); const base::GUID guid = base::GUID::GenerateRandomV4(); AddEntry(guid, "template", base::Time::Now()); // Reenter overview and verify the zero state desks templates buttons are // visible since there is one entry to view. ToggleOverview(); WaitForUI(); verify_button_visibilities(/*zero_state_shown=*/true, /*expanded_state_shown=*/false, /*trace_string=*/"one-desk-one-entry"); // Click on the templates button. It should expand the desks bar. ClickOnView(GetDesksTemplatesButtonForRoot(Shell::GetPrimaryRootWindow(), /*zero_state=*/true)); verify_button_visibilities(/*zero_state_shown=*/false, /*expanded_state_shown=*/true, /*trace_string=*/"expand-from-zero-state"); // Exit overview and create a new desk. ToggleOverview(); DesksController::Get()->NewDesk(DesksCreationRemovalSource::kKeyboard); // Reenter overview and verify the expanded state desks templates buttons are // visible since there is one entry to view. ToggleOverview(); WaitForUI(); verify_button_visibilities(/*zero_state_shown=*/false, /*expanded_state_shown=*/true, /*trace_string=*/"two-desk-one-entry"); // Exit overview and delete the entry. ToggleOverview(); DeleteEntry(guid); // Reenter overview and verify neither of the buttons are shown. ToggleOverview(); WaitForUI(); verify_button_visibilities(/*zero_state_shown=*/false, /*expanded_state_shown=*/false, /*trace_string=*/"two-desk-zero-entries"); } // Tests that the no windows widget is hidden when the desk templates grid is // shown. TEST_F(DesksTemplatesTest, NoWindowsLabelOnTemplateGridShow) { UpdateDisplay("400x300,400x300"); // At least one entry is required for the templates grid to be shown. AddEntry(base::GUID::GenerateRandomV4(), "template", base::Time::Now()); // Start overview mode. The no windows widget should be visible. ToggleOverview(); WaitForUI(); auto& grid_list = GetOverviewGridList(); ASSERT_EQ(2u, grid_list.size()); EXPECT_TRUE(grid_list[0]->no_windows_widget()); EXPECT_TRUE(grid_list[1]->no_windows_widget()); // Open the desk templates grid. The no windows widget should now be hidden. ShowDesksTemplatesGrids(); EXPECT_FALSE(grid_list[0]->no_windows_widget()); EXPECT_FALSE(grid_list[1]->no_windows_widget()); } // Tests that overview items are hidden when the desk templates grid is shown. TEST_F(DesksTemplatesTest, HideOverviewItemsOnTemplateGridShow) { UpdateDisplay("800x600,800x600"); AddEntry(base::GUID::GenerateRandomV4(), "template_1", base::Time::Now()); auto test_window = CreateTestWindow(); // Start overview mode. The window is visible in the overview mode. ToggleOverview(); WaitForUI(); ASSERT_TRUE(GetOverviewSession()); EXPECT_EQ(1.0f, test_window->layer()->opacity()); // Open the desk templates grid. This should hide the window. ShowDesksTemplatesGrids(); EXPECT_EQ(0.0f, test_window->layer()->opacity()); // Exit overview mode. The window is restored and visible again. ToggleOverview(); EXPECT_EQ(1.0f, test_window->layer()->opacity()); } // Tests that when the templates grid is shown and the active desk is closed, // overview items stay hidden. TEST_F(DesksTemplatesTest, OverviewItemsStayHiddenInTemplateGridOnDeskClose) { AddEntry(base::GUID::GenerateRandomV4(), "template_1", base::Time::Now()); // Create a test window in the current desk. DesksController* desks_controller = DesksController::Get(); auto test_window_1 = CreateTestWindow(); ASSERT_EQ(0, desks_controller->GetActiveDeskIndex()); EXPECT_EQ(1ul, desks_controller->active_desk()->windows().size()); // Create and activate a new desk, and create a test window there. desks_controller->NewDesk(DesksCreationRemovalSource::kKeyboard); Desk* desk = desks_controller->desks().back().get(); ActivateDesk(desk); auto test_window_2 = CreateTestWindow(); // Check that the active desk is the second desk, and that it contains one // window. ASSERT_EQ(1, desks_controller->GetActiveDeskIndex()); auto active_desk_windows = Shell::Get()->mru_window_tracker()->BuildMruWindowList(kActiveDesk); EXPECT_EQ(1ul, active_desk_windows.size()); auto all_windows = Shell::Get()->mru_window_tracker()->BuildMruWindowList(kAllDesks); EXPECT_EQ(2ul, all_windows.size()); // Start overview mode. `test_window_2` should be visible in overview mode. ToggleOverview(); WaitForUI(); ASSERT_TRUE(GetOverviewSession()); EXPECT_EQ(1.0f, test_window_2->layer()->opacity()); auto& overview_grid = GetOverviewGridList()[0]; EXPECT_FALSE(overview_grid->GetOverviewItemContaining(test_window_1.get())); EXPECT_TRUE(overview_grid->GetOverviewItemContaining(test_window_2.get())); // Open the desk templates grid. This should hide `test_window_2`. ShowDesksTemplatesGrids(); WaitForUI(); EXPECT_EQ(0.0f, test_window_2->layer()->opacity()); // While in the desk templates grid, delete the active desk by clicking on the // mini view close button. const auto* desks_bar_view = overview_grid->desks_bar_view(); auto* mini_view = desks_bar_view->FindMiniViewForDesk(desks_controller->active_desk()); ClickOnView(mini_view->close_desk_button()); // Expect we stay in the templates grid. ASSERT_TRUE(overview_grid->IsShowingDesksTemplatesGrid()); // Expect that the active desk is now the first desk. ASSERT_EQ(0, desks_controller->GetActiveDeskIndex()); // Expect both windows are not visible. EXPECT_EQ(0.0f, test_window_1->layer()->opacity()); EXPECT_EQ(0.0f, test_window_2->layer()->opacity()); // Exit overview mode. ToggleOverview(); // Expect both windows are visible. EXPECT_EQ(1.0f, test_window_1->layer()->opacity()); EXPECT_EQ(1.0f, test_window_2->layer()->opacity()); } // Tests the modality of the dialogs shown in desks templates. TEST_F(DesksTemplatesTest, DialogSystemModal) { UpdateDisplay("800x600,800x600"); ToggleOverview(); ASSERT_TRUE(GetOverviewSession()); // Show one of the dialogs. Activating the dialog keeps us in overview mode. auto* dialog_controller = DesksTemplatesDialogController::Get(); dialog_controller->ShowReplaceDialog(Shell::GetPrimaryRootWindow(), u"Bento"); EXPECT_TRUE(Shell::IsSystemModalWindowOpen()); ASSERT_TRUE(GetOverviewSession()); // Checks that pressing tab does not trigger overview keyboard traversal. SendKey(ui::VKEY_TAB); EXPECT_FALSE( GetOverviewSession()->highlight_controller()->IsFocusHighlightVisible()); // Fetch the widget for the dialog and test that it appears on the primary // root window. const views::Widget* dialog_widget = dialog_controller->dialog_widget(); ASSERT_TRUE(dialog_widget); EXPECT_EQ(Shell::GetPrimaryRootWindow(), dialog_widget->GetNativeWindow()->GetRootWindow()); // Hit escape to delete the dialog. Tests that there are no more system modal // windows open, and that we are still in overview because the dialog takes // the escape event, not the overview session. GetEventGenerator()->PressAndReleaseKey(ui::VKEY_ESCAPE); EXPECT_FALSE(Shell::IsSystemModalWindowOpen()); EXPECT_TRUE(GetOverviewSession()); } // Tests that the desks templates grid and item views are populated correctly. TEST_F(DesksTemplatesTest, DesksTemplatesGridItems) { UpdateDisplay("800x600,800x600"); const base::GUID uuid_1 = base::GUID::GenerateRandomV4(); const std::string name_1 = "template_1"; base::Time time_1 = base::Time::Now(); AddEntry(uuid_1, name_1, time_1); const base::GUID uuid_2 = base::GUID::GenerateRandomV4(); const std::string name_2 = "template_2"; base::Time time_2 = time_1 + base::Hours(13); AddEntry(uuid_2, name_2, time_2); OpenOverviewAndShowTemplatesGrid(); // Check that the grid is populated with the correct number of items, as // well as with the correct name and timestamp. for (auto& overview_grid : GetOverviewGridList()) { views::Widget* grid_widget = overview_grid->desks_templates_grid_widget(); ASSERT_TRUE(grid_widget); const DesksTemplatesGridView* templates_grid_view = static_cast<DesksTemplatesGridView*>(grid_widget->GetContentsView()); ASSERT_TRUE(templates_grid_view); std::vector<DesksTemplatesItemView*> grid_items = DesksTemplatesGridViewTestApi(templates_grid_view).grid_items(); ASSERT_EQ(2ul, grid_items.size()); // The grid item order is currently not guaranteed, so need to // verify that each template exists by looking them up by their // UUID. auto verify_template_grid_item = [grid_items](const base::GUID& uuid, const std::string& name) { auto iter = std::find_if(grid_items.cbegin(), grid_items.cend(), [uuid](const DesksTemplatesItemView* v) { return DesksTemplatesItemViewTestApi(v).uuid() == uuid; }); ASSERT_NE(grid_items.end(), iter); DesksTemplatesItemViewTestApi test_api(*iter); EXPECT_EQ(base::UTF8ToUTF16(name), test_api.name_view()->GetText()); EXPECT_FALSE(test_api.time_view()->GetText().empty()); }; verify_template_grid_item(uuid_1, name_1); verify_template_grid_item(uuid_2, name_2); } } // Tests that deleting templates in the templates grid functions correctly. TEST_F(DesksTemplatesTest, DISABLED_DeleteTemplate) { UpdateDisplay("800x600,800x600"); // Populate with several entries. const base::GUID uuid_1 = base::GUID::GenerateRandomV4(); AddEntry(uuid_1, "template_1", base::Time::Now()); const base::GUID uuid_2 = base::GUID::GenerateRandomV4(); AddEntry(uuid_2, "template_2", base::Time::Now() + base::Hours(13)); // This window should be hidden whenever the desk templates grid is open. auto test_window = CreateTestWindow(); OpenOverviewAndShowTemplatesGrid(); // The window is hidden because the desk templates grid is open. EXPECT_EQ(0.0f, test_window->layer()->opacity()); EXPECT_EQ(2ul, desk_model()->GetEntryCount()); // Delete the template with `uuid_1`. DeleteTemplate(uuid_1, /*expected_current_item_count=*/2); EXPECT_EQ(0.0f, test_window->layer()->opacity()); EXPECT_EQ(1ul, desk_model()->GetEntryCount()); // Verifies that the template with `uuid_1`, doesn't exist anymore. DeleteTemplate(uuid_1, /*expected_current_item_count=*/1, /*expect_template_exists=*/false); EXPECT_EQ(0.0f, test_window->layer()->opacity()); EXPECT_EQ(1ul, desk_model()->GetEntryCount()); // Delete the template with `uuid_2`. DeleteTemplate(uuid_2, /*expected_current_item_count=*/1); EXPECT_EQ(0ul, desk_model()->GetEntryCount()); // After all templates have been deleted, check to ensure we have exited the // Desks Templates Grid on all displays. Also check to make sure the hidden // windows and the save template button are shown again. EXPECT_EQ(1.0f, test_window->layer()->opacity()); for (auto& overview_grid : GetOverviewGridList()) EXPECT_FALSE(overview_grid->IsShowingDesksTemplatesGrid()); auto* save_template = GetSaveDeskAsTemplateButtonForRoot(Shell::GetPrimaryRootWindow()); EXPECT_TRUE(save_template->IsVisible()); } // Tests that the save desk as template button is disabled when the maximum // number of templates has been reached. TEST_F(DesksTemplatesTest, SaveDeskAsTemplateButtonDisabled) { // Create a test window in the current desk. auto test_window = CreateTestWindow(); aura::Window* root = Shell::GetPrimaryRootWindow(); // Open overview and save a template. OpenOverviewAndSaveTemplate(root); // The desks templates grid is now visible and `save_template` is no longer // visible, so exit overview to be able to click on it again. ToggleOverview(); // Verify that the entry has been added. ASSERT_EQ(1ul, GetAllEntries().size()); // Verify that the button is disabled after the maximum number of templates // have been added. AddEntry(base::GUID::GenerateRandomV4(), "template2", base::Time::Now()); AddEntry(base::GUID::GenerateRandomV4(), "template3", base::Time::Now()); AddEntry(base::GUID::GenerateRandomV4(), "template4", base::Time::Now()); AddEntry(base::GUID::GenerateRandomV4(), "template5", base::Time::Now()); AddEntry(base::GUID::GenerateRandomV4(), "template6", base::Time::Now()); ToggleOverview(); ASSERT_EQ(6ul, GetAllEntries().size()); auto* button = static_cast<PillButton*>( GetSaveDeskAsTemplateButtonForRoot(root)->GetContentsView()); EXPECT_EQ(views::Button::STATE_DISABLED, button->GetState()); } // Tests that clicking the save desk as template button shows the templates // grid. TEST_F(DesksTemplatesTest, SaveDeskAsTemplateButtonShowsDesksTemplatesGrid) { // There are no saved template entries and one test window initially. auto test_window = CreateTestWindow(); ToggleOverview(); WaitForUI(); // The `save_desk_as_template_widget` is visible when at least one window is // open. views::Widget* save_desk_as_template_widget = GetSaveDeskAsTemplateButtonForRoot(Shell::GetPrimaryRootWindow()); ASSERT_TRUE(save_desk_as_template_widget); EXPECT_TRUE(save_desk_as_template_widget->GetContentsView()->GetVisible()); // Click on `save_desk_as_template_widget` button. ClickOnView(save_desk_as_template_widget->GetContentsView()); ASSERT_EQ(1ul, GetAllEntries().size()); // Expect that the Desk Templates grid is visible. EXPECT_TRUE(GetOverviewGridList()[0]->IsShowingDesksTemplatesGrid()); } // Tests that launching templates from the templates grid functions correctly. // We test both clicking on the card, as well as clicking on the "Use template" // button that shows up on hover. Both should do the same thing. TEST_F(DesksTemplatesTest, LaunchTemplate) { DesksController* desks_controller = DesksController::Get(); ASSERT_EQ(0, desks_controller->GetActiveDeskIndex()); auto test_window = CreateTestWindow(); // Capture the current desk and open the templates grid. OpenOverviewAndSaveTemplate(Shell::Get()->GetPrimaryRootWindow()); ASSERT_EQ(1ul, GetAllEntries().size()); // Click on the grid item to launch the template. { DeskSwitchAnimationWaiter waiter; ClickOnView(GetItemViewFromOverviewGrid(/*grid_item_index=*/0)); WaitForUI(); waiter.Wait(); } // Verify that we have created and activated a new desk. EXPECT_EQ(2ul, desks_controller->desks().size()); EXPECT_EQ(1, desks_controller->GetActiveDeskIndex()); // Launching a template creates and activates a new desk, which also results // in exiting overview mode, so we check to make sure overview is closed. EXPECT_FALSE(InOverviewSession()); // This section tests clicking on the "Use template" button to launch the // template. OpenOverviewAndShowTemplatesGrid(); { DeskSwitchAnimationWaiter waiter; DesksTemplatesItemView* item_view = GetItemViewFromOverviewGrid( /*grid_item_index=*/0); ClickOnView(DesksTemplatesItemViewTestApi(item_view).launch_button()); WaitForUI(); waiter.Wait(); } EXPECT_EQ(3ul, desks_controller->desks().size()); EXPECT_EQ(2, desks_controller->GetActiveDeskIndex()); EXPECT_FALSE(InOverviewSession()); } // Tests that the order of DesksTemplatesItemView is in order. // TODO(chinsenj): Once ordering is finalized, update this comment to reflect // final ordering. Also this test case should use Browsers as well. TEST_F(DesksTemplatesTest, IconsOrder) { // Create a `DeskTemplate` using which has 5 apps and each app has 1 window. AddEntry(base::GUID::GenerateRandomV4(), "template_1", base::Time::Now(), CreateRestoreData(std::vector<int>(5, 1))); OpenOverviewAndShowTemplatesGrid(); // Get the icon views. DesksTemplatesItemView* item_view = GetItemViewFromOverviewGrid( /*grid_item_index=*/0); const std::vector<DesksTemplatesIconView*>& icon_views = DesksTemplatesItemViewTestApi(item_view).icon_views(); // The items previews should be ordered by activation index. Exclude the // final DesksTemplatesIconView since it will be the overflow counter. EXPECT_EQ(5u, icon_views.size()); for (size_t i = 0; i < icon_views.size() - 2; ++i) { int current_id; ASSERT_TRUE( base::StringToInt(icon_views[i]->icon_identifier(), &current_id)); int next_id; ASSERT_TRUE( base::StringToInt(icon_views[i + 1]->icon_identifier(), &next_id)); EXPECT_TRUE(current_id < next_id); } } // Tests that the overflow count view is visible, in bounds, displays the right // count when there is more than `DesksTemplatesIconContainer::kMaxIcons` icons. TEST_F(DesksTemplatesTest, OverflowIconView) { // Create a `DeskTemplate` using which has 1 app more than the max and each // app has 1 window. const int kNumOverflowApps = 1; std::vector<int> window_info( kNumOverflowApps + DesksTemplatesIconContainer::kMaxIcons, 1); AddEntry(base::GUID::GenerateRandomV4(), "template_1", base::Time::Now(), CreateRestoreData(window_info)); OpenOverviewAndShowTemplatesGrid(); // Get the icon views. DesksTemplatesItemView* item_view = GetItemViewFromOverviewGrid( /*grid_item_index=*/0); const std::vector<DesksTemplatesIconView*>& icon_views = DesksTemplatesItemViewTestApi(item_view).icon_views(); // There should only be the max number of icons plus the overflow icon. EXPECT_EQ(DesksTemplatesIconContainer::kMaxIcons + 1, static_cast<int>(icon_views.size())); // The overflow counter should have no identifier and its count should be // non-zero. It should also be visible and within the bounds of the host // DesksTemplatesItemView. DesksTemplatesIconViewTestApi overflow_icon_view{icon_views.back()}; EXPECT_FALSE(overflow_icon_view.icon_view()); EXPECT_TRUE(overflow_icon_view.count_label()); EXPECT_EQ(u"+1", overflow_icon_view.count_label()->GetText()); EXPECT_TRUE(overflow_icon_view.desks_templates_icon_view()->GetVisible()); EXPECT_TRUE( item_view->Contains(overflow_icon_view.desks_templates_icon_view())); } // Tests that when there isn't enough space to display // `DesksTemplatesIconContainer::kMaxIcons` icons and the overflow // icon view, the overflow icon view is visible and its count incremented by the // number of icons that had to be hidden. TEST_F(DesksTemplatesTest, OverflowIconViewIncrementsForHiddenIcons) { // Create a `DeskTemplate` using which has 3 apps more than // `DesksTemplatesIconContainer::kMaxIcons` and each app has 2 windows. const int kNumOverflowApps = 3; std::vector<int> window_info( kNumOverflowApps + DesksTemplatesIconContainer::kMaxIcons, 2); AddEntry(base::GUID::GenerateRandomV4(), "template_1", base::Time::Now(), CreateRestoreData(window_info)); OpenOverviewAndShowTemplatesGrid(); // Get the icon views. DesksTemplatesItemView* item_view = GetItemViewFromOverviewGrid( /*grid_item_index=*/0); const std::vector<DesksTemplatesIconView*>& icon_views = DesksTemplatesItemViewTestApi(item_view).icon_views(); // Even though there are more than `DesksTemplatesIconContainer::kMaxIcons`, // there should still be `DesksTemplatesIconContainer::kMaxIcons`+ 1 // DesksTemplatesIconView's created. EXPECT_EQ(icon_views.size(), DesksTemplatesIconContainer::kMaxIcons + 1u); // Count the number of hidden icon views and also check that there's a // contiguous block of visible icon views, followed by a contiguous block of // invisible icon views, followed by the overflow icon view. size_t num_hidden = 0; bool started_hiding_icon_views = false; for (size_t i = 0; i < icon_views.size(); ++i) { const bool is_visible = icon_views[i]->GetVisible(); if (!is_visible) { ++num_hidden; started_hiding_icon_views = true; } EXPECT_TRUE((is_visible && !started_hiding_icon_views) || (!is_visible && started_hiding_icon_views) || (is_visible && i == icon_views.size() - 1)); } // There should be at least one hidden view. EXPECT_LT(0u, num_hidden); // The overflow counter should have no identifier and its count should be // non-zero, accounting for the number of hidden app icons. It should also be // visible and within the bounds of the host DesksTemplatesItemView. DesksTemplatesIconViewTestApi overflow_icon_view{icon_views.back()}; EXPECT_FALSE(overflow_icon_view.icon_view()); EXPECT_TRUE(overflow_icon_view.count_label()); EXPECT_EQ(u"+5", overflow_icon_view.count_label()->GetText()); EXPECT_TRUE(overflow_icon_view.desks_templates_icon_view()->GetVisible()); EXPECT_TRUE( item_view->Contains(overflow_icon_view.desks_templates_icon_view())); } // Tests that when an app has more than 9 windows, its label is changed to "9+". TEST_F(DesksTemplatesTest, IconViewMoreThan9Windows) { // Create a `DeskTemplate` using which has 1 app with 10 windows. AddEntry(base::GUID::GenerateRandomV4(), "template_1", base::Time::Now(), CreateRestoreData(std::vector<int>{10})); // Enter overview and show the Desks Templates Grid. OpenOverviewAndShowTemplatesGrid(); // Get the icon views. DesksTemplatesItemView* item_view = GetItemViewFromOverviewGrid( /*grid_item_index=*/0); const std::vector<DesksTemplatesIconView*>& icon_views = DesksTemplatesItemViewTestApi(item_view).icon_views(); // There should only be 1 icon view for the app and 1 icon view for the // overflow. EXPECT_EQ(2u, icon_views.size()); // The app's icon view should have a "9+" label. DesksTemplatesIconViewTestApi icon_view(icon_views[0]); EXPECT_TRUE(icon_view.icon_view()); EXPECT_TRUE(icon_view.count_label()); EXPECT_EQ(u"9+", icon_view.count_label()->GetText()); // The overflow counter should not be visible. EXPECT_FALSE(icon_views.back()->GetVisible()); } // Tests that when there are less than `DesksTemplatesIconContainer::kMaxIcons` // the overflow icon is not visible. TEST_F(DesksTemplatesTest, OverflowIconViewHiddenOnNoOverflow) { // Create a `DeskTemplate` using which has // `DesksTemplatesIconContainer::kMaxIcons` apps and each app has 1 window. std::vector<int> window_info(DesksTemplatesIconContainer::kMaxIcons, 1); AddEntry(base::GUID::GenerateRandomV4(), "template_1", base::Time::Now(), CreateRestoreData(window_info)); OpenOverviewAndShowTemplatesGrid(); // Get the icon views. DesksTemplatesItemView* item_view = GetItemViewFromOverviewGrid( /*grid_item_index=*/0); const std::vector<DesksTemplatesIconView*>& icon_views = DesksTemplatesItemViewTestApi(item_view).icon_views(); // All the icon views should be visible and the overflow icon view should be // invisible. for (size_t i = 0; i < icon_views.size() - 1; ++i) EXPECT_TRUE(icon_views[i]->GetVisible()); EXPECT_FALSE(icon_views.back()->GetVisible()); } // Tests that the desks templates and save desk template buttons are hidden when // entering overview in tablet mode. TEST_F(DesksTemplatesTest, EnteringInTabletMode) { // Create a desk before entering tablet mode, otherwise the desks bar will not // show up. DesksController::Get()->NewDesk(DesksCreationRemovalSource::kKeyboard); // Create a window and add a test entry. Otherwise the templates UI wouldn't // show up in clamshell mode either. auto test_window_1 = CreateTestWindow(); AddEntry(base::GUID::GenerateRandomV4(), "template", base::Time::Now()); Shell::Get()->tablet_mode_controller()->SetEnabledForTest(true); // Test that the templates buttons are created but invisible. The save desk as // template button is not created. ToggleOverview(); WaitForUI(); aura::Window* root = Shell::GetPrimaryRootWindow(); auto* zero_state = GetDesksTemplatesButtonForRoot(root, /*zero_state=*/true); auto* expanded_state = GetDesksTemplatesButtonForRoot(root, /*zero_state=*/false); EXPECT_FALSE(zero_state->GetVisible()); EXPECT_FALSE(expanded_state->GetVisible()); EXPECT_FALSE(GetSaveDeskAsTemplateButtonForRoot(root)); } // Tests that the desks templates and save desk template buttons are hidden when // transitioning from clamshell to tablet mode. TEST_F(DesksTemplatesTest, ClamshellToTabletMode) { // Create a window and add a test entry. Otherwise the templates UI wouldn't // show up. auto test_window_1 = CreateTestWindow(); AddEntry(base::GUID::GenerateRandomV4(), "template", base::Time::Now()); // Test that on entering overview, the zero state desks templates button and // the save template button are visible. ToggleOverview(); WaitForUI(); aura::Window* root = Shell::GetPrimaryRootWindow(); auto* zero_state = GetDesksTemplatesButtonForRoot(root, /*zero_state=*/true); auto* expanded_state = GetDesksTemplatesButtonForRoot(root, /*zero_state=*/false); auto* save_template = GetSaveDeskAsTemplateButtonForRoot(root); EXPECT_TRUE(zero_state->GetVisible()); EXPECT_FALSE(expanded_state->GetVisible()); EXPECT_TRUE(save_template->IsVisible()); // Tests that after transitioning, we remain in overview mode and all the // buttons are invisible. Shell::Get()->tablet_mode_controller()->SetEnabledForTest(true); ASSERT_TRUE(GetOverviewSession()); EXPECT_FALSE(zero_state->GetVisible()); EXPECT_FALSE(expanded_state->GetVisible()); EXPECT_FALSE(save_template->IsVisible()); } // Tests that the desks templates grid gets hidden when transitioning to tablet // mode. TEST_F(DesksTemplatesTest, ShowingTemplatesGridToTabletMode) { // Create a window and add a test entry. Otherwise the templates UI wouldn't // show up. auto test_window_1 = CreateTestWindow(); AddEntry(base::GUID::GenerateRandomV4(), "template", base::Time::Now()); OpenOverviewAndShowTemplatesGrid(); aura::Window* root_window = Shell::GetPrimaryRootWindow(); ASSERT_TRUE(GetOverviewSession() ->GetGridWithRootWindow(root_window) ->desks_templates_grid_widget() ->IsVisible()); // Tests that after transitioning, we remain in overview mode and the grid is // hidden. Shell::Get()->tablet_mode_controller()->SetEnabledForTest(true); ASSERT_TRUE(GetOverviewSession()); EXPECT_FALSE(GetOverviewSession() ->GetGridWithRootWindow(root_window) ->desks_templates_grid_widget() ->IsVisible()); } TEST_F(DesksTemplatesTest, OverviewTabbing) { auto test_window = CreateTestWindow(); AddEntry(base::GUID::GenerateRandomV4(), "template1", base::Time::Now()); AddEntry(base::GUID::GenerateRandomV4(), "template2", base::Time::Now()); OpenOverviewAndShowTemplatesGrid(); DesksTemplatesItemView* first_item = GetItemViewFromOverviewGrid(0); DesksTemplatesItemView* second_item = GetItemViewFromOverviewGrid(1); // Testing that we first traverse the views of the first item. SendKey(ui::VKEY_TAB); EXPECT_EQ(first_item, GetHighlightedView()); // When we're done with the first item, we'll go on to the second. SendKey(ui::VKEY_TAB); EXPECT_EQ(second_item, GetHighlightedView()); } // Tests that the desks bar returns to zero state if the second-to-last desk is // deleted while viewing the templates grid. Also verifies that the zero state // buttons are visible. Regression test for https://crbug.com/1264989. TEST_F(DesksTemplatesTest, DesksBarReturnsToZeroState) { DesksController::Get()->NewDesk(DesksCreationRemovalSource::kKeyboard); const base::GUID uuid = base::GUID::GenerateRandomV4(); AddEntry(uuid, "template", base::Time::Now()); OpenOverviewAndShowTemplatesGrid(); aura::Window* root_window = Shell::GetPrimaryRootWindow(); auto* overview_grid = GetOverviewSession()->GetGridWithRootWindow(root_window); const auto* desks_bar_view = overview_grid->desks_bar_view(); // Close one of the desks. Test that we remain in expanded state. auto* mini_view = desks_bar_view->FindMiniViewForDesk( DesksController::Get()->active_desk()); ClickOnView(mini_view->close_desk_button()); auto* expanded_new_desk_button = desks_bar_view->expanded_state_new_desk_button(); auto* expanded_templates_button = desks_bar_view->expanded_state_desks_templates_button(); EXPECT_TRUE(expanded_new_desk_button->GetVisible()); EXPECT_TRUE(expanded_templates_button->GetVisible()); EXPECT_FALSE(desks_bar_view->IsZeroState()); // Delete the one and only template, which should hide the templates grid. DeleteTemplate(uuid, /*expected_current_item_count=*/1); EXPECT_FALSE(GetOverviewSession() ->GetGridWithRootWindow(root_window) ->desks_templates_grid_widget() ->IsVisible()); // Test that we are now in zero state. auto* zero_new_desk_button = desks_bar_view->zero_state_new_desk_button(); EXPECT_TRUE(zero_new_desk_button->GetVisible()); EXPECT_TRUE(desks_bar_view->IsZeroState()); } // Tests that the unsupported apps dialog is shown when a user attempts to save // an active desk with unsupported apps. TEST_F(DesksTemplatesTest, UnsupportedAppsDialog) { // `OpenOverviewAndSaveTemplate()` waits for the ui after it clicks on the // save template button. This will hang if a dialog is shown so we use this // helper function instead. auto open_overview_and_save_template = [this]() { auto* root = Shell::Get()->GetPrimaryRootWindow(); ToggleOverview(); WaitForUI(); auto* save_template = GetSaveDeskAsTemplateButtonForRoot(root); ASSERT_TRUE(save_template->IsVisible()); ClickOnView(save_template->GetContentsView()); }; // Create a crostini window. auto crostini_window = CreateTestWindow(); crostini_window->SetProperty(aura::client::kAppType, static_cast<int>(AppType::CROSTINI_APP)); // Create a normal window. auto test_window = CreateTestWindow(); // Open overview and click on the save template button. The unsupported apps // dialog should show up. open_overview_and_save_template(); EXPECT_TRUE(Shell::IsSystemModalWindowOpen()); // Decline the dialog. We should be out of overview now and no template should // have been saved. auto* dialog_controller = DesksTemplatesDialogController::Get(); dialog_controller->dialog_widget() ->widget_delegate() ->AsDialogDelegate() ->CancelDialog(); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(Shell::IsSystemModalWindowOpen()); EXPECT_FALSE(GetOverviewSession()); // Open overview again and click on the save template button. The unsupported // apps dialog should show up. open_overview_and_save_template(); EXPECT_TRUE(Shell::IsSystemModalWindowOpen()); // Accept the dialog. The template should have been saved. dialog_controller = DesksTemplatesDialogController::Get(); dialog_controller->dialog_widget() ->widget_delegate() ->AsDialogDelegate() ->AcceptDialog(); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(GetOverviewSession()); ASSERT_EQ(1ul, GetAllEntries().size()); } } // namespace ash
39.549161
80
0.723502
[ "object", "vector", "model" ]
f1fda526ff06f7e982b08d37fa9425039615bbfe
1,000
hpp
C++
src/countWorkerSystem.hpp
AlexAUT/WordCount
7afcbaa2583cba341b22d21da788a90bcc67ffbc
[ "MIT" ]
null
null
null
src/countWorkerSystem.hpp
AlexAUT/WordCount
7afcbaa2583cba341b22d21da788a90bcc67ffbc
[ "MIT" ]
null
null
null
src/countWorkerSystem.hpp
AlexAUT/WordCount
7afcbaa2583cba341b22d21da788a90bcc67ffbc
[ "MIT" ]
null
null
null
// // Created by alex on 11/24/17. // #ifndef WORDCOUNT_COUNTWORKERSYSTEM_HPP #define WORDCOUNT_COUNTWORKERSYSTEM_HPP #include <array> #include <condition_variable> #include <mutex> #include <queue> #include <string> #include <thread> #include <unordered_map> class CountWorkerSystem { public: typedef std::queue<std::string> LineQueue; typedef std::unordered_map<std::string, unsigned> WordCountMap; public: CountWorkerSystem(); explicit CountWorkerSystem(unsigned numberOfWorkers); ~CountWorkerSystem(); void addJob(const std::string& line); bool getJob(std::string& line); void addWords(const WordCountMap& map); void stop(); bool isRunning() const; const WordCountMap& getWordCountMap() const; private: bool mRunning; std::mutex mWordCountMutex; WordCountMap mWordCount; std::condition_variable mCondWaitForJobs; std::mutex mLinesToParseMutex; LineQueue mLinesToParse; std::vector<std::thread> mWorkers; }; #endif //WORDCOUNT_COUNTWORKERSYSTEM_HPP
20
65
0.76
[ "vector" ]
f1feb9b1d3bcaad2668ef5e7db135e1c254dfa1e
49,525
cpp
C++
programming/sampleProject/allData.cpp
ljyang100/dataScience
ad2b243673c570c18d83ab1a0cd1bb4694c17eac
[ "MIT" ]
2
2020-12-10T02:05:29.000Z
2021-05-30T15:23:56.000Z
programming/sampleProject/allData.cpp
ljyang100/dataScience
ad2b243673c570c18d83ab1a0cd1bb4694c17eac
[ "MIT" ]
null
null
null
programming/sampleProject/allData.cpp
ljyang100/dataScience
ad2b243673c570c18d83ab1a0cd1bb4694c17eac
[ "MIT" ]
1
2020-04-21T11:18:18.000Z
2020-04-21T11:18:18.000Z
#include "allData.h" //#include <chrono> //*** don't need this header even I use std::chrono::high_resolution_clock::time_point, because I have included std::chrono... void AllData::initializeTraderParameters() { m_volatilityFactorLong = 1.0; m_volatilityFactorShort = 1.0; m_closeLongPositions = false; m_closeShortPositions = false; //**** Always use {} for pairs in uniform initialization of a map. This is easy for initialzing a constant map with not-so-many element. m_manualMap.insert({ "symbol", 0 }); m_manualMap.insert({ "stopLossLong", 1 }); m_manualMap.insert({ "stopLossShort", 2 }); m_manualMap.insert({ "algoStringLong", 3 }); m_manualMap.insert({ "algoStringShort", 4 }); m_manualMap.insert({ "totalPosition", 5 }); m_historyMap.insert({ "date", 0 }); m_historyMap.insert({ "yearMonthDateString", 1 }); m_historyMap.insert({ "open", 2 }); m_historyMap.insert({ "high", 3 }); m_historyMap.insert({ "low", 4 }); m_historyMap.insert({ "close", 5 }); m_historyMap.insert({ "volume", 6 }); m_historyMap.insert({ "lastDownloadTime", 7 }); m_historyMap.insert({ "symbol", 8 }); AlgoLiteral algoLiteral; algoLiteral.LONG = "whiteSwanLong"; algoLiteral.SHORT = "whiteSwanShort"; m_algoString.push_back(algoLiteral); algoLiteral.LONG = "blackSwanLong"; algoLiteral.SHORT = "blackSwanShort"; m_algoString.push_back(algoLiteral); ////Part I trader parameters //****The following need to be done here because symbol selection code need. m_baseVector.clear(); m_baseNum.clear(); m_baseNum.push_back(5); m_baseNum.push_back(10); m_baseNum.push_back(20); m_baseNum.push_back(40); m_baseNum.push_back(80); //The number of bar may never be determined before downloading. m_VectorL.clear(); m_VectorS.clear(); m_VectorS_Test.clear(); /////////////////////////////////////////////////// //****** The following is for symbol selection only. m_index_deque.clear(); //***** The following is used for back testing and symbol selection std::string yearString = m_endDateIndex.substr(0, 4); //****IMPORTANT NOTES: start with first character (with index 0 but not 1). 4 is the length of the string, but not the index of the final character (like Python) std::string monthString; if (m_endDateIndex.at(4) == '0') monthString = m_endDateIndex.substr(5, 1); else monthString = m_endDateIndex.substr(4, 2); //**** This might be not necessary. atoi might have the ability of neglect zero before non-zero numbers. This is for 100% sure. std::string dayString; if (m_endDateIndex.at(6) == '0') dayString = m_endDateIndex.substr(7, 1); else dayString = m_endDateIndex.substr(6, 2); time_t now = time(0); struct tm *ts = localtime(&now); //**** I need initialize it before modify it later. ts->tm_year = atoi(yearString.c_str()) - 1900; ts->tm_mon = atoi(monthString.c_str()) - 1; //***** IMPORTANT. Without -1 there will be big problem.See the range of time variables below. mon runs from 0 to 11 ts->tm_mday = atoi(dayString.c_str()); //***** IMPORTANT With a -1 there will be big problem. See the range of time variables below. mday runs from 1 to 31 ts->tm_hour = 20; //**** This will include the historical data for the date shown in then m_endDateIndex, either I download in eastern or pacific time. //******Be careful of this setting. It might be have a day difference when downloading from IB, and get data from EOD download. ts->tm_min = 0; ts->tm_sec = 0; m_backTest_symbolSection_EndTime = mktime(ts); // Set a zero point makes things easier. if (m_mostRecentDate == true) m_backTest_symbolSection_EndTime = time(0); //**** Note m_mostRecentDate } void AllData::initializeOtherParameters() { //**** need figure out what is this. It should be same in all places? m_iSize = (m_traderParameters.maxSmallBarsConsidered - m_traderParameters.minSmallBarsConsidered) / m_traderParameters.stepSmallBars + 1; //**** This must be same as that of traderNormalLong.cpp m_orderIdLong = -1; m_orderIdShort = -1; m_orderIdReadyLong = false; m_orderIdReadyShort = false; m_positionUpdateDoneLong = false; m_accountSummaryDoneLong = false; m_executionDoneLong = false; m_positionUpdateDoneShort = false; m_accountSummaryDoneShort = false; m_executionDoneShort = false; m_openOrderUpdateDoneLong = false; m_updatePorfolioUpdateDoneLong = false; m_openOrderUpdateDoneShort = false; m_updatePorfolioUpdateDoneShort = false; m_myfileLong.open(m_errorOutputLong, std::ios::app), m_myfileShort.open(m_errorOutputShort, std::ios::app); m_historicalDataDone = false; time_t now; struct tm *ts; now = time(0); ts = localtime(&now); //I need only modify the following three fields. ts->tm_hour = 6; ts->tm_min = 30; ts->tm_sec = 0; m_initime = mktime(ts); m_tradingEndTime = m_initime + 6.5 * 60 * 60; //**** This must be after the initialization of m_initime; } void AllData::initializeBackTestVectors() { m_finishedTradesList.clear(); m_finishedTradeStructure_default.reqId = -1; m_finishedTradeStructure_default.symbol = "EMPTY"; m_finishedTradeStructure_default.longOrShort = "EMPTY"; m_finishedTradeStructure_default.OpenedDateIndex = 0; m_finishedTradeStructure_default.OpenedSmallBarIndex = 0; m_finishedTradeStructure_default.closedDateIndex = 0; m_finishedTradeStructure_default.closedSmallBarIndex = 0; m_finishedTradeStructure_default.opened = false; m_finishedTradeStructure_default.closed = false; m_finishedTradeStructure_default.algoString = "EMPTY"; m_finishedTradeStructure_default.sharesOpened = 0; m_finishedTradeStructure_default.gain_loss = 0; m_finishedTradeStructure_default.commissionOpened = 0; m_finishedTradeStructure_default.commissionClosed = 0; m_finishedTradeStructure_default.averageCost = 0; m_finishedTradeStructure_default.conditions.clear(); bool tempBool = false; for (unsigned int i = 0; i < m_traderParameters.maxNumConditions; i++) m_finishedTradeStructure_default.conditions.push_back(tempBool); m_traderVectorTest.clear(); TradeStructureTest tradeStructureTest; tradeStructureTest.longOpened = false; tradeStructureTest.longClosed = false; tradeStructureTest.shortOpened = false; tradeStructureTest.shortClosed = false; tradeStructureTest.OpenedDateIndex = 0; tradeStructureTest.smallBarIndex = 0; for (unsigned int reqId = 0; reqId < m_newtxtVector.size(); reqId++) m_traderVectorTest.push_back(tradeStructureTest); m_lastDayClose.clear(); for (unsigned int reqId = 0; reqId < m_newtxtVector.size(); reqId++) m_lastDayClose.push_back(0); } void AllData::initializeSymbolVectors_Prev() { //**** Part I Read in newly selected Symbols std::string newTradingSymbols = "C:/symbols/symbolsNEW_Prev"; newTradingSymbols.append(m_accountCode); newTradingSymbols.append(".txt"); std::ifstream i_inputFile(newTradingSymbols, std::ios_base::in); if (!i_inputFile.is_open()) printf("Failed in opening the file new.txt.\n"); std::string wholeLineString; std::string symbol; std::list<std::string> newSymbolsList; newSymbolsList.clear(); std::stringstream linestream; while (getline(i_inputFile, wholeLineString, '\n')) { linestream.clear(); linestream.str(wholeLineString); linestream >> symbol; newSymbolsList.push_back(symbol); }//while (getline(i_inputFile, wholeLineString, '\n')) i_inputFile.close(); //**** Part II Add old symbols that have position std::ifstream i_dataFile(m_manuals_NEW, std::ios_base::in); if (!i_dataFile.is_open()) printf("Failed in opening the file %s.\n", m_manuals_NEW.c_str()); else { TraderStructure manuals; std::string lineString, columnString; std::vector<std::string> columnStringVector; while (getline(i_dataFile, lineString, '\n')) { std::stringstream lineStream(lineString); columnStringVector.clear(); while (getline(lineStream, columnString, ',')) columnStringVector.push_back(columnString); if (m_manualMap.size() > 0 && m_manualMap.size() == columnStringVector.size()){ for (auto i = m_manualMap.begin(); i != m_manualMap.end(); ++i){ if ((*i).first == "symbol") manuals.symbol = columnStringVector[(*i).second]; else if ((*i).first == "totalPosition") manuals.totalPosition = std::stoi(columnStringVector[(*i).second]); } } else{ printf("something is wrong in update_historyVector().\n"); } if (manuals.totalPosition != 0) { for (auto it = newSymbolsList.begin(); it != std::prev(newSymbolsList.end(), 1); ++it) { if ((*it) < manuals.symbol && manuals.symbol < (*std::next(it, 1))) //****Note > and < cannot be >= or <=. The second term might be *std::next(it,1) newSymbolsList.insert(std::next(it, 1), manuals.symbol); } } }//while (getline(i_dataFile, dataString, '\n')) i_dataFile.close(); } //**** Part IV output the final symbol list. std::string oldSymbol = "C:/symbols/symbolsOLD"; oldSymbol.append(m_accountCode); oldSymbol.append(".txt"); std::string newSymbol = "C:/symbols/symbolsNEW"; newSymbol.append(m_accountCode); newSymbol.append(".txt"); remove(oldSymbol.c_str()); rename(newSymbol.c_str(), oldSymbol.c_str()); //**** rename new.txt to old.txt, but not the opposite. std::ofstream o_new(newSymbol, std::ios::app); for (auto element : newSymbolsList) if(element != "SPY") o_new << element << std::endl; o_new.close(); } void AllData::initializeSymbolVectors() { std::ifstream i_inputFile(m_newSymbols, std::ios_base::in); if (!i_inputFile.is_open()) printf("Failed in opening the file new.txt.\n"); std::istringstream instream; unsigned int reqId = 0; m_newtxtVector.clear(); std::string symbol = "SPY"; //******Cannot delete this symbol because of historical download etc. bool b = true; try { m_csTraderVector.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { //**** Use the same critical section of trader Vector. The symbol list might change in the future. m_newtxtVector.push_back(symbol); m_newtxtMap.insert({ symbol, reqId }); m_csTraderVector.LeaveCriticalSection(); } reqId = 1; //**** SPY take the first place already. std::string wholeLineString; while (getline(i_inputFile, wholeLineString, '\n')) { std::stringstream linestream; linestream.clear(); linestream.str(wholeLineString); linestream >> symbol; bool b = true; try { m_csTraderVector.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { //**** Use the same critical section of trader Vector. The symbol list might change in the future. m_newtxtVector.push_back(symbol); m_newtxtMap.insert({symbol, reqId}); reqId = reqId + 1; m_csTraderVector.LeaveCriticalSection(); } }//while (getline(i_inputFile, wholeLineString, '\n')) i_inputFile.close(); } void AllData::unhandledSymbols() { std::string excludedSymbols = "C:/symbols/excludedSymbols"; excludedSymbols.append(m_accountCode); excludedSymbols.append(".txt"); std::ifstream i_excludeFile(excludedSymbols, std::ios_base::in); if (!i_excludeFile.is_open()) printf("Failed in opening the file excludedSymbols.txt.\n"); std::stringstream linestream; std::string wholeLineString, symbol; while (getline(i_excludeFile, wholeLineString, '\n')) { linestream.clear(); linestream.str(wholeLineString); linestream >> symbol; //***** Remember the ordering of following two critical sections. The one for traderVector should always be in the first place. bool b = true; try { m_csTraderVector.EnterCriticalSection(); }catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { auto it = m_newtxtMap.find(symbol); if (it != m_newtxtMap.end()) { m_traderVector.longBuy[it->second].manualOrder = true; m_traderVector.longSell[it->second].manualOrder = true; m_traderVector.shortSell[it->second].manualOrder = true; m_traderVector.shortBuy[it->second].manualOrder = true; printf("Symbol %s has been set to manual order.\n", m_newtxtVector[it->second].c_str()); //**** Here m_newtxtVector is used for comparing with the symbol input in file. m_csTraderVector.LeaveCriticalSection(); } } } i_excludeFile.close(); } void AllData::initializeBaseVector(std::string string) { BaseStructure baseStructure; baseStructure.i = -1; //**** range index baseStructure.numDaysConsidered = -1; //baseStructure.symbol = "EMPTY"; baseStructure.frequency = 0; baseStructure.finalLow = 0; baseStructure.finalHigh = 0; baseStructure.min = -1; baseStructure.minIndex = -1; baseStructure.max = -1; baseStructure.maxIndex = -1; baseStructure.ATR = 0; baseStructure.volatility = 0; baseStructure.averageMoneyVolume = 0; baseStructure.averageShareVolume = 0; baseStructure.correlation = 0; baseStructure.slope = 0; baseStructure.intercept = 0; baseStructure.originX = 0; baseStructure.originY = 0; baseStructure.upperOscillaitonTimesVolatility = 0; baseStructure.downOscillaitonTimesVolatility = 0; baseStructure.leftToTotalOscillation = 0; baseStructure.upperLeftToTotalCrossing = 0; baseStructure.downLeftToTotalCrosing = 0; baseStructure.upTradingLineIntercept = 0; baseStructure.downTradingLineIntercept = 0; baseStructure.upBoundaryIntercept = 0; baseStructure.downBoundaryIntercept = 0; baseStructure.slopeLocalMin = 0; baseStructure.interceptLocalMin = 0; baseStructure.originXLocalMin = 0; baseStructure.originYLocalMin = 0; baseStructure.slopeLocalMax = 0; baseStructure.interceptLocalMax = 0; baseStructure.originXLocalMax = 0; baseStructure.originYLocalMax = 0; baseStructure.oscillationRate = 0; baseStructure.upDeviationPercentage = 0; baseStructure.downDeviationPercentage = 0; baseStructure.trendingPencentage = 0; baseStructure.maxDrawDownPercentage = 0; baseStructure.volatilityPriceRatio = 0; baseStructure.futureTrendingAmountVolatilityRatio = 0; baseStructure.maxGapPercentage = 0; baseStructure.gapToDeviationRatio = 0; m_baseVector.clear(); //**** std::vector<BaseStructure> tempVectorBase = *new(std::vector<BaseStructure>); tempVectorBase.clear(); if (string == "SYMBOL") { for (auto it = m_newtxtMap.begin(); it != m_newtxtMap.end(); ++it) tempVectorBase.push_back(baseStructure); } else { for (unsigned int j = 0; j < m_newtxtVector.size(); j++) tempVectorBase.push_back(baseStructure); } for (unsigned int i = 0; i < m_baseNum.size(); i++) m_baseVector.push_back(tempVectorBase); } void AllData::initializeCurrentDataVector() { //Part I: m_currentDataStructureVector CurrentDataStructure m_currentDataStructure; m_currentDataStructure.symbol = "EMPTY"; m_currentDataStructure.ask = -1; m_currentDataStructure.askSize = -1; m_currentDataStructure.bid = -1; m_currentDataStructure.bidSize = -1; m_currentDataStructure.last = -1; m_currentDataStructure.lastSize = -1; m_currentDataStructure.open = -1; m_currentDataStructure.high = -1; m_currentDataStructure.low = -1; m_currentDataStructure.close = -1; m_currentDataStructure.timeStamp = 0; m_currentDataStructureVector.clear(); for (unsigned int i = 0; i < m_newtxtVector.size(); i++) { m_currentDataStructure.symbol = m_newtxtVector[i]; m_currentDataStructure.reqId = i; m_currentDataStructureVector.push_back(m_currentDataStructure); } } void AllData::initializeOtherVectors() { // Part II: m_traderVector m_traderStructureDefault.myBid = 0; m_traderStructureDefault.totalPosition = 0; m_traderStructureDefault.buyingShares = 0; m_traderStructureDefault.currentTotalBuy = 0; m_traderStructureDefault.currentTotalSell = 0; m_traderStructureDefault.averageCost = 0; m_traderStructureDefault.closing = false; m_traderStructureDefault.opening = false; m_traderStructureDefault.cancelling = false; m_traderStructureDefault.orderId = 0; m_traderStructureDefault.symbol = "EMPTY"; m_traderStructureDefault.orderType = "EMPTY"; m_traderStructureDefault.orderUpdatedTime = time(0) * 2; //This value is good for hundreds of years starting from the year 2013. m_traderStructureDefault.lastModifiedTimeBuy = time(0); m_traderStructureDefault.lastModifiedTimeSell = time(0); m_traderStructureDefault.sellingShares = 0; m_traderStructureDefault.action = "EMPTY"; m_traderStructureDefault.myAsk = 0; m_traderStructureDefault.totalCancellationsBuy = 0; m_traderStructureDefault.totalCancellationsSell = 0; m_traderStructureDefault.totalDuplicateOrderBuy = 0; m_traderStructureDefault.totalDuplicateOrderSell = 0; m_traderStructureDefault.modifiedBuy = true; //This indicates we are not modifying, and thus ready to modify. m_traderStructureDefault.modifiedSell = true; m_traderStructureDefault.filledBuy = 0; m_traderStructureDefault.filledSell = 0; m_traderStructureDefault.numModifiedBuy = 0; m_traderStructureDefault.numModifiedSell = 0; m_traderStructureDefault.sessionClosing = false; m_traderStructureDefault.totalLongValue = 0; m_traderStructureDefault.totalShortValue = 0; m_traderStructureDefault.positionUpdatedTime = time(0) * 2; //**** The following is for backtesting. m_traderStructureDefault.lastFilledLongTime = 0; m_traderStructureDefault.lastFilledShortTime = 0; m_traderStructureDefault.filledPrice = 0; m_traderStructureDefault.needToClose = 0; m_traderStructureDefault.minPriceVariation = 0.01; m_traderStructureDefault.manualOrder = false; m_traderStructureDefault.calculatedBid = 0; m_traderStructureDefault.calculatedAsk = 0; m_traderStructureDefault.relevantShares = 0; m_traderStructureDefault.longHedgeOK = false; m_traderStructureDefault.shortHedgeOK = false; m_traderStructureDefault.stopLossLong = false; m_traderStructureDefault.stopLossShort = false; m_traderStructureDefault.basicOpen = false; m_traderStructureDefault.basicClose = false; m_traderStructureDefault.algoString = "EMPTY"; m_traderStructureDefault.conditions.clear(); for (unsigned int i = 0; i < m_traderParameters.maxNumConditions; i++) m_traderStructureDefault.conditions.push_back(false); //***** push_back(false) but not a push_back(var), where var = false. An extra copy will be occured. m_traderStructureDefault.priceChanged = false; m_traderStructureDefault.noBuyLong = false; m_traderStructureDefault.noSellLong = false; m_traderStructureDefault.noBuyShort = false; m_traderStructureDefault.noSellShort = false; m_traderStructureDefault.stoppedOut = false; m_traderVector.longBuy.clear(); m_traderVector.longSell.clear(); m_traderVector.shortBuy.clear(); m_traderVector.shortSell.clear(); for (unsigned int i = 0; i < m_newtxtVector.size(); i++) { m_traderStructureDefault.symbol = m_newtxtVector[i]; bool b = true; try{ m_csTraderVector.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { m_traderVector.longBuy.push_back(m_traderStructureDefault); m_traderVector.longSell.push_back(m_traderStructureDefault); m_traderVector.shortBuy.push_back(m_traderStructureDefault); m_traderVector.shortSell.push_back(m_traderStructureDefault); m_csTraderVector.LeaveCriticalSection(); } } } void AllData::L_BarVectorDefaul() { My_BarDataNormal barData; std::stringstream ss; ss << time(0); barData.date = "EMPTY"; barData.yearMonthDateString = "EMPTY"; barData.open = 0; barData.high = 0; barData.low = 0; barData.close = 0; barData.volume = 0; barData.lastDownloadTime = "0"; barData.symbol = "EMPTY"; //barData.reachToMaxTime = 0; //The reachToMax/MinTime is not used in smaller-than-day bars. //barData.reachToMinTime = 0; std::vector<My_BarDataNormal> m_tempVector; m_tempVector.clear(); for (unsigned int k = 0; k < m_numDataOfSingleSymbolL; k++) m_tempVector.push_back(barData); m_VectorL.clear(); for (unsigned int reqId = 0; reqId < m_newtxtVector.size(); reqId++) { bool b = true;//This is for the zeroth element of the vector m_VectorS try{ m_csVectorL.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { m_VectorL.push_back(m_tempVector); m_csVectorL.LeaveCriticalSection(); } } } void AllData::S_BarVectorDefaul() { My_BarDataNormal barData; std::stringstream ss; ss << time(0); barData.date = "EMPTY"; barData.open = 0; barData.high = 0; barData.low = 0; barData.close = 0; barData.volume = 0; barData.lastDownloadTime = "0"; barData.symbol = "EMPTY"; std::vector<My_BarDataNormal> m_tempVector; std::vector<std::vector<My_BarDataNormal>> m_tempVectorVector; m_tempVector.clear(); m_tempVectorVector.clear(); for (unsigned int k = 0; k < m_numDataOfSingleSymbolS; k++) m_tempVector.push_back(barData); for (unsigned int reqId = 0; reqId < m_newtxtVector.size(); reqId++) m_tempVectorVector.push_back(m_tempVector); m_VectorS.clear(); for (unsigned int i = 0; i < m_iSize; i++) //The zeroth element has been populated earlier. { bool b = true;//This is for the zeroth element of the vector m_VectorS try{ m_csVectorS.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { m_VectorS.push_back(m_tempVectorVector); m_csVectorS.LeaveCriticalSection(); } } } void AllData::update_manualsVector() { std::ifstream i_dataFile(m_manuals_NEW, std::ios_base::in); if (!i_dataFile.is_open()) printf("Failed in opening the file %s.\n", m_manuals_NEW.c_str()); else { TraderStructure manuals; std::string algoStringLong, algoStringShort; std::string lineString, columnString; std::vector<std::string> columnStringVector; while (getline(i_dataFile, lineString, '\n')) { std::stringstream lineStream(lineString); columnStringVector.clear(); while (getline(lineStream, columnString, ',')) { columnStringVector.push_back(columnString); } if (m_manualMap.size() > 0 && m_manualMap.size() == columnStringVector.size()){ for (auto i = m_manualMap.begin(); i != m_manualMap.end(); ++i){ if ((*i).first == "symbol") manuals.symbol = columnStringVector[(*i).second]; else if ((*i).first == "stopLossLong") manuals.stopLossLong = std::stod(columnStringVector[(*i).second]); else if ((*i).first == "stopLossShort") manuals.stopLossShort = std::stod(columnStringVector[(*i).second]); else if ((*i).first == "algoStringLong") algoStringLong = columnStringVector[(*i).second]; else if ((*i).first == "algoStringShort") algoStringShort = columnStringVector[(*i).second]; else if ((*i).first == "totalPosition") manuals.totalPosition = std::stoi(columnStringVector[(*i).second]); //**** The above can become more efficient if we can put myBarData.open/high...to a hetergeneous container. Anyway the above way already has the following advantages: //**** [1] Avoid hard-coding of vector index, and hence eliminate of possible index shuffling when new element is added or removed. [2] Even though == "open" etc is still hard coded, it can avoid mistakes of, e.g., mismatch open and high etc. } } else{ printf("something is wrong in update_historyVector().\n"); } int reqId = -1; for (unsigned int i = 0; i < m_newtxtVector.size(); i++) //*****Note for a symbol I need search only once but not (*numDataOfSingleSymbol) times. However, searching so many times is safe by verify one by one. If this does not consume too much time as compared other process. Just keep it as is. { if (manuals.symbol == m_newtxtVector[i]) { reqId = i; break; } } //end of for loop. if (reqId >= 0 && reqId < m_newtxtVector.size()) { bool b = true; try{ m_csTraderVector.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { m_traderVector.longBuy[reqId].symbol = manuals.symbol; m_traderVector.longBuy[reqId].stopLossLong = manuals.stopLossLong; m_traderVector.shortSell[reqId].stopLossShort = manuals.stopLossShort; m_traderVector.longBuy[reqId].algoString = algoStringLong; m_traderVector.shortSell[reqId].algoString = algoStringShort; //**** Note that the algoStringVector use the same critical section of traderVector. So whenever the appearance of this vector, it should be within the traderVector critical section. if (manuals.totalPosition > 0) m_traderVector.longBuy[reqId].totalPosition = manuals.totalPosition; else if (manuals.totalPosition < 0)m_traderVector.shortSell[reqId].totalPosition = manuals.totalPosition; m_csTraderVector.LeaveCriticalSection(); } } }//while (getline(i_dataFile, dataString, '\n')) i_dataFile.close(); time_t now = time(0); struct tm *ts; char buf[80]; ts = localtime(&now); strftime(buf, sizeof(buf), "%m-%d %H:%M:%S", ts); std::string tempString = buf; //strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts); // "ddd yyyy-mm-dd hh:mm:ss zzz" if (remove(m_manuals_OLD.c_str()) != 0) { printf("Error deleting file %s.\n", m_manuals_OLD.c_str()); } else { printf("File %s successfully deleted", m_manuals_OLD.c_str()); } int file_result; file_result = rename(m_manuals_NEW.c_str(), m_manuals_OLD.c_str()); //**** rename new.txt to old.txt, but not the opposite. if (file_result == 0) { printf("File name successfully changed from %s to %s.\n", m_manuals_NEW.c_str(), m_manuals_OLD.c_str()); } else { printf("Error occured when changing file name from %s to %s.\n", m_manuals_NEW.c_str(), m_manuals_OLD.c_str()); } std::ofstream o_new(m_manuals_NEW.c_str(), std::ios::app); for (unsigned int reqId = 0; reqId < m_newtxtVector.size(); reqId++) { bool b = true; try{ m_csTraderVector.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { int totalPosition = 0; if (m_traderVector.longBuy[reqId].totalPosition > 0) totalPosition = m_traderVector.longBuy[reqId].totalPosition; else if (m_traderVector.shortSell[reqId].totalPosition < 0) totalPosition = m_traderVector.shortSell[reqId].totalPosition; // feeding back poision should be in the same client? if (totalPosition != 0) { o_new << m_newtxtVector[reqId] << ',' << m_traderVector.longBuy[reqId].stopLossLong << ',' << m_traderVector.shortSell[reqId].stopLossShort << ',' << m_traderVector.longBuy[reqId].algoString << ',' << m_traderVector.shortSell[reqId].algoString << ',' << totalPosition << std::endl; } m_csTraderVector.LeaveCriticalSection(); } } o_new.close(); std::cout << "At " << tempString << ":" << " manuals successfully written to a new file " << m_manuals_NEW << std::endl; } //if (i_dataFile.is_open()) } void AllData::earningReportDate() { //Part I Calculate zero time points for several critical days. time_t todayTimeZeroPoint, nextTradingDayZeroPoint, ealiestTradingDayZeroPoint, latestTradingDayZeroPoint; time_t now = time(0);// If today is not trading day due to running the app during week ends, then I may specify in a wrong way. However, this will not make any harm. It will be corrected next trading day. struct tm *ts; ts = localtime(&now); ts->tm_hour = 0; ts->tm_min = 0; ts->tm_sec = 0; todayTimeZeroPoint = mktime(ts); // If today is not trading day due to running the app during week ends, then I may specify in a wrong way. However, this will not make any harm. It will be corrected next trading day. //**** Calculate nextTradingDayZeroPoint int counter = 0; while (1) { time_t newTime = todayTimeZeroPoint + (counter + 1) * 86400; ts = localtime(&newTime); if (ts->tm_wday != 0 && ts->tm_wday != 6) //**** If I want to be more precise, I should include a list of market holidays, which is different year after year. { nextTradingDayZeroPoint = newTime; //***** Here only for next business day, so I don't need a separate counter as in other places. break; } counter = counter + 1; } //**** Calculate latestTradingDayZeroPoint; unsigned int index = m_traderParameters.i_periodIndex; //**** Note I cannot use zeroth element because that is special for SPY and the .i = -1 in default. unsigned int expectedHoldingTimeUnits = m_baseNum[index] * m_traderParameters.closingDateFactor; // I will hold stocks for at least these days. unsigned int tradingDayCounter = 0; counter = 0; while (1) { time_t newTime = todayTimeZeroPoint + (counter + 1) * 86400; ts = localtime(&newTime); if (ts->tm_wday != 0 && ts->tm_wday != 6) { latestTradingDayZeroPoint = newTime; tradingDayCounter = tradingDayCounter + 1; } counter = counter + 1; if (tradingDayCounter >= expectedHoldingTimeUnits) break; } //**** Calculate ealiestTradingDayZeroPoint tradingDayCounter = 0; counter = 0; while (1) { time_t newTime = todayTimeZeroPoint - (counter + 1) * 86400; //**** Note minus sign ts = localtime(&newTime); if (ts->tm_wday != 0 && ts->tm_wday != 6) { ealiestTradingDayZeroPoint = newTime; tradingDayCounter = tradingDayCounter + 1; } counter = counter + 1; if (tradingDayCounter >= m_traderParameters.earliestTradingDayFactor) break; } //Part II Specify which symbol is not suitable to open position today, and which position need close today. std::ifstream i_dataFile(m_earningReportDate, std::ios_base::in); if (!i_dataFile.is_open()) printf("Failed in opening the file %s.\n", m_earningReportDate.c_str()); else { std::string dateString, symbolString; std::string lineString, columnString; std::vector<std::string> columnStringVector; std::stringstream date_ss, symbol_ss; while (getline(i_dataFile, lineString, '\n')) { std::stringstream lineStream(lineString); columnStringVector.clear(); while (getline(lineStream, columnString, ',')) // empty space is the delimir { columnStringVector.push_back(columnString); } time_t earningReportEpochTimeZeroPoint; if (columnStringVector.size() == 2) //***** Note here is hard-coded. { date_ss.clear(); symbol_ss.clear(); date_ss.str(columnStringVector[0]); symbol_ss.str(columnStringVector[1]); date_ss >> dateString; symbol_ss >> symbolString; std::string yearString = dateString.substr(0, 4); //****IMPORTANT NOTES: start with first character (with index 0 but not 1). 4 is the length of the string, but not the index of the final character (like Python) std::string monthString; if (dateString.at(4) == '0') monthString = dateString.substr(5, 1); else monthString = dateString.substr(4, 2); //**** This might be not necessary. atoi might have the ability of neglect zero before non-zero numbers. This is for 100% sure. std::string dayString; if (dateString.at(6) == '0') dayString = dateString.substr(7, 1); else dayString = dateString.substr(6, 2); time_t now = time(0); struct tm *ts = localtime(&now); //**** I need initialize it before modify it later. ts->tm_year = atoi(yearString.c_str()) - 1900; ts->tm_mon = atoi(monthString.c_str()) - 1; //***** IMPORTANT. Without -1 there will be big problem.See the range of time variables below. mon runs from 0 to 11 ts->tm_mday = atoi(dayString.c_str()); //***** IMPORTANT With a -1 there will be big problem. See the range of time variables below. mday runs from 1 to 31 ts->tm_hour = 0; ts->tm_min = 0; ts->tm_sec = 0; earningReportEpochTimeZeroPoint = mktime(ts); // Set a zero point makes things easier. //**** Note that using a give date, we can calculated the week day from this method. However, there are many other ways from web. The current way is very good, as long as I notice the month range (0-11), etc. } int reqId = -1; for (unsigned int i = 0; i < m_newtxtVector.size(); i++) //*****Note for a symbol I need search only once but not (*numDataOfSingleSymbol) times. However, searching so many times is safe by verify one by one. If this does not consume too much time as compared other process. Just keep it as is. { if (symbolString == m_newtxtVector[i]) { reqId = i; break; } } //end of for loop. if (reqId >= 0 && reqId < m_newtxtVector.size()) { bool b = true; try{ m_csTraderVector.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { if (earningReportEpochTimeZeroPoint >= ealiestTradingDayZeroPoint && earningReportEpochTimeZeroPoint <= latestTradingDayZeroPoint) { m_traderVector.shortSell[reqId].noSellShort = true; m_traderVector.longBuy[reqId].noBuyLong = true; time_t now = time(0); struct tm *ts; char buf[80]; ts = localtime(&now); strftime(buf, sizeof(buf), "%m-%d %H:%M:%S", ts); std::string tempString = buf; //strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts); // "ddd yyyy-mm-dd hh:mm:ss zzz" printf(" At %s, noBuyLong and noSellShort is set for symbol %s. \n", tempString.c_str(), m_newtxtVector[reqId].c_str()); } if ((earningReportEpochTimeZeroPoint == (todayTimeZeroPoint + 86400) ) //**** Note sometimes earning is out before trading start that day. || (earningReportEpochTimeZeroPoint > (todayTimeZeroPoint +86400) && earningReportEpochTimeZeroPoint < nextTradingDayZeroPoint) //**** This is for the case of, e.g., today is Friday, and report date is Saturday. || (earningReportEpochTimeZeroPoint == nextTradingDayZeroPoint)) { m_traderVector.longSell[reqId].needToClose = true; m_traderVector.shortBuy[reqId].needToClose = true; time_t now = time(0); struct tm *ts; char buf[80]; ts = localtime(&now); strftime(buf, sizeof(buf), "%m-%d %H:%M:%S", ts); std::string tempString = buf; //strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts); // "ddd yyyy-mm-dd hh:mm:ss zzz" printf(" At %s, needToClose is set for symbol is set for symbol %s. \n", tempString.c_str(), m_newtxtVector[reqId].c_str()); } m_csTraderVector.LeaveCriticalSection(); } } }//while (getline(i_dataFile, dataString, '\n')) i_dataFile.close(); } //if (i_dataFile.is_open()) } void AllData::update_historyVector() //***** This is for re-start during trading hours. { int fileVectorSize = 0; std::ifstream i_dataFile(m_vectorL_NEW, std::ios_base::in); if (!i_dataFile.is_open()) printf("Failed in opening the file %s.\n", m_vectorL_NEW.c_str()); else { My_BarDataNormal myBarData; std::string lineString, columnString; std::vector<std::string> columnStringVector; //***** Where will they be cleared again ?????? while (getline(i_dataFile, lineString, '\n')){ std::stringstream lineStream(lineString); columnStringVector.clear(); while (getline(lineStream, columnString, ',')) columnStringVector.push_back(columnString); if (m_historyMap.size() > 0 && m_historyMap.size() == columnStringVector.size()){ for (auto i = m_historyMap.begin(); i != m_historyMap.end(); ++i){ if ((*i).first == "symbol"){ myBarData.symbol = columnStringVector[(*i).second]; break; //**** Here I only find symbol of SPY to calculate the length of data range. } } } else{ printf("something is wrong in update_historyVector().\n"); } if (myBarData.symbol == "SPY") //**** Note this arrangement need the first symbol in the file is SPY. Otherwise the databaseVector fileVectorSize = fileVectorSize + 1; else break; }//while (getline(i_dataFile, dataString, '\n')) i_dataFile.close(); time_t now = time(0); struct tm *ts; char buf[80]; ts = localtime(&now); strftime(buf, sizeof(buf), "%m-%d %H:%M:%S", ts); std::string tempString = buf; //strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts); // "ddd yyyy-mm-dd hh:mm:ss zzz" printf(" At %s, the number of days for SPY is calculated as %d. \n", tempString.c_str(), fileVectorSize); } //if (i_dataFile.is_open()) bool b = true; //*****Note the critical section below is for absolutely thread safety for concurrent accessing of a traderStructureVector table, although this member function might not be run concurrently with other threads. try{ m_csVectorL.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { if (fileVectorSize > 0) { std::ifstream i_dataFile(m_vectorL_NEW, std::ios_base::in); if (!i_dataFile.is_open()) printf("Failed in opening the file %s.\n", m_vectorL_NEW.c_str()); else { My_BarDataNormal myBarData; std::string lineString, columnString; std::vector<std::string> columnStringVector; int lineNumber = -1; while (getline(i_dataFile, lineString, '\n')) //***** i_dataFile is of std::ifstream type, which is different from the lineStream below. { lineNumber = lineNumber + 1; std::stringstream lineStream(lineString); columnStringVector.clear(); while (getline(lineStream, columnString, ',')) columnStringVector.push_back(columnString); if (m_historyMap.size() > 0 && m_historyMap.size() == columnStringVector.size()){ for (auto i = m_historyMap.begin(); i != m_historyMap.end(); ++i){ if ((*i).first == "date") myBarData.date = columnStringVector[(*i).second]; else if ((*i).first == "yearMonthDateString") myBarData.yearMonthDateString = columnStringVector[(*i).second]; else if ((*i).first == "open") myBarData.open = std::stod(columnStringVector[(*i).second]); else if ((*i).first == "high") myBarData.high = std::stod(columnStringVector[(*i).second]); else if ((*i).first == "low") myBarData.low = std::stod(columnStringVector[(*i).second]); else if ((*i).first == "close") myBarData.close = std::stod(columnStringVector[(*i).second]); else if ((*i).first == "volume") myBarData.volume = std::stoi(columnStringVector[(*i).second]); else if ((*i).first == "lastDownloadTime") myBarData.lastDownloadTime = columnStringVector[(*i).second]; else if ((*i).first == "symbol") myBarData.symbol = columnStringVector[(*i).second]; //**** The above can become more efficient if we can put myBarData.open/high...to a hetergeneous container. Anyway the above way already has the following advantages: //**** [1] Avoid hard-coding of vector index, and hence eliminate of possible index shuffling when new element is added or removed. [2] Even though == "open" etc is still hard coded, it can avoid mistakes of, e.g., mismatch open and high etc. } } else{ printf("something is wrong in update_historyVector().\n"); } int reqId = -1; for (unsigned int i = 0; i < m_newtxtVector.size(); i++) //*****Note for a symbol I need search only once but not (*numDataOfSingleSymbol) times. However, searching so many times is safe by verify one by one. If this does not consume too much time as compared other process. Just keep it as is. { if (myBarData.symbol == m_newtxtVector[i]) { reqId = i; break; } } //end of for loop. int j; if (reqId >= 0 && reqId < m_newtxtVector.size()) //**** This is a double safety. It is redundant because the range of i above already guarantee that reqId has the same range. { int m_VectorSize = m_VectorL[0].size(); //**** Note the important points below. //**** m_VectorL[0].size() is the number related to today's SPY download. It might not be same as the SPY download of earlier days, when the number of elements is given by the databaseVectorSize. //***** Be very careful of the extra element in m_VectorL for SPY, which is set aside for today's day bar. if (fileVectorSize == m_VectorSize) //**** due to different downloading times or accident from IB these supposed-same variable might be different. { j = lineNumber % fileVectorSize; //**** Be very careful of the problem of extra today's bar. //**** A specific example: if in the database we have 0, 1, 2, 3, 4 | 5, 6, 7, 8, 9 |....each with 5-day historical data. However, note that the final day for each stock (e.g. 4, 9, etc.) are for allocated position for today's bar. //**** According to the definition of j = ID% m_VectorSize, j = 0, 1,... m_VectorSize-1 (j cannot be bigger than m_VectorSizee-1). And the index for today's bar is m_VectorSize-1. We can never use the contents of m_VectorSize-1 element in database to overwrite/update that of m_VectorL. //***** ***** ***** See comments below. //**** Here j cannot be m_VectorSiz-1 because this element is the last element which is set aside for today's bar. So if j = m_VectorSiz-1, then there is problem because this element always indicates a historical data bar not including today. //**** If we start app before trading session starts, an overwritten should be fine. But if in the middle of trading, such a overwritten is a disaster. //**** ***** ***** As said before. Because we normally overwrite before session starts, so it is ok to use today's bar data to overwrite because anyway it is a default. Therefore, we can use //**** ***** ***** " if (j >= 0 && j < m_VectorSize) " can cause no problems at all. if (j >= 0 && j < m_VectorSize) m_VectorL[reqId][j] = myBarData; //**** Note in OTC case, we have if (j >= 0 && j < (m_VectorSize-1) ) m_VectorL[reqId][j] = myBarData; } else if (fileVectorSize > m_VectorSize) { //****Also use a specific example to understand. int bias = fileVectorSize - m_VectorSize; j = lineNumber % fileVectorSize; if (j == 0) m_VectorL[reqId][0] = myBarData; //**** This is a special treatment because the first element stores important information such as manualBuy/Sell. else if ((j - bias) > 0 && (j - bias) < m_VectorSize) m_VectorL[reqId][j - bias] = myBarData; //**** j-bias > 0 because 0 is already assigned. For example, if bias = 2, then j=0 database element is assigned to zeroth element of m_Vector, j = 1 and 2 elements are discarded because j-bias not > 0. From j = 3, database element is assigned to first, 2nd... element of m_VectorL. //**** also j-bias can also be = m_VectorSize - 1 because there is an extra element in database for today's bar. However we won't assign its value to the m_VectorL here. } else if (fileVectorSize < m_VectorSize) { int bias = m_VectorSize - fileVectorSize; j = lineNumber % fileVectorSize; if (j == 0) { for (int J = 0; J < (bias + 1); J++) if (J >= 0 && J < m_VectorSize) m_VectorL[reqId][J] = myBarData; } //**** This is a special treatment because the first element stores important information. else if (j > 0) { if ((j + bias) < m_VectorSize) m_VectorL[reqId][j + bias] = myBarData; //**** Use a special databaseVector and m_Vector to arrange the index. else { time_t now = time(0); struct tm *ts; char buf[80]; ts = localtime(&now); strftime(buf, sizeof(buf), "%m-%d %H:%M:%S", ts); std::string tempString = buf; //strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts); // "ddd yyyy-mm-dd hh:mm:ss zzz" printf("At %s, this is impossible No. 1. \n", tempString.c_str()); } } } } }//while (getline(i_dataFile, dataString, '\n')) i_dataFile.close(); } //if (i_dataFile.is_open()) time_t now = time(0); struct tm *ts; char buf[80]; ts = localtime(&now); strftime(buf, sizeof(buf), "%m-%d %H:%M:%S", ts); std::string tempString = buf; //strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts); // "ddd yyyy-mm-dd hh:mm:ss zzz" std::ofstream o_new(m_vectorL_NEW.c_str(), std::ios::app); bool b = true; try{ m_csVectorL.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { for (unsigned int i = 0; i < m_newtxtVector.size(); i++) { for (unsigned int j = 0; j < m_VectorL[i].size(); j++) //numDataOfSingleSymbol Actually this also include an extra element for today's bar, not just the number of historical data downloaded. { o_new << m_VectorL[i][j].date << ',' << m_VectorL[i][j].yearMonthDateString<< ',' << m_VectorL[i][j].open << ',' << m_VectorL[i][j].high << ',' << m_VectorL[i][j].low << ',' << m_VectorL[i][j].close << ',' << m_VectorL[i][j].volume << ',' << m_VectorL[i][j].lastDownloadTime << ',' << m_VectorL[i][j].symbol << std::endl; } } m_csVectorL.LeaveCriticalSection(); } o_new.close(); printf("historical data have successfully been written to a new file after update.\n"); } //if (fileVectorSize > 0) m_csVectorL.LeaveCriticalSection(); } } void AllData::historyVectorLoad_backTest(std::vector<std::vector<My_BarDataNormal>> &m_vector, std::string &FileName) { int fileVectorSize = 0; std::ifstream i_dataFile(FileName, std::ios_base::in); if (!i_dataFile.is_open()) printf("Failed in opening the file %s.\n", FileName.c_str()); else { My_BarDataNormal myBarData; std::string lineString, columnString; std::vector<std::string> columnStringVector; //***** Where will they be cleared again ?????? while (getline(i_dataFile, lineString, '\n')) { std::stringstream lineStream(lineString); columnStringVector.clear(); while (getline(lineStream, columnString, ',')) columnStringVector.push_back(columnString); if (m_historyMap.size() > 0 && m_historyMap.size() == columnStringVector.size()){ for (auto i = m_historyMap.begin(); i != m_historyMap.end(); ++i){ if ((*i).first == "symbol"){ myBarData.symbol = columnStringVector[(*i).second]; break; //**** Here I only find symbol of SPY to calculate the length of data range. } } } else{ printf("something is wrong in update_historyVector().\n"); } if (myBarData.symbol == "SPY") //**** Note this arrangement need the first symbol in the file is SPY. Otherwise the databaseVector fileVectorSize = fileVectorSize + 1; else break; }//while (getline(i_dataFile, dataString, '\n')) i_dataFile.close(); time_t now = time(0); struct tm *ts; char buf[80]; ts = localtime(&now); strftime(buf, sizeof(buf), "%m-%d %H:%M:%S", ts); std::string tempString = buf; //strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts); // "ddd yyyy-mm-dd hh:mm:ss zzz" printf(" At %s, the number of bars for SPY is calculated as %d. \n", tempString.c_str(), fileVectorSize); } //if (i_dataFile.is_open()) if (fileVectorSize > 0) { std::vector<My_BarDataNormal> tempVector; tempVector.clear(); m_vector.clear(); std::ifstream i_dataFile(FileName, std::ios_base::in); if (!i_dataFile.is_open()) printf("Failed in opening the file %s.\n", FileName.c_str()); else { My_BarDataNormal myBarData; std::string lineString, columnString; std::vector<std::string> columnStringVector; while (getline(i_dataFile, lineString, '\n')) //***** i_dataFile is of std::ifstream type, which is different from the lineStream below. { std::stringstream lineStream(lineString); columnStringVector.clear(); while (getline(lineStream, columnString, ',')) columnStringVector.push_back(columnString); if (m_historyMap.size() > 0 && m_historyMap.size() == columnStringVector.size()){ for (auto i = m_historyMap.begin(); i != m_historyMap.end(); ++i){ if ((*i).first == "date") myBarData.date = columnStringVector[(*i).second]; else if ((*i).first == "yearMonthDateString") myBarData.yearMonthDateString = columnStringVector[(*i).second]; else if ((*i).first == "open") myBarData.open = std::stod(columnStringVector[(*i).second]); else if ((*i).first == "high") myBarData.high = std::stod(columnStringVector[(*i).second]); else if ((*i).first == "low") myBarData.low = std::stod(columnStringVector[(*i).second]); else if ((*i).first == "close") myBarData.close = std::stod(columnStringVector[(*i).second]); else if ((*i).first == "volume") myBarData.volume = std::stoi(columnStringVector[(*i).second]); else if ((*i).first == "lastDownloadTime") myBarData.lastDownloadTime = columnStringVector[(*i).second]; else if ((*i).first == "symbol") myBarData.symbol = columnStringVector[(*i).second]; //**** The above can become more efficient if we can put myBarData.open/high...to a hetergeneous container. Anyway the above way already has the following advantages: //**** [1] Avoid hard-coding of vector index, and hence eliminate of possible index shuffling when new element is added or removed. [2] Even though == "open" etc is still hard coded, it can avoid mistakes of, e.g., mismatch open and high etc. } } else{ printf("something is wrong in update_historyVector().\n"); } tempVector.push_back(myBarData); if (tempVector.size() == fileVectorSize){ m_vector.push_back(tempVector); tempVector.clear(); } }//while (getline(i_dataFile, dataString, '\n')) i_dataFile.close(); } //if (i_dataFile.is_open()) } //if (fileVectorSize > 0) m_csVectorL.LeaveCriticalSection(); } void AllData::MessageLimitation() { std::chrono::high_resolution_clock::time_point m_now, m_earlier; while (1) { bool b = true; try{ m_csTimeDeque.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { if (!m_timeDeque.empty()) { m_now = std::chrono::high_resolution_clock::now(); //***** now() is a static function and thus I can call without a high_resolution_clock instance. m_earlier = m_timeDeque.front(); if (std::chrono::duration_cast<std::chrono::seconds > (m_now - m_earlier).count() >= 1) m_timeDeque.pop_front(); } m_csTimeDeque.LeaveCriticalSection(); } std::this_thread::sleep_for(std::chrono::milliseconds(1)); } }
47.392344
300
0.700939
[ "vector" ]
f1ff303f92624f119ad2fbcd47ec5c96e00f8906
1,653
cpp
C++
aws-cpp-sdk-iotthingsgraph/source/model/DissociateEntityFromThingRequest.cpp
crazecdwn/aws-sdk-cpp
e74b9181a56e82ee04cf36a4cb31686047f4be42
[ "Apache-2.0" ]
1
2020-03-11T05:36:20.000Z
2020-03-11T05:36:20.000Z
aws-cpp-sdk-iotthingsgraph/source/model/DissociateEntityFromThingRequest.cpp
crazecdwn/aws-sdk-cpp
e74b9181a56e82ee04cf36a4cb31686047f4be42
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-iotthingsgraph/source/model/DissociateEntityFromThingRequest.cpp
crazecdwn/aws-sdk-cpp
e74b9181a56e82ee04cf36a4cb31686047f4be42
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/iotthingsgraph/model/DissociateEntityFromThingRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::IoTThingsGraph::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; DissociateEntityFromThingRequest::DissociateEntityFromThingRequest() : m_thingNameHasBeenSet(false), m_entityType(EntityType::NOT_SET), m_entityTypeHasBeenSet(false) { } Aws::String DissociateEntityFromThingRequest::SerializePayload() const { JsonValue payload; if(m_thingNameHasBeenSet) { payload.WithString("thingName", m_thingName); } if(m_entityTypeHasBeenSet) { payload.WithString("entityType", EntityTypeMapper::GetNameForEntityType(m_entityType)); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection DissociateEntityFromThingRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "IotThingsGraphFrontEndService.DissociateEntityFromThing")); return headers; }
27.098361
120
0.772535
[ "model" ]
7b0552e86ea45eca995f0a651ef1a49c9998f605
2,333
cc
C++
src/ft_ee_ua_read_op.cc
Incont/n-ftdi
fb9ec653b731c9e55d50a668be539b4774950c8b
[ "MIT" ]
2
2019-09-30T09:22:06.000Z
2019-09-30T14:40:11.000Z
src/ft_ee_ua_read_op.cc
Incont/n-ftdi
fb9ec653b731c9e55d50a668be539b4774950c8b
[ "MIT" ]
8
2019-09-05T05:18:45.000Z
2021-07-11T11:45:30.000Z
src/ft_ee_ua_read_op.cc
Incont/n-ftdi
fb9ec653b731c9e55d50a668be539b4774950c8b
[ "MIT" ]
3
2020-05-25T09:49:25.000Z
2020-06-29T18:34:47.000Z
#include "ft_ee_ua_read_op.h" Napi::Object FtEeUaReadOp::Init(Napi::Env env, Napi::Object exports) { exports.Set("eeUaReadSync", Napi::Function::New(env, FtEeUaReadOp::InvokeSync)); exports.Set("eeUaRead", Napi::Function::New(env, FtEeUaReadOp::Invoke)); return exports; } Napi::Object FtEeUaReadOp::InvokeSync(const Napi::CallbackInfo &info) { FT_HANDLE ftHandle = (FT_HANDLE)info[0].As<Napi::External<void>>().Data(); Napi::Buffer<unsigned char> buf = info[1].As<Napi::Buffer<unsigned char>>(); DWORD numBytesToRead = info[2].As<Napi::Number>().Uint32Value(); if (numBytesToRead > buf.ByteLength()) { numBytesToRead = buf.ByteLength(); } DWORD numBytesRead; unsigned char *uaBuffer = buf.Data(); FT_STATUS ftStatus = FT_EE_UARead(ftHandle, uaBuffer, numBytesToRead, &numBytesRead); return CreateResult(info.Env(), ftStatus, buf, numBytesRead); } Napi::Promise FtEeUaReadOp::Invoke(const Napi::CallbackInfo &info) { FT_HANDLE ftHandle = (FT_HANDLE)info[0].As<Napi::External<void>>().Data(); Napi::Buffer<unsigned char> buf = info[1].As<Napi::Buffer<unsigned char>>(); DWORD numBytesToRead = info[2].As<Napi::Number>().Uint32Value(); if (numBytesToRead > buf.ByteLength()) { numBytesToRead = buf.ByteLength(); } auto *operation = new FtEeUaReadOp(info.Env(), ftHandle, buf, numBytesToRead); operation->Queue(); return operation->Promise(); } FtEeUaReadOp::FtEeUaReadOp(Napi::Env env, FT_HANDLE ftHandle, Napi::Buffer<unsigned char> &uaBuffer, DWORD numBytesToRead) : FtBaseOp(env), ftHandle(ftHandle), numBytesToRead(numBytesToRead), objRef(Napi::Persistent(uaBuffer)) { this->uaBuffer = uaBuffer.Data(); } void FtEeUaReadOp::Execute() { ftStatus = FT_EE_UARead(ftHandle, uaBuffer, numBytesToRead, &numBytesRead); } void FtEeUaReadOp::OnOK() { Napi::HandleScope scope(Env()); deferred.Resolve(CreateResult(Env(), ftStatus, objRef.Value(), numBytesRead)); } Napi::Object FtEeUaReadOp::CreateResult(Napi::Env env, FT_STATUS ftStatus, Napi::Buffer<unsigned char> uaBuffer, DWORD numBytesRead) { Napi::Object result = Napi::Object::New(env); result.Set("ftStatus", ftStatus); result.Set("uaBuffer", uaBuffer); result.Set("numBytesRead", numBytesRead); return result; }
35.348485
132
0.697385
[ "object" ]
7b05a43e1daeaca1b45256e4a2bf946362f94a69
3,418
hpp
C++
src/GennyIda.hpp
fengjixuchui/REFramework
131b25ef58064b1c36cdd15072c30f5fbd9a7ad8
[ "MIT" ]
583
2021-06-05T06:56:54.000Z
2022-03-31T19:16:09.000Z
src/GennyIda.hpp
drowhunter/REFramework
49ef476d13439110cc0ae565cc323cd615d9b327
[ "MIT" ]
198
2021-07-13T02:54:19.000Z
2022-03-29T20:28:53.000Z
src/GennyIda.hpp
drowhunter/REFramework
49ef476d13439110cc0ae565cc323cd615d9b327
[ "MIT" ]
73
2021-07-12T18:52:12.000Z
2022-03-31T17:12:56.000Z
// SdkGenny - Genny.hpp - A single file header framework for generating C++ compatible SDKs // https://github.com/cursey/sdkgenny // GennyIda.hpp is an optional extra for SdkGenny that generates output intended to be consumed by IDA. #pragma once #include "Genny.hpp" namespace genny::ida { // Does a destructive transformation to the Sdk to make it's output parsable by IDA. inline void transform(Sdk& sdk) { auto g = sdk.global_ns(); std::unordered_set<EnumClass*> enum_classes{}; // Make plain enum types for all enum classes. g->get_all_in_children<EnumClass>(enum_classes); // We have to remove the enum class from it's owner before we can add a normal enum with the same name to it. // Variables may still reference the enum class however so we must keep them alive until all variables have had // their types changed to the normal enum versions. std::vector<std::unique_ptr<Object>> enumclass_keepalive{}; for (auto& e : enum_classes) { Enum* new_enum{}; auto owner = e->direct_owner(); if (auto ns_owner = dynamic_cast<Namespace*>(owner)) { enumclass_keepalive.emplace_back(ns_owner->remove(e)); new_enum = ns_owner->enum_(e->name()); } else if (auto owner_struct = dynamic_cast<Struct*>(owner)) { enumclass_keepalive.emplace_back(owner_struct->remove(e)); new_enum = owner_struct->enum_(e->name()); } else { continue; } for (auto&& [name, value] : e->values()) { new_enum->value(name, value); } new_enum->type(e->type()); } std::unordered_set<Type*> types{}; std::unordered_map<Type*, std::string> new_names{}; g->get_all_in_children<Type>(types); // Go through all the types making new names for them (but not setting them yet) and removing things like their // functions/constants and fixing their enum class types etc. for (auto&& t : types) { if (!t->is_a<Struct>() && !t->is_a<Enum>()) { continue; } auto owners = t->owners<Object>(); auto new_name = t->usable_name(); for (auto&& owner : owners) { if (!owner->usable_name().empty()) { new_name = owner->usable_name() + "::" + new_name; } } new_names.emplace(t, std::move(new_name)); t->simple_typename_generation(true); t->remove_all<Function>(); t->remove_all<Constant>(); // Convert all enum classes to normal enums for (auto&& v : t->get_all<Variable>()) { auto v_t = v->type(); if (!v_t->is_a<EnumClass>()) { continue; } auto owner = v_t->direct_owner(); if (auto owner_ns = dynamic_cast<Namespace*>(owner)) { v->type(owner_ns->enum_(v_t->name())); } else if (auto owner_struct = dynamic_cast<Struct*>(owner)) { v->type(owner_struct->enum_(v_t->name())); } } } // Now that all the new names have been built we can set them. for (auto&& [t, name] : new_names) { t->usable_name = [new_name = std::move(name)] { return new_name; }; if (!t->direct_owner()->is_a<Struct>()) { t->usable_name_decl = t->usable_name; } } sdk.generate_namespaces(false); } } // namespace genny::ida
33.509804
115
0.593622
[ "object", "vector", "transform" ]
7b090b5839bb590397bce37ab0dea7057841beee
1,695
cpp
C++
modules/face/test/test_mace.cpp
ptelang/opencv_contrib
dd68e396c76f1db4d82e5aa7a6545580939f9b9d
[ "Apache-2.0" ]
7,158
2016-07-04T22:19:27.000Z
2022-03-31T07:54:32.000Z
modules/face/test/test_mace.cpp
ptelang/opencv_contrib
dd68e396c76f1db4d82e5aa7a6545580939f9b9d
[ "Apache-2.0" ]
2,184
2016-07-05T12:04:14.000Z
2022-03-30T19:10:12.000Z
modules/face/test/test_mace.cpp
ptelang/opencv_contrib
dd68e396c76f1db4d82e5aa7a6545580939f9b9d
[ "Apache-2.0" ]
5,535
2016-07-06T12:01:10.000Z
2022-03-31T03:13:24.000Z
// This file is part of the OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. #include "test_precomp.hpp" #include <fstream> namespace opencv_test { namespace { const string FACE_DIR = "face"; const int WINDOW_SIZE = 64; class MaceTest { public: MaceTest(bool salt); void run(); protected: Ptr<MACE> mace; bool salt; }; MaceTest::MaceTest(bool use_salt) { mace = MACE::create(WINDOW_SIZE); salt = use_salt; } void MaceTest::run() { Rect david1 (125,66,58,56); Rect david2 (132,69,73,74); Rect detect (199,124,256,274); string folder = cvtest::TS::ptr()->get_data_path() + FACE_DIR; Mat train = imread(folder + "/david2.jpg", 0); Mat tst_p = imread(folder + "/david1.jpg", 0); Mat tst_n = imread(folder + "/detect.jpg", 0); vector<Mat> sam_train; sam_train.push_back( train(Rect(132,69,73,74)) ); sam_train.push_back( train(Rect(130,69,73,72)) ); sam_train.push_back( train(Rect(134,67,73,74)) ); sam_train.push_back( tst_p(Rect(125,66,58,56)) ); sam_train.push_back( tst_p(Rect(123,67,55,58)) ); sam_train.push_back( tst_p(Rect(125,65,58,60)) ); if (salt) mace->salt("it's david"); // "owner's" salt mace->train(sam_train); bool self_ok = mace->same(train(david2)); if (salt) mace->salt("this is a test"); // "other's" salt bool false_A = mace->same(tst_n(detect)); ASSERT_TRUE(self_ok); ASSERT_FALSE(false_A); } TEST(MACE_, unsalted) { MaceTest test(false); test.run(); } TEST(MACE_, salted) { MaceTest test(true); test.run(); } }} // namespace
24.565217
90
0.653097
[ "vector" ]
7b0940dd6f80a3ed392c8e8867febc6a723e8bce
6,261
cpp
C++
myproj/main.cpp
StanislawPluszkiewicz/OpenGL-Engine
fc8a0eab4c6314ca0179bf234505cc9a755f95aa
[ "MIT" ]
null
null
null
myproj/main.cpp
StanislawPluszkiewicz/OpenGL-Engine
fc8a0eab4c6314ca0179bf234505cc9a755f95aa
[ "MIT" ]
null
null
null
myproj/main.cpp
StanislawPluszkiewicz/OpenGL-Engine
fc8a0eab4c6314ca0179bf234505cc9a755f95aa
[ "MIT" ]
null
null
null
#include <fstream> #include <string> #include <vector> #include <GL/glew.h> #include <SDL2/SDL_main.h> #include <SDL2/SDL.h> #include <SDL2/SDL_opengl.h> #undef main #include "NFD/nfd.h" #include "helperFunctions.h" #include "myShader.h" #include "myCamera.h" #include "myObject3D.h" #include <glm/glm.hpp> using namespace std; #define INITIAL_WINDOW_WIDTH 640 #define INITIAL_WINDOW_HEIGHT 480 // SDL variables SDL_Window* window; SDL_GLContext glContext; int mouse_position[2]; bool mouse_button_pressed = false; bool quit = false; bool windowsize_changed = true; bool crystalballorfirstperson_view = true; // Camera parameters. myCamera *cam1; // Mesh object myObject3D *obj1; //Shader myShader *shader1; //Point to draw to illustrate picking glm::vec3 picked_point; bool isSilhouetteOn = false; // Process the event. void processEvents(SDL_Event current_event) { switch (current_event.type) { // window close button is pressed case SDL_QUIT: { quit = true; break; } case SDL_KEYDOWN: { if (current_event.key.keysym.sym == SDLK_ESCAPE) quit = true; if (current_event.key.keysym.sym == SDLK_UP) cam1->moveForward(0.1f); if (current_event.key.keysym.sym == SDLK_DOWN) cam1->moveBack(0.1f); if (current_event.key.keysym.sym == SDLK_LEFT) cam1->turnLeft(0.1f); if (current_event.key.keysym.sym == SDLK_RIGHT) cam1->turnRight(0.1f); if (current_event.key.keysym.sym == SDLK_v) crystalballorfirstperson_view = !crystalballorfirstperson_view; else if (current_event.key.keysym.sym == SDLK_o) { nfdchar_t *outPath = NULL; nfdresult_t result = NFD_OpenDialog("obj", NULL, &outPath); if (result != NFD_OKAY) return; myObject3D *obj_tmp = new myObject3D(); if (!obj_tmp->readMesh(outPath)) { delete obj_tmp; return; } delete obj1; obj1 = obj_tmp; obj1->computeNormals(); obj1->createObjectBuffers(); } else if (current_event.key.keysym.sym == SDLK_s) { isSilhouetteOn = !isSilhouetteOn; } break; } case SDL_MOUSEBUTTONDOWN: { mouse_position[0] = current_event.button.x; mouse_position[1] = current_event.button.y; mouse_button_pressed = true; const Uint8 *state = SDL_GetKeyboardState(NULL); if (state[SDL_SCANCODE_LCTRL]) { glm::vec3 ray = cam1->constructRay(mouse_position[0], mouse_position[1]); picked_point = obj1->closestVertex(ray, cam1->camera_eye); } break; } case SDL_MOUSEBUTTONUP: { mouse_button_pressed = false; break; } case SDL_MOUSEMOTION: { int x = current_event.motion.x; int y = current_event.motion.y; int dx = x - mouse_position[0]; int dy = y - mouse_position[1]; mouse_position[0] = x; mouse_position[1] = y; if ((dx == 0 && dy == 0) || !mouse_button_pressed) return; if ( (SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_LEFT)) && crystalballorfirstperson_view) cam1->crystalball_rotateView(dx, dy); else if ((SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_LEFT)) && !crystalballorfirstperson_view) cam1->firstperson_rotateView(dx, dy); else if (SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_RIGHT)) cam1->panView(dx, dy); break; } case SDL_WINDOWEVENT: { if (current_event.window.event == SDL_WINDOWEVENT_RESIZED) windowsize_changed = true; break; } case SDL_MOUSEWHEEL: { if (current_event.wheel.y < 0) cam1->moveBack(0.1f); else if (current_event.wheel.y > 0) cam1->moveForward(0.1f); break; } default : break; } } int main(int argc, char *argv[]) { // Using OpenGL 3.1 core SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); // Initialize video subsystem SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO); // Create window window = SDL_CreateWindow("IN4I24", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, INITIAL_WINDOW_WIDTH, INITIAL_WINDOW_HEIGHT, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE); // Create OpenGL context glContext = SDL_GL_CreateContext(window); // Initialize glew glewInit(); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_TEXTURE_2D); glDisable(GL_CULL_FACE); // Setting up OpenGL shaders shader1 = new myShader("shaders/light.vert.glsl", "shaders/light.frag.glsl"); myShader * shader2 = new myShader("shaders/light.vert.glsl", "shaders/silhouette.frag.glsl"); myShader * shaderTmp; // Read up the scene obj1 = new myObject3D(); obj1->readMesh("apple.obj"); obj1->computeNormals(); obj1->createObjectBuffers(); cam1 = new myCamera(); SDL_GetWindowSize(window, &cam1->window_width, &cam1->window_height); // display loop while (!quit) { if (windowsize_changed) { SDL_GetWindowSize(window, &cam1->window_width, &cam1->window_height); windowsize_changed = false; } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glViewport(0, 0, cam1->window_width, cam1->window_height); glm::mat4 projection_matrix = cam1->projectionMatrix(); glm::mat4 view_matrix = cam1->viewMatrix(); if (isSilhouetteOn) { shaderTmp = shader2; shaderTmp->start(); shaderTmp->setUniform("myview_matrix", view_matrix); shaderTmp->setUniform("myprojection_matrix", projection_matrix); shaderTmp->setUniform("mynormal_matrix", glm::transpose(glm::inverse(glm::mat3(view_matrix)))); } else { shaderTmp = shader1; shaderTmp->start(); shaderTmp->setUniform("input_color", glm::vec4(1, 1, 0, 0)); shaderTmp->setUniform("myview_matrix", view_matrix); shaderTmp->setUniform("myprojection_matrix", projection_matrix); } obj1->displayObject(shaderTmp); obj1->displayNormals(shaderTmp); glPointSize(6.0f); glBegin(GL_POINTS); glVertex3fv(&picked_point[0]); glEnd(); SDL_GL_SwapWindow(window); SDL_Event current_event; while (SDL_PollEvent(&current_event) != 0) processEvents(current_event); } // Freeing resources before exiting. // Destroy window if (glContext) SDL_GL_DeleteContext(glContext); if (window) SDL_DestroyWindow(window); // Quit SDL subsystems SDL_Quit(); return 0; }
24.649606
108
0.711388
[ "mesh", "object", "vector" ]
7b095cb112fa0bb3c54c788e4b731db1f75ba2a7
3,202
cpp
C++
source/format/BP1Aggregator.cpp
pnorbert/ADIOS2
6bd06b550431cf3e354a1a0b3f0d825e39fe97a9
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
source/format/BP1Aggregator.cpp
pnorbert/ADIOS2
6bd06b550431cf3e354a1a0b3f0d825e39fe97a9
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
source/format/BP1Aggregator.cpp
pnorbert/ADIOS2
6bd06b550431cf3e354a1a0b3f0d825e39fe97a9
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * BP1Aggregator.cpp * * Created on: Mar 21, 2017 * Author: wfg */ /// \cond EXCLUDE_FROM_DOXYGEN #include <fstream> #include <stdexcept> #include <vector> /// \endcond #include "format/BP1Aggregator.h" namespace adios { namespace format { BP1Aggregator::BP1Aggregator(MPI_Comm mpiComm, const bool debugMode) : m_MPIComm{mpiComm}, m_DebugMode{debugMode} { MPI_Comm_rank(m_MPIComm, &m_RankMPI); MPI_Comm_size(m_MPIComm, &m_SizeMPI); } BP1Aggregator::~BP1Aggregator() = default; void BP1Aggregator::WriteProfilingLog(const std::string fileName, const std::string &rankLog) { if (m_RankMPI == 0) { unsigned int sizeMPI = static_cast<unsigned int>(m_SizeMPI); std::vector<std::vector<char>> rankLogs( sizeMPI - 1); // rankLogs from other processes std::vector<int> rankLogsSizes(sizeMPI - 1, -1); // init with -1 std::vector<MPI_Request> requests(sizeMPI); std::vector<MPI_Status> statuses(sizeMPI); // first receive sizes for (unsigned int i = 1; i < sizeMPI; ++i) { MPI_Irecv(&rankLogsSizes[i - 1], 1, MPI_INT, i, 0, m_MPIComm, &requests[i]); } for (unsigned int i = 1; i < sizeMPI; ++i) { MPI_Wait(&requests[i], &statuses[i]); if (m_DebugMode == true) { if (rankLogsSizes[i - 1] == -1) { throw std::runtime_error( "ERROR: couldn't get size from rank " + std::to_string(i) + ", in ADIOS aggregator for Profiling.log\n"); } } rankLogs[i - 1].resize(rankLogsSizes[i - 1]); // allocate with zeros } // receive rankLog from other ranks for (unsigned int i = 1; i < sizeMPI; ++i) { MPI_Irecv(rankLogs[i - 1].data(), rankLogsSizes[i - 1], MPI_CHAR, i, 1, m_MPIComm, &requests[i]); } for (unsigned int i = 1; i < sizeMPI; ++i) { MPI_Wait(&requests[i], &statuses[i]); } // write file std::string logFile("log = { \n"); logFile += rankLog + "\n"; for (unsigned int i = 1; i < sizeMPI; ++i) { const std::string rankLogStr(rankLogs[i - 1].data(), rankLogs[i - 1].size()); logFile += rankLogStr + "\n"; } logFile += " }\n"; std::ofstream logStream(fileName); logStream.write(logFile.c_str(), logFile.size()); logStream.close(); } else { int rankLogSize = static_cast<int>(rankLog.size()); MPI_Request requestSize; MPI_Isend(&rankLogSize, 1, MPI_INT, 0, 0, m_MPIComm, &requestSize); MPI_Request requestRankLog; MPI_Isend(rankLog.data(), rankLogSize, MPI_CHAR, 0, 1, m_MPIComm, &requestRankLog); } } } // end namespace format } // end namespace adios
29.376147
80
0.53935
[ "vector" ]
7b11afc2d3425d7e2674dc184be3a144680c7be5
14,633
hpp
C++
nplus1/include/np1/rel/detail/helper.hpp
AnthonyNystrom/r17
a73f5faf07a554c9c693074192b34be834f3106c
[ "Apache-2.0" ]
1
2015-11-05T21:40:47.000Z
2015-11-05T21:40:47.000Z
nplus1/include/np1/rel/detail/helper.hpp
AnthonyNystrom/r17
a73f5faf07a554c9c693074192b34be834f3106c
[ "Apache-2.0" ]
null
null
null
nplus1/include/np1/rel/detail/helper.hpp
AnthonyNystrom/r17
a73f5faf07a554c9c693074192b34be834f3106c
[ "Apache-2.0" ]
null
null
null
// Copyright 2012 Matthew Nourse and n plus 1 computing pty limited unless otherwise noted. // Please see LICENSE file for details. #ifndef NP1_REL_DETAIL_HELPER_HPP #define NP1_REL_DETAIL_HELPER_HPP #include "np1/hash/fnv1a64.hpp" #include "np1/rel/rlang/dt.hpp" namespace np1 { namespace rel { namespace detail { namespace helper { uint64_t hash_add(uint8_t b, uint64_t hval) { return hash::fnv1a64::add(b, hval); } uint64_t hash_add(const char *p, size_t len, uint64_t hval) { return hash::fnv1a64::add(p, len, hval); } uint64_t hash_init(size_t somedata = 0x12345) { return hash::fnv1a64::init(somedata); } //TODO: remove this and use the str:: functions instead. int string_compare(const char *f1, size_t f1_length, const char *f2, size_t f2_length) { ssize_t compare_length = (f1_length > f2_length) ? f2_length : f1_length; int compare_result = memcmp(f1, f2, compare_length); if (0 == compare_result) { if (f1_length > f2_length) { return 1; } else if (f1_length < f2_length) { return -1; } return 0; } return compare_result; } //TODO: remove this and use the str:: functions instead. int istring_compare(const char *f1, size_t f1_length, const char *f2, size_t f2_length) { ssize_t compare_length = (f1_length > f2_length) ? f2_length : f1_length; int compare_result = strncasecmp(f1, f2, compare_length); if (0 == compare_result) { if (f1_length > f2_length) { return 1; } else if (f1_length < f2_length) { return -1; } return 0; } return compare_result; } uint64_t string_hash_add(const char *str, size_t length, uint64_t hval) { return hash_add(str, length, hval); } uint64_t istring_hash_add(const char *str, size_t length, uint64_t hval) { const char *end = str + length; for (; str < end; ++str) { hval = hash_add(tolower(*str), hval); } return hval; } inline const char *strip_leading_spaces_and_zeroes(const char *str, size_t length, size_t &new_length) { new_length = length; while ((new_length > 0) && ((' ' == *str) || ('0' == *str))) { ++str; --new_length; } return str; } inline const char *strip_leading_spaces(const char *str, size_t length, size_t &new_length) { new_length = length; while ((new_length > 0) && ((' ' == *str))) { ++str; --new_length; } return str; } // Concatenate two strings, allocating the result from the supplied heap object. template <typename Heap> inline str::ref string_concat(Heap &heap, const str::ref &one, const str::ref &two) { size_t new_length = one.length() + two.length(); char *new_s = heap.alloc(new_length); memcpy(new_s, one.ptr(), one.length()); memcpy(new_s + one.length(), two.ptr(), two.length()); return str::ref(new_s, new_length); } int uint_compare(const char *f1, size_t f1_length, const char *f2, size_t f2_length) { f1 = strip_leading_spaces_and_zeroes(f1, f1_length, f1_length); f2 = strip_leading_spaces_and_zeroes(f2, f2_length, f2_length); // Try to avoid the expense of converting to integer. if (f1_length > f2_length) { return 1; } if (f1_length < f2_length) { return -1; } // They are the same length. while (f1_length > 0) { if (*f1 > *f2) { return 1; } if (*f1 < *f2) { return -1; } ++f1; ++f2; --f1_length; } return 0; } uint64_t uint_hash_add(const char *field, size_t field_length, uint64_t hval) { field = strip_leading_spaces_and_zeroes(field, field_length, field_length); return hash_add(field, field_length, hval); } int int_compare(const char *f1, size_t f1_length, const char *f2, size_t f2_length) { f1 = strip_leading_spaces_and_zeroes(f1, f1_length, f1_length); f2 = strip_leading_spaces_and_zeroes(f2, f2_length, f2_length); // Avoid converting to integer if possible. if (*f1 == '-') { if (*f2 == '-') { ++f1; ++f2; --f1_length; --f2_length; return -(uint_compare(f1, f1_length, f2, f2_length)); } return -1; } if (*f2 == '-') { return 1; } return uint_compare(f1, f1_length, f2, f2_length); } uint64_t int_hash_add(const char *field, size_t field_length, uint64_t hval) { field = strip_leading_spaces_and_zeroes(field, field_length, field_length); return hash_add(field, field_length, hval); } int double_compare(const char *f1, size_t f1_length, const char *f2, size_t f2_length) { const double d1 = str::dec_to_double(f1, f1_length); const double d2 = str::dec_to_double(f2, f2_length); if (d1 > d2) { return 1; } if (d1 < d2) { return -1; } return 0; } uint64_t double_hash_add(const char *field, size_t field_length, uint64_t hval) { field = strip_leading_spaces_and_zeroes(field, field_length, field_length); return hash_add(field, field_length, hval); } // Convert a boolean field to a number. True is 1, false is 0. int bool_to_int(const char *f, size_t length) { if (length > 0) { if ('1' == *f) { return 1; } if ('0' == *f) { return 0; } char error_string[128]; sprintf(error_string, "Invalid boolean value: '%c' (0x%x)", *f, (int)*f); NP1_ASSERT(false, error_string); } return 0; } // Compare two boolean fields. true is 1, false is 0. int bool_compare(const char *f1, size_t f1_length, const char *f2, size_t f2_length) { f1 = strip_leading_spaces(f1, f1_length, f1_length); f2 = strip_leading_spaces(f2, f2_length, f2_length); int f1_val = bool_to_int(f1, f1_length); int f2_val = bool_to_int(f2, f2_length); return (f1_val - f2_val); } uint64_t bool_hash_add(const char *field, size_t field_length, uint64_t hval) { field = strip_leading_spaces(field, field_length, field_length); return hash_add(field, field_length, hval); } const char *ipnumber_to_number(uint64_t &num, const char *ipnumber, const char *max_end_of_number) { char *end_p; num = str::partial_dec_to_int64(ipnumber, max_end_of_number, &end_p); return end_p; } // Convert an IP address component to a number and return a pointer to // the end of the component. const char *ipaddress_component_to_number(unsigned int &num, const char *start, const char *end_of_string, const char *ipaddress, size_t length) { if (start >= end_of_string) { NP1_ASSERT(false, "Invalid IP address, start >= end_of_string"); } uint64_t ui64 = 0; const char *end_p = ipnumber_to_number(ui64, start, end_of_string); if ((ui64 <= 255) && (end_p != start) && ((*end_p == '.') || (end_p == end_of_string))) { num = (unsigned int)ui64; return end_p; } NP1_ASSERT(false, "Invalid IP address: '" + str::ref(ipaddress, length).to_string() + "'"); return 0; } // Convert an IP address to a number. unsigned int ipaddress_to_number(const char *ipaddress, size_t length) { unsigned int component0 = 0; unsigned int component1 = 0; unsigned int component2 = 0; unsigned int component3 = 0; const char *end_of_ipaddress = ipaddress + length; const char *end_component; end_component = ipaddress_component_to_number(component0, ipaddress, end_of_ipaddress, ipaddress, length); end_component = ipaddress_component_to_number(component1, end_component + 1, end_of_ipaddress, ipaddress, length); end_component = ipaddress_component_to_number(component2, end_component + 1, end_of_ipaddress, ipaddress, length); ipaddress_component_to_number(component3, end_component + 1, end_of_ipaddress, ipaddress, length); unsigned int ipnumber = component0 * 16777216; ipnumber += component1 * 65536; ipnumber += component2 * 256; ipnumber += component3; return ipnumber; } // Compare to unsigned integers. int compare_c_uints(unsigned int ui1, unsigned int ui2) { if (ui1 < ui2) { return -1; } if (ui1 > ui2) { return 1; } return 0; } // Compare two fields that may be IP addresses or IP numbers. int ipaddress_or_ipnumber_compare(const char *f1, size_t f1_length, const char *f2, size_t f2_length) { f1 = strip_leading_spaces_and_zeroes(f1, f1_length, f1_length); f2 = strip_leading_spaces_and_zeroes(f2, f2_length, f2_length); bool f1_is_ip_number = !memchr(f1, '.', f1_length); bool f2_is_ip_number = !memchr(f2, '.', f2_length); if (f1_is_ip_number) { if (f2_is_ip_number) { return uint_compare(f1, f1_length, f2, f2_length); } uint64_t f1_number; const char *end_p = ipnumber_to_number(f1_number, f1, f1 + f1_length); if (end_p != f1 + f1_length) { NP1_ASSERT(false, "Invalid IP number: " + std::string(f1, f1_length)); } unsigned int f2_number = ipaddress_to_number(f2, f2_length); //TODO: this cast is probably unsafe. return compare_c_uints((unsigned int)f1_number, f2_number); } if (f2_is_ip_number) { uint64_t f2_number; const char *end_p = ipnumber_to_number(f2_number, f2, f2 + f2_length); if (end_p != f2 + f2_length) { NP1_ASSERT(false, "Invalid IP number: " + std::string(f2, f2_length)); } unsigned int f1_number = ipaddress_to_number(f1, f1_length); //TODO: this cast is probably unsafe. return compare_c_uints((unsigned int)f1_number, f2_number); } return compare_c_uints(ipaddress_to_number(f1, f1_length), ipaddress_to_number(f2, f2_length)); } int ipaddress_or_ipnumber_compare(const str::ref &f1, const str::ref &f2) { return ipaddress_or_ipnumber_compare(f1.ptr(), f1.length(), f2.ptr(), f2.length()); } // Hash an ipnumber or ipaddress field. uint64_t ipnumber_or_ipaddress_hash_add(const char *field, size_t field_length, uint64_t hval) { field = strip_leading_spaces_and_zeroes(field, field_length, field_length); return hash_add(field, field_length, hval); } // Figure out if a heading refers to "this" record or the "other" record. typedef enum { RECORD_IDENTIFIER_THIS, RECORD_IDENTIFIER_OTHER } record_identifier_type; record_identifier_type get_heading_record_identifier( const str::ref &heading_name, str::ref &heading_name_without_record_identifier) { static const char *THIS_STRING = "this"; static const size_t THIS_STRING_LENGTH = strlen(THIS_STRING); static const char *OTHER_STRING = "other"; static const size_t OTHER_STRING_LENGTH = strlen(OTHER_STRING); static const char *PREV_STRING = "prev"; static const size_t PREV_STRING_LENGTH = strlen(PREV_STRING); // By default, the token text refers to "this" record. const char *heading_name_p = heading_name.ptr(); const char *dot = strchr(heading_name_p, '.'); record_identifier_type type = RECORD_IDENTIFIER_THIS; if (!dot) { type = RECORD_IDENTIFIER_THIS; } else if (str::cmp(heading_name_p, dot - heading_name_p, THIS_STRING, THIS_STRING_LENGTH) == 0) { type = RECORD_IDENTIFIER_THIS; heading_name_p += THIS_STRING_LENGTH + 1; } else if (str::cmp(heading_name_p, dot - heading_name_p, OTHER_STRING, OTHER_STRING_LENGTH) == 0) { type = RECORD_IDENTIFIER_OTHER; heading_name_p += OTHER_STRING_LENGTH + 1; } else if (str::cmp(heading_name_p, dot - heading_name_p, PREV_STRING, PREV_STRING_LENGTH) == 0) { type = RECORD_IDENTIFIER_OTHER; heading_name_p += PREV_STRING_LENGTH + 1; } else { NP1_ASSERT(false, "Invalid record identifier prefix in " + std::string(heading_name.ptr()) + " Valid values are:\n" + std::string(THIS_STRING) + "\n" + std::string(OTHER_STRING) + "\n" + std::string(PREV_STRING) + "\n"); } heading_name_without_record_identifier = str::ref(heading_name_p, strlen(heading_name_p)); return type; } // Get a heading name without the type tag, if it has a type tag. str::ref get_heading_without_type_tag(const str::ref &heading_name) { const char *colon = (const char *)memchr(heading_name.ptr(), ':', heading_name.length()); if (!colon) { return heading_name; } if (heading_name.ptr() + heading_name.length() - 1 == colon) { return heading_name; } return str::ref(colon + 1, heading_name.length() - (colon - heading_name.ptr()) - 1); } str::ref get_heading_without_type_tag(const std::string &heading_name) { return get_heading_without_type_tag(str::ref(heading_name)); } // Get the type tag out of the heading name. Returns a null str::ref on // failure. str::ref get_heading_type_tag(const str::ref &heading_name) { const char *colon = (const char *)memchr(heading_name.ptr(), ':', heading_name.length()); if (!colon) { return str::ref(); } if (heading_name.ptr() + heading_name.length() - 1 == colon) { return str::ref(); } if (colon == heading_name.ptr()) { return str::ref(); } return str::ref(heading_name.ptr(), colon - heading_name.ptr()); } str::ref get_heading_type_tag(const char *heading_name) { return get_heading_type_tag(str::ref(heading_name)); } str::ref get_heading_type_tag(const std::string &heading_name) { return get_heading_type_tag(str::ref(heading_name)); } // Get the type tag out of the heading name, crash the process on error. str::ref mandatory_get_heading_type_tag(const str::ref &heading_name) { str::ref type_tag = get_heading_type_tag(heading_name); NP1_ASSERT(!type_tag.is_null(), "Type tag not found in heading: " + heading_name.to_string()); return type_tag; } str::ref mandatory_get_heading_type_tag(const std::string &heading_name) { return mandatory_get_heading_type_tag(str::ref(heading_name)); } std::string make_typed_heading_name(const std::string &type_name, const std::string &name) { return type_name + ":" + name; } std::string convert_to_valid_header_name(const str::ref &s) { std::string result; const char *p = s.ptr(); const char *end = p + s.length(); for (; p < end; ++p) { if (isalnum(*p)) { result.push_back(*p); } else if (':' == *p) { if (rlang::dt::is_valid_tag(str::ref(s.ptr(), p - s.ptr()))) { result.push_back(*p); } else { result.push_back('_'); } } else { result.push_back('_'); } } return result; } } // namespaces } } } #endif
27.819392
106
0.6594
[ "object" ]
7b1693a84bdf8b4fd287a080e255b882c06b9aba
104,340
cpp
C++
CT/InputGenerator.cpp
bredelings/Compatibility-Testing
d775a1a052bf09655a154bc115eb95ce00f40d9e
[ "MIT" ]
null
null
null
CT/InputGenerator.cpp
bredelings/Compatibility-Testing
d775a1a052bf09655a154bc115eb95ce00f40d9e
[ "MIT" ]
null
null
null
CT/InputGenerator.cpp
bredelings/Compatibility-Testing
d775a1a052bf09655a154bc115eb95ce00f40d9e
[ "MIT" ]
null
null
null
//MIT License // //Copyright (c) 2018 Lei Liu // //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. // // Detailed implementation of InputGenerator.h // This class uses two main algorithms: // 1. when generating a unbiased binary tree, the algorithm proposed by Martin Orr are used // 2. when generating a unbiased binary tree, a random number shall be generated as one of the parameter of Martin Orr's method // the random number is implemented by using the method of , this method will finally return a 32 bit integer number #include "InputGenerator.h" #include <chrono> #include <algorithm> using namespace std; //can be deleted later void postorder(in_tree* t){ if(t != NULL){ postorder(t->l_child); postorder(t->r_child); cout << "tree label ----- " << t->label << " < ------- > "; if(t->parent){ cout << t->parent->label << endl; } else{ cout << endl; } } } //can be deleted later void preorder(in_tree* t){ if(t != NULL){ cout << "tree label ----- " << t->label << " < ------- > "; if(t->parent){ cout << t->parent->label << endl; } else{ cout << endl; } preorder(t->l_child); preorder(t->r_child); } } //can be deleted later void preorder_non(in_tree_non2* t){ if(t != NULL){ cout << "tree label ----- " << t->label << " < ------- > "; if(t->parent){ cout << t->parent->label << endl; } else{ cout << endl; } for(int i = 0 ; i < t->children.size(); i++){ preorder_non(t->children[i]); } } } //can be deleted later void preorder_2(in_tree* t){ if(t != NULL){ cout << "tree label ---- " << t->label << " < ------- > "; if(t->substract_parent){ cout << t->substract_parent->label << endl; } else cout << endl; preorder_2(t->substract_l_child); preorder_2(t->substract_r_child); } } void preorder_non2_2(in_tree_non2* t){ if(t != NULL){ cout << "tree label ---- " << t->label << " < ------- > "; if(t->substract_parent){ cout << t->substract_parent->label << endl; } else{ cout << endl; } for(int i = 0 ; i < t->substract_children.size(); i++){ preorder_non2_2(t->substract_children[i]); } } } void InputGenerator::check_children_count(in_tree* root){ if(root != NULL){ if(root->substract_l_child == NULL && root->substract_r_child != NULL){ internal_label = true; } else if(root->substract_l_child != NULL && root->substract_r_child == NULL){ internal_label = true; } check_children_count(root->substract_l_child); check_children_count(root->substract_r_child); } } // 1. generate a non-binary degree tree as a seed tree // 2. generate a list of input trees // 3. generate a hpu list multimap<string, unordered_map<string, linked_list_entry> > InputGenerator::construct_non_binary_degree_tree( int number_of_nodes, int number_of_subsets, int degree) { //initialize the stack structure _vec_stack_non2._stack_top = 1; _vec_stack_non2._vector_stack = new vector<in_tree_non2*>; label_list = new vector<string>; node_list_non2 = new vector<in_tree_non2*>; //step 1 in_tree_non2* non2_tree_root = non_binary_tree_builder_leaf_label_only(number_of_nodes, number_of_subsets, degree); //step 2 build_up_preorder_stack_non2(non2_tree_root); //step 3 multimap<string, unordered_map<string, linked_list_entry> > _input_trees = build_hpu_non2(non2_tree_root, degree); return _input_trees; } //construct a specified binary tree, and a set of basic triplets //add some more additional triplets randomly //extract each subtree by using subsets multimap<string, unordered_map<string, linked_list_entry> > InputGenerator::construct_specifiedTriples( int number_of_labels, double portion, double lper) { //initialize the stack structure _vec_stack._stack_top = -1; _vec_stack._vector_stack = new vector<in_tree*>; label_list = new vector<string>; node_list = new vector<in_tree*>; internal_nodes_vec = new vector<string>; label_parent_map = new unordered_map<string, in_tree*>; in_use_triplet = new unordered_set<string>; //step 1 initial_tree4triplet_test(number_of_labels, portion, lper); //step 2 build_up_preorder_stack(tree_root); //step 3 multimap<string, unordered_map<string, linked_list_entry> > _input_trees = build_triple_hpu(tree_root); return _input_trees; } //construct a binary tree, and a set of subsets with size of 3 //extract each subtree by using subsets multimap<string, unordered_map<string, linked_list_entry> > InputGenerator::construct_triples(int number_of_nodes) { //initialize the stack structure _vec_stack._stack_top = -1; _vec_stack._vector_stack = new vector<in_tree*>; label_list = new vector<string>; node_list = new vector<in_tree*>; //step 1 triple_builder_leaf_label_only(number_of_nodes); //step 2 build_up_preorder_stack(tree_root); //step 3 multimap<string, unordered_map<string, linked_list_entry> > _input_trees = build_triple_hpu(tree_root); return _input_trees; } //construct a binary tree, and a set of subtrees by extracting each subtree from the binary tree multimap<string, unordered_map<string, linked_list_entry> > InputGenerator::construct_tree_leaf_label_only(int number_of_nodes, int number_of_subsets) { //initialize the stack structure _vec_stack._stack_top = -1; _vec_stack._vector_stack = new vector<in_tree*>; label_list = new vector<string>; node_list = new vector<in_tree*>; //step 1 binary_tree_builder_leaf_label_only(number_of_nodes, number_of_subsets); //step 2 build_up_preorder_stack(tree_root); //step 3 multimap<string, unordered_map<string, linked_list_entry> > _input_trees = build_hpu(tree_root); return _input_trees; } //main entry of input generator //1. construct the binary tree using buttom-up method //2. construct the preorder sequence of the binary tree //3. subtract the trees according to the subsets and convert binary tree to linked list tree(hpu) multimap<string, unordered_map<string, linked_list_entry> > InputGenerator::construct_tree_with_internal_label(int number_of_nodes, int number_of_subsets) { //initialize the stack structure _vec_stack._stack_top = -1; _vec_stack._vector_stack = new vector<in_tree*>; label_list = new vector<string>; node_list = new vector<in_tree*>; //step 1 binary_tree_builder_with_internal_label(number_of_nodes, number_of_subsets); //step 2 build_up_preorder_stack(tree_root); //step 3 multimap<string, unordered_map<string, linked_list_entry> > _input_trees = build_hpu(tree_root); return _input_trees; } //construct the preorder sequence by using non-recursive method void InputGenerator::build_up_preorder_stack_non2(in_tree_non2 *root) { preorder_stack_non2 = new stack<in_tree_non2*>; preorder_stack_non2->push(root); while(!(preorder_stack_non2->empty())){ in_tree_non2* cur_node = preorder_stack_non2->top(); preorder_stack_non2->pop(); if(cur_node != NULL){ _vec_stack_non2._vector_stack->push_back(cur_node); _vec_stack_non2._stack_top++; for(int i = (int)cur_node->children.size() - 1 ; i >= 0; i--){ preorder_stack_non2->push(cur_node->children[i]); } } } delete preorder_stack_non2; } //construct the preorder sequence by using non-recursive method void InputGenerator::build_up_preorder_stack(in_tree *root) { preorder_stack = new stack<in_tree*>; in_tree* cur_node = root; while(cur_node != NULL || !(preorder_stack->empty())){ while(cur_node != NULL){ _vec_stack._vector_stack->push_back(cur_node); _vec_stack._stack_top++; preorder_stack->push(cur_node); cur_node = cur_node->l_child; } if(!(preorder_stack->empty())){ cur_node = preorder_stack->top(); preorder_stack->pop(); cur_node = cur_node->r_child; } } delete preorder_stack; } //this method is designed to build up all subsets with size of 3 void InputGenerator::triple_subset() { int subset_index = 1; for(int i = 0; i < label_list->size() - 2; i++){ string label1 = (*label_list)[i]; for(int j = i + 1; j < label_list->size() - 1; j++){ string label2 = (*label_list)[j]; for(int k = j + 1; k < label_list->size(); k++){ string label3 = (*label_list)[k]; unordered_map<int, unordered_set<string> >::iterator subsetsByindex_finder = subsetsByindex.find(subset_index); if(subsetsByindex_finder != subsetsByindex.end()){ subsetsByindex_finder->second.insert(label1); subsetsByindex_finder->second.insert(label2); subsetsByindex_finder->second.insert(label3); } else{ unordered_set<string> temp_set; temp_set.insert(label1); temp_set.insert(label2); temp_set.insert(label3); subsetsByindex.insert(unordered_map<int, unordered_set<string> >::value_type(subset_index, temp_set)); subset_index++; } } } } } //this method is designed to insert the label of a node into some subsets //this method will ensure each label is in at least one subset void InputGenerator::insert_to_subset(int subset_number, string _node_value){ //generate random number 0 or 1, insert this label into corresponding subset random_device subset_rd; mt19937_64 subset_mt(subset_rd()); uniform_int_distribution<int> subset_dist(0, 1); int _label_in_no_subsets = 0; for(int i = 0; i < subset_number; i++){ int temp_random = subset_dist(subset_mt); if(temp_random == 1){ unordered_map<int, unordered_set<string> >::iterator subsetsByindex_finder = subsetsByindex.find(i + 1); if(subsetsByindex_finder != subsetsByindex.end()){ //find it subsetsByindex_finder->second.insert(_node_value); } else{ unordered_set<string> temp_set; temp_set.insert(_node_value); subsetsByindex.insert(unordered_map<int, unordered_set<string> >::value_type(i + 1, temp_set)); } } else{ unordered_map<int, unordered_set<string> >::iterator subsetsByindex_finder = subsetsByindex.find(i + 1); if(subsetsByindex_finder == subsetsByindex.end()){ unordered_set<string> temp_set; subsetsByindex.insert(unordered_map<int, unordered_set<string> >::value_type(i + 1, temp_set)); } _label_in_no_subsets++; } } //ensure that every label is in the one of the subsets if(_label_in_no_subsets == subset_number){ random_device add_subset_rd; mt19937_64 add_subset_mt(add_subset_rd()); uniform_int_distribution<int> add_subset_dist(1, subset_number); int add_subset_random_number = add_subset_dist(add_subset_mt); unordered_map<int, unordered_set<string> >::iterator subsetsByindex_finder = subsetsByindex.find(add_subset_random_number); if(subsetsByindex_finder != subsetsByindex.end()){ //find it subsetsByindex_finder->second.insert(_node_value); } else{ unordered_set<string> temp_set; temp_set.insert(_node_value); subsetsByindex.insert(unordered_map<int, unordered_set<string> >::value_type(add_subset_random_number, temp_set)); } } } //main method for constructing a binary tree from buttom to up //this method will generate a reasoning number k of leaf nodes which is less than the number of labeled nodes N given //then it will build up a binary tree with 2k - 1 nodes which contains N labeled nodes and 2k - 1 - N unlabeled nodes //which means that some of the internal nodes should be labeled void InputGenerator::binary_tree_builder_with_internal_label(int N, int subset_number) { //firstly, randomly generate a reasoning number which is between [N/2 +1/2, N -1] if N is an odd number which is larger than 2 //between [N/2 + 3/2, N - 1] if N is an even number which is larger than 3 //when N is 1 and 2, situations will be discussed seperately if(N == 1){ in_tree* _temp_tree_node = new in_tree(); backUpTreeNode->insert(_temp_tree_node); _temp_tree_node->label = "label_1"; _temp_tree_node->selected_child = false; label_list->push_back("label_1"); for(int i = 0; i < subset_number; i++){ unordered_map<int, unordered_set<string> >::iterator subsetsByindex_finder = subsetsByindex.find(i + 1); if(subsetsByindex_finder != subsetsByindex.end()){ //find it subsetsByindex_finder->second.insert("label_1"); } else{ unordered_set<string> temp_set; temp_set.insert("label_1"); subsetsByindex.insert(unordered_map<int, unordered_set<string> >::value_type(i + 1, temp_set)); } } tree_root = _temp_tree_node; } else if(N == 2){ in_tree* _temp_tree_node1 = new in_tree(); in_tree* _temp_tree_node2 = new in_tree(); backUpTreeNode->insert(_temp_tree_node1); backUpTreeNode->insert(_temp_tree_node2); _temp_tree_node1->label = "label_1"; _temp_tree_node1->selected_child = false; _temp_tree_node2->label = "label_2"; _temp_tree_node2->selected_child = false; label_list->push_back("label_1"); label_list->push_back("label_2"); _temp_tree_node1->l_child = _temp_tree_node2; _temp_tree_node2->parent = _temp_tree_node1; for(int i = 0; i < 2; i++){ stringstream ss; ss << i + 1; string _temp_tree_node_value = "label_" + ss.str(); insert_to_subset(subset_number, _temp_tree_node_value); } tree_root = _temp_tree_node1; } else if(N >= 3){ int leaf_number = 0; int total_node_number = 0; random_device leaf_number_rd; mt19937_64 leaf_number_mt(leaf_number_rd()); if(N % 2 == 0){ //if the number of input is even uniform_int_distribution<int> leaf_number_dist((N + 1)/2 + 1, N - 1); leaf_number = leaf_number_dist(leaf_number_mt); } else{ //if the number of input is odd uniform_int_distribution<int> leaf_number_dist((N + 1)/2, N - 1); leaf_number = leaf_number_dist(leaf_number_mt); } total_node_number = leaf_number * 2 - 1; //construct the leaf vector for(int i = 0; i < leaf_number; i++){ stringstream ss; ss << label_count++; in_tree* _temp_tree_node = new in_tree(); backUpTreeNode->insert(_temp_tree_node); string _temp_tree_node_value = "label_" + ss.str(); _temp_tree_node->label = _temp_tree_node_value; _temp_tree_node->selected_child = false; node_list->push_back(_temp_tree_node); label_list->push_back(_temp_tree_node_value); insert_to_subset(subset_number, _temp_tree_node_value); } int remaining_label_number = N - leaf_number; int remaining_node_number = total_node_number - leaf_number; random_device input_index_rd; mt19937_64 input_index_mt(input_index_rd()); while(node_list->size() > 1){ uniform_int_distribution<int> input_index_dist(1, (int)node_list->size()); int index_1 = input_index_dist(input_index_mt) - 1; int index_2 = input_index_dist(input_index_mt) - 1; if(index_1 == index_2){ if(index_2 < node_list->size() - 1){ index_2++; } else{ index_2--; } } in_tree* _temp_tree_node1 = (*node_list)[index_1]; in_tree* _temp_tree_node2 = (*node_list)[index_2]; in_tree* _temp_tree_node3 = new in_tree(); backUpTreeNode->insert(_temp_tree_node3); _temp_tree_node3->selected_child = false; stringstream ss; ss << label_count++; if(remaining_label_number < remaining_node_number){ if(remaining_label_number > 0){ random_device label_or_not_rd; mt19937_64 label_or_not_mt(label_or_not_rd()); uniform_int_distribution<int> label_or_not_dist(0,1); int label_or_not = label_or_not_dist(label_or_not_mt); if(label_or_not == 1){ _temp_tree_node3->label = "ilabel_" + ss.str(); remaining_label_number--; label_list->push_back(_temp_tree_node3->label); insert_to_subset(subset_number, _temp_tree_node3->label); } else{ _temp_tree_node3->label = "unlabel_" + ss.str(); } } else{ _temp_tree_node3->label = "unlabel_" + ss.str(); } remaining_node_number--; } else{ _temp_tree_node3->label = "ilabel_" + ss.str(); remaining_node_number--; remaining_label_number--; label_list->push_back(_temp_tree_node3->label); insert_to_subset(subset_number, _temp_tree_node3->label); } _temp_tree_node3->l_child = _temp_tree_node1; _temp_tree_node3->r_child = _temp_tree_node2; _temp_tree_node1->parent = _temp_tree_node3; _temp_tree_node2->parent = _temp_tree_node3; if(index_1 < index_2){ vector<in_tree*>::iterator ele = node_list->begin() + index_2; node_list->erase(ele); ele = node_list->begin() + index_1; node_list->erase(ele); } else{ vector<in_tree*>::iterator ele = node_list->begin() + index_1; node_list->erase(ele); ele = node_list->begin() + index_2; node_list->erase(ele); } node_list->push_back(_temp_tree_node3); } tree_root = (*node_list)[0]; } } //only consider the situation that N >= 3, which is designed for experiments in_tree_non2* InputGenerator::non_binary_tree_builder_leaf_label_only(int N, int subset_number, int degree) { in_tree_non2* return_root = NULL; if(N >= degree){ //construct the leaf vector for(int i = 0; i < N; i++){ stringstream ss; ss << label_count++; in_tree_non2* _temp_tree_node = new in_tree_non2(); backUpNonTreeNode->insert(_temp_tree_node); string _temp_tree_node_value = "label_" + ss.str(); _temp_tree_node->label = _temp_tree_node_value; node_list_non2->push_back(_temp_tree_node); label_list->push_back(_temp_tree_node_value); insert_to_subset(subset_number, _temp_tree_node_value); } random_device input_index_rd; mt19937_64 input_index_mt(input_index_rd()); while(node_list_non2->size() > 1){ uniform_int_distribution<int> input_index_dist(1, (int)node_list_non2->size()); unordered_set<int> index_set; for(int i = 0; i < degree; i++){ int temp_index = input_index_dist(input_index_mt) - 1; unordered_set<int>::iterator index_iterator = index_set.find(temp_index); while(index_iterator != index_set.end()){ if(index_set.size() == node_list_non2->size()){ break; } temp_index = input_index_dist(input_index_mt) - 1; index_iterator = index_set.find(temp_index); } index_set.insert(temp_index); } in_tree_non2* _temp_tree_node1 = new in_tree_non2(); backUpNonTreeNode->insert(_temp_tree_node1); stringstream ss; ss << label_count++; _temp_tree_node1->label = "unlabel_" + ss.str(); priority_queue<int> decrease_index; for(unordered_set<int>::iterator index_it = index_set.begin(); index_it != index_set.end(); index_it++){ int temp_index = *index_it; decrease_index.push(temp_index); in_tree_non2* _temp_tree_node2 = (*node_list_non2)[temp_index]; _temp_tree_node1->children.push_back(_temp_tree_node2); _temp_tree_node2->parent = _temp_tree_node1; } while(!decrease_index.empty()){ int temp_index = decrease_index.top(); decrease_index.pop(); vector<in_tree_non2*>::iterator ele = node_list_non2->begin() + temp_index; node_list_non2->erase(ele); } node_list_non2->push_back(_temp_tree_node1); } return_root = (*node_list_non2)[0]; } return return_root; } //compute the necessary triplets randomly void InputGenerator::additional_triplets(int N, double portion) { int tripletAmount = N * (N - 1) * (N - 2) / 6; int tripletNeeded = (int)ceil(tripletAmount * portion / 100); int subsetIndex = (int)subsetsByindex.size() + 1; if(tripletNeeded <= tripletAmount){ int tripletAdditional = tripletNeeded - (int)subsetsByindex.size(); random_device addition_device; mt19937_64 addition_mt(addition_device()); int tripletCount = 0; while(tripletCount < tripletAdditional){ uniform_int_distribution<int> addition_dist(0, (int)internal_nodes_vec->size() - 1); int ranNumber = addition_dist(addition_mt); string _temp_label = (*internal_nodes_vec)[ranNumber]; if(_temp_label != tree_root->label){ unordered_map<string, vector<unordered_set<string> *> *>::iterator tripletFinder = potential_tripletbylabel->find(_temp_label); if(tripletFinder != potential_tripletbylabel->end()){ int ponSize = (int)tripletFinder->second->size(); if(ponSize > 0){ long long seed2 = chrono::system_clock::now().time_since_epoch().count(); shuffle((tripletFinder->second)->begin(), (tripletFinder->second)->end(), default_random_engine((unsigned)seed2)); subsetsByindex.insert(unordered_map<int, unordered_set<string> >::value_type(subsetIndex++, *((*(tripletFinder->second))[0]))); tripletFinder->second->erase(tripletFinder->second->begin()); tripletCount++; } else{ internal_nodes_vec->erase(internal_nodes_vec->begin() + ranNumber); } } } } } else{ cout << "Error: Can not generate needed triplets!" << endl; exit(0); } } //compute the potential triplets that will be used for testing void InputGenerator::potential_triplets() { for(int i = 0; i < internal_nodes_vec->size() - 1; i++){ string _temp_label = (*internal_nodes_vec)[i]; if(_temp_label != tree_root->label){ //compute the labels which do not belong to this current node's descendant lists unordered_set<string> *_ld_set = new unordered_set<string>; unordered_set<string> *_rd_set = new unordered_set<string>; unordered_set<string> *_rest_label = new unordered_set<string>; backUpPtrSet->insert(_ld_set); backUpPtrSet->insert(_rd_set); backUpPtrSet->insert(_rest_label); unordered_map<string, unordered_set<string> *>::iterator set_finder = left_descendant->find(_temp_label); if(set_finder != left_descendant->end()){ _ld_set = set_finder->second; } set_finder = right_descendant->find(_temp_label); if(set_finder != right_descendant->end()){ _rd_set = set_finder->second; } for(int a = 0; a < label_list->size(); a++){ unordered_set<string>::iterator label_finder = _ld_set->find((*label_list)[a]); if(label_finder != _ld_set->end()){ //find it continue; } else{ label_finder = _rd_set->find((*label_list)[a]); if(label_finder != _rd_set->end()){ //find it continue; } else{ _rest_label->insert((*label_list)[a]); } } } //compute the triplets at this current node, add those which are not used in the basic triplets set //into potential triplets set for(unordered_set<string>::iterator lf_label = _ld_set->begin(); lf_label != _ld_set->end(); lf_label++){ string label1 = *lf_label; for(unordered_set<string>::iterator rg_label = _rd_set->begin(); rg_label != _rd_set->end(); rg_label++){ string label2 = *rg_label; for(unordered_set<string>::iterator rs_label = _rest_label->begin(); rs_label != _rest_label->end(); rs_label++){ string label3 = *rs_label; string strA = label1; string strB = label2; string strC = label3; if(strA > strB){ string strTemp = strA; strA = strB; strB = strTemp; } if(strA > strC){ string strTemp = strA; strA = strC; strC = strTemp; } if(strB > strC){ string strTemp = strB; strB = strC; strC = strTemp; } string potential_triplet_str = strA + strB + strC; unordered_set<string>::iterator inuse_finder = in_use_triplet->find(potential_triplet_str); if(inuse_finder == in_use_triplet->end()){ //cannot find it unordered_set<string> *_pon_triplet = new unordered_set<string>; backUpPtrSet->insert(_pon_triplet); _pon_triplet->insert(strA); _pon_triplet->insert(strB); _pon_triplet->insert(strC); unordered_map<string, vector<unordered_set<string> *> *>::iterator pTriple_finder = potential_tripletbylabel->find(_temp_label); if(pTriple_finder != potential_tripletbylabel->end()){ //find it pTriple_finder->second->push_back(_pon_triplet); } else{ //cannot find it vector<unordered_set<string> *> *pTriple_vec = new vector<unordered_set<string>*>; pTriple_vec->push_back(_pon_triplet); potential_tripletbylabel->insert(unordered_map<string, vector<unordered_set<string> *> *>::value_type(_temp_label, pTriple_vec)); } } } } } } } } //compute the basic triplets that can be used to construct the phylogenetic tree these triples void InputGenerator::basic_triplets() { int subset_index = 1; for(int i = 0; i < internal_nodes_vec->size() - 1; i++){ string _temp_label = (*internal_nodes_vec)[i]; if(_temp_label != tree_root->label){ //choose two labels from this current node's left descendants and right descendants string strA; string strB; unordered_map<string, unordered_set<string> *>::iterator set_finder = left_descendant->find(_temp_label); if(set_finder != left_descendant->end()){ unordered_set<string> *_l_set = set_finder->second; strA = *(_l_set->begin()); } set_finder = right_descendant->find(_temp_label); if(set_finder != right_descendant->end()){ unordered_set<string> *_r_set = set_finder->second; strB = *(_r_set->begin()); } in_tree* _parent_node = new in_tree(); backUpTreeNode->insert(_parent_node); unordered_map<string, in_tree*>::iterator parent_finder = label_parent_map->find(_temp_label); if(parent_finder != label_parent_map->end()){ _parent_node = parent_finder->second; } string strC; if(_temp_label == _parent_node->l_child->label){ unordered_map<string, unordered_set<string> *>::iterator parent_set_finder = right_descendant->find(_parent_node->label); if(parent_set_finder != right_descendant->end()){ //find it strC = *(parent_set_finder->second->begin()); } } else if(_temp_label == _parent_node->r_child->label){ unordered_map<string, unordered_set<string> *>::iterator parent_set_finder = left_descendant->find(_parent_node->label); if(parent_set_finder != left_descendant->end()){ //find it strC = *(parent_set_finder->second->begin()); } } unordered_set<string> _temp_triplet_set; _temp_triplet_set.insert(strA); _temp_triplet_set.insert(strB); _temp_triplet_set.insert(strC); if(strA > strB){ string strTemp = strA; strA = strB; strB = strTemp; } if(strA > strC){ string strTemp = strA; strA = strC; strC = strTemp; } if(strB > strC){ string strTemp = strB; strB = strC; strC = strTemp; } string inuseStr = strA + strB + strC; in_use_triplet->insert(inuseStr); subsetsByindex.insert(unordered_map<int, unordered_set<string> >::value_type(subset_index++, _temp_triplet_set)); } } } //the method for constructing a bianry tree with specified percentage in_tree* InputGenerator::initial_tree_construction(double lper, int lindex, int hindex) { int array_length = hindex - lindex + 1; int mindex = 0; if(array_length > 1){ mindex = lindex + (int)ceil(array_length * lper / 100) - 1; in_tree* _lchild = initial_tree_construction(lper, lindex, mindex); in_tree* _rchild = initial_tree_construction(lper, mindex + 1, hindex); in_tree* _pnode = new in_tree(); backUpTreeNode->insert(_pnode); _pnode->selected_child = false; stringstream ss; ss << label_count++; _pnode->label = "unlabel_" + ss.str(); _pnode->l_child = _lchild; _pnode->r_child = _rchild; _lchild->parent = _pnode; _rchild->parent = _pnode; internal_nodes_vec->push_back(_pnode->label); label_parent_map->insert(unordered_map<string, in_tree*>::value_type(_lchild->label, _pnode)); label_parent_map->insert(unordered_map<string, in_tree*>::value_type(_rchild->label, _pnode)); if(_lchild->l_child == NULL && _lchild->r_child == NULL){ unordered_set<string> *_temp_set = new unordered_set<string>; backUpPtrSet->insert(_temp_set); _temp_set->insert(_lchild->label); left_descendant->insert(unordered_map<string, unordered_set<string> *>::value_type(_pnode->label, _temp_set)); } else if(_lchild->l_child != NULL && _lchild->r_child != NULL){ unordered_set<string> *_temp_set = new unordered_set<string>; unordered_set<string> *_ld_set = new unordered_set<string>; unordered_set<string> *_rd_set = new unordered_set<string>; backUpPtrSet->insert(_temp_set); backUpPtrSet->insert(_ld_set); backUpPtrSet->insert(_rd_set); unordered_map<string, unordered_set<string>* >::iterator set_finder = left_descendant->find(_lchild->label); if(set_finder != left_descendant->end()){ //find it _ld_set = set_finder->second; } set_finder = right_descendant->find(_lchild->label); if(set_finder != right_descendant->end()){ //find it _rd_set = set_finder->second; } for(unordered_set<string>::iterator set_it = _ld_set->begin(); set_it != _ld_set->end(); set_it++){ _temp_set->insert(*set_it); } for(unordered_set<string>::iterator set_it = _rd_set->begin(); set_it != _rd_set->end(); set_it++){ _temp_set->insert(*set_it); } left_descendant->insert(unordered_map<string, unordered_set<string>* >::value_type(_pnode->label, _temp_set)); } if(_rchild->l_child == NULL && _rchild->r_child == NULL){ unordered_set<string> *_temp_set = new unordered_set<string>; backUpPtrSet->insert(_temp_set); _temp_set->insert(_rchild->label); right_descendant->insert(unordered_map<string, unordered_set<string> *>::value_type(_pnode->label, _temp_set)); } else if(_rchild->l_child != NULL && _rchild->r_child != NULL){ unordered_set<string> *_temp_set = new unordered_set<string>; unordered_set<string> *_ld_set = new unordered_set<string>; unordered_set<string> *_rd_set = new unordered_set<string>; backUpPtrSet->insert(_temp_set); backUpPtrSet->insert(_ld_set); backUpPtrSet->insert(_rd_set); unordered_map<string, unordered_set<string>* >::iterator set_finder = left_descendant->find(_rchild->label); if(set_finder != left_descendant->end()){ //find it _ld_set = set_finder->second; } set_finder = right_descendant->find(_rchild->label); if(set_finder != right_descendant->end()){ //find it _rd_set = set_finder->second; } for(unordered_set<string>::iterator set_it = _ld_set->begin(); set_it != _ld_set->end(); set_it++){ _temp_set->insert(*set_it); } for(unordered_set<string>::iterator set_it = _rd_set->begin(); set_it != _rd_set->end(); set_it++){ _temp_set->insert(*set_it); } right_descendant->insert(unordered_map<string, unordered_set<string>* >::value_type(_pnode->label, _temp_set)); } return _pnode; } else{ return (*node_list)[lindex]; } } //main method for constructing a binary tree from top to bottom //this tree is constructed with specified percentage of left children and right children //at the same time, build up label array and all triples void InputGenerator::initial_tree4triplet_test(int N, double portion, double lper) { if(N >= 3){ //construct the leaf vector for(int i = 0; i < N; i++){ stringstream ss; ss << label_count++; in_tree* _temp_tree_node = new in_tree(); backUpTreeNode->insert(_temp_tree_node); string _temp_tree_node_value = "label_" + ss.str(); _temp_tree_node->label = _temp_tree_node_value; _temp_tree_node->selected_child = false; node_list->push_back(_temp_tree_node); label_list->push_back(_temp_tree_node_value); } //wlog, make r_per the smaller percentage double l_per = 0; if(lper < 100 - lper){ l_per = lper; } else{ l_per = 100 - lper; } //randomly rotate the node_list long long seed = chrono::system_clock::now().time_since_epoch().count(); shuffle(node_list->begin(), node_list->end(), default_random_engine((unsigned)seed)); left_descendant = new unordered_map<string, unordered_set<string>* >; right_descendant = new unordered_map<string, unordered_set<string>* >; tree_root = initial_tree_construction(l_per, 0, (int)node_list->size() - 1); //compute basic triplets basic_triplets(); //compute all other potential triplets potential_triplets(); //compute all necessary additional triplets randomly additional_triplets(N, portion); } } //main method for constructing a binary tree from bottom to up //meanwhile, build up label array and all subsets with size of 3 void InputGenerator::triple_builder_leaf_label_only(int N) { if(N >= 3){ //construct the leaf vector for(int i = 0; i < N; i++){ stringstream ss; ss << label_count++; in_tree* _temp_tree_node = new in_tree(); backUpTreeNode->insert(_temp_tree_node); string _temp_tree_node_value = "label_" + ss.str(); _temp_tree_node->label = _temp_tree_node_value; _temp_tree_node->selected_child = false; node_list->push_back(_temp_tree_node); label_list->push_back(_temp_tree_node_value); } //construct the subsets triple_subset(); //random approach // random_device input_index_rd; // mt19937_64 input_index_mt(input_index_rd()); // while(node_list->size() > 1){ // uniform_int_distribution<int> input_index_dist(1, (int)node_list->size()); // int index_1 = input_index_dist(input_index_mt) - 1; // int index_2 = input_index_dist(input_index_mt) - 1; // if(index_1 == index_2){ // if(index_2 < node_list->size() - 1){ // index_2++; // } // else{ // index_2--; // } // } // in_tree* _temp_tree_node1 = (*node_list)[index_1]; // in_tree* _temp_tree_node2 = (*node_list)[index_2]; // in_tree* _temp_tree_node3 = new in_tree(); // _temp_tree_node3->selected_child = false; // stringstream ss; // ss << label_count++; // _temp_tree_node3->label = "unlabel_" + ss.str(); // // _temp_tree_node3->l_child = _temp_tree_node1; // _temp_tree_node3->r_child = _temp_tree_node2; // _temp_tree_node1->parent = _temp_tree_node3; // _temp_tree_node2->parent = _temp_tree_node3; // // if(index_1 < index_2){ // vector<in_tree*>::iterator ele = node_list->begin() + index_2; // node_list->erase(ele); // ele = node_list->begin() + index_1; // node_list->erase(ele); // } // else{ // vector<in_tree*>::iterator ele = node_list->begin() + index_1; // node_list->erase(ele); // ele = node_list->begin() + index_2; // node_list->erase(ele); // } // node_list->push_back(_temp_tree_node3); // } // tree_root = (*node_list)[0]; //caterpiller approach // long long seed = chrono::system_clock::now().time_since_epoch().count(); // shuffle(node_list->begin(), node_list->end(), default_random_engine((unsigned)seed)); // while(node_list->size() > 1){ // int index_1 = (int)node_list->size() - 1; // int index_2 = (int)node_list->size() - 2; // in_tree* _temp_tree_node1 = (*node_list)[index_1]; // in_tree* _temp_tree_node2 = (*node_list)[index_2]; // in_tree* _temp_tree_node3 = new in_tree(); // _temp_tree_node3->selected_child = false; // stringstream ss; // ss << label_count++; // _temp_tree_node3->label = "unlabel_" + ss.str(); // // _temp_tree_node3->l_child = _temp_tree_node1; // _temp_tree_node3->r_child = _temp_tree_node2; // _temp_tree_node1->parent = _temp_tree_node3; // _temp_tree_node2->parent = _temp_tree_node3; // // vector<in_tree*>::iterator ele = node_list->begin() + index_1; // node_list->erase(ele); // ele = node_list->begin() + index_2; // node_list->erase(ele); // // node_list->push_back(_temp_tree_node3); // } // tree_root = (*node_list)[0]; //another random approach long long seed = chrono::system_clock::now().time_since_epoch().count(); while(node_list->size() > 1){ shuffle(node_list->begin(), node_list->end(), default_random_engine((unsigned)seed)); int index_1 = (int)node_list->size() - 1; int index_2 = (int)node_list->size() - 2; in_tree* _temp_tree_node1 = (*node_list)[index_1]; in_tree* _temp_tree_node2 = (*node_list)[index_2]; in_tree* _temp_tree_node3 = new in_tree(); backUpTreeNode->insert(_temp_tree_node3); _temp_tree_node3->selected_child = false; stringstream ss; ss << label_count++; _temp_tree_node3->label = "unlabel_" + ss.str(); _temp_tree_node3->l_child = _temp_tree_node1; _temp_tree_node3->r_child = _temp_tree_node2; _temp_tree_node1->parent = _temp_tree_node3; _temp_tree_node2->parent = _temp_tree_node3; vector<in_tree*>::iterator ele = node_list->begin() + index_1; node_list->erase(ele); ele = node_list->begin() + index_2; node_list->erase(ele); node_list->push_back(_temp_tree_node3); } tree_root = (*node_list)[0]; } else{ cout << "Size of labels is too small!" << endl; } } //main method for constructing a binary tree from buttom to up //this method is going to construct a binary tree with N leaves //based on the properties of a binary tree, if a binary tree contains N leaves, then //it will have N - 1 non-leaf nodes. void InputGenerator::binary_tree_builder_leaf_label_only(int N, int subset_number) { if(N == 1){ in_tree* _temp_tree_node = new in_tree(); backUpTreeNode->insert(_temp_tree_node); _temp_tree_node->label = "label_1"; _temp_tree_node->selected_child = false; label_list->push_back("label_1"); for(int i = 0; i < subset_number; i++){ unordered_map<int, unordered_set<string> >::iterator subsetsByindex_finder = subsetsByindex.find(i + 1); if(subsetsByindex_finder != subsetsByindex.end()){ //find it subsetsByindex_finder->second.insert("label_1"); } else{ unordered_set<string> temp_set; temp_set.insert("label_1"); subsetsByindex.insert(unordered_map<int, unordered_set<string> >::value_type(i + 1, temp_set)); } } tree_root = _temp_tree_node; } else if(N > 1){ //construct the leaf vector for(int i = 0; i < N; i++){ stringstream ss; ss << label_count++; in_tree* _temp_tree_node = new in_tree(); backUpTreeNode->insert(_temp_tree_node); string _temp_tree_node_value = "label_" + ss.str(); _temp_tree_node->label = _temp_tree_node_value; _temp_tree_node->selected_child = false; node_list->push_back(_temp_tree_node); label_list->push_back(_temp_tree_node_value); insert_to_subset(subset_number, _temp_tree_node_value); } random_device input_index_rd; mt19937_64 input_index_mt(input_index_rd()); while(node_list->size() > 1){ uniform_int_distribution<int> input_index_dist(1, (int)node_list->size()); int index_1 = input_index_dist(input_index_mt) - 1; int index_2 = input_index_dist(input_index_mt) - 1; if(index_1 == index_2){ if(index_2 < node_list->size() - 1){ index_2++; } else{ index_2--; } } in_tree* _temp_tree_node1 = (*node_list)[index_1]; in_tree* _temp_tree_node2 = (*node_list)[index_2]; in_tree* _temp_tree_node3 = new in_tree(); backUpTreeNode->insert(_temp_tree_node3); _temp_tree_node3->selected_child = false; stringstream ss; ss << label_count++; _temp_tree_node3->label = "unlabel_" + ss.str(); _temp_tree_node3->l_child = _temp_tree_node1; _temp_tree_node3->r_child = _temp_tree_node2; _temp_tree_node1->parent = _temp_tree_node3; _temp_tree_node2->parent = _temp_tree_node3; if(index_1 < index_2){ vector<in_tree*>::iterator ele = node_list->begin() + index_2; node_list->erase(ele); ele = node_list->begin() + index_1; node_list->erase(ele); } else{ vector<in_tree*>::iterator ele = node_list->begin() + index_1; node_list->erase(ele); ele = node_list->begin() + index_2; node_list->erase(ele); } node_list->push_back(_temp_tree_node3); } tree_root = (*node_list)[0]; } } //subtract the input trees from the original binary tree void InputGenerator::subtract_tree_non2(unordered_set<string> subset, in_tree_non2* _tree_root, int degree) { if(_tree_root != NULL){ while(_vec_stack_non2._stack_top >= 0){ in_tree_non2* _temp_node = (*_vec_stack_non2._vector_stack)[_vec_stack_non2._stack_top--]; if(_temp_node != _tree_root){ //if the current node is not the root of the tree if(_temp_node->children.empty()){ //if this node is the leaf //check if this node is in the current subset unordered_set<string>::iterator _subset_element_finder = subset.find(_temp_node->label); if(_subset_element_finder != subset.end()){ //indicate that this node is selected as one of the element in the current subset _temp_node->substract_parent = _temp_node->parent; for(int i = 0 ; i < _temp_node->parent->children.size(); i++){ if(_temp_node->parent->children[i] == _temp_node){ _temp_node->parent->substract_children.push_back(_temp_node); } } } } else{ //if this node is not the leaf //check if this node is in the current subset unordered_set<string>::iterator _subset_element_finder = subset.find(_temp_node->label); if(_subset_element_finder != subset.end()){ //indicate that this node is selected as one of the element in the current subset _temp_node->substract_parent = _temp_node->parent; for(int i = 0 ; i < _temp_node->parent->children.size(); i++){ if(_temp_node->parent->children[i] == _temp_node){ _temp_node->parent->substract_children.push_back(_temp_node); } } } else{ //indicate that this node is not selected as one of the element in the current subset if(!_temp_node->substract_children.empty()){ if(_temp_node->substract_children.size() == 1){ for(int i = 0 ; i < _temp_node->substract_children.size(); i++){ _temp_node->substract_children[i]->substract_parent = _temp_node->parent; _temp_node->parent->substract_children.push_back(_temp_node->substract_children[i]); } } else{ in_tree_non2* _new_node = new in_tree_non2(); backUpNonTreeNode->insert(_new_node); stringstream ss; ss << final_label++; _new_node->label = "f_" + ss.str(); for(int i = 0; i < _temp_node->substract_children.size(); i++){ _new_node->substract_children.push_back(_temp_node->substract_children[i]); _temp_node->substract_children[i]->substract_parent = _new_node; } _new_node->substract_parent = _temp_node->parent; _temp_node->parent->substract_children.push_back(_new_node); } } } } } else{ unordered_set<string>::iterator _subset_element_finder = subset.find(_temp_node->label); if(_subset_element_finder != subset.end()){ //if the root is in the subset sub_tree_root_non2 = _temp_node; } else{ //if the root is not in the subset if(!_temp_node->substract_children.empty()){ if(_temp_node->substract_children.size() == 1){ sub_tree_root_non2 = _temp_node->substract_children[0]; sub_tree_root_non2->substract_parent = NULL; } else{ in_tree_non2* _new_node = new in_tree_non2(); backUpNonTreeNode->insert(_new_node); stringstream ss; ss << final_label++; _new_node->label = "f_" + ss.str(); _new_node->substract_parent = NULL; for(int i = 0 ; i < _temp_node->substract_children.size(); i++){ _new_node->substract_children.push_back(_temp_node->substract_children[i]); _temp_node->substract_children[i]->substract_parent = _new_node; } sub_tree_root_non2 = _new_node; } } else{ in_tree_non2* _new_node = new in_tree_non2(); backUpNonTreeNode->insert(_new_node); _new_node->label = _temp_node->label; sub_tree_root_non2 = _new_node; } } } } } } //given a set of subsets, subtract the input trees from the original binary tree void InputGenerator::subtract_tree(unordered_set<string> subset) { if(tree_root != NULL){ while(_vec_stack._stack_top >= 0){ in_tree* _temp_node = (*_vec_stack._vector_stack)[_vec_stack._stack_top--]; if(_temp_node != tree_root){ if(_temp_node->l_child == NULL && _temp_node->r_child == NULL){ //if this node is the leaf //check if this node is in the current subset unordered_set<string>::iterator _subset_element_finder = subset.find(_temp_node->label); if(_subset_element_finder != subset.end()){ //indicate that this node is selected as one of the element in the current subset _temp_node->substract_parent = _temp_node->parent; if(_temp_node->parent->l_child == _temp_node){ _temp_node->parent->substract_l_child = _temp_node; } else if(_temp_node->parent->r_child == _temp_node){ _temp_node->parent->substract_r_child = _temp_node; } } else{ //indicate that this node is not selected as one of the element in the current subset if(_temp_node->parent->l_child == _temp_node){ _temp_node->parent->substract_l_child = NULL; } else if(_temp_node->parent->r_child == _temp_node){ _temp_node->parent->substract_r_child = NULL; } } } else{ //if this node is not the leaf //check if this node is in the current subset unordered_set<string>::iterator _subset_element_finder = subset.find(_temp_node->label); if(_subset_element_finder != subset.end()){ //indicate that this node is selected as one of the element in the current subset _temp_node->substract_parent = _temp_node->parent; if(_temp_node->parent->l_child == _temp_node){ _temp_node->parent->substract_l_child = _temp_node; } else if(_temp_node->parent->r_child == _temp_node){ _temp_node->parent->substract_r_child = _temp_node; } } else{ //indicate that this node is not selected as one of the element in the current subset if(_temp_node->substract_l_child == NULL && _temp_node->substract_r_child != NULL){ _temp_node->substract_r_child->substract_parent = _temp_node->parent; if(_temp_node->parent->l_child == _temp_node){ _temp_node->parent->substract_l_child = _temp_node->substract_r_child; } else if(_temp_node->parent->r_child == _temp_node){ _temp_node->parent->substract_r_child = _temp_node->substract_r_child; } } else if(_temp_node->substract_l_child != NULL && _temp_node->substract_r_child == NULL){ _temp_node->substract_l_child->substract_parent = _temp_node->parent; if(_temp_node->parent->l_child == _temp_node){ _temp_node->parent->substract_l_child = _temp_node->substract_l_child; } else if(_temp_node->parent->r_child == _temp_node){ _temp_node->parent->substract_r_child = _temp_node->substract_l_child; } } else if(_temp_node->substract_l_child != NULL && _temp_node->substract_r_child != NULL){ in_tree* _new_node = new in_tree(); backUpTreeNode->insert(_new_node); stringstream ss; ss << final_label++; _new_node->label = "f_" + ss.str(); _new_node->substract_l_child = _temp_node->substract_l_child; _temp_node->substract_l_child->substract_parent = _new_node; _new_node->substract_r_child = _temp_node->substract_r_child; _temp_node->substract_r_child->substract_parent = _new_node; _new_node->substract_parent = _temp_node->parent; if(_temp_node->parent->l_child == _temp_node){ _temp_node->parent->substract_l_child = _new_node; } else if(_temp_node->parent->r_child == _temp_node){ _temp_node->parent->substract_r_child = _new_node; } } else{ if(_temp_node->parent->l_child == _temp_node){ _temp_node->parent->substract_l_child = NULL; } else if(_temp_node->parent->r_child == _temp_node){ _temp_node->parent->substract_r_child = NULL; } } } } } else{ unordered_set<string>::iterator _subset_element_finder = subset.find(_temp_node->label); if(_subset_element_finder != subset.end()){ //if the root is in the subset sub_tree_root = _temp_node; } else{ //if the root is not in the subset if(_temp_node->substract_l_child != NULL && _temp_node->substract_r_child != NULL){ in_tree* _new_node = new in_tree(); backUpTreeNode->insert(_new_node); stringstream ss; ss << final_label++; _new_node->label = "f_" + ss.str(); _new_node->substract_parent = NULL; _new_node->substract_l_child = _temp_node->substract_l_child; _temp_node->substract_l_child->substract_parent = _new_node; _new_node->substract_r_child = _temp_node->substract_r_child; _temp_node->substract_r_child->substract_parent = _new_node; sub_tree_root = _new_node; } else if(_temp_node->substract_l_child != NULL && _temp_node->substract_r_child == NULL){ sub_tree_root = _temp_node->substract_l_child; sub_tree_root->substract_parent = NULL; } else if(_temp_node->substract_l_child == NULL && _temp_node->substract_r_child != NULL){ sub_tree_root = _temp_node->substract_r_child; sub_tree_root->substract_parent = NULL; } else{ in_tree* _new_node = new in_tree(); _new_node->label = _temp_node->label; sub_tree_root = _new_node; } } } } } } //this method is designed for converting a non-binary subtree from tree-like structure to linked-list like structure void InputGenerator::convert_non2_subtree_to_linked_list(unordered_map<string, linked_list_entry> &l_list, int tree_num, in_tree_non2* subtree_root) { queue<in_tree_non2*> *_tree_node_queue = new queue<in_tree_non2*>; _tree_node_queue->push(subtree_root); while(!_tree_node_queue->empty()){ in_tree_non2* _temp_node = _tree_node_queue->front(); _tree_node_queue->pop(); for(int i = 0; i < _temp_node->substract_children.size(); i++){ if(_temp_node->substract_children[i] != NULL){ _tree_node_queue->push(_temp_node->substract_children[i]); unordered_map<string, linked_list_entry>::iterator _linked_list_entry = l_list.find(_temp_node->label); if(_linked_list_entry != l_list.end()){ linked_list_entry *n = new linked_list_entry(_temp_node->substract_children[i]->label, WHITE, tree_num); backUpEntrySet->insert(n); _linked_list_entry->second.ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n->value, *n)); } else{ linked_list_entry *n1 = new linked_list_entry(_temp_node->label, WHITE, tree_num); linked_list_entry *n2 = new linked_list_entry(_temp_node->substract_children[i]->label, WHITE, tree_num); backUpEntrySet->insert(n1); backUpEntrySet->insert(n2); n1->ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n2->value, *n2)); l_list.insert(map<string, linked_list_entry>::value_type(n1->value, *n1)); } _linked_list_entry = l_list.find(_temp_node->substract_children[i]->label); if(_linked_list_entry != l_list.end()){ linked_list_entry *n = new linked_list_entry(_temp_node->label, WHITE, tree_num); backUpEntrySet->insert(n); _linked_list_entry->second.ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n->value, *n)); } else{ linked_list_entry *n1 = new linked_list_entry(_temp_node->substract_children[i]->label, WHITE, tree_num); linked_list_entry *n2 = new linked_list_entry(_temp_node->label, WHITE, tree_num); backUpEntrySet->insert(n1); backUpEntrySet->insert(n2); n1->ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n2->value, *n2)); l_list.insert(map<string, linked_list_entry>::value_type(n1->value, *n1)); } //incrementally insert this pair of edge into HPU _linked_list_entry = global_hpu.find(_temp_node->label); unordered_map<string, linked_list_entry>::iterator _linked_list_entry2 = global_hpu.find(_temp_node->substract_children[i]->label); if(_linked_list_entry != global_hpu.end() && _linked_list_entry2 != global_hpu.end()){ //indicate that they have already been in the HPU //need to check if there is an edge between them //if there is, then check if belongs set is correct //if not, then build up the edge, and update corresponding info correctly auto _node_exist_entry = _linked_list_entry->second.ajcn_list.find(_temp_node->substract_children[i]->label); if(_node_exist_entry == _linked_list_entry->second.ajcn_list.end()){ //indicate that there is no edge between them from the parent node's side of view linked_list_entry *n = new linked_list_entry(_temp_node->substract_children[i]->label, WHITE, tree_num); backUpEntrySet->insert(n); _linked_list_entry->second.ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n->value, *n)); } //then check if belongs set contains tree_num unordered_set<int>::iterator belong_set_entry = _linked_list_entry->second.belongs.find(tree_num); if(belong_set_entry == _linked_list_entry->second.belongs.end()){ _linked_list_entry->second.belongs.insert(tree_num); _linked_list_entry->second.kl += 1; } _node_exist_entry = _linked_list_entry2->second.ajcn_list.find(_temp_node->label); if(_node_exist_entry == _linked_list_entry2->second.ajcn_list.end()){ //indicate that there is no edge between them from the child node's side of view linked_list_entry *n = new linked_list_entry(_temp_node->label, WHITE, tree_num); backUpEntrySet->insert(n); _linked_list_entry2->second.ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n->value, *n)); } //then check if belongs set contains tree_num belong_set_entry = _linked_list_entry2->second.belongs.find(tree_num); if(belong_set_entry == _linked_list_entry2->second.belongs.end()){ _linked_list_entry2->second.belongs.insert(tree_num); _linked_list_entry2->second.kl += 1; } } else if(_linked_list_entry == global_hpu.end() && _linked_list_entry2 == global_hpu.end()){ //indicate that they are not in the HPU linked_list_entry *n1 = new linked_list_entry(_temp_node->label, WHITE, tree_num); linked_list_entry *n2 = new linked_list_entry(_temp_node->label, WHITE, tree_num); linked_list_entry *n3 = new linked_list_entry(_temp_node->substract_children[i]->label, WHITE, tree_num); linked_list_entry *n4 = new linked_list_entry(_temp_node->substract_children[i]->label, WHITE, tree_num); backUpEntrySet->insert(n1); backUpEntrySet->insert(n2); backUpEntrySet->insert(n3); backUpEntrySet->insert(n4); n1->ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n4->value, *n4)); n3->ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n2->value, *n2)); global_hpu.insert(unordered_map<string, linked_list_entry>::value_type(n1->value, *n1)); global_hpu.insert(unordered_map<string, linked_list_entry>::value_type(n3->value, *n3)); } else if(_linked_list_entry != global_hpu.end() && _linked_list_entry2 == global_hpu.end()){ //indicate that the parent node is in HPU linked_list_entry *n1 = new linked_list_entry(_temp_node->substract_children[i]->label, WHITE, tree_num); backUpEntrySet->insert(n1); _linked_list_entry->second.ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n1->value, *n1)); unordered_set<int>::iterator belong_set_entry = _linked_list_entry->second.belongs.find(tree_num); if(belong_set_entry == _linked_list_entry->second.belongs.end()){ //indicate the current parent node is from another tree, therefore, belongs set needs to be updated //kl of this parent node needs to be updated _linked_list_entry->second.belongs.insert(tree_num); _linked_list_entry->second.kl += 1; } linked_list_entry *n2 = new linked_list_entry(_temp_node->substract_children[i]->label, WHITE, tree_num); linked_list_entry *n3 = new linked_list_entry(_temp_node->label, WHITE, tree_num); backUpEntrySet->insert(n2); backUpEntrySet->insert(n3); n2->ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n3->value, *n3)); global_hpu.insert(unordered_map<string, linked_list_entry>::value_type(n2->value, *n2)); } else if(_linked_list_entry == global_hpu.end() && _linked_list_entry2 != global_hpu.end()){ //indicate that the child node is in HPU linked_list_entry *n1 = new linked_list_entry(_temp_node->label, WHITE, tree_num); backUpEntrySet->insert(n1); _linked_list_entry2->second.ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n1->value, *n1)); unordered_set<int>::iterator belong_set_entry = _linked_list_entry2->second.belongs.find(tree_num); if(belong_set_entry == _linked_list_entry2->second.belongs.end()){ _linked_list_entry2->second.belongs.insert(tree_num); _linked_list_entry2->second.kl += 1; } linked_list_entry *n2 = new linked_list_entry(_temp_node->label, WHITE, tree_num); linked_list_entry *n3 = new linked_list_entry(_temp_node->substract_children[i]->label, WHITE, tree_num); backUpEntrySet->insert(n2); backUpEntrySet->insert(n3); n2->ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n3->value, *n3)); global_hpu.insert(unordered_map<string, linked_list_entry>::value_type(n2->value, *n2)); } graph_Edge ge; ge.endp1 = _temp_node->label; ge.endp2 = _temp_node->substract_children[i]->label; unordered_map<int, unordered_set<graph_Edge, hash_Edge> >::iterator _parent_child_relation_entry = father_child.find(tree_num); if(_parent_child_relation_entry != father_child.end()){ _parent_child_relation_entry->second.insert(ge); } else{ unordered_set<graph_Edge, hash_Edge> tempset; tempset.insert(ge); father_child.insert(unordered_map<int, unordered_set<graph_Edge, hash_Edge> >::value_type(tree_num, tempset)); } } } } delete _tree_node_queue; } //this method is designed for converting a subtree from tree-like structure to linked list like structure void InputGenerator::convert_subtree_to_linked_list(unordered_map<string, linked_list_entry> &l_list, int tree_num) { queue<in_tree*> *_tree_node_queue = new queue<in_tree*>; _tree_node_queue->push(sub_tree_root); while(!(_tree_node_queue->empty())){ in_tree* _temp_node = _tree_node_queue->front(); _tree_node_queue->pop(); if(_temp_node->substract_l_child != NULL){ _tree_node_queue->push(_temp_node->substract_l_child); unordered_map<string, linked_list_entry>::iterator _linked_list_entry = l_list.find(_temp_node->label); if(_linked_list_entry != l_list.end()){ linked_list_entry *n = new linked_list_entry(_temp_node->substract_l_child->label, WHITE, tree_num); backUpEntrySet->insert(n); _linked_list_entry->second.ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n->value, (*n))); } else{ linked_list_entry *n1 = new linked_list_entry(_temp_node->label, WHITE, tree_num); linked_list_entry *n2 = new linked_list_entry(_temp_node->substract_l_child->label, WHITE, tree_num); backUpEntrySet->insert(n1); backUpEntrySet->insert(n2); n1->ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n2->value, *n2)); l_list.insert(map<string, linked_list_entry>::value_type(n1->value, *n1)); } _linked_list_entry = l_list.find(_temp_node->substract_l_child->label); if(_linked_list_entry != l_list.end()){ linked_list_entry *n = new linked_list_entry(_temp_node->label, WHITE, tree_num); backUpEntrySet->insert(n); _linked_list_entry->second.ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n->value, (*n))); } else{ linked_list_entry *n1 = new linked_list_entry(_temp_node->substract_l_child->label, WHITE, tree_num); linked_list_entry *n2 = new linked_list_entry(_temp_node->label, WHITE, tree_num); backUpEntrySet->insert(n1); backUpEntrySet->insert(n2); n1->ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n2->value, *n2)); l_list.insert(map<string, linked_list_entry>::value_type(n1->value, *n1)); } //incrementally insert this pair of edge into HPU _linked_list_entry = global_hpu.find(_temp_node->label); unordered_map<string, linked_list_entry>::iterator _linked_list_entry2 = global_hpu.find(_temp_node->substract_l_child->label); if(_linked_list_entry != global_hpu.end() && _linked_list_entry2 != global_hpu.end()){ //indicate that they have already been in the HPU //need to check if there is an edge between them //if there is, then check if belongs set is correct //if not, then build up the edge, and update corresponding info correctly auto _node_exist_entry = _linked_list_entry->second.ajcn_list.find(_temp_node->substract_l_child->label); if(_node_exist_entry == _linked_list_entry->second.ajcn_list.end()){ //indicate that there is no edge between them from the parent node's side of view linked_list_entry *n = new linked_list_entry(_temp_node->substract_l_child->label, WHITE, tree_num); backUpEntrySet->insert(n); _linked_list_entry->second.ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n->value, *n)); } //then check if belongs set contains tree_num unordered_set<int>::iterator belong_set_entry = _linked_list_entry->second.belongs.find(tree_num); if(belong_set_entry == _linked_list_entry->second.belongs.end()){ _linked_list_entry->second.belongs.insert(tree_num); _linked_list_entry->second.kl += 1; } _node_exist_entry = _linked_list_entry2->second.ajcn_list.find(_temp_node->label); if(_node_exist_entry == _linked_list_entry2->second.ajcn_list.end()){ //indicate that there is no edge between them from the child node's side of view linked_list_entry *n = new linked_list_entry(_temp_node->label, WHITE, tree_num); backUpEntrySet->insert(n); _linked_list_entry2->second.ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n->value, *n)); } //then check if belongs set contains tree_num belong_set_entry = _linked_list_entry2->second.belongs.find(tree_num); if(belong_set_entry == _linked_list_entry2->second.belongs.end()){ _linked_list_entry2->second.belongs.insert(tree_num); _linked_list_entry2->second.kl += 1; } } else if(_linked_list_entry == global_hpu.end() && _linked_list_entry2 == global_hpu.end()){ //indicate that they are not in the HPU linked_list_entry *n1 = new linked_list_entry(_temp_node->label, WHITE, tree_num); linked_list_entry *n2 = new linked_list_entry(_temp_node->label, WHITE, tree_num); linked_list_entry *n3 = new linked_list_entry(_temp_node->substract_l_child->label, WHITE, tree_num); linked_list_entry *n4 = new linked_list_entry(_temp_node->substract_l_child->label, WHITE, tree_num); backUpEntrySet->insert(n1); backUpEntrySet->insert(n2); backUpEntrySet->insert(n3); backUpEntrySet->insert(n4); n1->ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n4->value, *n4)); n3->ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n2->value, *n2)); global_hpu.insert(unordered_map<string, linked_list_entry>::value_type(n1->value, *n1)); global_hpu.insert(unordered_map<string, linked_list_entry>::value_type(n3->value, *n3)); } else if(_linked_list_entry != global_hpu.end() && _linked_list_entry2 == global_hpu.end()){ //indicate that the parent node is in HPU linked_list_entry *n1 = new linked_list_entry(_temp_node->substract_l_child->label, WHITE, tree_num); backUpEntrySet->insert(n1); _linked_list_entry->second.ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n1->value, *n1)); unordered_set<int>::iterator belong_set_entry = _linked_list_entry->second.belongs.find(tree_num); if(belong_set_entry == _linked_list_entry->second.belongs.end()){ //indicate the current parent node is from another tree, therefore, belongs set needs to be updated //kl of this parent node needs to be updated _linked_list_entry->second.belongs.insert(tree_num); _linked_list_entry->second.kl += 1; } linked_list_entry *n2 = new linked_list_entry(_temp_node->substract_l_child->label, WHITE, tree_num); linked_list_entry *n3 = new linked_list_entry(_temp_node->label, WHITE, tree_num); backUpEntrySet->insert(n2); backUpEntrySet->insert(n3); n2->ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n3->value, *n3)); global_hpu.insert(unordered_map<string, linked_list_entry>::value_type(n2->value, *n2)); } else if(_linked_list_entry == global_hpu.end() && _linked_list_entry2 != global_hpu.end()){ //indicate that the child node is in HPU linked_list_entry *n1 = new linked_list_entry(_temp_node->label, WHITE, tree_num); backUpEntrySet->insert(n1); _linked_list_entry2->second.ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n1->value, *n1)); unordered_set<int>::iterator belong_set_entry = _linked_list_entry2->second.belongs.find(tree_num); if(belong_set_entry == _linked_list_entry2->second.belongs.end()){ _linked_list_entry2->second.belongs.insert(tree_num); _linked_list_entry2->second.kl += 1; } linked_list_entry *n2 = new linked_list_entry(_temp_node->label, WHITE, tree_num); linked_list_entry *n3 = new linked_list_entry(_temp_node->substract_l_child->label, WHITE, tree_num); backUpEntrySet->insert(n2); backUpEntrySet->insert(n3); n2->ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n3->value, *n3)); global_hpu.insert(unordered_map<string, linked_list_entry>::value_type(n2->value, *n2)); } graph_Edge ge; ge.endp1 = _temp_node->label; ge.endp2 = _temp_node->substract_l_child->label; unordered_map<int, unordered_set<graph_Edge, hash_Edge> >::iterator _parent_child_relation_entry = father_child.find(tree_num); if(_parent_child_relation_entry != father_child.end()){ _parent_child_relation_entry->second.insert(ge); } else{ unordered_set<graph_Edge, hash_Edge> tempset; tempset.insert(ge); father_child.insert(unordered_map<int, unordered_set<graph_Edge, hash_Edge> >::value_type(tree_num, tempset)); } _temp_node->substract_l_child->substract_parent = NULL; _temp_node->substract_l_child = NULL; } if(_temp_node->substract_r_child != NULL){ _tree_node_queue->push(_temp_node->substract_r_child); unordered_map<string, linked_list_entry>::iterator _linked_list_entry = l_list.find(_temp_node->label); if(_linked_list_entry != l_list.end()){ linked_list_entry *n = new linked_list_entry(_temp_node->substract_r_child->label, WHITE, tree_num); backUpEntrySet->insert(n); _linked_list_entry->second.ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n->value, (*n))); } else{ linked_list_entry *n1 = new linked_list_entry(_temp_node->label, WHITE, tree_num); linked_list_entry *n2 = new linked_list_entry(_temp_node->substract_r_child->label, WHITE, tree_num); backUpEntrySet->insert(n1); backUpEntrySet->insert(n2); n1->ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n2->value, *n2)); l_list.insert(map<string, linked_list_entry>::value_type(n1->value, *n1)); } _linked_list_entry = l_list.find(_temp_node->substract_r_child->label); if(_linked_list_entry != l_list.end()){ linked_list_entry *n = new linked_list_entry(_temp_node->label, WHITE, tree_num); backUpEntrySet->insert(n); _linked_list_entry->second.ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n->value, (*n))); } else{ linked_list_entry *n1 = new linked_list_entry(_temp_node->substract_r_child->label, WHITE, tree_num); linked_list_entry *n2 = new linked_list_entry(_temp_node->label, WHITE, tree_num); backUpEntrySet->insert(n1); backUpEntrySet->insert(n2); n1->ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n2->value, *n2)); l_list.insert(map<string, linked_list_entry>::value_type(n1->value, *n1)); } //incrementally insert this pair of edge into HPU _linked_list_entry = global_hpu.find(_temp_node->label); unordered_map<string, linked_list_entry>::iterator _linked_list_entry2 = global_hpu.find(_temp_node->substract_r_child->label); if(_linked_list_entry != global_hpu.end() && _linked_list_entry2 != global_hpu.end()){ //indicate that they have already been in the HPU //need to check if there is an edge between them //if there is, then check if belongs set is correct //if not, then build up the edge, and update corresponding info correctly auto _node_exist_entry = _linked_list_entry->second.ajcn_list.find(_temp_node->substract_r_child->label); if(_node_exist_entry == _linked_list_entry->second.ajcn_list.end()){ //indicate that there is no edge between them from the parent node's side of view linked_list_entry *n = new linked_list_entry(_temp_node->substract_r_child->label, WHITE, tree_num); backUpEntrySet->insert(n); _linked_list_entry->second.ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n->value, *n)); } //then check if belongs set contains tree_num unordered_set<int>::iterator belong_set_entry = _linked_list_entry->second.belongs.find(tree_num); if(belong_set_entry == _linked_list_entry->second.belongs.end()){ _linked_list_entry->second.belongs.insert(tree_num); _linked_list_entry->second.kl += 1; } _node_exist_entry = _linked_list_entry2->second.ajcn_list.find(_temp_node->label); if(_node_exist_entry == _linked_list_entry2->second.ajcn_list.end()){ //indicate that there is no edge between them from the child node's side of view linked_list_entry *n = new linked_list_entry(_temp_node->label, WHITE, tree_num); backUpEntrySet->insert(n); _linked_list_entry2->second.ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n->value, *n)); } //then check if belongs set contains tree_num belong_set_entry = _linked_list_entry2->second.belongs.find(tree_num); if(belong_set_entry == _linked_list_entry2->second.belongs.end()){ _linked_list_entry2->second.belongs.insert(tree_num); _linked_list_entry2->second.kl += 1; } } else if(_linked_list_entry == global_hpu.end() && _linked_list_entry2 == global_hpu.end()){ //indicate that they are not in the HPU linked_list_entry *n1 = new linked_list_entry(_temp_node->label, WHITE, tree_num); linked_list_entry *n2 = new linked_list_entry(_temp_node->label, WHITE, tree_num); linked_list_entry *n3 = new linked_list_entry(_temp_node->substract_r_child->label, WHITE, tree_num); linked_list_entry *n4 = new linked_list_entry(_temp_node->substract_r_child->label, WHITE, tree_num); backUpEntrySet->insert(n1); backUpEntrySet->insert(n2); backUpEntrySet->insert(n3); backUpEntrySet->insert(n4); n1->ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n4->value, *n4)); n3->ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n2->value, *n2)); global_hpu.insert(unordered_map<string, linked_list_entry>::value_type(n1->value, *n1)); global_hpu.insert(unordered_map<string, linked_list_entry>::value_type(n3->value, *n3)); } else if(_linked_list_entry != global_hpu.end() && _linked_list_entry2 == global_hpu.end()){ //indicate that the parent node is in HPU linked_list_entry *n1 = new linked_list_entry(_temp_node->substract_r_child->label, WHITE, tree_num); backUpEntrySet->insert(n1); _linked_list_entry->second.ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n1->value, *n1)); unordered_set<int>::iterator belong_set_entry = _linked_list_entry->second.belongs.find(tree_num); if(belong_set_entry == _linked_list_entry->second.belongs.end()){ //indicate the current parent node is from another tree, therefore, belongs set needs to be updated //kl of this parent node needs to be updated _linked_list_entry->second.belongs.insert(tree_num); _linked_list_entry->second.kl += 1; } linked_list_entry *n2 = new linked_list_entry(_temp_node->substract_r_child->label, WHITE, tree_num); linked_list_entry *n3 = new linked_list_entry(_temp_node->label, WHITE, tree_num); backUpEntrySet->insert(n2); backUpEntrySet->insert(n3); n2->ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n3->value, *n3)); global_hpu.insert(unordered_map<string, linked_list_entry>::value_type(n2->value, *n2)); } else if(_linked_list_entry == global_hpu.end() && _linked_list_entry2 != global_hpu.end()){ //indicate that the child node is in HPU linked_list_entry *n1 = new linked_list_entry(_temp_node->label, WHITE, tree_num); backUpEntrySet->insert(n1); _linked_list_entry2->second.ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n1->value, *n1)); unordered_set<int>::iterator belong_set_entry = _linked_list_entry2->second.belongs.find(tree_num); if(belong_set_entry == _linked_list_entry2->second.belongs.end()){ _linked_list_entry2->second.belongs.insert(tree_num); _linked_list_entry2->second.kl += 1; } linked_list_entry *n2 = new linked_list_entry(_temp_node->label, WHITE, tree_num); linked_list_entry *n3 = new linked_list_entry(_temp_node->substract_r_child->label, WHITE, tree_num); backUpEntrySet->insert(n2); backUpEntrySet->insert(n3); n2->ajcn_list.insert(unordered_map<string, linked_list_entry>::value_type(n3->value, *n3)); global_hpu.insert(unordered_map<string, linked_list_entry>::value_type(n2->value, *n2)); } graph_Edge ge; ge.endp1 = _temp_node->label; ge.endp2 = _temp_node->substract_r_child->label; unordered_map<int, unordered_set<graph_Edge, hash_Edge> >::iterator _parent_child_relation_entry = father_child.find(tree_num); if(_parent_child_relation_entry != father_child.end()){ _parent_child_relation_entry->second.insert(ge); } else{ unordered_set<graph_Edge, hash_Edge> tempset; tempset.insert(ge); father_child.insert(unordered_map<int, unordered_set<graph_Edge, hash_Edge> >::value_type(tree_num, tempset)); } _temp_node->substract_r_child->substract_parent = NULL; _temp_node->substract_r_child = NULL; } } delete _tree_node_queue; } //convert each input tree to linked-list structure multimap<string, unordered_map<string, linked_list_entry> > InputGenerator::build_hpu_non2(in_tree_non2 *&tree, int degree) { final_label = 1; multimap<string, unordered_map<string, linked_list_entry> > graph; graph.clear(); random_device random_label_rd; mt19937_64 random_label_mt(random_label_rd()); uniform_int_distribution<int> random_label_dist(0, (int)label_list->size() - 1); int random_index_for_label = random_label_dist(random_label_mt); string random_label = (*label_list)[random_index_for_label]; for(unordered_map<int, unordered_set<string> >::iterator _subsets_viewer = subsetsByindex.begin(); _subsets_viewer != subsetsByindex.end(); _subsets_viewer++) { _vec_stack_non2._stack_top = (int)_vec_stack_non2._vector_stack->size() - 1; //firstly, we need to pre-process the tree according to each subset int _index_of_subsets = _subsets_viewer->first; _subsets_viewer->second.insert(random_label); unordered_set<string> _subset = _subsets_viewer->second; //subtracting the tree in order to get the linked list unordered_map<string, linked_list_entry> _linked_list_for_subset; _linked_list_for_subset.clear(); subtract_tree_non2(_subset, tree, degree); if(sub_tree_root_non2->substract_children.empty()){ //if the input tree only contains one single node linked_list_entry *n1 = new linked_list_entry(sub_tree_root_non2->label, WHITE, _index_of_subsets); backUpEntrySet->insert(n1); unordered_map<string, linked_list_entry>::iterator _linked_list_entry = global_hpu.find(sub_tree_root_non2->label); if(_linked_list_entry != global_hpu.end()){ //indicate that this node has already been in the HPU //then check if kl and belongs set need to be updated unordered_set<int>::iterator belong_set_entry = _linked_list_entry->second.belongs.find(_index_of_subsets); if(belong_set_entry == _linked_list_entry->second.belongs.end()){ _linked_list_entry->second.belongs.insert(_index_of_subsets); _linked_list_entry->second.kl += 1; } } else{ //indicate that this node is not in the HPU linked_list_entry *n2 = new linked_list_entry(sub_tree_root_non2->label, WHITE, _index_of_subsets); backUpEntrySet->insert(n2); global_hpu.insert(unordered_map<string, linked_list_entry>::value_type(n2->value, *n2)); } } else{ convert_non2_subtree_to_linked_list(_linked_list_for_subset, _index_of_subsets, sub_tree_root_non2); } linked_list_entry _temp_entry; if(sub_tree_root_non2 != NULL){ unordered_map<string, linked_list_entry>::iterator _linked_list_entry_iter = _linked_list_for_subset.find(sub_tree_root_non2->label); if(_linked_list_entry_iter != _linked_list_for_subset.end()){ _temp_entry = _linked_list_entry_iter->second; graph.insert(multimap<string, unordered_map<string, linked_list_entry> >::value_type(_temp_entry.value, _linked_list_for_subset)); } else{ cout << "Error occurs when generating the HPU!" << endl; } } clear_substract_structure(tree); } return graph; } //convert each input tree to linked-list structure multimap<string, unordered_map<string, linked_list_entry> > InputGenerator::build_triple_hpu(in_tree *&tree) { final_label = 1; multimap<string, unordered_map<string, linked_list_entry> > graph; graph.clear(); for(unordered_map<int, unordered_set<string> >::iterator _subsets_viewer = subsetsByindex.begin(); _subsets_viewer != subsetsByindex.end(); _subsets_viewer++){ _vec_stack._stack_top = (int)_vec_stack._vector_stack->size() - 1; //firstly, we need to pre-process the tree according to each subset int _index_of_subsets = _subsets_viewer->first; unordered_set<string> _subset = _subsets_viewer->second; //subtracting the tree in order to get the linked list unordered_map<string, linked_list_entry> _linked_list_for_subset; _linked_list_for_subset.clear(); subtract_tree(_subset); if(sub_tree_root->substract_l_child == NULL && sub_tree_root->substract_r_child == NULL){ linked_list_entry *n1 = new linked_list_entry(sub_tree_root->label, WHITE, _index_of_subsets); backUpEntrySet->insert(n1); _linked_list_for_subset.insert(unordered_map<string, linked_list_entry>::value_type(n1->value, *n1)); unordered_map<string, linked_list_entry>::iterator _linked_list_entry = global_hpu.find(sub_tree_root->label); if(_linked_list_entry != global_hpu.end()){ //indicate that this node is in the HPU //then check if kl and belongs set need to be updated unordered_set<int>::iterator belong_set_entry = _linked_list_entry->second.belongs.find(_index_of_subsets); if(belong_set_entry == _linked_list_entry->second.belongs.end()){ _linked_list_entry->second.belongs.insert(_index_of_subsets); _linked_list_entry->second.kl += 1; } } else{ //indicate that this node is not in HPU linked_list_entry *n2 = new linked_list_entry(sub_tree_root->label, WHITE, _index_of_subsets); backUpEntrySet->insert(n2); global_hpu.insert(unordered_map<string, linked_list_entry>::value_type(n2->value, *n2)); } } else{ convert_subtree_to_linked_list(_linked_list_for_subset, _index_of_subsets); } linked_list_entry _temp_entry; if(sub_tree_root != NULL){ unordered_map<string, linked_list_entry>::iterator _linked_list_entry_finder = _linked_list_for_subset.find(sub_tree_root->label); if(_linked_list_entry_finder != _linked_list_for_subset.end()){ _temp_entry = _linked_list_entry_finder->second; graph.insert(multimap<string, unordered_map<string, linked_list_entry> >::value_type(_temp_entry.value, _linked_list_for_subset)); } else{ cout << "Error occurs when generating the HPU!" << endl; } } } return graph; } //convert each input tree to linked-list structure multimap<string, unordered_map<string, linked_list_entry> > InputGenerator::build_hpu(in_tree *&tree) { final_label = 1; multimap<string, unordered_map<string, linked_list_entry> > graph; graph.clear(); random_device random_label_rd; mt19937_64 random_label_mt(random_label_rd()); uniform_int_distribution<int> random_label_dist(0, (int)label_list->size() - 1); int random_index_for_label = random_label_dist(random_label_mt); string random_label = (*label_list)[random_index_for_label]; for(unordered_map<int, unordered_set<string> >::iterator _subsets_viewer = subsetsByindex.begin(); _subsets_viewer != subsetsByindex.end(); _subsets_viewer++){ _vec_stack._stack_top = (int)_vec_stack._vector_stack->size() - 1; //firstly, we need to pre-process the tree according to each subset int _index_of_subsets = _subsets_viewer->first; _subsets_viewer->second.insert(random_label); unordered_set<string> _subset = _subsets_viewer->second; //subtracting the tree in order to get the linked list unordered_map<string, linked_list_entry> _linked_list_for_subset; _linked_list_for_subset.clear(); subtract_tree(_subset); check_children_count(sub_tree_root); if(sub_tree_root->substract_l_child == NULL && sub_tree_root->substract_r_child == NULL){ linked_list_entry *n1 = new linked_list_entry(sub_tree_root->label, WHITE, _index_of_subsets); backUpEntrySet->insert(n1); _linked_list_for_subset.insert(unordered_map<string, linked_list_entry>::value_type(n1->value, *n1)); unordered_map<string, linked_list_entry>::iterator _linked_list_entry = global_hpu.find(sub_tree_root->label); if(_linked_list_entry != global_hpu.end()){ //indicate that this node is in the HPU //then check if kl and belongs set need to be updated unordered_set<int>::iterator belong_set_entry = _linked_list_entry->second.belongs.find(_index_of_subsets); if(belong_set_entry == _linked_list_entry->second.belongs.end()){ _linked_list_entry->second.belongs.insert(_index_of_subsets); _linked_list_entry->second.kl += 1; } } else{ //indicate that this node is not in HPU linked_list_entry *n2 = new linked_list_entry(sub_tree_root->label, WHITE, _index_of_subsets); backUpEntrySet->insert(n2); global_hpu.insert(unordered_map<string, linked_list_entry>::value_type(n2->value, *n2)); } } else{ convert_subtree_to_linked_list(_linked_list_for_subset, _index_of_subsets); } linked_list_entry _temp_entry; if(sub_tree_root != NULL){ unordered_map<string, linked_list_entry>::iterator _linked_list_entry_finder = _linked_list_for_subset.find(sub_tree_root->label); if(_linked_list_entry_finder != _linked_list_for_subset.end()){ _temp_entry = _linked_list_entry_finder->second; graph.insert(multimap<string, unordered_map<string, linked_list_entry> >::value_type(_temp_entry.value, _linked_list_for_subset)); } else{ cout << "Error occurs when generating the HPU!" << endl; } } } return graph; } void InputGenerator::clear_substract_structure(in_tree_non2 *_tree_root) { stack<in_tree_non2*> temp_stack; temp_stack.push(_tree_root); while(!temp_stack.empty()){ in_tree_non2* temp_node = temp_stack.top(); temp_stack.pop(); if(temp_node != NULL){ for(int i = 0 ; i < temp_node->children.size(); i++){ temp_stack.push(temp_node->children[i]); } temp_node->substract_children.clear(); temp_node->substract_parent = NULL; } } } InputGenerator::~InputGenerator() { for(unordered_set<linked_list_entry*>::iterator iterator1 = backUpEntrySet->begin(); iterator1 != backUpEntrySet->end(); iterator1++){ delete *iterator1; } delete backUpEntrySet; for(unordered_set<in_tree*>::iterator iterator2 = backUpTreeNode->begin(); iterator2 != backUpTreeNode->end(); iterator2++){ delete *iterator2; } delete backUpTreeNode; delete _vec_stack._vector_stack; delete label_list; delete node_list; delete node_list_non2; delete internal_nodes_vec; delete label_parent_map; delete in_use_triplet; for(unordered_set<unordered_set<string>*>::iterator iterator3 = backUpPtrSet->begin(); iterator3 != backUpPtrSet->end(); iterator3++){ delete *iterator3; } delete backUpPtrSet; for(unordered_map<string, vector<unordered_set<string> *> *>::iterator iterator3 = potential_tripletbylabel->begin(); iterator3 != potential_tripletbylabel->end(); iterator3++){ delete iterator3->second; } delete potential_tripletbylabel; delete left_descendant; delete right_descendant; for(unordered_set<in_tree_non2*>::iterator iterator4 = backUpNonTreeNode->begin(); iterator4 != backUpNonTreeNode->end(); iterator4++){ delete *iterator4; } delete backUpNonTreeNode; delete _vec_stack_non2._vector_stack; }
50.405797
161
0.592323
[ "vector" ]
7b1a4db2b87a4b47f1d18fbf88dfe6927dc9791c
1,510
cpp
C++
src/main/cpp/weismarts/zmq/ZMsg.cpp
match08/zmq-android
d13c2277ec76cb6fef3cf23fa9572d9dc24a4d16
[ "MIT" ]
null
null
null
src/main/cpp/weismarts/zmq/ZMsg.cpp
match08/zmq-android
d13c2277ec76cb6fef3cf23fa9572d9dc24a4d16
[ "MIT" ]
null
null
null
src/main/cpp/weismarts/zmq/ZMsg.cpp
match08/zmq-android
d13c2277ec76cb6fef3cf23fa9572d9dc24a4d16
[ "MIT" ]
null
null
null
// // Created by weismarts on 9/26/21. // #include "ZMsg.h" ZMsg::ZMsg(){ }; void ZMsg::Add(char* msg) { _multipart.addstr(std::string(msg)); } void ZMsg::Add(void* msg, size_t len) { _multipart.addmem(msg, len); } void ZMsg::Add(std::string msg) { _multipart.addstr(msg); } void ZMsg::Add(zmq::message_t &msg) { _multipart.add(zmq::message_t(msg.data(), msg.size())); } void ZMsg::AddAll(std::vector<std::string> msgs) { for (int i = 0; i < msgs.size(); ++i) { const std::string msg = msgs[i];//std::string ((char*)msgs[i].data(), msgs[i].size()); _multipart.addstr(msg); } } ZMsg ZMsg::RecvMsg(ZMQSocket *socket, bool wait) { ZMsg zMsg; std::vector<zmq::message_t> recv_msgs; const auto ret = zmq::recv_multipart( *socket->getPtr(), std::back_inserter(recv_msgs), wait? zmq::recv_flags::none : zmq::recv_flags::dontwait); if(!ret) return zMsg; const size_t len = recv_msgs.size(); for (int i = 0; i < len; ++i) { zMsg.Add(recv_msgs[i].data(), recv_msgs[i].size()); } return zMsg; } bool ZMsg::Send(ZMQSocket *socket, int flags) { return _multipart.send(*socket->getPtr(), flags); } size_t ZMsg::Size() { return _multipart.size(); } std::string ZMsg::Peekstr(size_t index) { return _multipart.peekstr(index); } std::string ZMsg::Str() { return _multipart.str(); } void *ZMsg::AtData(size_t n) { return _multipart.at(n).data(); } void ZMsg::Destroy() { _multipart.clear(); }
18.414634
120
0.616556
[ "vector" ]
7b29c384137d34b3eb7a67199cd3d88ba785cadd
11,666
cpp
C++
cpp/SmurffCpp/Sessions/TrainSession.cpp
ExaScience/smurff
29c3859badca49275833024cd77f8ca7fa6f76be
[ "MIT" ]
65
2017-06-23T14:01:58.000Z
2022-03-10T16:13:48.000Z
cpp/SmurffCpp/Sessions/TrainSession.cpp
ExaScience/smurff
29c3859badca49275833024cd77f8ca7fa6f76be
[ "MIT" ]
143
2017-08-11T10:43:52.000Z
2021-09-23T17:07:51.000Z
cpp/SmurffCpp/Sessions/TrainSession.cpp
ExaScience/smurff
29c3859badca49275833024cd77f8ca7fa6f76be
[ "MIT" ]
14
2018-05-17T18:33:28.000Z
2021-12-23T20:41:32.000Z
#include "TrainSession.h" #include <fstream> #include <string> #include <iomanip> #include <SmurffCpp/Utils/omp_util.h> #include <SmurffCpp/Utils/Distribution.h> #include <SmurffCpp/Utils/MatrixUtils.h> #include <SmurffCpp/Utils/counters.h> #include <SmurffCpp/Utils/Error.h> #include <SmurffCpp/Utils/StringUtils.h> #include <SmurffCpp/Configs/Config.h> #include <SmurffCpp/Priors/PriorFactory.h> #include <SmurffCpp/result.h> #include <SmurffCpp/StatusItem.h> namespace smurff { void TrainSession::init() { THROWERROR_ASSERT_MSG(!m_is_init, "TrainSession::init called twice"); getConfig().validate(); if (!getConfig().getSaveName().empty()) { // create state file m_stateFile = std::make_shared<StateFile>(getConfig().getSaveName(), true); //save config m_stateFile->saveConfig(getConfig()); // close stateFile is we do not need it anymore if (!getConfig().getSaveFreq() && !getConfig().getCheckpointFreq()) m_stateFile.reset(); } // initialize pred if (getConfig().getTest().hasData()) { m_pred = Result(getConfig().getTest(), getConfig().getNSamples()); m_pred.setSavePred(getConfig().getSavePred()); if (getConfig().getClassify()) m_pred.setThreshold(getConfig().getThreshold()); } // init data data_ptr = Data::create(getConfig().getData()); // initialize priors std::shared_ptr<IPriorFactory> priorFactory = this->create_prior_factory(); for (std::size_t i = 0; i < getConfig().getPriorTypes().size(); i++) { m_priors.push_back(priorFactory->create_prior(*this, i)); m_priors.back()->setMode(i); } //init omp threads::init(getConfig().getVerbose(), getConfig().getNumThreads()); //initialize random generator initRng(); //init performance counters perf_data_init(); //initialize test set m_pred.init(); //initialize train matrix (centring and noise model) data().init(); //initialize model (samples) model().init(getConfig().getNumLatent(), data().dim(), getConfig().getModelInitType(), getConfig().getSaveModel()); //initialize priors for (auto &p : m_priors) p->init(); // all basic init done m_is_init = true; //write info to console if (getConfig().getVerbose()) info(std::cout, ""); //restore trainSession (model, priors) bool resume = restore(m_iter); //print trainSession status to console if (getConfig().getVerbose()) printStatus(std::cout, resume); } void TrainSession::run() { init(); while (step()) ; } bool TrainSession::step() { COUNTER("step"); THROWERROR_ASSERT_MSG(m_is_init, "TrainSession::init() needs to be called before ::step()") // go to the next iteration m_iter++; bool isStep = m_iter < getConfig().getBurnin() + getConfig().getNSamples(); if (isStep) { auto starti = tick(); for (unsigned i=0; i<m_priors.size(); ++i) { m_priors[i]->sample_latents(); m_priors[i]->update_prior(); } data().update(model()); auto endi = tick(); //WARNING: update is an expensive operation because of sort (when calculating AUC) m_pred.update(m_model, m_iter < getConfig().getBurnin()); m_secs_per_iter = endi - starti; m_secs_total += m_secs_per_iter; printStatus(std::cout); save(); } return isStep; } std::ostream &TrainSession::info(std::ostream &os, std::string indent) const { os << indent << name << " {\n"; os << indent << " Data: {" << std::endl; data().info(os, indent + " "); os << indent << " }" << std::endl; os << indent << " Model: {" << std::endl; model().info(os, indent + " "); os << indent << " }" << std::endl; os << indent << " Priors: {" << std::endl; for (auto &p : m_priors) p->info(os, indent + " "); os << indent << " }" << std::endl; os << indent << " Result: {" << std::endl; m_pred.info(os, indent + " "); os << indent << " }" << std::endl; os << indent << " Config: {" << std::endl; getConfig().info(os, indent + " "); os << indent << " }" << std::endl; os << indent << "}\n"; return os; } void TrainSession::save() { //do not save if 'never save' mode is selected if (!getConfig().getSaveFreq() && !getConfig().getCheckpointFreq()) return; std::int32_t isample = m_iter - getConfig().getBurnin() + 1; std::int32_t niter = getConfig().getBurnin() + getConfig().getNSamples(); //save if checkpoint threshold overdue if ( getConfig().getCheckpointFreq() && ( ((tick() - m_lastCheckpointTime) >= getConfig().getCheckpointFreq()) || (m_iter == niter - 1) // also save checkpoint in last iteration ) ) { std::int32_t icheckpoint = m_iter + 1; //save this iteration saveInternal(icheckpoint, true); //remove previous iteration if required (initial m_lastCheckpointIter is -1 which means that it does not exist) m_stateFile->removeOldCheckpoints(); //upddate counters m_lastCheckpointTime = tick(); m_lastCheckpointIter = m_iter; } //save model during sampling stage if (getConfig().getSaveFreq() && isample > 0) { //save_freq > 0: check modulo - do not save if not a save iteration if (getConfig().getSaveFreq() > 0 && (isample % getConfig().getSaveFreq()) != 0) { // don't save } //save_freq < 0: save last iter - do not save if (final model) mode is selected and not a final iteration else if (getConfig().getSaveFreq() < 0 && isample < getConfig().getNSamples()) { // don't save } else { //do save this iteration saveInternal(isample, false); } } // close after final step if (m_iter == niter - 1) m_stateFile.reset(); } void TrainSession::saveInternal(int iteration, bool checkpoint) { bool final = iteration == getConfig().getNSamples(); SaveState saveState = m_stateFile->createStep(iteration, checkpoint, final || checkpoint); if (getConfig().getVerbose()) { std::cout << "-- Saving model, predictions,... into '" << m_stateFile->getPath() << "'." << std::endl; } double start = tick(); m_model.save(saveState); m_pred.save(saveState); for (auto &p : m_priors) p->save(saveState); double stop = tick(); if (getConfig().getVerbose()) { std::cout << "-- Done saving model. Took " << stop - start << " seconds." << std::endl; } } bool TrainSession::restore(int &iteration) { //if there is nothing to restore - start from initial iteration iteration = -1; //to keep track at what time we last checkpointed m_lastCheckpointTime = tick(); m_lastCheckpointIter = -1; if (getConfig().getRestoreName().empty()) return false; // open state file StateFile restoreFile(getConfig().getRestoreName()); if (!restoreFile.hasCheckpoint()) return false; SaveState saveState = restoreFile.openCheckpoint(); if (getConfig().getVerbose()) std::cout << "-- Restoring model, predictions,... from '" << restoreFile.getPath() << "'." << std::endl; m_model.restore(saveState); m_pred.restore(saveState); for (auto &p : m_priors) p->restore(saveState); //restore last iteration index if (saveState.isCheckpoint()) { iteration = saveState.getIsample() - 1; //restore original state //to keep track at what time we last checkpointed m_lastCheckpointTime = tick(); m_lastCheckpointIter = iteration; } else { iteration = saveState.getIsample() + getConfig().getBurnin() - 1; //restore original state //to keep track at what time we last checkpointed m_lastCheckpointTime = tick(); m_lastCheckpointIter = iteration; } return true; } const Result &TrainSession::getResult() const { return m_pred; } StatusItem TrainSession::getStatus() const { THROWERROR_ASSERT(m_is_init); StatusItem ret; if (m_iter < 0) { ret.phase = "Initial"; ret.iter = m_iter + 1; ret.phase_iter = 0; } else if (m_iter < getConfig().getBurnin()) { ret.phase = "Burnin"; ret.iter = m_iter + 1; ret.phase_iter = getConfig().getBurnin(); } else { ret.phase = "Sample"; ret.iter = m_iter - getConfig().getBurnin() + 1; ret.phase_iter = getConfig().getNSamples(); } for (int i = 0; i < (int)model().nmodes(); ++i) { ret.model_norms.push_back(model().U(i).norm()); } ret.train_rmse = data().train_rmse(model()); ret.rmse_avg = m_pred.rmse_avg; ret.rmse_1sample = m_pred.rmse_1sample; ret.auc_avg = m_pred.auc_avg; ret.auc_1sample = m_pred.auc_1sample; ret.elapsed_iter = m_secs_per_iter; ret.elapsed_total = m_secs_total; ret.nnz_per_sec = (double)(data().nnz()) / m_secs_per_iter; ret.samples_per_sec = (double)(model().nsamples()) / m_secs_per_iter; return ret; } void TrainSession::printStatus(std::ostream &output, bool resume) { if (!getConfig().getVerbose()) return; auto status_item = getStatus(); std::string resumeString = resume ? "Continue from " : std::string(); if (getConfig().getVerbose() > 0) { if (m_iter < 0) { output << " ====== Initial phase ====== " << std::endl; } else if (m_iter < getConfig().getBurnin() && m_iter == 0) { output << " ====== Sampling (burning phase) ====== " << std::endl; } else if (m_iter == getConfig().getBurnin()) { output << " ====== Burn-in complete, averaging samples ====== " << std::endl; } output << resumeString << status_item.asString() << std::endl; if (getConfig().getVerbose() > 1) { output << std::fixed << std::setprecision(4) << " RMSE train: " << status_item.train_rmse << std::endl; output << " Priors:" << std::endl; for (const auto &p : m_priors) p->status(output, " "); output << " Model:" << std::endl; model().status(output, " "); output << " Noise:" << std::endl; data().status(output, " "); } if (getConfig().getVerbose() > 2) { output << " Compute Performance: " << status_item.samples_per_sec << " samples/sec, " << status_item.nnz_per_sec << " nnz/sec" << std::endl; } } } std::string StatusItem::getCsvHeader() { return "phase;iter;phase_len;rmse_avg;rmse_1samp;train_rmse;auc_avg;auc_1samp;elapsed_1samp;elapsed_total"; } std::string StatusItem::asCsvString() const { char ret[1024]; snprintf(ret, 1024, "%s;%d;%d;%.4f;%.4f;%.4f;%.4f;:%.4f;%0.1f;%0.1f", phase.c_str(), iter, phase_iter, rmse_avg, rmse_1sample, train_rmse, auc_1sample, auc_avg, elapsed_iter, elapsed_total); return ret; } void TrainSession::initRng() { //init random generator if (getConfig().getRandomSeedSet()) init_bmrng(getConfig().getRandomSeed()); else init_bmrng(); } std::shared_ptr<IPriorFactory> TrainSession::create_prior_factory() const { return std::make_shared<PriorFactory>(); } } // end namespace smurff
27.842482
153
0.587862
[ "model" ]
7b3445a808addbcd55389640b4e0bf0f95bf835a
4,754
cc
C++
src/Modules/Legacy/DataIO/WriteField.cc
mhansen1/SCIRun
9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba
[ "Unlicense" ]
null
null
null
src/Modules/Legacy/DataIO/WriteField.cc
mhansen1/SCIRun
9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba
[ "Unlicense" ]
null
null
null
src/Modules/Legacy/DataIO/WriteField.cc
mhansen1/SCIRun
9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba
[ "Unlicense" ]
null
null
null
/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2015 Scientific Computing and Imaging Institute, University of Utah. 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. */ /// @author /// Elisha R. Hughes, /// CVRTI, /// University of Utah, /// based on: /// Steven G. Parker, /// Department of Computer Science, /// University of Utah. /// July 1994 /// /// @date November 2004 #include <Dataflow/Network/Ports/FieldPort.h> #include <Dataflow/Modules/DataIO/GenericWriter.h> #include <Core/ImportExport/Field/FieldIEPlugin.h> namespace SCIRun { template class GenericWriter<FieldHandle>; /// @class WriteField /// @brief This module writes a field to file /// /// (a SCIRun .fld file and various other file formats using a plugin system). class WriteField : public GenericWriter<FieldHandle> { protected: GuiString gui_types_; GuiString gui_exporttype_; GuiInt gui_increment_; GuiInt gui_current_; virtual bool call_exporter(const std::string &filename); public: WriteField(GuiContext* ctx); virtual ~WriteField() {} virtual void execute(); }; DECLARE_MAKER(WriteField) WriteField::WriteField(GuiContext* ctx) : GenericWriter<FieldHandle>("WriteField", ctx, "DataIO", "SCIRun"), gui_types_(get_ctx()->subVar("types", false)), gui_exporttype_(get_ctx()->subVar("exporttype"), ""), gui_increment_(get_ctx()->subVar("increment"), 0), gui_current_(get_ctx()->subVar("current"), 0) { FieldIEPluginManager mgr; std::vector<std::string> exporters; mgr.get_exporter_list(exporters); std::string exporttypes = "{"; exporttypes += "{{SCIRun Field Binary} {.fld} } "; exporttypes += "{{SCIRun Field ASCII} {.fld} } "; for (unsigned int i = 0; i < exporters.size(); i++) { FieldIEPlugin *pl = mgr.get_plugin(exporters[i]); if (pl->fileextension != "") { exporttypes += "{{" + exporters[i] + "} {" + pl->fileextension + "} } "; } else { exporttypes += "{{" + exporters[i] + "} {.*} } "; } } exporttypes += "}"; gui_types_.set(exporttypes); } bool WriteField::call_exporter(const std::string &filename) { const std::string ftpre = gui_exporttype_.get(); const std::string::size_type loc = ftpre.find(" ("); const std::string ft = ftpre.substr(0, loc); FieldIEPluginManager mgr; FieldIEPlugin *pl = mgr.get_plugin(ft); if (pl) { return pl->filewriter(this, handle_, filename.c_str()); } return false; } void WriteField::execute() { const std::string ftpre = gui_exporttype_.get(); const std::string::size_type loc = ftpre.find(" ("); const std::string ft = ftpre.substr(0, loc); exporting_ = !(ft == "" || ft == "SCIRun Field Binary" || ft == "SCIRun Field ASCII" || ft == "Binary"); // Determine if we're ASCII or Binary std::string ab = "Binary"; if (ft == "SCIRun Field ASCII") ab = "ASCII"; filetype_.set(ab); //get the current file name const std::string oldfilename=filename_.get(); //determine if we should increment an index in the file name if (gui_increment_.get()) { //warn the user if they try to use 'Increment' incorrectly const std::string::size_type loc2 = oldfilename.find("%d"); if(loc2 == std::string::npos) { remark("To use the increment function, there must be a '%d' in the file name."); } char buf[1024]; int current=gui_current_.get(); sprintf(buf, filename_.get().c_str(), current); filename_.set(buf); gui_current_.set(current+1); } GenericWriter<FieldHandle>::execute(); if (gui_increment_.get()) filename_.set(oldfilename); } } // End namespace SCIRun
27.479769
86
0.675642
[ "vector" ]
7b3755849b95a0368ae34d2d8f9702bb9882c4c6
943
hpp
C++
src/platform/socket.hpp
traplol/malang
3c02f4f483b7580a557841c31a65bf190fd1228f
[ "MIT" ]
4
2017-10-31T14:01:58.000Z
2019-07-16T04:53:32.000Z
src/platform/socket.hpp
traplol/malang
3c02f4f483b7580a557841c31a65bf190fd1228f
[ "MIT" ]
null
null
null
src/platform/socket.hpp
traplol/malang
3c02f4f483b7580a557841c31a65bf190fd1228f
[ "MIT" ]
2
2018-01-23T12:59:07.000Z
2019-07-16T04:53:39.000Z
#ifndef MALANG_SOCKET_HPP #define MALANG_SOCKET_HPP #include <string> #include <vector> namespace plat { enum socket_result { ERR_Close_Fail = -6, ERR_Recv_Fail = -5, ERR_Send_Fail = -4, ERR_Connection_Failed = -3, ERR_Socket_Acquisition_Failed = -2, ERR_Address_Info = -1, OK = 0, }; using socket = void*; socket_result socket_open(const char *host, const char *port, socket &out_socket); socket_result socket_close(socket socket); socket_result socket_send(socket socket, const char *data, size_t size, size_t &bytes_written); socket_result socket_send(socket socket, const std::string &data, size_t &bytes_written); socket_result socket_send(socket socket, const std::vector<char> &data, size_t &bytes_written); socket_result socket_recv(socket socket, char *buffer, size_t buffer_len, size_t &bytes_read); } #endif /* MALANG_SOCKET_HPP */
31.433333
99
0.703075
[ "vector" ]
7b3b42f4000c25d37ee3bfe99d498039f2085a6b
4,366
cpp
C++
platforms/codeforces/all/codeforces_59_E.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
2
2020-09-17T09:04:00.000Z
2020-11-20T19:43:18.000Z
platforms/codeforces/all/codeforces_59_E.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
null
null
null
platforms/codeforces/all/codeforces_59_E.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
null
null
null
#define IS_TEST 1 #if IS_TEST == 1 #include "../headers.hpp" #else #include <bits/stdc++.h> #endif // https://codeforces.com/contest/59/problem/E using namespace std; struct Vertex final { int x{-1}; int y{-1}; bool operator==(const Vertex& vertex) const noexcept { return x == vertex.x and y == vertex.y; } }; namespace std { template<> struct hash<Vertex> { size_t operator()(const Vertex& v) const noexcept { uint64_t h = 0; h <<= 32; h ^= hash<int32_t>()(v.x); h = hash<int64_t>()(h); h <<= 32; h ^= hash<int32_t>()(v.y); h = hash<int64_t>()(h); return h; } }; } // namespace std void bfs( const vector<Vertex>& sources, const int final_city, const unordered_map<Vertex, vector<Vertex>>& G) { unordered_map<Vertex, Vertex> p; vector<vector<bool>> visited(final_city + 1, vector<bool>(final_city + 1)); queue<Vertex> q; for (const auto& vertex : sources) { if (vertex.y == final_city) { printf("1\n%d %d\n", vertex.x, vertex.y); return; } q.push({vertex}); visited[vertex.x][vertex.y] = true; } while (not q.empty()) { const Vertex v = q.front(); q.pop(); if (G.count(v)) { for (const auto& vertex : G.at(v)) { if (visited[vertex.x][vertex.y]) { continue; } visited[vertex.x][vertex.y] = true; q.push(vertex); p[vertex] = v; if (vertex.y == final_city) { vector<Vertex> res; for (Vertex v = vertex; v.x != -1; v = p[v]) { res.push_back(v); } printf("%lu\n", res.size()); for (auto it = res.crbegin(); it != res.crend(); ++it) { if (it == res.crbegin()) { printf("%d %d ", it->x, it->y); } else { printf("%d ", it->y); } } printf("\n"); return; } } } } printf("-1\n"); } void solve(istream& ss) { int cities_num, roads_num, forbidden_num; ss >> cities_num >> roads_num >> forbidden_num; const int final_city = cities_num; vector<vector<int>> cities(cities_num + 1); int from, to; for (int i = 0; i < roads_num; ++i) { ss >> from >> to; cities[from].push_back(to); cities[to].push_back(from); } vector<tuple<int, int, int>> forbids(forbidden_num + 1); int first, second, third; for (int i = 0; i < forbidden_num; ++i) { ss >> first >> second >> third; forbids[i] = {first, second, third}; } sort(forbids.begin(), forbids.end()); unordered_map<Vertex, vector<Vertex>> G; vector<Vertex> S; G.reserve(32768); G.max_load_factor(0.25); for (int i = 0; i < cities.size(); ++i) { for (int j : cities.at(i)) { if (i == 1) { S.push_back({i, j}); } for (int k : cities.at(j)) { if (k != 1 and j != 1) { const auto t = make_tuple(i, j, k); if (not binary_search(forbids.begin(), forbids.end(), t)) { G[{i, j}].push_back({j, k}); } } } } } bfs(S, final_city, G); } void test() { { const char data[] = R"(4 4 1 1 2 2 3 3 4 1 3 1 3 4)"; istringstream ss(data); solve(ss); } { const char data[] = R"(4 4 1 1 2 2 3 3 4 1 3 1 4 3)"; istringstream ss(data); solve(ss); } { const char data[] = R"(3 1 0 1 2)"; istringstream ss(data); solve(ss); } { const char data[] = R"(4 4 2 1 2 2 3 3 4 1 3 1 2 3 1 3 4)"; istringstream ss(data); solve(ss); } { const char data[] = R"(2 1 0 1 2)"; istringstream ss(data); solve(ss); } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); #if IS_TEST == 1 test(); #else solve(cin); #endif return 0; }
21.613861
79
0.446404
[ "vector" ]
0da5a64fe00dbdac36250b7e6263529d1c07790c
565
cpp
C++
src/0022.cpp
downdemo/LeetCode-Solutions-in-Cpp17
e6ad1bd56ecea08fc418a9b50e78bdac23860e9f
[ "MIT" ]
38
2020-03-05T06:38:32.000Z
2022-03-11T02:32:14.000Z
src/0022.cpp
downdemo/LeetCode-Solutions-in-Cpp17
e6ad1bd56ecea08fc418a9b50e78bdac23860e9f
[ "MIT" ]
null
null
null
src/0022.cpp
downdemo/LeetCode-Solutions-in-Cpp17
e6ad1bd56ecea08fc418a9b50e78bdac23860e9f
[ "MIT" ]
16
2020-04-02T15:13:20.000Z
2022-02-25T07:34:35.000Z
class Solution { public: vector<string> generateParenthesis(int n) { vector<string> res; dfs(res, "", n, n); return res; } void dfs(vector<string>& res, string s, int l_parenthese, int r_parenthese) { if (l_parenthese == 0 && r_parenthese == 0) { res.emplace_back(s); return; } if (l_parenthese <= r_parenthese) { if (l_parenthese > 0) { dfs(res, s + '(', l_parenthese - 1, r_parenthese); } if (r_parenthese > 0) { dfs(res, s + ')', l_parenthese, r_parenthese - 1); } } } };
23.541667
79
0.557522
[ "vector" ]
0da9c750fbc1d6dd292cb9f3c8267077c0ae8354
4,076
cpp
C++
Uncategorized/phantom1.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
Uncategorized/phantom1.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
Uncategorized/phantom1.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() #define gc getchar() #define pc(x) putchar(x) template<typename T> void scan(T &x){x = 0;bool _=0;T c=gc;_=c==45;c=_?gc:c;while(c<48||c>57)c=gc;for(;c<48||c>57;c=gc);for(;c>47&&c<58;c=gc)x=(x<<3)+(x<<1)+(c&15);x=_?-x:x;} template<typename T> void printn(T n){bool _=0;_=n<0;n=_?-n:n;char snum[65];int i=0;do{snum[i++]=char(n%10+48);n/= 10;}while(n);--i;if (_)pc(45);while(i>=0)pc(snum[i--]);} template<typename First, typename ... Ints> void scan(First &arg, Ints&... rest){scan(arg);scan(rest...);} template<typename T> void print(T n){printn(n);pc(10);} template<typename First, typename ... Ints> void print(First arg, Ints... rest){printn(arg);pc(32);print(rest...);} using namespace std; using ll = __int128; //mt19937_64 g(chrono::steady_clock::now().time_since_epoch().count()); //mt19937_64 g((uint64_t) new char); mt19937_64 g(0); int randint(int l, int r){return uniform_int_distribution<int>(l, r)(g);} long long randl(long long l, long long r){return uniform_int_distribution<long long>(l, r)(g);} template<class T> T gcd(T _a, T _b){return _b == 0 ? _a : gcd(_b, _a%_b);} template<class T, class U> T fpow(T _base, U _pow, T _mod){_base %= _mod; T _x = 1; for(; _pow > 0; _pow >>= 1){ if(_pow&1) _x = _x*_base%_mod; _base = _base*_base%_mod;} return _x;} template<class T> T divmod(T _a, T _b, T _mod){return _a*fpow(_b, _mod-2, _mod)%_mod;} // O(iterations * complexity of fpow) template<class T> bool isprime(T N, int iterations = 7){ if(N < 2 or N%6%4 != 1) return (N|1) == 3; vector<T> A = {2, 325, 9375, 28178, 450775, 9780504, 1795265022}; while(int(A.size()) < iterations) A.emplace_back(uniform_int_distribution<long long>(1795265023, numeric_limits<long long>::max())(g)); int s = 0; while(!(((N-1)>>s)&1)) s++; T d = N>>s; for(T a: A){ T p = fpow(a%N, d, N); int i = s; while(p != 1 and p != N-1 and a%N and i--) p = p*p%N; if(p != N-1 and i != s) return 0; } return 1; } template<class T> T count_divisors(T N){ ll ret = 1, m = cbrtl(N); for(ll i = 2; i <= m; i++){ ll cnt = 0; while(N%i == 0){ N /= i; cnt++; } ret *= cnt+1; } // N is now either 1, p, pq, or p^2 if(N > 1){ if(isprime(N)) ret *= 2; else{ ll p = sqrtl(N); if(p*p == N) ret *= 3; else ret *= 4; } } return ret; } // https://github.com/bqi343/USACO/blob/master/Implementations/content/number-theory%20(11.1)/Primality/Sieve.h // returns a boolean array of whether prime and a list of primes template<class T> pair<vector<bool>, vector<T>> fast_sieve(T N){ vector<bool> p(N+1, 1); vector<T> primes = {2}; p[0] = p[1] = 0; for(T i = 4; i <= N; i += 2) p[i] = 0; for(T i = 3; i*i <= N; i += 2) if(p[i]) for(T j = i*i; j <= N; j += i*2) p[j] = 0; for(T i = 3; i <= N; i += 2) if(p[i]) primes.emplace_back(i); return {move(p), move(primes)}; } // https://cp-algorithms.com/algebra/prime-sieve-linear.html // returns an array of the lowest prime factor (other than 1) of each integer and a list of primes template<class T> pair<vector<T>, vector<T>> linear_sieve(T N){ vector<T> low(N+1, 0); vector<T> primes; for(T i = 2; i <= N; i++){ if(!low[i]) low[i] = i, primes.emplace_back(i); for(T j = 0; j < (T)size(primes) and primes[j] <= low[i] and i*primes[j] <= N; j++) low[i*primes[j]] = primes[j]; } return {move(low), move(primes)}; } int main(){ // test primality checks on https://cboj.ca/problem/factor2 // ll n; // scan(n); // print(count_divisors(n)); // test sieves on https://dmoj.ca/problem/phantom1 // auto v = linear_sieve((__int128)1e6).first; // auto v = fast_sieve((__int128)1e6).first; auto a = linear_sieve((__int128)1e6).second; int q; scan(q); while(q--){ int l, r, ans = 0; scan(l, r); // for(int i = l; i < r; i++) // ans += v[i] == i; // for(int i = l; i < r; i++) // ans += v[i]; for(auto i: a) ans += i >= l and i < r; cout<<ans<<'\n'; } }
33.138211
183
0.576791
[ "vector" ]
0daac429bf666529098396fed823762a854b1d4d
730
cpp
C++
1-100/1-twoSum.cpp
serverglen/LeeCode
21240d050a688e3d51a2f4d4effdb14476c42e34
[ "Apache-2.0" ]
null
null
null
1-100/1-twoSum.cpp
serverglen/LeeCode
21240d050a688e3d51a2f4d4effdb14476c42e34
[ "Apache-2.0" ]
null
null
null
1-100/1-twoSum.cpp
serverglen/LeeCode
21240d050a688e3d51a2f4d4effdb14476c42e34
[ "Apache-2.0" ]
null
null
null
/* * 1. 两数之和 * * 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。 * * 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。 * * 你可以按任意顺序返回答案。 * * 示例 1: * * 输入:nums = [2,7,11,15], target = 9 * 输出:[0,1] * 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。 * * 示例 2: * * 输入:nums = [3,2,4], target = 6 * 输出:[1,2] * * 示例 3: * * 输入:nums = [3,3], target = 6 * 输出:[0,1] */ class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { int n = nums.size(); for (int i = 0; i < n - 1; ++i) { for (int j = i + 1; j < n; ++j) { if (nums[i] + nums[j] == target) { return {i, j}; } } } return {}; } };
17.804878
76
0.452055
[ "vector" ]
0dad59511379a5c2b18978e82e07ae9cd32fbb05
338
cpp
C++
notes/code4/smallIntTest.cpp
suryaavala/advancedcpp
84c1847bf42ff744f99b4c0f94b77cfa71ca00d8
[ "MIT" ]
null
null
null
notes/code4/smallIntTest.cpp
suryaavala/advancedcpp
84c1847bf42ff744f99b4c0f94b77cfa71ca00d8
[ "MIT" ]
null
null
null
notes/code4/smallIntTest.cpp
suryaavala/advancedcpp
84c1847bf42ff744f99b4c0f94b77cfa71ca00d8
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <iterator> #include "SmallInt.h" int main() { std::vector<SmallInt> vec{SmallInt{3}, SmallInt{1}, SmallInt{2}}; std::sort(vec.begin(), vec.end()); std::copy(vec.begin(), vec.end(), std::ostream_iterator<SmallInt>(std::cout, " ")); }
22.533333
67
0.647929
[ "vector" ]
0db0d5bbef0ffd50ca9b809ecf999ad77be83cd1
2,099
cpp
C++
src/thunderbots/software/test/primitive/stop_primitive.cpp
qgolsteyn/Software
08beaa44059519b1ed2954079e436790393da6db
[ "MIT" ]
null
null
null
src/thunderbots/software/test/primitive/stop_primitive.cpp
qgolsteyn/Software
08beaa44059519b1ed2954079e436790393da6db
[ "MIT" ]
null
null
null
src/thunderbots/software/test/primitive/stop_primitive.cpp
qgolsteyn/Software
08beaa44059519b1ed2954079e436790393da6db
[ "MIT" ]
null
null
null
/** * This file contains the unit tests for the StopPrimitive class */ #include "ai/primitive/stop_primitive.h" #include <gtest/gtest.h> #include <string.h> TEST(StopPrimTest, construct_with_no_params_test) { const std::string stop_prim_name = "Stop Primitive"; StopPrimitive stop_prim = StopPrimitive(0, true); EXPECT_EQ(0, stop_prim.getRobotId()); EXPECT_EQ(stop_prim_name, stop_prim.getPrimitiveName()); } TEST(StopPrimTest, get_robot_id_test) { unsigned int robot_id = 4U; StopPrimitive stop_prim = StopPrimitive(robot_id, false); EXPECT_EQ(robot_id, stop_prim.getRobotId()); } TEST(StopPrimTest, extra_bits_test) { const bool coast = false; StopPrimitive stop_prim = StopPrimitive(0, coast); std::vector<bool> extra_bits = stop_prim.getExtraBits(); EXPECT_EQ(coast, extra_bits[0]); } TEST(StopPrimTest, paramater_array_test) { const unsigned int robot_id = 2U; const bool coast = false; StopPrimitive stop_primitive = StopPrimitive(robot_id, coast); std::vector<double> param_array = stop_primitive.getParameters(); EXPECT_EQ(param_array, std::vector<double>()); } TEST(StopPrimTest, get_coast_test) { const bool coast = false; StopPrimitive stop_prim = StopPrimitive(0, coast); EXPECT_EQ(coast, stop_prim.robotShouldCoast()); } TEST(StopPrimitiveTest, create_primitive_from_message_test) { const unsigned int robot_id = 3U; const bool coast = false; StopPrimitive stop_prim = StopPrimitive(robot_id, coast); thunderbots_msgs::Primitive prim_message = stop_prim.createMsg(); StopPrimitive new_prim = StopPrimitive(prim_message); std::vector<bool> extra_bits = new_prim.getExtraBits(); EXPECT_EQ("Stop Primitive", new_prim.getPrimitiveName()); EXPECT_EQ(robot_id, new_prim.getRobotId()); EXPECT_EQ(coast, extra_bits[0]); EXPECT_EQ(stop_prim.getParameters(), std::vector<double>()); } int main(int argc, char **argv) { std::cout << argv[0] << std::endl; testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
24.406977
69
0.715579
[ "vector" ]
0dc1183a53b33347774ae1370a2fb5861d364268
3,345
cpp
C++
backdoor/hilbert.cpp
Javantea/coastermelt
8a521ff4cea9304e700859332b5582eb6d79ccec
[ "MIT" ]
146
2015-01-02T19:42:04.000Z
2021-11-27T19:27:12.000Z
backdoor/hilbert.cpp
Javantea/coastermelt
8a521ff4cea9304e700859332b5582eb6d79ccec
[ "MIT" ]
3
2015-02-20T10:59:53.000Z
2022-02-07T19:11:08.000Z
backdoor/hilbert.cpp
Javantea/coastermelt
8a521ff4cea9304e700859332b5582eb6d79ccec
[ "MIT" ]
20
2015-02-27T01:56:19.000Z
2021-06-27T09:26:13.000Z
/* * Fast hilbert curve transform in C++ * * Adapted from http://en.wikipedia.org/wiki/Hilbert_curve * Inspired by http://xkcd.com/195/ * Deterministically and contiguously maps an (x,y) * coordinate in a 4096x4096 image to a 24-bit value. * * Copyright (c) 2014 Micah Elizabeth Scott * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <Python.h> #include <algorithm> static unsigned hilbert(unsigned x, unsigned y, unsigned size) { unsigned d = 0; for (unsigned s = size/2; s; s >>= 1) { unsigned rx = (x & s) > 0; unsigned ry = (y & s) > 0; d += s * s * ((3 * rx) ^ ry); if (ry == 0) { if (rx == 1) { x = s-1 - x; y = s-1 - y; } std::swap(x,y); } } return d; } static PyObject* py_hilbert(PyObject *self, PyObject *args) { unsigned x, y, size = 4096; if (!PyArg_ParseTuple(args, "II|I", &x, &y, &size)) { return 0; } return PyLong_FromUnsignedLong(hilbert(x, y, size)); } static PyObject* py_test(PyObject *self) { // Make sure the mapping is 1:1 unsigned* buffer = new unsigned[0x1000000]; if (!buffer) return PyErr_NoMemory(); memset(buffer, 0, 0x4000000); for (unsigned x = 0; x < 4096; x++) { for (unsigned y = 0; y < 4096; y++) { unsigned a = hilbert(x, y, 4096); if (a > 0xFFFFFF) { PyErr_SetString(PyExc_ValueError, "Hilbert result out of range"); delete[] buffer; return 0; } if (buffer[a]) { PyErr_SetString(PyExc_ValueError, "Location used twice"); delete[] buffer; return 0; } buffer[a] = 1; } } delete[] buffer; Py_RETURN_NONE; } static PyMethodDef module_methods[] = { { "hilbert", (PyCFunction) py_hilbert, METH_VARARGS, "hilbert(x, y, size=4096) -> address\n" }, { "test", (PyCFunction) py_test, METH_NOARGS, "test() -> None\n" }, {0} }; static PyModuleDef module_def = { .m_base = PyModuleDef_HEAD_INIT, .m_name = "hilbert", .m_methods = module_methods, }; PyMODINIT_FUNC PyInit_hilbert(void) { return PyModule_Create(&module_def); }
28.109244
83
0.611958
[ "transform" ]
0dc377830d8fd45d0b47a0869c9fe39522dcfcaf
25,747
cpp
C++
source/Main.cpp
stanford-mast/GraphTool
03fb86829c50e5dc28af2af21174460bf3bbe6e7
[ "BSD-3-Clause" ]
null
null
null
source/Main.cpp
stanford-mast/GraphTool
03fb86829c50e5dc28af2af21174460bf3bbe6e7
[ "BSD-3-Clause" ]
null
null
null
source/Main.cpp
stanford-mast/GraphTool
03fb86829c50e5dc28af2af21174460bf3bbe6e7
[ "BSD-3-Clause" ]
null
null
null
/***************************************************************************** * GraphTool * Tools for manipulating graphs. ***************************************************************************** * Authored by Samuel Grossman * Department of Electrical Engineering, Stanford University * Copyright (c) 2016-2017 *************************************************************************//** * @file Main.cpp * Program entry point and primary control flow. *****************************************************************************/ #include "Graph.h" #include "GraphReaderFactory.h" #include "GraphTransformFactory.h" #include "GraphWriterFactory.h" #include "IGraphReader.h" #include "IGraphTransform.h" #include "IGraphWriter.h" #include "OptionContainer.h" #include "Options.h" #include "VersionInfo.h" #include <cstddef> #include <cstdint> #include <cstdio> #include <map> #include <string> #include <vector> namespace GraphTool { // -------- CONSTANTS -------------------------------------------------- // /// Command-line option that specifies input file name. static const std::string kOptionInputFile = "inputfile"; /// Command-line option that specifies input file format. static const std::string kOptionInputFormat = "inputformat"; /// Command-line option that specifies input weight type. static const std::string kOptionInputWeights = "inputweights"; /// Command-line option that specifies input processing options. static const std::string kOptionInputOptions = "inputoptions"; /// Command-line option that specifies output file name. static const std::string kOptionOutputFile = "outputfile"; /// Command-line option that specifies output file format. static const std::string kOptionOutputFormat = "outputformat"; /// Command-line option that specifies output weight type. static const std::string kOptionOutputWeights = "outputweights"; /// Command-line option that specifies output vertex grouping. static const std::string kOptionOutputGrouping = "outputgroup"; /// Command-line option that specifies output processing options. static const std::string kOptionOutputOptions = "outputoptions"; /// Command-line option that specifies a graph transformation operation. static const std::string kOptionTransform = "transform"; // -------- LOCALS ----------------------------------------------------- // /// Application version information string. static const std::string applicationVersionString = __PROGRAM_NAME " v" __PROGRAM_VERSION " for " __PLATFORM_NAME ", compiled on " __DATE__ " at " __TIME__ ".\n"; /// Holds a mapping from edge data type to string. static const std::map<EEdgeDataType, std::string> edgeDataTypeStrings = { { EEdgeDataType::EdgeDataTypeVoid, "unweighted" }, { EEdgeDataType::EdgeDataTypeInteger, "integer-weighted" }, { EEdgeDataType::EdgeDataTypeFloatingPoint, "floating-point-weighted" }, }; /// Holds a mapping from graph file result code to error string. static const std::map<EGraphResult, std::string> graphErrorStrings = { { EGraphResult::GraphResultSuccess, "Success" }, { EGraphResult::GraphResultErrorNoMemory, "Failed to allocate memory" }, { EGraphResult::GraphResultErrorCannotOpenFile, "Unable to open file" }, { EGraphResult::GraphResultErrorIO, "I/O error" }, { EGraphResult::GraphResultErrorFormat, "Graph format error" }, { EGraphResult::GraphResultErrorUnknown, "Unknown error" }, }; /// Lists the command-line options that can be used to request help. static const std::vector<std::string> cmdlineHelpStrings = { #ifdef __PLATFORM_WINDOWS "?", #endif "help", }; /// Lists the command-line options that can be used to request the application version. static const std::vector<std::string> cmdlineVersionStrings = { "version", }; /// Lists the prefixes that are allowed at the start of command-line options. static const std::vector<std::string> cmdlinePrefixStrings = { #ifdef __PLATFORM_WINDOWS "/", #endif "--", }; /// Holds a mapping from command-line option string to edge data type enumeration value. static const std::map<std::string, int64_t> cmdlineEdgeDataTypeStrings = { { "void", EEdgeDataType::EdgeDataTypeVoid }, { "none", EEdgeDataType::EdgeDataTypeVoid }, { "unweighted", EEdgeDataType::EdgeDataTypeVoid }, { "Void", EEdgeDataType::EdgeDataTypeVoid }, { "None", EEdgeDataType::EdgeDataTypeVoid }, { "Unweighted", EEdgeDataType::EdgeDataTypeVoid }, { "int", EEdgeDataType::EdgeDataTypeInteger }, { "integer", EEdgeDataType::EdgeDataTypeInteger }, { "uint", EEdgeDataType::EdgeDataTypeInteger }, { "Int", EEdgeDataType::EdgeDataTypeInteger }, { "Integer", EEdgeDataType::EdgeDataTypeInteger }, { "Uint", EEdgeDataType::EdgeDataTypeInteger }, { "UInt", EEdgeDataType::EdgeDataTypeInteger }, { "float", EEdgeDataType::EdgeDataTypeFloatingPoint }, { "floatingpoint", EEdgeDataType::EdgeDataTypeFloatingPoint }, { "double", EEdgeDataType::EdgeDataTypeFloatingPoint }, { "Float", EEdgeDataType::EdgeDataTypeFloatingPoint }, { "Floatingpoint", EEdgeDataType::EdgeDataTypeFloatingPoint }, { "FloatingPoint", EEdgeDataType::EdgeDataTypeFloatingPoint }, { "Double", EEdgeDataType::EdgeDataTypeFloatingPoint }, }; /// Holds a mapping from command-line option string to output edge grouping value. static const std::map<std::string, int64_t> cmdlineOutputGroupingEnum = { { "s", 0ll }, { "src", 0ll }, { "source", 0ll }, { "sourcevertex", 0ll }, { "S", 0ll }, { "Src", 0ll }, { "Source", 0ll }, { "Sourcevertex", 0ll }, { "SourceVertex", 0ll }, { "d", 1ll }, { "dst", 1ll }, { "dest", 1ll }, { "destination", 1ll }, { "destinationvertex", 1ll }, { "D", 1ll }, { "Dst", 1ll }, { "Dest", 1ll }, { "Destination", 1ll }, { "Destinationvertex", 1ll }, { "DestinationVertex", 1ll }, }; /// Holds all specified command-line options, mapped from the strings used to identify them. static std::map<std::string, OptionContainer*> cmdlineSpecifiedOptions = { { kOptionInputFile, new OptionContainer(EOptionValueType::OptionValueTypeString) }, { kOptionInputFormat, new EnumOptionContainer(*(GraphReaderFactory::GetGraphReaderStrings()), OptionContainer::kUnlimitedValueCount) }, { kOptionInputWeights, new EnumOptionContainer(cmdlineEdgeDataTypeStrings, EEdgeDataType::EdgeDataTypeVoid, 1) }, { kOptionInputOptions, new OptionContainer("") }, { kOptionOutputFile, new OptionContainer(EOptionValueType::OptionValueTypeString, OptionContainer::kUnlimitedValueCount) }, { kOptionOutputFormat, new EnumOptionContainer(*(GraphWriterFactory::GetGraphWriterStrings()), OptionContainer::kUnlimitedValueCount) }, { kOptionOutputWeights, new EnumOptionContainer(cmdlineEdgeDataTypeStrings, EEdgeDataType::EdgeDataTypeVoid, OptionContainer::kUnlimitedValueCount) }, { kOptionOutputGrouping, new EnumOptionContainer(cmdlineOutputGroupingEnum, 0ll, OptionContainer::kUnlimitedValueCount) }, { kOptionOutputOptions, new OptionContainer("", OptionContainer::kUnlimitedValueCount) }, { kOptionTransform, new EnumOptionContainer(*(GraphTransformFactory::GetGraphTransformStrings()), INT64_MAX, OptionContainer::kUnlimitedValueCount) }, }; /// Dynamically builds the documentation string to use to display help to the user. /// @param [in] cmdline Command-line path to display in the string. /// @return Fully-formatted documentation string. std::string MakeDocumentationString(const char* const cmdline) { // Build the usage line. std::string docstring = "Usage: "; docstring += cmdline; docstring += " [options]\n"; // Build any subsequent usage lines. if (0 != cmdlineHelpStrings.size()) { docstring += " "; docstring += cmdline; docstring += " "; docstring += cmdlinePrefixStrings[0]; docstring += cmdlineHelpStrings[0]; docstring += "\n"; } if (0 != cmdlineVersionStrings.size()) { docstring += " "; docstring += cmdline; docstring += " "; docstring += cmdlinePrefixStrings[0]; docstring += cmdlineVersionStrings[0]; docstring += "\n"; } // Add the required options header. docstring += "\nRequired:\n"; docstring += " "; docstring += cmdlinePrefixStrings[0]; docstring += kOptionInputFile; docstring += "=<input-graph>\n"; docstring += " Path of the file containing the input graph.\n"; docstring += " Must be specified exactly once.\n"; docstring += " "; docstring += cmdlinePrefixStrings[0]; docstring += kOptionInputFormat; docstring += "=<input-format>\n"; docstring += " Format of the input graph.\n"; docstring += " Must be specified exactly once.\n"; docstring += " See documentation for supported values.\n"; docstring += " "; docstring += cmdlinePrefixStrings[0]; docstring += kOptionOutputFile; docstring += "=<output-graph>\n"; docstring += " Path of the file to which the output graph should be written.\n"; docstring += " Must be specified at least once, but may be specified multiple times.\n"; docstring += " One output file is produced for each filename given.\n"; docstring += " "; docstring += cmdlinePrefixStrings[0]; docstring += kOptionOutputFormat; docstring += "=<input-format>\n"; docstring += " Format of each output graph.\n"; docstring += " Must be specified once per output file.\n"; docstring += " See documentation for supported values.\n"; // Add the options header. docstring += "\nOptions:\n"; // Print any help string information. if (0 != cmdlineHelpStrings.size()) { docstring += " "; docstring += cmdlinePrefixStrings[0]; docstring += cmdlineHelpStrings[0]; docstring += "\n"; docstring += " Prints this information and exits.\n"; } // Prints any version string information. if (0 != cmdlineVersionStrings.size()) { docstring += " "; docstring += cmdlinePrefixStrings[0]; docstring += cmdlineVersionStrings[0]; docstring += "\n"; docstring += " Prints version information and exits.\n"; } docstring += " "; docstring += cmdlinePrefixStrings[0]; docstring += kOptionInputOptions; docstring += "=<input-options-string>\n"; docstring += " Comma-delimited list of input graph options and values.\n"; docstring += " Fine-tunes the behavior of graph reading functionality.\n"; docstring += " Optional; may be specified at most once.\n"; docstring += " See documentation for supported values and defaults.\n"; docstring += " "; docstring += cmdlinePrefixStrings[0]; docstring += kOptionInputWeights; docstring += "=<input-weights-string>\n"; docstring += " Type of weights, if any, to be read from the input file.\n"; docstring += " Optional; may be specified at most once.\n"; docstring += " See documentation for supported values and defaults.\n"; docstring += " "; docstring += cmdlinePrefixStrings[0]; docstring += kOptionOutputGrouping; docstring += "=<output-vertex-grouping-string>\n"; docstring += " Output edge grouping mode.\n"; docstring += " Specifies that edges should be grouped by source or destination vertex.\n"; docstring += " Optional; may be specified at most once per output file.\n"; docstring += " See documentation for supported values and defaults.\n"; docstring += " "; docstring += cmdlinePrefixStrings[0]; docstring += kOptionOutputOptions; docstring += "=<output-options-string>\n"; docstring += " Comma-delimited list of output graph options and values.\n"; docstring += " Fine-tunes the behavior of graph writing functionality.\n"; docstring += " Optional; may be specified at most once per output file.\n"; docstring += " See documentation for supported values and defaults.\n"; docstring += " "; docstring += cmdlinePrefixStrings[0]; docstring += kOptionOutputWeights; docstring += "=<output-weights-string>\n"; docstring += " Type of weights, if any, to be written to the input file.\n"; docstring += " Optional; may be specified at most once per output file.\n"; docstring += " See documentation for supported values and defaults.\n"; docstring += " "; docstring += cmdlinePrefixStrings[0]; docstring += kOptionTransform; docstring += "=<transform-string>\n"; docstring += " Transformation operation to be applied.\n"; docstring += " Transformation operations are applied in command-line order.\n"; docstring += " Optional; may be specified as many times as needed.\n"; docstring += " See documentation for supported values and defaults.\n"; return docstring; } /// Prints an error message about a graph file operation to the standard error console. /// @param [in] cmdline Command-line path to display in the string. /// @param [in] filename Filename to display in the string. /// @param [in] code Error code that should be printed. /// @param [in] operationIsRead `true` to show that an error occurred during read, `false` to show that it happened during write. void PrintGraphFileError(const char* const cmdline, const char* const filename, const EGraphResult code, const bool operationIsRead) { fprintf(stderr, "%s: Error %s %s: %s.\n", cmdline, (operationIsRead ? "reading" : "writing"), filename, graphErrorStrings.at(code).c_str()); } } // -------- ENTRY POINT ---------------------------------------------------- // using namespace GraphTool; /// Program entry point. /// @param [in] argc Number of command-line arguments. /// @param [in] argv Command-line argument strings. /// @return Program exit code. 0 means successful termination, anything else indicates an error. int main(const int argc, const char* const argv[]) { // Build the string to display when requesting help. const std::string documentationString = MakeDocumentationString(argv[0]); // Initialize the command-line option parser. Options commandLineOptions(argv[0], cmdlineSpecifiedOptions, &cmdlinePrefixStrings, &cmdlineVersionStrings, &cmdlineHelpStrings, &documentationString, &applicationVersionString); // Submit all command-line options for parsing. if (!(commandLineOptions.FillFromStringArray(argc - 1, &argv[1]))) return __LINE__; // Validate that all required values are present and required relationships hold. if (!(commandLineOptions.ValidateOptions() && commandLineOptions.VerifyEqualValueCount(kOptionOutputFile.c_str(), kOptionOutputFormat.c_str()))) return __LINE__; // Get the input file name. const OptionContainer* optionValues = commandLineOptions.GetOptionValues(kOptionInputFile); if (NULL == optionValues) return __LINE__; std::string inputGraphFile; if (!(optionValues->QueryValue(inputGraphFile))) return __LINE__; // Get the output file names. optionValues = commandLineOptions.GetOptionValues(kOptionOutputFile); if (NULL == optionValues) return __LINE__; std::vector<std::string> outputGraphFiles(optionValues->GetValueCount()); for (size_t i = 0; i < optionValues->GetValueCount(); ++i) { if (!(optionValues->QueryValueAt(i, outputGraphFiles[i]))) return __LINE__; } // Figure out the input edge data type. optionValues = commandLineOptions.GetOptionValues(kOptionInputWeights); if (NULL == optionValues) return __LINE__; int64_t readerEdgeDataTypeEnum; if (!(optionValues->QueryValue(readerEdgeDataTypeEnum))) return __LINE__; // Create the graph reader object. optionValues = commandLineOptions.GetOptionValues(kOptionInputFormat); if (NULL == optionValues) return __LINE__; int64_t optionGraphFormatEnum; if (!(optionValues->QueryValue(optionGraphFormatEnum))) return __LINE__; IGraphReader* reader = GraphReaderFactory::CreateGraphReader((EGraphReaderType)optionGraphFormatEnum, (EEdgeDataType)readerEdgeDataTypeEnum); if (NULL == reader) return __LINE__; // Figure out the output edge data types and create the graph writer objects. optionValues = commandLineOptions.GetOptionValues(kOptionOutputFormat); if (NULL == optionValues) return __LINE__; std::vector<IGraphWriter*> writers(optionValues->GetValueCount()); std::vector<EEdgeDataType> writersEdgeDataType(optionValues->GetValueCount()); { const OptionContainer* optionValuesOutputEdgeDataType = commandLineOptions.GetOptionValues(kOptionOutputWeights); if (NULL == optionValuesOutputEdgeDataType) return __LINE__; for (size_t i = 0; i < optionValues->GetValueCount(); ++i) { int64_t writerEdgeDataTypeEnum; if (!(optionValuesOutputEdgeDataType->QueryValueAt(i, writerEdgeDataTypeEnum))) return __LINE__; if (!(optionValues->QueryValueAt(i, optionGraphFormatEnum))) return __LINE__; IGraphWriter* writer = GraphWriterFactory::CreateGraphWriter((EGraphWriterType)optionGraphFormatEnum, (EEdgeDataType)writerEdgeDataTypeEnum); if (NULL == writer) return __LINE__; writers[i] = writer; writersEdgeDataType[i] = (EEdgeDataType)writerEdgeDataTypeEnum; } } // Figure out the correct grouping mode for each writer. optionValues = commandLineOptions.GetOptionValues(kOptionOutputGrouping); if (NULL == optionValues) return __LINE__; std::vector<bool> writerGroupByDestination(writers.size()); for (size_t i = 0; i < writers.size(); ++i) { int64_t optionOutputGroupingEnum; if (!(optionValues->QueryValueAt(i, optionOutputGroupingEnum))) return __LINE__; writerGroupByDestination[i] = ((0ll == optionOutputGroupingEnum) ? false : true); } // Consistency check. if (!(writers.size() == outputGraphFiles.size())) return __LINE__; // Create transformation objects. optionValues = commandLineOptions.GetOptionValues(kOptionTransform); if (NULL == optionValues) return __LINE__; std::vector<IGraphTransform*> transforms(optionValues->GetValueCount()); for (size_t i = 0; i < optionValues->GetValueCount(); ++i) { int64_t transformTypeEnum; if (!(optionValues->QueryValueAt(i, transformTypeEnum))) return __LINE__; transforms[i] = GraphTransformFactory::CreateGraphTransform((EGraphTransformType)transformTypeEnum); } // Submit input and output options to all of the readers and writers, respectively. optionValues = commandLineOptions.GetOptionValues(kOptionInputOptions); if (NULL == optionValues) return __LINE__; { std::string inputOptions; if (!(optionValues->QueryValue(inputOptions))) return __LINE__; // TODO: submit reader options } optionValues = commandLineOptions.GetOptionValues(kOptionOutputOptions); if (NULL == optionValues) return __LINE__; for (size_t i = 0; i < optionValues->GetValueCount(); ++i) { std::string outputOptions; if (!(optionValues->QueryValueAt(i, outputOptions))) return __LINE__; // TODO: submit writer options } // Read the input graph. Graph graph; EGraphResult fileResult = reader->ReadGraphFromFile(inputGraphFile.c_str(), graph); if (EGraphResult::GraphResultSuccess != fileResult) { PrintGraphFileError(argv[0], inputGraphFile.c_str(), fileResult, true); return __LINE__; } else { printf("Read graph %s.\n", inputGraphFile.c_str()); printf("Graph contains %llu vertices and %llu edges.\n", (long long unsigned int)graph.GetNumVertices(), (long long unsigned int)graph.GetNumEdges()); } // Perform transformations. for (size_t i = 0; i < transforms.size(); ++i) { if (NULL != transforms[i]) { const EGraphResult transformResult = transforms[i]->ApplyTransformation(graph); if (EGraphResult::GraphResultSuccess == transformResult) puts("Applied transform."); else { puts("Failed to apply transform."); return __LINE__; } } } // Write the output graphs. for (size_t i = 0; i < writers.size(); ++i) { fileResult = writers[i]->WriteGraphToFile(outputGraphFiles[i].c_str(), graph, writerGroupByDestination[i]); if (EGraphResult::GraphResultSuccess != fileResult) { PrintGraphFileError(argv[0], outputGraphFiles[i].c_str(), fileResult, false); } else { printf("Wrote %s-grouped %s graph %s.\n", (writerGroupByDestination[i] ? "destination" : "source"), edgeDataTypeStrings.at(writersEdgeDataType[i]).c_str(), outputGraphFiles[i].c_str()); } } // Print final messages and exit. printf("Exiting.\n"); exit(0); }
47.155678
206
0.55187
[ "object", "vector", "transform" ]
0dc52544d17e322a1931dee19a3028024be56d93
9,370
hpp
C++
oanda_v20/include/oanda/v20/endpoint/Transaction.hpp
CodeRancher/offcenter_oanda
c7817299b2c7199508307b2379179923e3f60fdc
[ "Apache-2.0" ]
null
null
null
oanda_v20/include/oanda/v20/endpoint/Transaction.hpp
CodeRancher/offcenter_oanda
c7817299b2c7199508307b2379179923e3f60fdc
[ "Apache-2.0" ]
null
null
null
oanda_v20/include/oanda/v20/endpoint/Transaction.hpp
CodeRancher/offcenter_oanda
c7817299b2c7199508307b2379179923e3f60fdc
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2021 Scott Brauer * * 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 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 Transaction.hpp * @author Scott Brauer * @date 02-07-2021 */ #ifndef OANDA_V20_ENDPOINT_TRANSACTION_HPP #define OANDA_V20_ENDPOINT_TRANSACTION_HPP #include <nlohmann/json.hpp> #include <cpprest/http_headers.h> #include "oanda/v20/json/JsonToFrom.hpp" #include "oanda/v20/endpoint/OandaEndpointParameters.hpp" #include "oanda/v20/endpoint/OandaEndpointResponses.hpp" namespace oanda { namespace v20 { namespace endpoint { namespace transaction { namespace transactions { /** * */ class Parameters: public oanda::v20::endpoint::OandaEndpointParameters { public: explicit Parameters(): OandaEndpointParameters(), acceptDateTimeFormat("Accept-Datetime-Format", endpoint::ParameterType::HEADER, *this), accountID("accountID", endpoint::ParameterType::PATH, *this), from("from", endpoint::ParameterType::QUERY, *this), to("to", endpoint::ParameterType::QUERY, *this), pageSize("pageSize", endpoint::ParameterType::QUERY, *this), type("type", endpoint::ParameterType::QUERY, *this) {} /// Format of DateTime fields in the request and response. AcceptDatetimeFormatParameter acceptDateTimeFormat; /// Account Identifier [required] Parameter accountID; /// The starting time (inclusive) of the time range for the Transactions being queried. [default=Account Creation Time] Parameter from; /// The ending time (inclusive) of the time range for the Transactions being queried. [default=Request Time] Parameter to; /// The number of Transactions to include in each page of the results. [default=100, maximum=1000] Parameter pageSize; /// A filter for restricting the types of Transactions to retrieve. Parameter type; }; /** * */ class Request {}; /** * */ struct Response { // Response Headers /// The unique identifier generated for the request std::string requestID; /// The starting time provided in the request. oanda::v20::primitives::DateTime from; /// The ending time provided in the request. oanda::v20::primitives::DateTime to; /// The pageSize provided in the request int pageSize; /// The Transaction-type filter provided in the request std::vector<oanda::v20::transaction::TransactionFilter> type; /// The number of Transactions that are contained in the pages returned int count; /// The list of URLs that represent idrange queries providing the data for /// each page in the query results std::vector<oanda::v20::common::String> pages; /// The ID of the most recent Transaction created for the Account oanda::v20::transaction::TransactionID lastTransactionID; }; void to_json(nlohmann::json& j, const Request& p); void from_json(const nlohmann::json& j, Request& p); void to_json(nlohmann::json& j, const Response& p); void from_json(const nlohmann::json& j, Response& p); void parseHeader(const web::http::http_headers& h, Response& p); } /* namespace transactions */ namespace transaction { /** * */ class Parameters: public oanda::v20::endpoint::OandaEndpointParameters { public: explicit Parameters(): OandaEndpointParameters(), acceptDateTimeFormat("Accept-Datetime-Format", endpoint::ParameterType::HEADER, *this), accountID("accountID", endpoint::ParameterType::PATH, *this), transactionID("transactionID", endpoint::ParameterType::PATH, *this) {} AcceptDatetimeFormatParameter acceptDateTimeFormat; ///< Format of DateTime fields in the request and response. Parameter accountID; ///< Account Identifier [required] Parameter transactionID; ///< A Transaction ID [required] }; /** * */ class Request {}; /** * */ struct Response { std::string requestID; ///< The unique identifier generated for the request /// The details of the Transaction requested oanda::v20::transaction::Transaction transaction; /// The ID of the most recent Transaction created for the Account oanda::v20::transaction::TransactionID lastTransactionID; }; // Json void to_json(nlohmann::json& j, const Request& p); void from_json(const nlohmann::json& j, Request& p); void to_json(nlohmann::json& j, const Response& p); void from_json(const nlohmann::json& j, Response& p); void parseHeader(const web::http::http_headers& h, Response& p); } /* namespace transaction */ namespace transactionsrange { /** * */ class Parameters: public oanda::v20::endpoint::OandaEndpointParameters { public: explicit Parameters(): OandaEndpointParameters(), acceptDateTimeFormat("Accept-Datetime-Format", endpoint::ParameterType::HEADER, *this), accountID("accountID", endpoint::ParameterType::PATH, *this), from("from", endpoint::ParameterType::QUERY, *this), to("to", endpoint::ParameterType::QUERY, *this), type("type", endpoint::ParameterType::QUERY, *this) {} /// Format of DateTime fields in the request and response. AcceptDatetimeFormatParameter acceptDateTimeFormat; /// Account Identifier [required] Parameter accountID; /// The starting Transaction ID (inclusive) to fetch. [required] Parameter from; /// The ending Transaction ID (inclusive) to fetch. [required] Parameter to; /// The filter that restricts the types of Transactions to retrieve. Parameter type; }; /** * */ class Request {}; /** * */ struct Response { std::string requestID; ///< The unique identifier generated for the request /// The list of Transactions that satisfy the request. std::vector<oanda::v20::transaction::Transaction> transactions; /// The ID of the most recent Transaction created for the Account oanda::v20::transaction::TransactionID lastTransactionID; }; // Json void to_json(nlohmann::json& j, const Request& p); void from_json(const nlohmann::json& j, Request& p); void to_json(nlohmann::json& j, const Response& p); void from_json(const nlohmann::json& j, Response& p); void parseHeader(const web::http::http_headers& h, Response& p); } /* namespace transactionsrange */ namespace transactionssince { /** * */ class Parameters: public oanda::v20::endpoint::OandaEndpointParameters { public: explicit Parameters(): OandaEndpointParameters(), acceptDateTimeFormat("Accept-Datetime-Format", endpoint::ParameterType::HEADER, *this), accountID("accountID", endpoint::ParameterType::PATH, *this), id("id", endpoint::ParameterType::QUERY, *this), type("type", endpoint::ParameterType::QUERY, *this) {} AcceptDatetimeFormatParameter acceptDateTimeFormat; ///< Format of DateTime fields in the request and response. Parameter accountID; ///< Account Identifier [required] Parameter id; ///< The ID of the last Transaction fetched. This query will return all Transactions newer than the TransactionID. [required] Parameter type; ///< A filter for restricting the types of Transactions to retrieve. }; /** * */ class Request {}; /** * */ struct Response { std::string requestID; ///< The unique identifier generated for the request /// The list of Transactions that satisfy the request. std::vector<oanda::v20::transaction::Transaction> transactions; /// The ID of the most recent Transaction created for the Account oanda::v20::transaction::TransactionID lastTransactionID; }; // Json void to_json(nlohmann::json& j, const Request& p); void from_json(const nlohmann::json& j, Request& p); void to_json(nlohmann::json& j, const Response& p); void from_json(const nlohmann::json& j, Response& p); void parseHeader(const web::http::http_headers& h, Response& p); } /* namespace transactionssince */ namespace transactionsstream { /** * */ class Parameters: public oanda::v20::endpoint::OandaEndpointParameters { public: explicit Parameters(): OandaEndpointParameters(), acceptDateTimeFormat("Accept-Datetime-Format", endpoint::ParameterType::HEADER, *this), accountID("accountID", endpoint::ParameterType::PATH, *this) {} AcceptDatetimeFormatParameter acceptDateTimeFormat; ///< Format of DateTime fields in the request and response. Parameter accountID; ///< Account Identifier [required] }; /** * */ class Request {}; /** * */ struct Response { // std::string requestID; ///< The unique identifier generated for the request // oanda::v20::instrument::PositionBook positionBook; ///< The instrument’s position book }; // Json void to_json(nlohmann::json& j, const Request& p); void from_json(const nlohmann::json& j, Request& p); void to_json(nlohmann::json& j, const Response& p); void from_json(const nlohmann::json& j, Response& p); void parseHeader(const web::http::http_headers& h, Response& p); } /* namespace transactionsstream */ } /* namespace transaction */ } /* namespace endpoint */ } /* namespace v20 */ } /* namespace oanda */ #endif /* OANDA_V20_ENDPOINT_TRANSACTION_HPP */
28.919753
141
0.721345
[ "vector" ]
0dd68de1e7dc62e916fce3407fb50f46e02bc82a
3,191
cpp
C++
willow/src/patterns/nlllwithsoftmaxgraddirect.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
61
2020-07-06T17:11:46.000Z
2022-03-12T14:42:51.000Z
willow/src/patterns/nlllwithsoftmaxgraddirect.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
1
2021-02-25T01:30:29.000Z
2021-11-09T11:13:14.000Z
willow/src/patterns/nlllwithsoftmaxgraddirect.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
6
2020-07-15T12:33:13.000Z
2021-11-07T06:55:00.000Z
// Copyright (c) 2019 Graphcore Ltd. All rights reserved. #include <popart/graph.hpp> #include <popart/op/nll.hpp> #include <popart/op/softmax.hpp> #include <popart/patterns/nlllwithsoftmaxgraddirect.hpp> #include <popart/patterns/patterns.hpp> #include <popart/tensor.hpp> #include <popart/tensors.hpp> namespace popart { bool NlllWithSoftmaxGradDirect::matches(Op *op) const { // 1. Matches only on SoftmaxGradDirectOp // 2. Corresponding fwd NllOp op must exist // 3. NllOp and SoftmaxGradDirectOp must be on same IPU // 4. NllOp and SoftmaxGradDirectOp must be on same PipelineStage // 1. auto sfmgdOp = dynamic_cast<SoftmaxGradDirectOp *>(op); if (sfmgdOp == nullptr) { return false; } // 2. if (!sfmgdOp->hasNlllFwdOp()) { return false; } // 3. auto fwdLossOp = sfmgdOp->nlllFwdOp(); if (sfmgdOp->getOptionalVGraphId() != fwdLossOp->getOptionalVGraphId()) { return false; } // 4. if (sfmgdOp->getOptionalPipelineStage() != fwdLossOp->getOptionalPipelineStage()) { return false; } return true; } std::vector<const Tensor *> NlllWithSoftmaxGradDirect::touches(Op *) const { return {}; } bool NlllWithSoftmaxGradDirect::apply(Op *op) const { auto sfmgdOp = dynamic_cast<SoftmaxGradDirectOp *>(op); auto fwdLossOp = sfmgdOp->nlllFwdOp(); auto &graph = op->getGraph(); auto label = sfmgdOp->inTensor(SoftmaxGradDirectOp::getLabelInIndex()); auto probs = sfmgdOp->inTensor(SoftmaxGradDirectOp::getProbsInIndex()); auto gradIn = sfmgdOp->inTensor(SoftmaxGradDirectOp::getGradProbsInIndex()); auto sfm_grad = sfmgdOp->outTensor(0); auto loss = fwdLossOp->outTensor(0); // create the new op OpId nlllsfmgdId = graph.moveIntoGraph(std::unique_ptr<Op>( new NlllWithSoftmaxGradDirectOp(sfmgdOp->getOptionalIgnoreIndex(), sfmgdOp->getReductionType(), sfmgdOp->getSettings()))); Op *nlllsfmgd = graph.getOp(nlllsfmgdId); // Remove the SoftmaxGradDirectOp connections sfmgdOp->disconnectAllInputs(); sfmgdOp->disconnectAllOutputs(); // Remove the forward NllOp connections fwdLossOp->disconnectAllInputs(); fwdLossOp->disconnectAllOutputs(); // Connect up the new NlllWithSoftmaxGradDirectOp nlllsfmgd->connectInTensor(NlllWithSoftmaxGradDirectOp::getProbsInIndex(), probs->id); nlllsfmgd->connectInTensor(NlllWithSoftmaxGradDirectOp::getLabelInIndex(), label->id); nlllsfmgd->connectInTensor(NlllWithSoftmaxGradDirectOp::getGradProbsInIndex(), gradIn->id); nlllsfmgd->connectOutTensor(NlllWithSoftmaxGradDirectOp::getGradOutIndex(), sfm_grad->id); nlllsfmgd->connectOutTensor(NlllWithSoftmaxGradDirectOp::getLossOutIndex(), loss->id); nlllsfmgd->setup(); // Remove old ops sfmgdOp->getGraph().eraseOp(sfmgdOp->id); fwdLossOp->getGraph().eraseOp(fwdLossOp->id); return true; } namespace { static PatternCreator<NlllWithSoftmaxGradDirect> PreUniReplPattern("NlllWithSoftmaxGradDirect"); } } // namespace popart
31.594059
80
0.685365
[ "vector" ]
0dd7c1ec406fcde0ab28d9aeec323e66f1c414c7
4,730
cxx
C++
Libs/MRML/Widgets/qMRMLNavigationView.cxx
forfullstack/slicersources-src
91bcecf037a27f3fad4c0ab57e8286fc258bb0f5
[ "Apache-2.0" ]
null
null
null
Libs/MRML/Widgets/qMRMLNavigationView.cxx
forfullstack/slicersources-src
91bcecf037a27f3fad4c0ab57e8286fc258bb0f5
[ "Apache-2.0" ]
null
null
null
Libs/MRML/Widgets/qMRMLNavigationView.cxx
forfullstack/slicersources-src
91bcecf037a27f3fad4c0ab57e8286fc258bb0f5
[ "Apache-2.0" ]
null
null
null
/*============================================================================== Program: 3D Slicer Copyright (c) Kitware Inc. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. This file was originally developed by Julien Finet, Kitware Inc. and was partially funded by NIH grant 3P41RR013218-12S1 ==============================================================================*/ // qMRML includes #include "qMRMLColors.h" #include "qMRMLNavigationView.h" // MRML includes #include <vtkMRMLViewNode.h> #include <vtkMRMLScene.h> // VTK includes #include <vtkWeakPointer.h> //----------------------------------------------------------------------------- class qMRMLNavigationViewPrivate { Q_DECLARE_PUBLIC(qMRMLNavigationView); protected: qMRMLNavigationView* const q_ptr; public: qMRMLNavigationViewPrivate(qMRMLNavigationView& object); ~qMRMLNavigationViewPrivate(); vtkMRMLScene* MRMLScene; vtkWeakPointer<vtkMRMLViewNode> MRMLViewNode; }; //-------------------------------------------------------------------------- // qMRMLNavigationViewPrivate methods //--------------------------------------------------------------------------- qMRMLNavigationViewPrivate::qMRMLNavigationViewPrivate(qMRMLNavigationView& object) : q_ptr(&object) { this->MRMLScene = nullptr; } //--------------------------------------------------------------------------- qMRMLNavigationViewPrivate::~qMRMLNavigationViewPrivate() = default; // -------------------------------------------------------------------------- // qMRMLNavigationView methods // -------------------------------------------------------------------------- qMRMLNavigationView::qMRMLNavigationView(QWidget* _parent) : Superclass(_parent) , d_ptr(new qMRMLNavigationViewPrivate(*this)) { // Set default background color this->setBackgroundColor(QColor::fromRgbF( vtkMRMLViewNode::defaultBackgroundColor()[0], vtkMRMLViewNode::defaultBackgroundColor()[1], vtkMRMLViewNode::defaultBackgroundColor()[2])); } // -------------------------------------------------------------------------- qMRMLNavigationView::~qMRMLNavigationView() = default; //------------------------------------------------------------------------------ void qMRMLNavigationView::setMRMLScene(vtkMRMLScene* newScene) { Q_D(qMRMLNavigationView); if (d->MRMLScene == newScene) { return; } this->qvtkReconnect(d->MRMLScene, newScene, vtkMRMLScene::NodeAddedEvent, this, SLOT(updateFromMRMLScene())); this->qvtkReconnect(d->MRMLScene, newScene, vtkMRMLScene::NodeRemovedEvent, this, SLOT(updateFromMRMLScene())); this->qvtkReconnect(d->MRMLScene, newScene, vtkMRMLScene::EndBatchProcessEvent, this, SLOT(updateFromMRMLScene())); d->MRMLScene = newScene; if (!d->MRMLViewNode || newScene != d->MRMLViewNode->GetScene()) { this->setMRMLViewNode(nullptr); } this->updateFromMRMLScene(); } //--------------------------------------------------------------------------- void qMRMLNavigationView::setMRMLViewNode(vtkMRMLViewNode* newViewNode) { Q_D(qMRMLNavigationView); if (d->MRMLViewNode == newViewNode) { return; } this->qvtkReconnect(d->MRMLViewNode, newViewNode, vtkCommand::ModifiedEvent, this, SLOT(updateFromMRMLViewNode())); d->MRMLViewNode = newViewNode; this->updateFromMRMLViewNode(); // Enable/disable widget this->setEnabled(d->MRMLViewNode != nullptr); } //--------------------------------------------------------------------------- vtkMRMLViewNode* qMRMLNavigationView::mrmlViewNode()const { Q_D(const qMRMLNavigationView); return d->MRMLViewNode; } //--------------------------------------------------------------------------- void qMRMLNavigationView::updateFromMRMLScene() { Q_D(qMRMLNavigationView); if (!d->MRMLScene || d->MRMLScene->IsBatchProcessing()) { return; } this->updateBounds(); } //--------------------------------------------------------------------------- void qMRMLNavigationView::updateFromMRMLViewNode() { Q_D(qMRMLNavigationView); if (!d->MRMLViewNode) { return; } double backgroundColor[3]; d->MRMLViewNode->GetBackgroundColor(backgroundColor); this->setBackgroundColor( QColor::fromRgbF(backgroundColor[0], backgroundColor[1], backgroundColor[2])); }
31.959459
83
0.563002
[ "object", "3d" ]
0dd9391486257bcd68a31c51254604779e412e01
3,490
cpp
C++
RenderDocEventStatistics/RenderDocEventStatistics/GeneratorCommand.cpp
BleedingChips/Ue4LightweightTool
afe436f0bbdf15ff02a0d4464f4ab5a9d4733df3
[ "MIT" ]
1
2021-03-21T16:54:50.000Z
2021-03-21T16:54:50.000Z
RenderDocEventStatistics/RenderDocEventStatistics/GeneratorCommand.cpp
BleedingChips/Ue4LightweightTool
afe436f0bbdf15ff02a0d4464f4ab5a9d4733df3
[ "MIT" ]
null
null
null
RenderDocEventStatistics/RenderDocEventStatistics/GeneratorCommand.cpp
BleedingChips/Ue4LightweightTool
afe436f0bbdf15ff02a0d4464f4ab5a9d4733df3
[ "MIT" ]
null
null
null
#include "GeneratorCommand.h" #include <sstream> using namespace PO::Tool; std::tuple<std::u16string, size_t> clear_name(const std::u16string& b) { size_t index = 0; auto start = b.begin(); for (; start != b.end(); ++start) { if (*start != u' ' && *start != u'\\' && *start != u'-') break; ++index; } auto end = start; auto end_ite = end; for (; end_ite != b.end(); ++end_ite) { if (*end_ite != u' ') end = end_ite; } if (end != b.end()) ++end; return { { start, end }, index }; } std::vector<draw_commend> GeneratorCommand(const std::filesystem::path& path) { Lexical::regex_analyzer_wrapper_utf16 raw( { { u"\\|", 1 }, { u"\\s*[0-9]+.?[0-9]*\\s*", 2 }, //{ u"\\s*\\\\?\\-\\s([a-z]|[A-Z]|\\s|_|\\(|\\)|=|\\.|,|[0-9]|\\:|\\#)*", 3 }, { u"[^\\|]*", 3 }, { u"\\s+", 4 } } ); Lexical::regex_analyzer_wrapper_utf16 raw2( { { u"[0-9]+\\.?[0-9]*",2 }, { u".*",3 }, { u"", 4 }, } ); std::vector<draw_commend> all_command; Doc::loader_utf16 lu16(path); if (lu16.is_open()) { Lexical::stream_analyzer_wrapper_utf16 saw( [&](char16_t* output, size_t avalible) -> size_t { size_t result = lu16.read_one(output, avalible); if (!lu16.end_of_file()) return result; return 0; }, Lexical::line_analyzer{} ); size_t line_count = 0; draw_commend current_command; while (saw.generate_token()) { if (saw.cast_token<Lexical::line_analyzer::Token>() == Lexical::line_analyzer::Token::Line) { ++line_count; if (line_count >= 4) { raw.set_string(saw.string()); size_t state = 0; while (raw.generate_token()) { if (raw.token() == 1) { state += 1; } else { std::u16string clear{ raw.string().begin(), raw.string().end() }; auto result = clear_name(clear); raw2.set_string(std::get<0>(result)); if (raw2.generate_token()) { if (state == 0) { if (raw2.token() == 1) current_command.EID = 0; else if (raw2.token() == 2) { std::wstring tem = reinterpret_cast<const wchar_t*>(std::get<0>(result).c_str()); std::wstringstream wss; wss << tem; wss >> current_command.EID; //current_command.EID = (current_command.EID - 3) / 2; } } else if (state == 1) { current_command.name = std::get<0>(result); current_command.leval = (std::get<1>(result) - 3) / 2; } else if (state == 2) { std::wstring tem = reinterpret_cast<const wchar_t*>(std::get<0>(result).c_str()); std::wstringstream wss; wss << tem; wss >> current_command.draw; } else if (state == 3) { if (raw2.token() == 2) { std::wstring tem = reinterpret_cast<const wchar_t*>(std::get<0>(result).c_str()); std::wstringstream wss; wss << tem; wss >> current_command.duration; } } } else if (state == 0) current_command.EID = 0; } } if (state != 3) { struct da : std::exception { const char* what() const noexcept { return "Unable to recognize"; } }; throw da{}; } all_command.push_back(current_command); } } //std::wcout << reinterpret_cast<const wchar_t*>(saw.string().c_str()) <<L"]" << std::endl; } } return all_command; }
23.581081
94
0.515759
[ "vector" ]
0de02f52ad459e51fb59940949e29d049338636d
17,258
cc
C++
spartyjet-4.0.2_mac/External/fastjet-3.0.0/tools/JetMedianBackgroundEstimator.cc
mickypaganini/SSI2016-jet-clustering
a340558957f55159197e845850fc16e622082e7e
[ "MIT" ]
3
2018-06-15T09:12:17.000Z
2021-06-20T15:58:21.000Z
spartyjet-4.0.2_mac/External/fastjet-3.0.0/tools/JetMedianBackgroundEstimator.cc
mickypaganini/SSI2016-jet-clustering
a340558957f55159197e845850fc16e622082e7e
[ "MIT" ]
1
2016-08-19T23:48:43.000Z
2016-08-20T01:01:34.000Z
spartyjet-4.0.2_mac/External/fastjet-3.0.0/tools/JetMedianBackgroundEstimator.cc
mickypaganini/SSI2016-jet-clustering
a340558957f55159197e845850fc16e622082e7e
[ "MIT" ]
6
2016-08-18T23:16:00.000Z
2020-04-13T01:13:20.000Z
//STARTHEADER // $Id: JetMedianBackgroundEstimator.cc 2616 2011-09-30 18:03:40Z salam $ // // Copyright (c) 2005-2011, Matteo Cacciari, Gavin P. Salam and Gregory Soyez // //---------------------------------------------------------------------- // This file is part of FastJet. // // FastJet 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. // // The algorithms that underlie FastJet have required considerable // development and are described in hep-ph/0512210. If you use // FastJet as part of work towards a scientific publication, please // include a citation to the FastJet paper. // // FastJet is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with FastJet. If not, see <http://www.gnu.org/licenses/>. //---------------------------------------------------------------------- //ENDHEADER #include "fastjet/tools/JetMedianBackgroundEstimator.hh" #include <fastjet/ClusterSequenceArea.hh> #include <fastjet/ClusterSequenceStructure.hh> #include <iostream> FASTJET_BEGIN_NAMESPACE // defined in fastjet/internal/base.hh using namespace std; double BackgroundJetScalarPtDensity::result(const PseudoJet & jet) const { std::vector<PseudoJet> constituents = jet.constituents(); double scalar_pt = 0; for (unsigned i = 0; i < constituents.size(); i++) { scalar_pt += pow(constituents[i].perp(), _pt_power); } return scalar_pt / jet.area(); } //---------------------------------------------------------------------- double BackgroundRescalingYPolynomial::result(const PseudoJet & jet) const { double y = jet.rap(); double y2 = y*y; double rescaling = _a0 + _a1*y + _a2*y2 + _a3*y2*y + _a4*y2*y2; return rescaling; } /// allow for warnings LimitedWarning JetMedianBackgroundEstimator::_warnings; LimitedWarning JetMedianBackgroundEstimator::_warnings_zero_area; LimitedWarning JetMedianBackgroundEstimator::_warnings_preliminary; //--------------------------------------------------------------------- // class JetMedianBackgroundEstimator // Class to estimate the density of the background per unit area //--------------------------------------------------------------------- //---------------------------------------------------------------------- // ctors and dtors //---------------------------------------------------------------------- // ctor that allows to set only the particles later on JetMedianBackgroundEstimator::JetMedianBackgroundEstimator(const Selector &rho_range, const JetDefinition &jet_def, const AreaDefinition &area_def) : _rho_range(rho_range), _jet_def(jet_def), _area_def(area_def) { // initialise things decently reset(); // make a few checks _check_jet_alg_good_for_median(); } //---------------------------------------------------------------------- // ctor from a cluster sequence // - csa the ClusterSequenceArea to use // - rho_range the Selector specifying which jets will be considered JetMedianBackgroundEstimator::JetMedianBackgroundEstimator( const Selector &rho_range, const ClusterSequenceAreaBase &csa) : _rho_range(rho_range), _jet_def(JetDefinition()){ // initialise things properly reset(); // tell the BGE about the cluster sequence set_cluster_sequence(csa); } //---------------------------------------------------------------------- // setting a new event //---------------------------------------------------------------------- // tell the background estimator that it has a new event, composed // of the specified particles. void JetMedianBackgroundEstimator::set_particles(const vector<PseudoJet> & particles) { // make sure that we have been provided a genuine jet definition if (_jet_def.jet_algorithm() == undefined_jet_algorithm) throw Error("JetMedianBackgroundEstimator::set_particles can only be called if you set the jet (and area) definition explicitly through the class constructor"); // initialise things decently (including setting uptodate to false!) //reset(); _uptodate=false; // cluster the particles // // One may argue that it is better to cache the particles and only // do the clustering later but clustering the particles now has 2 // practical advantages: // - it allows to une only '_included_jets' in all that follows // - it avoids adding another flag to ensure particles are // clustered only once ClusterSequenceArea *csa = new ClusterSequenceArea(particles, _jet_def, _area_def); _included_jets = csa->inclusive_jets(); // store the CS for later on _csi = csa->structure_shared_ptr(); csa->delete_self_when_unused(); } //---------------------------------------------------------------------- // (re)set the cluster sequence (with area support) to be used by // future calls to rho() etc. // // \param csa the cluster sequence area // // Pre-conditions: // - one should be able to estimate the "empty area" (i.e. the area // not occupied by jets). This is feasible if at least one of the following // conditions is satisfied: // ( i) the ClusterSequence has explicit ghosts // (ii) the range selected has a computable area. // - the jet algorithm must be suited for median computation // (otherwise a warning will be issues) // // Note that selectors with e.g. hardest-jets exclusion do not have // a well-defined area. For this reasons, it is STRONGLY advised to // use an area with explicit ghosts. void JetMedianBackgroundEstimator::set_cluster_sequence(const ClusterSequenceAreaBase & csa) { _csi = csa.structure_shared_ptr(); // sanity checks //--------------- // (i) check the alg is appropriate _check_jet_alg_good_for_median(); // (ii) check that, if there are no explicit ghosts, the selector has a finite area if ((!csa.has_explicit_ghosts()) && (!_rho_range.has_finite_area())){ throw Error("JetMedianBackgroundEstimator: either an area with explicit ghosts (recommended) or a Selector with finite area is needed (to allow for the computation of the empty area)"); } // get the initial list of jets _included_jets = csa.inclusive_jets(); _uptodate = false; } //---------------------------------------------------------------------- // (re)set the jets (which must have area support) to be used by future // calls to rho() etc.; for the conditions that must be satisfied // by the jets, see the Constructor that takes jets. void JetMedianBackgroundEstimator::set_jets(const vector<PseudoJet> &jets) { if (! jets.size()) throw Error("JetMedianBackgroundEstimator::JetMedianBackgroundEstimator: At least one jet is needed to compute the background properties"); // sanity checks //--------------- // (o) check that there is an underlying CS shared by all the jets if (! (jets[0].has_associated_cluster_sequence()) && (jets[0].has_area())) throw Error("JetMedianBackgroundEstimator::JetMedianBackgroundEstimator: the jets used to estimate the background properties must be associated with a valid ClusterSequenceAreaBase"); _csi = jets[0].structure_shared_ptr(); ClusterSequenceStructure * csi = dynamic_cast<ClusterSequenceStructure*>(_csi()); const ClusterSequenceAreaBase * csab = csi->validated_csab(); for (unsigned int i=1;i<jets.size(); i++){ if (! jets[i].has_associated_cluster_sequence()) // area automatic if the next test succeeds throw Error("JetMedianBackgroundEstimator::set_jets(...): the jets used to estimate the background properties must be associated with a valid ClusterSequenceAreaBase"); if (jets[i].structure_shared_ptr().get() != _csi.get()) throw Error("JetMedianBackgroundEstimator::set_jets(...): all the jets used to estimate the background properties must share the same ClusterSequence"); } // (i) check the alg is appropriate _check_jet_alg_good_for_median(); // (ii) check that, if there are no explicit ghosts, the selector has a finite area if ((!csab->has_explicit_ghosts()) && (!_rho_range.has_finite_area())){ throw Error("JetMedianBackgroundEstimator: either an area with explicit ghosts (recommended) or a Selector with finite area is needed (to allow for the computation of the empty area)"); } // get the initial list of jets _included_jets = jets; // ensure recalculation of quantities that need it _uptodate = false; } //---------------------------------------------------------------------- // retrieving fundamental information //---------------------------------------------------------------- // get rho, the median background density per unit area double JetMedianBackgroundEstimator::rho() const { if (_rho_range.takes_reference()) throw Error("The background estimation is obtained from a selector that takes a reference jet. rho(PseudoJet) should be used in that case"); _recompute_if_needed(); return _rho; } // get sigma, the background fluctuations per unit area double JetMedianBackgroundEstimator::sigma() const { if (_rho_range.takes_reference()) throw Error("The background estimation is obtained from a selector that takes a reference jet. rho(PseudoJet) should be used in that case"); _recompute_if_needed(); return _sigma; } // get rho, the median background density per unit area, locally at // the position of a given jet. // // If the Selector associated with the range takes a reference jet // (i.e. is relocatable), then for subsequent operations the // Selector has that jet set as its reference. double JetMedianBackgroundEstimator::rho(const PseudoJet & jet) { _recompute_if_needed(jet); double our_rho = _rho; if (_rescaling_class != 0) { our_rho *= (*_rescaling_class)(jet); } return our_rho; } // get sigma, the background fluctuations per unit area, // locally at the position of a given jet. // // If the Selector associated with the range takes a reference jet // (i.e. is relocatable), then for subsequent operations the // Selector has that jet set as its reference. double JetMedianBackgroundEstimator::sigma(const PseudoJet &jet) { _recompute_if_needed(jet); double our_sigma = _sigma; if (_rescaling_class != 0) { our_sigma *= (*_rescaling_class)(jet); } return our_sigma; } //---------------------------------------------------------------------- // configuring behaviour //---------------------------------------------------------------------- // reset to default values // // set the variou options to their default values void JetMedianBackgroundEstimator::reset(){ // set the remaining default parameters set_use_area_4vector(); // true by default set_provide_fj2_sigma(false); // reset the computed values _rho = _sigma = 0.0; _n_jets_used = _n_empty_jets = 0; _empty_area = _mean_area = 0.0; _included_jets.clear(); _jet_density_class = 0; // null pointer _rescaling_class = 0; // null pointer _uptodate = false; } // Set a pointer to a class that calculates the quantity whose // median will be calculated; if the pointer is null then pt/area // is used (as occurs also if this function is not called). void JetMedianBackgroundEstimator::set_jet_density_class(const FunctionOfPseudoJet<double> * jet_density_class) { _warnings_preliminary.warn("JetMedianBackgroundEstimator::set_jet_density_class: density classes are still preliminary in FastJet 3.0. Their interface may differ in future releases (without guaranteeing backward compatibility)."); _jet_density_class = jet_density_class; _uptodate = false; } //---------------------------------------------------------------------- // description //---------------------------------------------------------------------- string JetMedianBackgroundEstimator::description() const { ostringstream desc; desc << "JetMedianBackgroundEstimator, using " << _jet_def.description() << " with " << _area_def.description() << " and selecting jets with " << _rho_range.description(); return desc.str(); } //---------------------------------------------------------------------- // computation of the background properties //---------------------------------------------------------------------- // for estimation using a relocatable selector (i.e. local range) // this allows to set its position. Note that this HAS to be called // before any attempt to compute the background properties void JetMedianBackgroundEstimator::_recompute_if_needed(const PseudoJet &jet){ // if the range is relocatable, handles its relocation if (_rho_range.takes_reference()){ // check that the reference is not the same as the previous one // (would avoid an unnecessary recomputation) if (jet == _current_reference) return; // relocate the range and make sure things get recomputed the next // time one tries to get some information _rho_range.set_reference(jet); _uptodate=false; } _recompute_if_needed(); } // do the actual job void JetMedianBackgroundEstimator::_compute() const { // check if the clustersequence is still valid _check_csa_alive(); // fill the vector of pt/area (or the quantity from the jet density class) // - in the range vector<double> vector_for_median; double total_area = 0.0; _n_jets_used = 0; // apply the selector to the included jets vector<PseudoJet> selected_jets = _rho_range(_included_jets); // compute the pt/area for the selected jets for (unsigned i = 0; i < selected_jets.size(); i++) { const PseudoJet & current_jet = selected_jets[i]; double this_area = (_use_area_4vector) ? current_jet.area_4vector().perp() : current_jet.area(); if (this_area>0){ double median_input; if (_jet_density_class == 0) { median_input = current_jet.perp()/this_area; } else { median_input = (*_jet_density_class)(current_jet); } if (_rescaling_class != 0) { median_input /= (*_rescaling_class)(current_jet); } vector_for_median.push_back(median_input); total_area += this_area; _n_jets_used++; } else { _warnings_zero_area.warn("JetMedianBackgroundEstimator::_compute(...): discarded jet with zero area. Zero-area jets may be due to (i) too large a ghost area (ii) a jet being outside the ghost range (iii) the computation not being done using an appropriate algorithm (kt;C/A)."); } } // there is nothing inside our region, so answer will always be zero if (vector_for_median.size() == 0) { _rho = 0.0; _sigma = 0.0; _mean_area = 0.0; return; } // determine the number of empty jets const ClusterSequenceAreaBase * csab = (dynamic_cast<ClusterSequenceStructure*>(_csi()))->validated_csab(); if (csab->has_explicit_ghosts()) { _empty_area = 0.0; _n_empty_jets = 0; } else { _empty_area = csab->empty_area(_rho_range); _n_empty_jets = csab->n_empty_jets(_rho_range); } double total_njets = _n_jets_used + _n_empty_jets; total_area += _empty_area; double stand_dev; _median_and_stddev(vector_for_median, _n_empty_jets, _rho, stand_dev, _provide_fj2_sigma); // process and store the results (_rho was already stored above) _mean_area = total_area / total_njets; _sigma = stand_dev * sqrt(_mean_area); // record that the computation has been performed _uptodate = true; } // check that the underlying structure is still alive; // throw an error otherwise void JetMedianBackgroundEstimator::_check_csa_alive() const{ ClusterSequenceStructure* csa = dynamic_cast<ClusterSequenceStructure*>(_csi()); if (csa == 0) { throw Error("JetMedianBackgroundEstimator: there is no cluster sequence associated with the JetMedianBackgroundEstimator"); } if (! dynamic_cast<ClusterSequenceStructure*>(_csi())->has_associated_cluster_sequence()) throw Error("JetMedianBackgroundEstimator: modifications are no longer possible as the underlying ClusterSequence has gone out of scope"); } // check that the algorithm used for the clustering is suitable for // background estimation (i.e. either kt or C/A). // Issue a warning otherwise void JetMedianBackgroundEstimator::_check_jet_alg_good_for_median() const{ const JetDefinition * jet_def = &_jet_def; // if no explicit jet def has been provided, fall back on the // cluster sequence if (_jet_def.jet_algorithm() == undefined_jet_algorithm){ const ClusterSequence * cs = dynamic_cast<ClusterSequenceStructure*>(_csi())->validated_cs(); jet_def = &(cs->jet_def()); } if (jet_def->jet_algorithm() != kt_algorithm && jet_def->jet_algorithm() != cambridge_algorithm && jet_def->jet_algorithm() != cambridge_for_passive_algorithm) { _warnings.warn("JetMedianBackgroundEstimator: jet_def being used may not be suitable for estimating diffuse backgrounds (good alternatives are kt, cam)"); } } FASTJET_END_NAMESPACE
38.782022
284
0.668849
[ "vector" ]
0de2a4a837ae661ea9ddf104d72c979e224a1d47
1,868
cc
C++
src/0027_remove_element/remove_element.cc
youngqqcn/LeetCodeNodes
62bbd30fbdf1640526d7fc4437cde1b05d67fc8f
[ "MIT" ]
1
2021-05-23T02:15:03.000Z
2021-05-23T02:15:03.000Z
src/0027_remove_element/remove_element.cc
youngqqcn/LeetCodeNotes
62bbd30fbdf1640526d7fc4437cde1b05d67fc8f
[ "MIT" ]
null
null
null
src/0027_remove_element/remove_element.cc
youngqqcn/LeetCodeNotes
62bbd30fbdf1640526d7fc4437cde1b05d67fc8f
[ "MIT" ]
null
null
null
// author: yqq // date: 2021-05-27 20:49:31 // descriptions: #include <iostream> #include <vector> #include <set> using namespace std; class Solution { public: // 暴力查找 // int removeElement(vector<int> &nums, int val) // { // int i = 0; // int removed_count = 0; // 已经移除的元素个数 // for (; i + removed_count < nums.size();) // { // if (val == nums[i]) // { // for (int j = i; j < nums.size() - removed_count - 1; j++) // { // nums[j] = nums[j + 1]; // } // removed_count++; // continue; // } // i++; // } // return nums.size() - removed_count; // } // 双指针法 int removeElement(vector<int> &nums, int val) { int slow_idx = 0; for(int fast_idx = 0; fast_idx < nums.size(); fast_idx++) { if(val != nums[fast_idx]) { nums[slow_idx] = nums[fast_idx]; slow_idx++; } } return slow_idx; } }; void test(vector<int> nums, int val, vector<int> expected) { Solution sol; int len = sol.removeElement(nums, val); if (len != expected.size()) { for (auto item : nums) { cout << item << ","; } cout << endl; cout << "FAILED" << endl; return; } set<int> newNums(nums.begin(), nums.begin() + len); for (int i = 0; i < len; i++) { if (newNums.find(expected[i]) == newNums.end()) { cout << "FAILED" << endl; return; } } cout << "PASSED" << endl; } int main() { test({3, 2, 2, 3}, 3, {2, 2}); test({0, 1, 2, 2, 3, 0, 4, 2}, 2, {0, 1, 4, 0, 3}); // cout << "hello world" << endl; return 0; }
22.238095
76
0.422377
[ "vector" ]
0df38439bf1b1fd719b0a3b7f23e404fcb566d9b
788
cpp
C++
ex_agorithm/chips.cpp
chaixiang2002/code-works
1c8a61a2dc29e755dd16e48d49d7b4a03b91973e
[ "Unlicense" ]
null
null
null
ex_agorithm/chips.cpp
chaixiang2002/code-works
1c8a61a2dc29e755dd16e48d49d7b4a03b91973e
[ "Unlicense" ]
null
null
null
ex_agorithm/chips.cpp
chaixiang2002/code-works
1c8a61a2dc29e755dd16e48d49d7b4a03b91973e
[ "Unlicense" ]
null
null
null
#include <iostream> #include <vector> #include "e2.hpp" using namespace std; void conquer(vector<chip>& chips){ if(chips.size()==1){ return; } vector<chip>::iterator fast; vector<chip>::iterator slow; fast=chips.begin(); ++fast; slow=chips.begin(); while (slow!=chips.end() && fast!=chips.end()) { vector<chip>::iterator tmp; if(fast->test_to(*slow) && slow->test_to(*fast)){ auto iter=chips.erase(slow); ++slow; ++fast; } else { fast=chips.erase(fast); slow=chips.erase(slow); } } conquer(chips); } int main(){ vector<chip> chips; insert_test(chips); //vector<chip> res;//vv conquer(chips); print_all(chips); return 0; }
21.297297
57
0.541878
[ "vector" ]
0df7dcea4b8b403fae2952562978a39a116bb46a
2,268
cpp
C++
modules/task_2/yashina_d_linear_block_filtration_omp/main.cpp
allnes/pp_2022_spring
159191f9c2f218f8b8487f92853cc928a7652462
[ "BSD-3-Clause" ]
null
null
null
modules/task_2/yashina_d_linear_block_filtration_omp/main.cpp
allnes/pp_2022_spring
159191f9c2f218f8b8487f92853cc928a7652462
[ "BSD-3-Clause" ]
null
null
null
modules/task_2/yashina_d_linear_block_filtration_omp/main.cpp
allnes/pp_2022_spring
159191f9c2f218f8b8487f92853cc928a7652462
[ "BSD-3-Clause" ]
2
2022-03-31T17:48:22.000Z
2022-03-31T18:06:07.000Z
// Copyright 2018 Nesterov Alexander #include <gtest/gtest.h> #include <vector> #include "./yashina_d_linear_block_filtration_omp.h" TEST(Omp, Test_img_1) { int weight = 10; int height = 10; double* m = create_random_kernel(3, 3.0); std::vector< std::vector<double> >image(height); getRandomImg(&image, weight, height); ASSERT_NO_THROW(getParallelOperations(&image, m, weight, height)); delete[] m; } TEST(Omp, Test_img_2) { int weight = 12; int height = 10; double* m = create_random_kernel(3, 3.0); std::vector< std::vector<double> >image(height); getRandomImg(&image, weight, height); std::vector< std::vector<double> > copy_image(image); getSequentialOperations(&image, m, weight, height); getParallelOperations(&copy_image, m, weight, height); ASSERT_EQ(image, copy_image); delete[] m; } TEST(Omp, Test_img_3) { int weight = 12; int height = 10; double* m = create_random_kernel(3, 3.0); std::vector< std::vector<double> >image(height); getRandomImg(&image, weight, height); std::vector< std::vector<double> > copy_image(image); getSequentialOperations(&image, m, weight, height); getParallelOperations(&copy_image, m, weight, height); ASSERT_EQ(image, copy_image); delete[] m; } TEST(Omp, Test_img_4) { int weight = 12; int height = 10; double* m = create_random_kernel(3, 3.0); std::vector< std::vector<double> >image(height); getRandomImg(&image, weight, height); std::vector< std::vector<double> > copy_image(image); getSequentialOperations(&image, m, weight, height); getParallelOperations(&copy_image, m, weight, height); ASSERT_EQ(image, copy_image); delete[] m; } TEST(Omp, Test_img_5) { int weight = 12; int height = 10; double* m = create_random_kernel(3, 3.0); std::vector< std::vector<double> >image(height); getRandomImg(&image, weight, height); std::vector< std::vector<double> > copy_image(image); getSequentialOperations(&image, m, weight, height); getParallelOperations(&copy_image, m, weight, height); ASSERT_EQ(image, copy_image); delete[] m; } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
32.869565
70
0.671076
[ "vector" ]
0dfda019f56f0f5b867e429513eea5f6b8465e47
29,846
cc
C++
src/Molecule_Lib/reaction_from_smirks.cc
michaelweiss092/LillyMol
a2b7d1d8a07ef338c754a0a2e3b2624aac694cc9
[ "Apache-2.0" ]
53
2018-06-01T13:16:15.000Z
2022-02-23T21:04:28.000Z
src/Molecule_Lib/reaction_from_smirks.cc
michaelweiss092/LillyMol
a2b7d1d8a07ef338c754a0a2e3b2624aac694cc9
[ "Apache-2.0" ]
19
2018-08-14T13:43:18.000Z
2021-09-24T12:53:11.000Z
src/Molecule_Lib/reaction_from_smirks.cc
michaelweiss092/LillyMol
a2b7d1d8a07ef338c754a0a2e3b2624aac694cc9
[ "Apache-2.0" ]
19
2018-10-23T19:41:01.000Z
2022-02-17T08:14:00.000Z
#include <stdlib.h> #include <memory> #include "misc.h" //#define TESTING_STUFF #ifdef TESTING_STUFF #include "cmdline.h" #include "aromatic.h" #endif #include "iwreaction.h" #include "molecule_to_query.h" static int smirks_lost_atom_means_remove_frgment = 0; void set_smirks_lost_atom_means_remove_frgment(int s) { smirks_lost_atom_means_remove_frgment = s; } int IWReaction::construct_from_smirks(const const_IWSubstring & smirks) { if (! smirks.starts_with("F:")) return _construct_from_smirks(smirks); IWString fname(smirks); fname.remove_leading_chars(2); iwstring_data_source input(fname.null_terminated_chars()); if (! input.good()) { cerr << "IWReaction::construct_from_smirks:cannot open '" << fname << "'\n"; return 0; } const_IWSubstring buffer; if (! input.next_record(buffer)) { cerr << "IWReaction::const_IWSubstring:cannot read smirks from '" << fname << "'\n"; return 0; } return _construct_from_smirks(buffer); } int IWReaction::_construct_from_smirks(const const_IWSubstring & smirks) { int square_bracket_level = 0; const int n = smirks.length(); int first_open_angle = -1; int second_open_angle = -1; for (int i = 0; i < n; ++i) { const char c = smirks[i]; if (']' == c) square_bracket_level--; else if ('[' == c) square_bracket_level++; else if (0 == square_bracket_level && '>' == c) { if (first_open_angle < 0) first_open_angle = i; else { second_open_angle = i; break; } } } if (second_open_angle < 0) { cerr << "IWReaction::build_from_smirks:yipes, did not find >> construct '" << smirks << "'\n"; return 0; } const_IWSubstring reagents, products; smirks.from_to(0, first_open_angle - 1, reagents); //cerr << "Reagents " << reagents << endl; smirks.from_to(second_open_angle + 1, smirks.length() - 1, products); //cerr << "products " << products << endl; return construct_from_smirks(reagents, products); } void fetch_closing_paren(const_IWSubstring & buffer, IWString & token) { int paren_level = 1; for (auto i = 1; i < buffer.length(); ++i) { const auto c = buffer[i]; if ('(' == c) paren_level++; else if (')' == c) { paren_level--; if (0 == paren_level) { buffer.from_to(1, i-1, token); buffer += i; return; } } } cerr << "fetch_closing_paren:did not find closing paren '" << buffer << "'\n"; // should not happen return; } /* We try to match the Daylight component level grouping thing, WITH THE EXCEPTION OF THE ZERO LEVEL CONCEPT So, (smarts1.smarts2).smarts3 means smarts1 and smarts2 must be in the scaffold, and smarts3 is in the sidechain. */ static int tokenise_smarts_into_components(const_IWSubstring smarts, // pass by value resizable_array_p<IWString> & components) { //cerr << "Smarts '" << smarts << "'\n"; while (smarts.length() > 0) { // cerr << " smarts '" << smarts << "'\n"; if (smarts.starts_with('(')) { IWString * c = new IWString; fetch_closing_paren(smarts, *c); components.add(c); smarts++; if (smarts.starts_with('.')) smarts++; } else { IWString * s = new IWString; // cerr << "Check " << smarts.length() << " characters\n"; for (int i = 0; i < smarts.length(); ++i) { const char c = smarts[i]; if ('.' != c) { s->add(c); continue; } if (smarts.matches_at_position(i, "...", 3)) { *s << "..."; i += 2; continue; } // cerr << "Found '" << *s << "'\n"; components.add(s); smarts += i; // cerr << "Smarts updated to " << smarts << endl; break; } if (s->length()) { components.add(s); smarts += s->length(); } } } return components.number_elements(); } #ifdef NO_LONGER_USED_JJJJJ static void file_scope_identify_atom_map_numbers(const Substructure_Query & q, extending_resizable_array<int> & numbers_in_use) { for (int i = 0; i < q.number_elements(); ++i) { q[i]->identify_atom_map_numbers(numbers_in_use); } return; } static void file_scope_identify_atom_map_numbers(const Molecule & m, extending_resizable_array<int> & numbers_in_use) { const int matoms = m.natoms(); for (int i = 0; i < matoms; ++i) { const auto a = m.atom_map_number(i); if (0 == a) continue; numbers_in_use[a]++; } return; } #endif int IWReaction::construct_from_smirks(const const_IWSubstring & reagents, const const_IWSubstring & products) { if (0 != reagents.balance('(', ')')) { cerr << "IWReaction::construct_from_smirks:unbalanced parentheses in reagent specification '" << reagents << "'\n"; return 0; } resizable_array_p<IWString> smarts; if (! tokenise_smarts_into_components(reagents, smarts)) { cerr << "IWReaction::construct_from_smirks:cannot separate reagent smarts\n"; return 0; } //#define DEBUG_SMIRKS_TOKENISING #ifdef DEBUG_SMIRKS_TOKENISING cerr << "From '" << reagents << "' generate\n"; for (auto i = 0; i < smarts.number_elements(); ++i) { const IWString & s = *(smarts[i]); cerr << ' ' << s << '\n'; } #endif const IWString & s = *(smarts[0]); if (! this->create_from_smarts(s)) { cerr << "IWReaction::construct_from_smirks:cannot interpret scaffold smarts '" << s << "'\n"; return 0; } for (auto i = 1; i < smarts.number_elements(); ++i) { Sidechain_Reaction_Site * r = new Sidechain_Reaction_Site; if (! r->create_from_smarts(*smarts[i])) { cerr << "IWReaction::construct_from_smirks:invalid sidechain smarts '" << (*smarts[i]) << "'\n"; delete r; return 0; } _sidechains.add(r); } Substructure_Query product_molecule; if (! product_molecule.create_from_smarts(products)) { cerr << "IWReaction::construct_from_smirks:invalid product " << products << endl; return 0; } // the RHS cannot contain ambiguous elements if (product_molecule.any_query_atom([] (const Substructure_Atom * q) { if (q->element().number_elements() > 1) return 1; else return 0; })) { cerr << "IWReaction::_identify_changes_from_smirks:RHS has multiple elements, impossible\n"; return 0; } // GAther up all the atom map numbers that are in use on both sides extending_resizable_array<int> ramn; // reagent atom map numbers this->identify_atom_map_numbers(ramn); const auto ns = _sidechains.number_elements(); for (int i = 0; i < ns; ++i) { _sidechains[i]->identify_atom_map_numbers(ramn); } #ifdef DEBUG_CONSTRUCT_FROM_SMIRKS cerr << "Reagent atom numbers"; for (int i = 0; i < ramn.number_elements(); ++i) { if (ramn[i] > 0) cerr << ' ' << i; } cerr << endl; #endif // On the LHS, each atom map number must be used once int h = 0; // highest atom man number in use for (int i = 1; i < ramn.number_elements(); ++i) { if (0 == ramn[i]) continue; h = i; if (1 == ramn[i]) continue; cerr << "IWReaction::construct_from_smirks:atom map number " << i << " found " << ramn[i] << " occurrences\n"; return 0; } const int h2 = product_molecule.highest_atom_map_number(); if (h2 > h) h = h2; #ifdef DEBUG_CONSTRUCT_FROM_SMIRKS cerr << "Highest atom map number in use " << h << endl; #endif // We need to assign atom map numbers to unmapped atoms in the product. These are, by definition // orphan atoms. product_molecule.assign_atom_map_numbers(h); #ifdef DEBUG_CONSTRUCT_FROM_SMIRKS cerr << "After assigning atom map number to product atoms, h = " << h << endl; #endif // Ensure that all atom numbers are present. Identify any orphans - atoms in the products that // do not have a corresponding atom in the reagents extending_resizable_array<int> pamn(0); product_molecule.identify_atom_map_numbers(pamn); if (0 == pamn.number_elements()) { cerr << "IWReaction::construct_from_smirks:No mapped atoms on RHS, cannot continue\n"; return 0; } int istop = h + 1; resizable_array<int> orphan_atoms; for (int i = 1; i < istop; i++) { #ifdef DEBUG_CONSTRUCT_FROM_SMIRKS cerr << "i = " << i << " ran " << ramn[i] << " pan " << pamn[i] << endl; #endif if (1 == ramn[i] && 1 == pamn[i]) // one occurrence on LHS and RHS continue; if (0 == ramn[i] && 0 == pamn[i]) // atom map number not used either side, OK continue; if (ramn[i] == pamn[i]) // equal, but not 1, bad { cerr << "IWReaction::construct_from_smirks:atom map " << i << " used " << ramn[i] << " in reagents and " << pamn[i] << " in products\n"; return 0; } if (1 == ramn[i] && 0 == pamn[i]) // atom disappears, this is OK continue; if (0 == ramn[i] && 1 == pamn[i]) { orphan_atoms.add(i); continue; } cerr << "IWReaction::construct_from_smirks:atom number mismatch, atom " << i << " in reagents " << ramn[i] << " in products " << pamn[i] << endl; return 0; } Molecule orphan_molecule; if (orphan_atoms.number_elements()) { Sidechain_Reaction_Site * x = new Sidechain_Reaction_Site(); if (! _create_orphan_molecule(orphan_atoms, orphan_molecule, product_molecule, *x)) { cerr << "IWReaction::_identify_changes_from_smirks:cannot construct orphan molecule, has " << orphan_atoms.number_elements() << " orphan atoms\n"; delete x; return 0; } _sidechains.add(x); } for (int i = 0; i < _sidechains.number_elements(); ++i) { _sidechains[i]->set_sidechain_number(i); } IWString foo ("FOO.qry"); product_molecule.write_msi(foo); return _identify_changes_from_smirks(ramn, h+1, orphan_molecule, product_molecule); } static int add_bond_to_orphan(Molecule & orphan_molecule, const atom_number_t a1, const atom_number_t a2, const Substructure_Bond * b) { if (orphan_molecule.are_bonded(a1, a2)) // this process will find most bonds twice return 0; const bond_type_t bt = b->types_matched(); if (IS_SINGLE_BOND(bt)) orphan_molecule.add_bond(a1, a2, SINGLE_BOND); else if (IS_DOUBLE_BOND(bt)) orphan_molecule.add_bond(a1, a2, DOUBLE_BOND); else if (IS_TRIPLE_BOND(bt)) orphan_molecule.add_bond(a1, a2, TRIPLE_BOND); else { cerr << "IWReaction::_create_orphan_molecule:bond type not unitary form " << bt << ", assuming single bond!!\n"; orphan_molecule.add_bond(a1, a2, SINGLE_BOND); } return 1; } int IWReaction::_create_orphan_molecule(const resizable_array<int> & orphan_atoms, // atom map numbers Molecule & orphan_molecule, const Substructure_Query & product_molecule, Sidechain_Reaction_Site & sc) { const int n = orphan_atoms.number_elements(); const int mx = orphan_atoms.max_val(); // convenient to have two cross reference arrays int * mol2qry = new int[n];std::unique_ptr<int[]> free_mol2qry(mol2qry); int * amap2mol = new_int(mx + 1, -1); std::unique_ptr<int[]> free_amap2mol(amap2mol); const Substructure_Atom ** query_atoms = new const Substructure_Atom *[n]; std::unique_ptr<const Substructure_Atom *[]> free_query_atoms(query_atoms); //resizable_array<const Substructure_Atom *> query_atoms; for (int i = 0; i < orphan_atoms.number_elements(); ++i) { const int oi = orphan_atoms[i]; const Substructure_Atom * qi = product_molecule.query_atom_with_atom_map_number(oi); const Substructure_Atom_Specifier * si; if (qi->ncomponents() > 0) // was complex smarts si = qi->component(0); else // was simple si = qi; assert (NULL != qi); const auto & e = si->element(); if (0 == e.number_elements()) { cerr << "IWReaction::_create_orphan_molecule:RHS orphan atom has no element specified, impossible. Atom map " << oi << endl; return 0; } const int x = orphan_molecule.natoms(); query_atoms[x] = qi; // the X'th query atom amap2mol[oi] = x; // atom map OI is atom X in molecule orphan_molecule.add(e[0]); orphan_molecule.set_atom_map_number(x, oi); const auto & iso = si->isotope(); if (iso.number_elements() > 0) orphan_molecule.set_isotope(x, iso[0]); const auto & fc = si->formal_charge(); if (fc.number_elements() > 0) orphan_molecule.set_formal_charge(x, fc[0]); } // Now the atoms have been added do the bonds. We need to handle both bonds within the orphan // atoms, and bonds to other parts of the products for (int i = 0; i < orphan_atoms.number_elements(); ++i) { const Substructure_Atom * qi = query_atoms[i]; const int nc = qi->number_children(); for (int j = 0; j < nc; ++j) // scan all atoms attached to the corresponding query atom { const Substructure_Atom * c = qi->child(j); const Substructure_Bond * b = c->bond_to_parent(); const int atom_number_in_orphan = amap2mol[c->atom_map_number()]; if (atom_number_in_orphan >= 0) add_bond_to_orphan(orphan_molecule, i, atom_number_in_orphan, b); } const auto & bonds = qi->bonds(); for (int j = 0; j < bonds.number_elements(); ++j) { const Substructure_Bond * b = bonds[j]; const Substructure_Atom * a = b->a(); const int atom_number_in_orphan = amap2mol[a->atom_map_number()]; if (atom_number_in_orphan >= 0) add_bond_to_orphan(orphan_molecule, i, atom_number_in_orphan, b); } } sc.set_single_reagent(orphan_molecule); #ifdef DEBUG_CONSTRUCT_FROM_SMIRKS cerr << "Build orphan molecule " << orphan_molecule.smiles() << endl; #endif return 1; } /* There appear to be two fundamentally different type of products. if all product atoms are mapped to a query atom on the LHS, this reaction can be used for enumerations of numerous reagents. If there are orphan atoms on the RHS, not present on the LHS, then we must assume this is a fixed reagent sidechain. As we look at the molecules on the RHS, there will be two kinds of atoms. Those with a corresponding atom number on the reagent side. For those we just set the element, charge and isotope. Those which do not appear on the reagent side. for these, we must figure out how they are attached to those that appear on the LHS */ int IWReaction::_identify_changes_from_smirks(const extending_resizable_array<int> & atom_map_numbers_in_reagents, const int istop, const Molecule & orphan_molecule, const Substructure_Query & product_molecule) { #ifdef DEBUG_CONSTRUCT_FROM_SMIRKS cerr << "IWReaction::_identify_changes_from_smirks:must examine " << istop << " mapped atoms\n"; product_molecule.print_connectivity_graph(cerr); #endif resizable_array<int> atoms_lost; for (int i = 0; i < istop; i++) { // cerr << "Atom map i " << i << " mapped in reagents " << atom_map_numbers_in_reagents[i] << endl; if (atom_map_numbers_in_reagents[i] <= 0) // atom map number not present on LHS, orphan continue; Reaction_Site * r1 = _reaction_site_with_atom_map_number(i); assert (NULL != r1); const Substructure_Atom * q1 = r1->query_atom_with_atom_map_number(i); assert (NULL != q1); const Substructure_Atom * q2 = product_molecule.query_atom_with_atom_map_number(i); if (NULL == q2) // atom eliminated in products atoms_lost.add(i); else _discern_atomic_changes(*r1, *q1, *q2); } if (atoms_lost.number_elements()) { for (int i = 0; i < atoms_lost.number_elements(); ++i) { const int j = atoms_lost[i]; Reaction_Site * r = _reaction_site_with_atom_map_number(j); assert (NULL != r); const Substructure_Atom * s = r->query_atom_with_atom_map_number(j); assert (NULL != s); const int x = s->initial_atom_number(); if (smirks_lost_atom_means_remove_frgment) r->add_fragment_to_be_removed(x); else r->add_atom_to_be_removed(x); } } #ifdef DEBUG_CONSTRUCT_FROM_SMIRKS for (int i = 1; i < istop; ++i) { cerr << i << " atom_map_numbers_in_reagents " << atom_map_numbers_in_reagents[i] << endl; } #endif // Any bond changes. this must be done on a per sidechain basis because there may be bonding // changes that occur just within a given sidechain // e.g. ([CH3:1].[NH2D1:2]).[OH:3]-[C:4]=[O:5]>>[CH2:1]-[NH:2]-[C:4]=[O:5] for (int i = 0; i < istop; i++) { // cerr << i << " atom_map_numbers_in_reagents " << atom_map_numbers_in_reagents[i] << endl; Reaction_Site * i_site = _reaction_site_with_atom_map_number(i); // may be NULL for (int j = i + 1; j < istop; j++) { // cerr << i << ',' << j << " atom_map_numbers_in_reagents " << atom_map_numbers_in_reagents[i] << " j " << ' ' << atom_map_numbers_in_reagents[j] << endl; if (atom_map_numbers_in_reagents[i] <= 0 && atom_map_numbers_in_reagents[j] <= 0) // numbers not used continue; Reaction_Site * j_site = _reaction_site_with_atom_map_number(j); // may be NULL if (NULL == i_site && NULL == j_site) // should not happen continue; const Substructure_Bond * bonded_in_product = product_molecule.bond_between_atom_map_numbers(i, j); // cerr << "Between mapped atoms " << i << " and " << j << " bnd " << bonded_in_product << " Product\n"; const Substructure_Bond * bonded_in_reagent; if (i_site == j_site) // two mapped atoms in same reagent bonded_in_reagent = i_site->bond_between_atom_map_numbers(i, j); else // not in same reagent, therefore not bonded bonded_in_reagent = NULL; // cerr << "bonded? " << bonded_in_reagent << ' ' << bonded_in_product << endl; if (NULL == bonded_in_reagent && NULL == bonded_in_product) // no bond btw I and J either side continue; bond_type_t btr = NULL == bonded_in_reagent ? INVALID_BOND_TYPE : BOND_TYPE_ONLY(bonded_in_reagent->types_matched()); bond_type_t btp = NULL == bonded_in_product ? INVALID_BOND_TYPE : BOND_TYPE_ONLY(bonded_in_product->types_matched()); if (btr == btp) // same bond type, no need to change anything continue; // the bonding changes. Is it a removal, an addition or a change? What components are involved? // cerr << "Between atoms " << i << " and " << j << " reagent? " << bonded_in_reagent << " (" << btr << ") products " << bonded_in_product << " (" << btp << ")\n"; // cerr << "Sites " << i_site << " and " << j_site << endl; if (i_site == j_site) // new/changed or removed bond in the same component { const Substructure_Atom * ai = i_site->query_atom_with_atom_map_number(i); const Substructure_Atom * aj = j_site->query_atom_with_atom_map_number(j); // cerr << "Atom numbers " << ai->initial_atom_number() << " and " << aj->initial_atom_number() << " xBTP " << btp << endl; if (INVALID_BOND_TYPE == btp) // bond is removed i_site->add_bond_to_be_broken(ai->initial_atom_number(), aj->initial_atom_number()); else // new or changed i_site->add_bond_to_be_made(ai->initial_atom_number(), aj->initial_atom_number(), btp); continue; } if (NULL != i_site && NULL != j_site) // new inter partile bond btw existing reagents { // cerr << "Adding inter particle bond btw " << i << " and " << j << endl; if (! _from_smirks_add_inter_particle_bond(i, i_site, j, j_site, btp)) return 0; continue; } // One of these atom map numbers is not present on the LHS // cerr << "Bond involves different sites. I " << i_site << " J " << j_site << " type " << btp << endl; assert (INVALID_BOND_TYPE != btp); if (NULL == i_site) { const Substructure_Atom * q2 = j_site->query_atom_with_atom_map_number(j); const atom_number_t x2 = q2->initial_atom_number(); const atom_number_t x1 = orphan_molecule.atom_with_atom_map_number(i); const int r = _sidechain_with_mapped_atom(j); _sidechains.last_item()->add_inter_particle_bond(r, x2, x1, btp); } else if (NULL == j_site) { const Substructure_Atom * q1 = i_site->query_atom_with_atom_map_number(i); const atom_number_t x1 = q1->initial_atom_number(); const atom_number_t x2 = orphan_molecule.atom_with_atom_map_number(j); const int r = _sidechain_with_mapped_atom(i); _sidechains.last_item()->add_inter_particle_bond(r, x1, x2, btp); } else // HUH! return 0; } } // deal with chirality sometime - hard... return 1; } /* This is complicated, because we do not know which reaction component contains the two atoms. It might be from the scaffold to one of the sidechains, or it might involve two sidechains */ int IWReaction::_from_smirks_add_inter_particle_bond(int amap1, Reaction_Site * a1site, int amap2, Reaction_Site * a2site, bond_type_t bt) { assert (NULL != a1site); assert (NULL != a2site); const Substructure_Atom * a1 = a1site->query_atom_with_atom_map_number(amap1); const Substructure_Atom * a2 = a2site->query_atom_with_atom_map_number(amap2); assert (NULL != a1); assert (NULL != a2); // If either one of the sites is the scaffold, handle specially if (a1site == this) { const int r2 = _sidechain_with_mapped_atom(amap2); _sidechains[r2]->add_inter_particle_bond(-1, a1->initial_atom_number(), a2->initial_atom_number(), bt); } else if (a2site == this) { const int r1 = _sidechain_with_mapped_atom(amap1); _sidechains[r1]->add_inter_particle_bond(-1, a2->initial_atom_number(), a1->initial_atom_number(), bt); } else // different sidechains { const int r1 = _sidechain_with_mapped_atom(amap1); const int r2 = _sidechain_with_mapped_atom(amap2); _sidechains[r1]->add_inter_particle_bond(r2, a2->initial_atom_number(), a1->initial_atom_number(), bt); } return 1; } /* Atom A1 is in the scaffold. We need to find which sidechain has a2 */ int IWReaction::_from_smirks_add_inter_particle_bond_involves_scaffold(int a1, int a2, bond_type_t bt) { int r2 = -1; for (auto i = 0; i < _sidechains.number_elements(); ++i) { Substructure_Atom * x = _sidechains[i]->query_atom_with_atom_map_number(a2); if (NULL == x) continue; r2 = i; break; } cerr << "Atom " << a1 << " in scaffold, atom " << a2 << " in sidechain " << r2 << endl; if (r2 < 0) { cerr << "IWReaction::_from_smirks_add_inter_particle_bond_involves_scaffold:no sidechain for " << a2 << endl; return 0; } _sidechains[r2]->add_inter_particle_bond(0, a1, a2, bt); return 1; } /* Due to how the Substructure_Atom object is built, the attributes will be in the first Substructure_Atom_Specifier component. Fetch that if it is present */ int IWReaction::_discern_atomic_changes(Reaction_Site & r, const Substructure_Atom & q1, const Substructure_Atom & q2) { const int nc1 = q1.ncomponents(); const int nc2 = q2.ncomponents(); const auto a = q1.initial_atom_number(); if (nc1 > 0 && nc2 > 0) return _discern_atomic_changes_specifier(r, a, *q1.component(0), *q2.component(0)); if (nc1 > 0) return _discern_atomic_changes_specifier(r, a, *q1.component(0), q2); if (nc2 > 0) return _discern_atomic_changes_specifier(r, a, q1, *q2.component(0)); return _discern_atomic_changes_specifier(r, a, q1, q2); } int IWReaction::_discern_atomic_changes_specifier(Reaction_Site & r, const atom_number_t a, const Substructure_Atom_Specifier & q1, const Substructure_Atom_Specifier & q2) { const auto & e2 = q2.element(); if (e2.number_elements() > 1) { cerr << "IWReaction::_discern_atomic_changes:RHS has multiple elements\n"; for (int i = 0; i < e2.number_elements(); ++i) { cerr << ' ' << e2[i]; } cerr << endl; return 0; } if (e2.number_elements() > 0) { Reaction_Change_Element * rce = new Reaction_Change_Element; rce->set_atom(a); rce->set_element(e2[0]); r.add_element_to_be_changed(rce); } const auto & fc1 = q1.Substructure_Atom_Specifier::formal_charge(); const auto & fc2 = q2.Substructure_Atom_Specifier::formal_charge(); int need_to_set_formal_charge = 99; if (0 == fc1.number_elements() && 0 == fc2.number_elements()) // not specified either side ; else if (fc1.number_elements() > 0 && 0 == fc2.number_elements()) // set on LHS, but not on right need_to_set_formal_charge = 0; else if (fc2.number_elements() > 0) // set on RHS, must set need_to_set_formal_charge = fc2[0]; if (99 != need_to_set_formal_charge) r.add_formal_charge_to_assign(a, need_to_set_formal_charge); const auto & iso1 = q1.isotope(); const auto & iso2 = q2.isotope(); if (iso2.number_elements() > 1) { cerr << "IWReaction::_discern_atomic_changes:RHS has multiple isotopes\n"; return 0; } int need_to_set_isotope = 2776704; if (0 == iso1.number_elements() && 0 == iso2.number_elements()) ; else if (iso1.number_elements() > 0 && 0 == iso2.number_elements()) need_to_set_isotope = 0; else if (iso2.number_elements()) need_to_set_isotope = iso2[0]; if (2776704 != need_to_set_isotope) r.add_isotope_to_be_placed(a, need_to_set_isotope); //cerr << "need_to_set_isotope " << need_to_set_isotope << endl; const aromaticity_type_t arom1 = q1.Substructure_Atom_Specifier::aromaticity(); const aromaticity_type_t arom2 = q2.Substructure_Atom_Specifier::aromaticity(); if (arom1 != arom2) // finish this sometime... { } return 1; } const Element * Substructure_Atom::first_specified_element() const { if (_element.number_elements()) return _element[0]; for (int i = 0; i < _components.number_elements(); i++) { const Substructure_Atom_Specifier * c = _components[i]; if (c->element().number_elements()) return c->element()[0]; } return NULL; } int Substructure_Atom::first_specified_formal_charge() const { if (_formal_charge.number_elements()) return _formal_charge[0]; for (int i = 0; i < _components.number_elements(); i++) { const Substructure_Atom_Specifier * c = _components[i]; const Min_Max_Specifier<int> & fc = c->formal_charge(); if (fc.number_elements()) return fc[0]; } return 0; } int Substructure_Atom::first_specified_isotope() const { if (_isotope.number_elements()) return _isotope[0]; for (int i = 0; i < _components.number_elements(); i++) { const Substructure_Atom_Specifier * c = _components[i]; const Min_Max_Specifier<int> & iso = c->isotope(); if (iso.number_elements()) return iso[0]; } return 0; } #ifdef TESTING_STUFF static int verbose = 0; static void usage(int rc) { exit(rc); } template <typename T> int test_reaction_from_smirks_record(const const_IWSubstring & buffer, T & output) { IWReaction rxn; if (! rxn.construct_from_smirks(buffer)) { cerr << "Invalid smirks\n"; return 0; } return 1; } template <typename T> int test_reaction_from_smirks(iwstring_data_source & input, T & output) { const_IWSubstring buffer; while (input.next_record(buffer)) { if (! test_reaction_from_smirks_record(buffer, output)) { cerr << "Fatal error processing '" << buffer << "'\n"; return 0; } } return 1; } template <typename T> int test_reaction_from_smirks(const char * fname, T & output) { iwstring_data_source input(fname); if (! input.good()) { cerr << "Cannot open '" << fname << "'\n"; return 0; } return test_reaction_from_smirks(input, output); } static int test_reaction_from_smirks(const int argc, char ** argv) { Command_Line cl(argc, argv, "vA:E:i:g:l"); if (cl.unrecognised_options_encountered()) { cerr << "Unrecognised options encountered\n"; usage(1); } verbose = cl.option_count('v'); if (cl.option_present('A')) { if (! process_standard_aromaticity_options(cl, verbose, 'A')) { cerr << "Cannot initialise aromaticity specifications\n"; usage(5); } } else set_global_aromaticity_type(Daylight); if (cl.option_present('E')) { if (! process_elements(cl, verbose, 'E')) { cerr << "Cannot initialise elements\n"; return 6; } } if (0 == cl.number_elements()) { cerr << "Insufficient arguments\n"; usage(1); } return 0; } int main(int argc, char **argv) { int rc = test_reaction_from_smirks(argc, argv); return rc; } #endif
27.841418
166
0.624573
[ "object" ]
df04badb3c5b01700c08754d605459ea600674c6
1,913
cpp
C++
day1.cpp
aspingley/designpatternsekvira
02565628bde608018e8536688e9e7e98303d78c3
[ "Apache-2.0" ]
1
2021-01-14T13:25:55.000Z
2021-01-14T13:25:55.000Z
day1.cpp
aspingley/designpatternsekvira
02565628bde608018e8536688e9e7e98303d78c3
[ "Apache-2.0" ]
null
null
null
day1.cpp
aspingley/designpatternsekvira
02565628bde608018e8536688e9e7e98303d78c3
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <string> // RAII: Resource Acquisition Is Initialization class Sample{ private: public: }; class Chair{ private: std::string _legs; unsigned short _numLegs; public: unsigned short getLegsCount(){ return _numLegs; } void setLegsCount(unsigned short l){ _numLegs = l; } }; class Cuboid{ double _width; double _length; double _height; public: Cuboid(double width, double height, double length){ _width = width; _height = height; _length = length; } double getArea(){ return _width * _height * _length; } }; class Rectangle: public Cuboid{ //double _width; //double _length; public: Rectangle(double width, double length): Cuboid(width, 1, length){ //_width = width; //_length = length; } }; class Shape{ public: virtual double area() = 0; // pure virtual function }; //void setShape(Shape){ //} class Rectangle2 : public Shape{ double _l; double _b; public: Rectangle2(double l, double b){ _l = l; _b = b; } double area() { return _l * _b; } }; class Triangle : public Shape{ double _h; double _b; public: Triangle(double h, double b){ _h = h; _b = b; } double area() { return 0.5 * _h * _b; } }; int main(){ Shape* s = nullptr; Rectangle2 r2(10,7); s = &r2; std::cout << "Rectangle = " << s->area() << std::endl; Triangle t1(10,5); s = &t1; std::cout << "Triangle = " << s->area() << std::endl; /*Sample s; Cuboid c(2,4,5); std::cout << c.getArea() << std::endl; Rectangle r(5,6); std::cout << r.getArea() << std::endl;*/ }
18.219048
69
0.510193
[ "shape" ]
df0a0f102fb39c9941ae6f11149427e4128f2607
1,992
cpp
C++
restformance/RequestAnalyzer.cpp
tsunday/restformance
c98970e39f30afb3e5ce69181df70494dcf73118
[ "Apache-2.0" ]
null
null
null
restformance/RequestAnalyzer.cpp
tsunday/restformance
c98970e39f30afb3e5ce69181df70494dcf73118
[ "Apache-2.0" ]
null
null
null
restformance/RequestAnalyzer.cpp
tsunday/restformance
c98970e39f30afb3e5ce69181df70494dcf73118
[ "Apache-2.0" ]
null
null
null
#include "stdafx.h" #include "RequestAnalyzer.h" #include <thread> #include <algorithm> #include <numeric> #include <chrono> RequestAnalyzer::RequestAnalyzer(std::shared_ptr<Request> _request){ request = _request; } pplx::task<void> RequestAnalyzer::invokeRepeatedRequest(const method mtd, const int count, const milliseconds time_delta, string_t body){ return pplx::create_task([=] { for (int i=0; i < count; i++){ std::this_thread::sleep_for(time_delta); auto task = request->invokeRequest(mtd, body); task.wait(); auto result = std::pair<status_code, milliseconds>( task.get().status_code(), request->getLastResponseTime()); results.push_back(result); } }); } std::vector<std::pair<status_code, milliseconds>> RequestAnalyzer::getResults() const { return results; } std::wstring RequestAnalyzer::getRequestURI() { return request->getUrl() + request->getResource(); } void RequestAnalyzer::setRequest(std::shared_ptr<Request> r) { request = r; results.clear(); } milliseconds RequestAnalyzer::getLastResponseTime(){ return results.back().second; } milliseconds RequestAnalyzer::getMaxResponseTime(){ return std::max_element( results.begin(), results.end(), [](const std::pair<status_code, milliseconds> &a, const std::pair<status_code, milliseconds> &b){ return (a.second < b.second); })->second; } milliseconds RequestAnalyzer::getMinResponseTime(){ return std::min_element( results.begin(), results.end(), [](const std::pair<status_code, milliseconds> &a, const std::pair<status_code, milliseconds> &b){ return (a.second < b.second); })->second; } long RequestAnalyzer::getAvarageResponseTime(){ long sum = 0; for (auto r : results) sum += r.second.count(); return sum / results.size(); }
28.457143
137
0.634036
[ "vector" ]
df0a8db2eb89a199acdd515797e40af69cb5feb5
4,387
cpp
C++
source/nx/content_meta.cpp
tiliarou/Tinfoil-2
f80d8b2c52e44c273f41547321830917e5f3b572
[ "MIT" ]
9
2020-12-24T00:12:29.000Z
2022-02-22T11:37:45.000Z
source/nx/content_meta.cpp
tiliarou/Tinfoil-2
f80d8b2c52e44c273f41547321830917e5f3b572
[ "MIT" ]
null
null
null
source/nx/content_meta.cpp
tiliarou/Tinfoil-2
f80d8b2c52e44c273f41547321830917e5f3b572
[ "MIT" ]
1
2020-07-20T01:30:03.000Z
2020-07-20T01:30:03.000Z
#include "nx/content_meta.hpp" #include <string.h> #include "util/title_util.hpp" #include "debug.h" #include "error.hpp" namespace nx::ncm { ContentMeta::ContentMeta() { m_bytes.Resize(sizeof(ContentMetaHeader)); } ContentMeta::ContentMeta(u8* data, size_t size) : m_bytes(size) { if (size < sizeof(ContentMetaHeader)) throw std::runtime_error("Content meta data size is too small!"); m_bytes.Resize(size); memcpy(m_bytes.GetData(), data, size); } ContentMetaHeader ContentMeta::GetContentMetaHeader() { return m_bytes.Read<ContentMetaHeader>(0); } NcmMetaRecord ContentMeta::GetContentMetaKey() { NcmMetaRecord metaRecord; ContentMetaHeader contentMetaHeader = this->GetContentMetaHeader(); memset(&metaRecord, 0, sizeof(NcmMetaRecord)); metaRecord.titleId = contentMetaHeader.titleId; metaRecord.version = contentMetaHeader.titleVersion; metaRecord.type = static_cast<u8>(contentMetaHeader.type); return metaRecord; } // TODO: Cache this std::vector<ContentRecord> ContentMeta::GetContentRecords() { ContentMetaHeader contentMetaHeader = this->GetContentMetaHeader(); std::vector<ContentRecord> contentRecords; HashedContentRecord* hashedContentRecords = (HashedContentRecord*)(m_bytes.GetData() + sizeof(ContentMetaHeader) + contentMetaHeader.extendedHeaderSize); for (unsigned int i = 0; i < contentMetaHeader.contentCount; i++) { HashedContentRecord hashedContentRecord = hashedContentRecords[i]; // Don't install delta fragments. Even patches don't seem to install them. if (static_cast<u8>(hashedContentRecord.record.contentType) <= 5) { contentRecords.push_back(hashedContentRecord.record); } } return contentRecords; } void ContentMeta::GetInstallContentMeta(tin::data::ByteBuffer& installContentMetaBuffer, ContentRecord& cnmtContentRecord, bool ignoreReqFirmVersion) { ContentMetaHeader contentMetaHeader = this->GetContentMetaHeader(); std::vector<ContentRecord> contentRecords = this->GetContentRecords(); // Setup the content meta header InstallContentMetaHeader installContentMetaHeader; installContentMetaHeader.extendedHeaderSize = contentMetaHeader.extendedHeaderSize; installContentMetaHeader.contentCount = contentRecords.size() + 1; // Add one for the cnmt content record installContentMetaHeader.contentMetaCount = contentMetaHeader.contentMetaCount; installContentMetaBuffer.Append<InstallContentMetaHeader>(installContentMetaHeader); // Setup the meta extended header LOG_DEBUG("Install content meta pre size: 0x%lx\n", installContentMetaBuffer.GetSize()); installContentMetaBuffer.Resize(installContentMetaBuffer.GetSize() + contentMetaHeader.extendedHeaderSize); LOG_DEBUG("Install content meta post size: 0x%lx\n", installContentMetaBuffer.GetSize()); auto* extendedHeaderSourceBytes = m_bytes.GetData() + sizeof(ContentMetaHeader); u8* installExtendedHeaderStart = installContentMetaBuffer.GetData() + sizeof(InstallContentMetaHeader); memcpy(installExtendedHeaderStart, extendedHeaderSourceBytes, contentMetaHeader.extendedHeaderSize); // Optionally disable the required system version field if (ignoreReqFirmVersion && (contentMetaHeader.type == ContentMetaType::APPLICATION || contentMetaHeader.type == ContentMetaType::PATCH)) { installContentMetaBuffer.Write<u32>(0, sizeof(InstallContentMetaHeader) + 8); } // Setup cnmt content record installContentMetaBuffer.Append<ContentRecord>(cnmtContentRecord); // Setup the content records for (auto& contentRecord : contentRecords) { installContentMetaBuffer.Append<ContentRecord>(contentRecord); } if (contentMetaHeader.type == ContentMetaType::PATCH) { PatchMetaExtendedHeader* patchMetaExtendedHeader = (PatchMetaExtendedHeader*)extendedHeaderSourceBytes; installContentMetaBuffer.Resize(installContentMetaBuffer.GetSize() + patchMetaExtendedHeader->extendedDataSize); } } }
40.247706
161
0.704126
[ "vector" ]
df1173c970bc8e3770d3a5416f032419ae1d5fd3
2,872
hpp
C++
include/oogl/VertexBuffer.hpp
rharel/cpp-oogl
e8fd19649cc113aff43ddb8d805ca356e9a6b02c
[ "MIT" ]
1
2019-08-28T19:03:45.000Z
2019-08-28T19:03:45.000Z
include/oogl/VertexBuffer.hpp
rharel/cpp-oogl
e8fd19649cc113aff43ddb8d805ca356e9a6b02c
[ "MIT" ]
null
null
null
include/oogl/VertexBuffer.hpp
rharel/cpp-oogl
e8fd19649cc113aff43ddb8d805ca356e9a6b02c
[ "MIT" ]
1
2019-08-28T19:03:51.000Z
2019-08-28T19:03:51.000Z
/** * Vertex Buffer Object. * * @author Raoul Harel * @url github/rharel/cpp-oogl */ #pragma once #include <glew/glew.h> #include <oogl/GLObject.hpp> namespace oogl { /** * This class wraps around OpenGL vertex buffer objects. * Vertex buffers store vertex data to be used in the rendering pipeline. */ class VertexBuffer : public GLObject { public: enum class Binding : GLenum { Array = GL_ARRAY_BUFFER, AtomicCounter = GL_ATOMIC_COUNTER_BUFFER, CopyRead = GL_COPY_READ_BUFFER, CopyWrite = GL_COPY_WRITE_BUFFER, DispatchIndirect = GL_DISPATCH_INDIRECT_BUFFER, DrawIndirect = GL_DRAW_INDIRECT_BUFFER, ElementArray = GL_ELEMENT_ARRAY_BUFFER, PixelPack = GL_PIXEL_PACK_BUFFER, PixelUnpack = GL_PIXEL_UNPACK_BUFFER, Query = GL_QUERY_BUFFER, ShaderStorage = GL_SHADER_STORAGE_BUFFER, Texture = GL_TEXTURE_BUFFER, TransformFeedback = GL_TRANSFORM_FEEDBACK_BUFFER, Uniform = GL_UNIFORM_BUFFER }; enum class Usage : GLenum { StaticDraw = GL_STATIC_DRAW, StaticRead = GL_STATIC_READ, StaticCopy = GL_STATIC_COPY, DynamicDraw = GL_DYNAMIC_DRAW, DynamicRead = GL_DYNAMIC_READ, DynamicCopy = GL_DYNAMIC_COPY, StreamDraw = GL_STREAM_DRAW, StreamRead = GL_STREAM_READ, StreamCopy = GL_STREAM_COPY }; /** * Creates a new buffer. * Default binding target is the array buffer. * Default usage is static-draw. */ VertexBuffer(); /** * Creates a new buffer with given binding target. * Default usage is static-draw. */ VertexBuffer(Binding target); /** * Creates a new buffer with given binding target and usage. */ VertexBuffer(Binding target, Usage usage); /** * Deletes buffer. */ ~VertexBuffer() override; /** * Binds to context. */ void Bind() override; /** * Binds to the context at given target. */ void BindToTarget(Binding target); /** * Uploads data to the buffer. */ void UploadData ( GLsizeiptr byte_count, const GLvoid* data ); /** * Sets the binding target. */ void set_binding_target(Binding value); /** * Gets usage policy. */ Usage usage() const; /** * Sets usage policy. */ void set_usage(Usage value); private: Usage usage_; }; } #include <oogl/VertexBuffer.cpp>
24.547009
77
0.549095
[ "object" ]
df126ba4a22e529560ec6aab3f09050067560efc
8,804
cpp
C++
src/mongo/client/connection_string.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/client/connection_string.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/client/connection_string.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2018-present MongoDB, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * <http://www.mongodb.com/licensing/server-side-public-license>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the Server Side Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #include <set> #include "mongo/platform/basic.h" #include "mongo/client/connection_string.h" #include "mongo/base/status_with.h" #include "mongo/util/str.h" namespace mongo { ConnectionString::ConnectionString(const HostAndPort& server) : _type(ConnectionType::kStandalone) { _servers.push_back(server); _finishInit(); } ConnectionString::ConnectionString(StringData replicaSetName, std::vector<HostAndPort> servers) : _type(ConnectionType::kReplicaSet), _servers(std::move(servers)), _replicaSetName(replicaSetName.toString()) { _finishInit(); } // TODO: unify c-tors ConnectionString::ConnectionString(ConnectionType type, const std::string& s, const std::string& replicaSetName) { _type = type; _replicaSetName = replicaSetName; _fillServers(s); _finishInit(); } ConnectionString::ConnectionString(ConnectionType type, std::vector<HostAndPort> servers, const std::string& replicaSetName) : _type(type), _servers(std::move(servers)), _replicaSetName(replicaSetName) { _finishInit(); } ConnectionString::ConnectionString(const std::string& s, ConnectionType connType) : _type(connType) { _fillServers(s); _finishInit(); } ConnectionString::ConnectionString(ConnectionType connType) : _type(connType), _string("<local>") { invariant(_type == ConnectionType::kLocal); } ConnectionString ConnectionString::forReplicaSet(StringData replicaSetName, std::vector<HostAndPort> servers) { return ConnectionString(replicaSetName, std::move(servers)); } ConnectionString ConnectionString::forStandalones(std::vector<HostAndPort> servers) { return ConnectionString(ConnectionType::kStandalone, std::move(servers), ""); } ConnectionString ConnectionString::forLocal() { return ConnectionString(ConnectionType::kLocal); } // TODO: rewrite parsing make it more reliable void ConnectionString::_fillServers(std::string s) { // // Custom-handled servers/replica sets start with '$' // According to RFC-1123/952, this will not overlap with valid hostnames // (also disallows $replicaSetName hosts) // if (s.find('$') == 0) { _type = ConnectionType::kCustom; } std::string::size_type idx = s.find('/'); if (idx != std::string::npos) { _replicaSetName = s.substr(0, idx); s = s.substr(idx + 1); if (_type != ConnectionType::kCustom) _type = ConnectionType::kReplicaSet; } while ((idx = s.find(',')) != std::string::npos) { _servers.push_back(HostAndPort(s.substr(0, idx))); s = s.substr(idx + 1); } _servers.push_back(HostAndPort(s)); if (_servers.size() == 1 && _type == ConnectionType::kInvalid) { _type = ConnectionType::kStandalone; } } void ConnectionString::_finishInit() { switch (_type) { case ConnectionType::kStandalone: uassert(ErrorCodes::FailedToParse, "Cannot specify a replica set name for a standalone ConnectionString", _replicaSetName.empty()); break; case ConnectionType::kReplicaSet: uassert(ErrorCodes::FailedToParse, "Must specify set name for replica set ConnectionStrings", !_replicaSetName.empty()); uassert(ErrorCodes::FailedToParse, "Replica set ConnectionStrings must have at least one server specified", _servers.size() >= 1); break; default: uassert(ErrorCodes::FailedToParse, "ConnectionStrings must specify at least one server", _servers.size() > 0); } // Needed here as well b/c the parsing logic isn't used in all constructors // TODO: Refactor so that the parsing logic *is* used in all constructors if (_type == ConnectionType::kStandalone && _servers.size() > 0) { if (_servers[0].host().find('$') == 0) { _type = ConnectionType::kCustom; } } std::stringstream ss; if (_type == ConnectionType::kReplicaSet) { ss << _replicaSetName << "/"; } for (unsigned i = 0; i < _servers.size(); i++) { if (i > 0) { ss << ","; } ss << _servers[i].toString(); } _string = ss.str(); } ConnectionString ConnectionString::makeUnionWith(const ConnectionString& other) { invariant(type() == other.type()); invariant(getSetName() == other.getSetName()); std::set<HostAndPort> servers{_servers.begin(), _servers.end()}; servers.insert(other._servers.begin(), other._servers.end()); return ConnectionString( type(), std::vector<HostAndPort>(servers.begin(), servers.end()), getSetName()); } bool ConnectionString::operator==(const ConnectionString& other) const { if (_type != other._type) { return false; } switch (_type) { case ConnectionType::kInvalid: return true; case ConnectionType::kStandalone: return _servers[0] == other._servers[0]; case ConnectionType::kReplicaSet: return _replicaSetName == other._replicaSetName && _servers == other._servers; case ConnectionType::kCustom: return _string == other._string; case ConnectionType::kLocal: return true; } MONGO_UNREACHABLE; } bool ConnectionString::operator!=(const ConnectionString& other) const { return !(*this == other); } StatusWith<ConnectionString> ConnectionString::parse(const std::string& url) { const std::string::size_type i = url.find('/'); // Replica set if (i != std::string::npos && i != 0) { return ConnectionString(ConnectionType::kReplicaSet, url.substr(i + 1), url.substr(0, i)); } const int numCommas = str::count(url, ','); // Single host if (numCommas == 0) { HostAndPort singleHost; Status status = singleHost.initialize(url); if (!status.isOK()) { return status; } return ConnectionString(singleHost); } if (numCommas == 2) { return Status(ErrorCodes::FailedToParse, str::stream() << "mirrored config server connections are not supported; for " "config server replica sets be sure to use the replica set " "connection string"); } return Status(ErrorCodes::FailedToParse, str::stream() << "invalid url [" << url << "]"); } ConnectionString ConnectionString::deserialize(StringData url) { return uassertStatusOK(parse(url.toString())); } std::string ConnectionString::typeToString(ConnectionType type) { switch (type) { case ConnectionType::kInvalid: return "invalid"; case ConnectionType::kStandalone: return "standalone"; case ConnectionType::kReplicaSet: return "replicaSet"; case ConnectionType::kCustom: return "custom"; case ConnectionType::kLocal: return "local"; } MONGO_UNREACHABLE; } } // namespace mongo
34.124031
100
0.634257
[ "vector" ]
df179aadd329ff25fd471a436243564b6a0655b7
7,796
cxx
C++
ds/adsi/msext/clocalty.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
ds/adsi/msext/clocalty.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
ds/adsi/msext/clocalty.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//--------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1992 - 1995 // // File: cLocality.cxx // // Contents: Locality object // // History: 11-1-95 krishnag Created. // //---------------------------------------------------------------------------- #include "ldap.hxx" #pragma hdrstop struct _propmap { LPTSTR pszADsProp; LPTSTR pszLDAPProp; } aLocalityPropMapping[] = { // { TEXT("Description"), TEXT("description") }, { TEXT("LocalityName"), TEXT("l") }, { TEXT("PostalAddress"), TEXT("street") } // NTDS // { TEXT("SeeAlso"), TEXT("seeAlso") } }; // Class CLDAPLocality // IADsExtension::PrivateGetIDsOfNames()/Invoke(), Operate() not included DEFINE_IADsExtension_Implementation(CLDAPLocality) DEFINE_IPrivateDispatch_Implementation(CLDAPLocality) DEFINE_DELEGATING_IDispatch_Implementation(CLDAPLocality) DEFINE_CONTAINED_IADs_Implementation(CLDAPLocality) DEFINE_CONTAINED_IADsPutGet_Implementation(CLDAPLocality, aLocalityPropMapping) CLDAPLocality::CLDAPLocality(): _pUnkOuter(NULL), _pADs(NULL), _fDispInitialized(FALSE), _pDispMgr(NULL) { ENLIST_TRACKING(CLDAPLocality); } HRESULT CLDAPLocality::CreateLocality( IUnknown *pUnkOuter, REFIID riid, void **ppvObj ) { HRESULT hr = S_OK; CLDAPLocality FAR * pLocality = NULL; IADs FAR * pADs = NULL; CAggregateeDispMgr FAR * pDispMgr = NULL; // // our extension object only works in a provider (aggregator) environment // environment // ASSERT(pUnkOuter); ASSERT(ppvObj); ASSERT(IsEqualIID(riid, IID_IUnknown)); pLocality = new CLDAPLocality(); if (pLocality == NULL) { hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); } // // Ref Count = 1 from object tracker // // // CAggregateeDispMgr to handle // IADsExtension::PrivateGetIDsOfNames()/PrivatInovke() // pDispMgr = new CAggregateeDispMgr; if (pDispMgr == NULL) { hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); } pLocality->_pDispMgr = pDispMgr; hr = pDispMgr->LoadTypeInfoEntry( LIBID_ADs, IID_IADsLocality, (IADsLocality *)pLocality, DISPID_REGULAR ); BAIL_ON_FAILURE(hr); // // Store the pointer to the pUnkOuter object to delegate all IUnknown // calls to the aggregator AND DO NOT add ref this pointer // pLocality->_pUnkOuter = pUnkOuter; // // Ccache pADs Pointer to delegate all IDispatch calls to // the aggregator. But release immediately to avoid the aggregatee // having a reference count on the aggregator -> cycle ref counting // hr = pUnkOuter->QueryInterface( IID_IADs, (void **)&pADs ); // // Our spec stated extesnion writers can expect the aggregator in our // provider ot support IDispatch. If not, major bug. // ASSERT(SUCCEEDED(hr)); pADs->Release(); // see doc above pUnkOuter->QI pLocality->_pADs = pADs; // // pass non-delegating IUnknown back to the aggregator // *ppvObj = (INonDelegatingUnknown FAR *) pLocality; RRETURN(hr); error: if (pLocality) delete pLocality; *ppvObj = NULL; RRETURN(hr); } CLDAPLocality::~CLDAPLocality( ) { // // Remember that the aggregatee has no reference counts to // decrement. // delete _pDispMgr; } STDMETHODIMP CLDAPLocality::QueryInterface( REFIID iid, LPVOID FAR* ppv ) { HRESULT hr = S_OK; hr = _pUnkOuter->QueryInterface(iid,ppv); RRETURN(hr); } STDMETHODIMP CLDAPLocality::NonDelegatingQueryInterface( REFIID iid, LPVOID FAR* ppv ) { ASSERT(ppv); if (IsEqualIID(iid, IID_IADsLocality)) { *ppv = (IADsLocality FAR *) this; } else if (IsEqualIID(iid, IID_IADsExtension)) { *ppv = (IADsExtension FAR *) this; } else if (IsEqualIID(iid, IID_IUnknown)) { // // probably not needed since our 3rd party extension does not stand // alone and provider does not ask for this, but to be safe // *ppv = (INonDelegatingUnknown FAR *) this; } else { *ppv = NULL; return E_NOINTERFACE; } // // Delegating AddRef to aggregator for IADsExtesnion and. // AddRef on itself for IPrivateUnknown. (both tested.) // ((IUnknown *) (*ppv)) -> AddRef(); return S_OK; } STDMETHODIMP CLDAPLocality::ADSIInitializeObject( THIS_ BSTR lpszUserName, BSTR lpszPassword, long lnReserved ) { CCredentials NewCredentials(lpszUserName, lpszPassword, lnReserved); _Credentials = NewCredentials; RRETURN(S_OK); } STDMETHODIMP CLDAPLocality::ADSIInitializeDispatchManager( long dwExtensionId ) { HRESULT hr = S_OK; if (_fDispInitialized) { RRETURN(E_FAIL); } hr = _pDispMgr->InitializeDispMgr(dwExtensionId); if (SUCCEEDED(hr)) { _fDispInitialized = TRUE; } RRETURN(hr); } STDMETHODIMP CLDAPLocality::get_Description(THIS_ BSTR FAR* retval) { GET_PROPERTY_BSTR((IADsLocality *)this,Description); } STDMETHODIMP CLDAPLocality::put_Description(THIS_ BSTR bstrDescription) { PUT_PROPERTY_BSTR((IADsLocality *)this,Description); } STDMETHODIMP CLDAPLocality::get_LocalityName(THIS_ BSTR FAR* retval) { GET_PROPERTY_BSTR((IADsLocality *)this,LocalityName); } STDMETHODIMP CLDAPLocality::put_LocalityName(THIS_ BSTR bstrLocalityName) { PUT_PROPERTY_BSTR((IADsLocality *)this,LocalityName); } STDMETHODIMP CLDAPLocality::get_PostalAddress(THIS_ BSTR FAR* retval) { GET_PROPERTY_BSTR((IADsLocality *)this,PostalAddress); } STDMETHODIMP CLDAPLocality::put_PostalAddress(THIS_ BSTR bstrPostalAddress) { PUT_PROPERTY_BSTR((IADsLocality *)this,PostalAddress); } STDMETHODIMP CLDAPLocality::get_SeeAlso(THIS_ VARIANT FAR* retval) { GET_PROPERTY_VARIANT((IADsLocality *)this,SeeAlso); } STDMETHODIMP CLDAPLocality::put_SeeAlso(THIS_ VARIANT vSeeAlso) { PUT_PROPERTY_VARIANT((IADsLocality *)this,SeeAlso); } STDMETHODIMP CLDAPLocality::ADSIReleaseObject() { delete this; RRETURN(S_OK); } // // IADsExtension::Operate() // STDMETHODIMP CLDAPLocality::Operate( THIS_ DWORD dwCode, VARIANT varData1, VARIANT varData2, VARIANT varData3 ) { HRESULT hr = S_OK; switch (dwCode) { case ADS_EXT_INITCREDENTIALS: hr = InitCredentials( &varData1, &varData2, &varData3 ); break; default: hr = E_FAIL; break; } RRETURN(hr); } HRESULT CLDAPLocality::InitCredentials( VARIANT * pvarUserName, VARIANT * pvarPassword, VARIANT * pvarFlags ) { BSTR bstrUser = NULL; BSTR bstrPwd = NULL; DWORD dwFlags = 0; ASSERT(V_VT(pvarUserName) == VT_BSTR); ASSERT(V_VT(pvarPassword) == VT_BSTR); ASSERT(V_VT(pvarFlags) == VT_I4); bstrUser = V_BSTR(pvarUserName); bstrPwd = V_BSTR(pvarPassword); dwFlags = V_I4(pvarFlags); CCredentials NewCredentials(bstrUser, bstrPwd, dwFlags); _Credentials = NewCredentials; RRETURN(S_OK); }
20.624339
80
0.602232
[ "object" ]
df1811cbf8e2f6dc4f6bf5f2c886f2de1824bd7d
9,166
cxx
C++
main-probe.cxx
miquelramirez/t1
6696db1d1e12f93811dc17b8d921a19a75b549b5
[ "Apache-2.0" ]
null
null
null
main-probe.cxx
miquelramirez/t1
6696db1d1e12f93811dc17b8d921a19a75b549b5
[ "Apache-2.0" ]
null
null
null
main-probe.cxx
miquelramirez/t1
6696db1d1e12f93811dc17b8d921a19a75b549b5
[ "Apache-2.0" ]
null
null
null
/* Alexandre Albore, Miguel Ramirez, Hector Geffner T1: A conformant planner Copyright UPF (C) 2010 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 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <cstdlib> #include <fstream> #include <signal.h> #include "utils.hxx" #include "PDDL.hxx" #include "nff_options.hxx" #include "global_options.hxx" #include "nff_belief.hxx" #include "nff_minisat.hxx" #include "nff_search_node.hxx" #include "nff_bsearch.hxx" #include "nff_log.hxx" #include "nff_ipc.hxx" #include "nff_planner_stats.hxx" #include "nff_mutexes.hxx" void load_test_sequence( std::string fname, std::vector<PDDL::Operator*>& ops ) { PDDL::Task& the_task = PDDL::Task::instance(); std::ifstream instream( fname.c_str() ); if ( instream.fail() ) { std::cerr << "Could not open " << fname << std::endl; std::exit(1); } while ( !instream.eof() ) { char buffer[2048]; std::string line; instream.getline( buffer, 2048, '\n' ); line.assign( buffer ); if (!line.empty() ) { std::cout << "Got " << line << " from " << fname << std::endl; bool found = false; for ( unsigned k = 0; k < the_task.prototype_ops().size(); k++ ) { PDDL::Operator* op = the_task.prototype_ops()[k]; if ( the_task.str_tab().get_token( op->code() ) == line ) { ops.push_back(op); found = true; break; } } if ( !found ) { std::cerr << "Operator " << line << " does not exist" << std::endl; std::exit(1); } } } instream.close(); for ( unsigned k = 0; k < ops.size(); k++ ) { std::cout << "Loaded "; the_task.print_operator( ops[k], std::cout ); std::cout << std::endl; } } void handle_exit() { NFF::Log& log = NFF::Log::instance(); NFF::Planner_Stats& stats = NFF::Planner_Stats::instance(); log.stream() << ";; heuristic_computations=" << stats.heuristic_computations() << std::endl; log.stream() << ";; expanded_ehc=" << stats.expanded_ehc() << std::endl; log.stream() << ";; generated_ehc=" << stats.generated_ehc() << std::endl; log.stream() << ";; expanded_bfs=" << stats.expanded_bfs() << std::endl; log.stream() << ";; generated_bfs=" << stats.generated_bfs() << std::endl; log.stream() << ";; primary_expansions=" << stats.primary_expansions() << std::endl; log.stream() << ";; secondary_expansions=" << stats.secondary_expansions() << std::endl; log.stream() << ";; tertiary_expansions=" << stats.tertiary_expansions() << std::endl; log.stream() << ";; entailment_tests=" << stats.entailment_tests() << std::endl; log.stream() << ";; sat_solver_calls=" << stats.sat_solver_calls() << std::endl; log.stream() << ";; max_num_clauses=" << stats.max_num_clauses() << std::endl; log.stream() << ";; problem_inconsistent=" << ( stats.problem_inconsistent() ? "yes" : "no" ) << std::endl; log.stream() << ";; initial_sample_h=" << stats.initial_sample_heuristic() << std::endl; log.stream() << ";; initial_card_h=" << stats.initial_card_heuristic() << std::endl; log.stream() << ";; avg_dead_models=" << stats.num_dead_models() << std::endl; log.stream() << ";; dead_samples_replaced=" << stats.dead_samples_replaced() << std::endl; log.stream() << ";; width_1=" << ( stats.is_width_1() ? "yes" : "no" ) << std::endl; // log.stream() << ";; hash_size=" << stats.hashtable_nodes() << std::endl; log.stream() << ";; nodes_mem=" << stats.node_megabytes() << std::endl; log.stream() << ";; b0_mc=" << stats.b0_mc() << std::endl; log.stream().flush(); log.stream().close(); } void handle_signal( int signum ) { NFF::Log& log = NFF::Log::instance(); NFF::Planner_Stats& stats = NFF::Planner_Stats::instance(); log.stream() << ";; heuristic_computations=" << stats.heuristic_computations() << std::endl; log.stream() << ";; expanded_ehc=" << stats.expanded_ehc() << std::endl; log.stream() << ";; generated_ehc=" << stats.generated_ehc() << std::endl; log.stream() << ";; expanded_bfs=" << stats.expanded_bfs() << std::endl; log.stream() << ";; generated_bfs=" << stats.generated_bfs() << std::endl; log.stream() << ";; primary_expansions=" << stats.primary_expansions() << std::endl; log.stream() << ";; secondary_expansions=" << stats.secondary_expansions() << std::endl; log.stream() << ";; tertiary_expansions=" << stats.tertiary_expansions() << std::endl; log.stream() << ";; entailment_tests=" << stats.entailment_tests() << std::endl; log.stream() << ";; sat_solver_calls=" << stats.sat_solver_calls() << std::endl; log.stream() << ";; max_num_clauses=" << stats.max_num_clauses() << std::endl; log.stream() << ";; problem_inconsistent=" << ( stats.problem_inconsistent() ? "yes" : "no" ) << std::endl; log.stream() << ";; initial_sample_h=" << stats.initial_sample_heuristic() << std::endl; log.stream() << ";; initial_card_h=" << stats.initial_card_heuristic() << std::endl; log.stream() << ";; avg_dead_models=" << stats.num_dead_models() << std::endl; log.stream() << ";; dead_samples_replaced=" << stats.dead_samples_replaced() << std::endl; log.stream() << ";; width_1=" << ( stats.is_width_1() ? "yes" : "no" ) << std::endl; // log.stream() << ";; hash_size=" << stats.hashtable_nodes() << std::endl; log.stream() << ";; nodes_mem=" << stats.node_megabytes() << std::endl; log.stream() << ";; b0_mc=" << stats.b0_mc() << std::endl; log.stream().close(); std::exit( signum ); } void register_signal_handlers() { int signals[] = { SIGXCPU, SIGTERM, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV }; for ( int i = 0; i < 7; i++ ) signal( signals[i], handle_signal ); } int main( int argc, char** argv ) { register_signal_handlers(); double t0, tf; NFF_Options::parse_command_line( argc, argv ); NFF_Options& prog_opts = NFF_Options::instance(); NFF::Ipc& ipc = NFF::Ipc::instance(); NFF::Log& log = NFF::Log::instance(); log.stream() << ";; t1 - A Heuristic Search Conformant Planner" << std::endl; log.stream() << ";; Alexandre Albore, Hector Geffner & Miquel Ramirez (c) 2010" << std::endl; PDDL::Task& task = PDDL::Task::instance(); task.setup(); t0 = time_used(); if ( prog_opts.use_invariant_xors() || prog_opts.use_invariant_diameter() ) { NFF::Mutexes& m = NFF::Mutexes::instance(); task.set_mutexes( &m ); m.create_mutexes(); } task.calculate_relevance(); tf = time_used(); log.stream() << ";; preprocessing="; report_interval( t0, tf, log.stream() ); if ( prog_opts.verbose_mode() ) { std::ofstream fluents_out( "fluents.list" ); std::ofstream ops_out( "operators.list" ); std::ofstream init_out( "initial.list" ); std::ofstream goal_out( "goal.list" ); task.print_fluents( fluents_out ); task.print_operators( ops_out ); task.print_initial_state( init_out ); task.print_goal_state( goal_out ); fluents_out.close(); ops_out.close(); } std::cout << "Fluents=" << task.fluents().size() << std::endl; std::cout << "Operators=" << task.useful_ops().size() << std::endl; log.stream() << ";; domain=" << task.domain_name() << std::endl; log.stream() << ";; problem=" << task.problem_name() << std::endl; log.stream() << ";; fluents=" << task.fluents().size() << std::endl; log.stream() << ";; operators=" << task.useful_ops().size() << std::endl; if ( prog_opts.output_ipc() ) { ipc.stream() << task.fluents().size()-1 << std::endl; for (unsigned f = 0; f < task.fluents().size()-1; f++) { task.print_fluent( f, ipc.stream() ); ipc.stream() << " "; } ipc.stream() << std::endl << "%%" << std::endl; ipc.stream() << task.prototype_ops().size() << std::endl; for (unsigned f = 0; f < task.prototype_ops().size(); f++) { task.print_operator( task.prototype_ops()[f], ipc.stream() ); ipc.stream() << " "; } ipc.stream() << std::endl << "%%" << std::endl; } if ( NFF_Options::instance().only_grounding() ) { std::cout << "Stopping after PDDL task has been processed" << std::endl; std::exit(0); } /** Now starts the proper search **/ NFF::BeliefSearch::BeliefSearch search; if ( !prog_opts.test_sequence().empty() ) { std::vector<PDDL::Operator*> plan_prefix; load_test_sequence( prog_opts.test_sequence(), plan_prefix ); search.execute( plan_prefix ); std::exit(0); } if ( prog_opts.only_initial_node() ) { search.process_root_node(); handle_exit(); std::exit(0); } search.solve(); handle_exit(); std::exit(0); return 0; }
37.260163
108
0.618045
[ "vector" ]
df1e23938907717a7b3ab1f0075b055efa0f7bed
2,792
hpp
C++
shift/service/public/shift/service/service_host.hpp
cspanier/shift
5b3b9be310155fbc57d165d06259b723a5728828
[ "Apache-2.0" ]
2
2018-11-28T18:14:08.000Z
2020-08-06T07:44:36.000Z
shift/service/public/shift/service/service_host.hpp
cspanier/shift
5b3b9be310155fbc57d165d06259b723a5728828
[ "Apache-2.0" ]
4
2018-11-06T21:01:05.000Z
2019-02-19T07:52:52.000Z
shift/service/public/shift/service/service_host.hpp
cspanier/shift
5b3b9be310155fbc57d165d06259b723a5728828
[ "Apache-2.0" ]
null
null
null
#ifndef SHIFT_SERVICE_SERVICEHOST_HPP #define SHIFT_SERVICE_SERVICEHOST_HPP #include <cstdint> #include <memory> #include <vector> #include <chrono> #include <shift/core/boost_disable_warnings.hpp> #include <boost/asio/ip/address.hpp> #include <shift/core/boost_restore_warnings.hpp> #include <shift/core/singleton.hpp> #include <shift/serialization/types.hpp> #include "shift/service/types.hpp" namespace shift::service { /// The central service host class which takes care of basic network /// communication to find other service hosts on the local network. /// @remarks /// Because the service library is based on the network library, you need /// to instantiate the network::network_host singleton before creating this /// one. Also note that you need to regularly call network_host::receive in /// order to process messages received from remote services. class service_host final : public core::singleton<service_host, core::create::using_new> { public: /// Default constructor. service_host(); /// Destructor. ~service_host(); /// void bind_addresses(std::vector<boost::asio::ip::address> addresses); /// void multicast_addresses(boost::asio::ip::address_v4 multicast_address4, boost::asio::ip::address_v6 multicast_address6); /// Starts the service host. bool start(serialization::protocol_version_t protocol_version, serialization::protocol_version_t required_version); /// Orders the service host to stop operation. void stop(); /// Returns true until the service host is ordered to stop. bool running() const; /// Publish service information across the network. This method has to be /// called on a regular basis to make different instances find each other. void publish(); /// Returns the list of local address which are used for service /// communication. const std::vector<boost::asio::ip::address>& bind_addresses() const; /// Returns the addresses being used for service discovery. std::pair<const boost::asio::ip::address_v4&, const boost::asio::ip::address_v6&> multicast_addresses() const; /// Returns the protocol version initially set when the host was started. serialization::protocol_version_t protocol_version() const; /// Returns the local host's GUID. guid_t guid() const; /// Overwrites the local host's GUID. void guid(guid_t new_guid); bool debug_multicasts = false; bool debug_handshakes = false; bool debug_service_registration = false; bool debug_service_calls = false; /// Registers a service. void register_service(basic_service& service); /// Deregisters a service. void deregister_service(basic_service& service); class impl; private: std::unique_ptr<impl> _impl; friend class impl; }; } #endif
29.702128
77
0.734599
[ "vector" ]
df20a069f83d6eceb8b51621d3f5ce2c722fc687
4,019
cpp
C++
plugins/single_plugins/extra-gestures.cpp
EdwardBetts/wayfire
10eb4dbe4ed1c930702bc271e41ed29ff9fa8b7d
[ "MIT" ]
1,249
2018-08-20T02:39:53.000Z
2022-03-31T08:04:02.000Z
plugins/single_plugins/extra-gestures.cpp
EdwardBetts/wayfire
10eb4dbe4ed1c930702bc271e41ed29ff9fa8b7d
[ "MIT" ]
1,084
2018-08-14T19:44:47.000Z
2022-03-31T14:08:10.000Z
plugins/single_plugins/extra-gestures.cpp
EdwardBetts/wayfire
10eb4dbe4ed1c930702bc271e41ed29ff9fa8b7d
[ "MIT" ]
190
2018-09-10T09:52:59.000Z
2022-03-30T23:53:29.000Z
#include <wayfire/plugin.hpp> #include <wayfire/core.hpp> #include <wayfire/touch/touch.hpp> #include <wayfire/view.hpp> #include <wayfire/option-wrapper.hpp> #include <wayfire/output-layout.hpp> #include <wayfire/output.hpp> #include <wayfire/util/log.hpp> namespace wf { using namespace touch; class extra_gestures_plugin_t : public plugin_interface_t { std::unique_ptr<gesture_t> touch_and_hold_move; std::unique_ptr<gesture_t> tap_to_close; wf::option_wrapper_t<int> move_fingers{"extra-gestures/move_fingers"}; wf::option_wrapper_t<int> move_delay{"extra-gestures/move_delay"}; wf::option_wrapper_t<int> close_fingers{"extra-gestures/close_fingers"}; public: void init() override { this->grab_interface->capabilities = CAPABILITY_MANAGE_COMPOSITOR; build_touch_and_hold_move(); move_fingers.set_callback([=] () { build_touch_and_hold_move(); }); move_delay.set_callback([=] () { build_touch_and_hold_move(); }); wf::get_core().add_touch_gesture({touch_and_hold_move}); build_tap_to_close(); close_fingers.set_callback([=] () { build_tap_to_close(); }); wf::get_core().add_touch_gesture({tap_to_close}); } /** * Run an action on the view under the touch points, if the touch points * are on the current output and the view is toplevel. */ void execute_view_action(std::function<void(wayfire_view)> action) { auto& core = wf::get_core(); auto state = core.get_touch_state(); auto center_touch_point = state.get_center().current; wf::pointf_t center = {center_touch_point.x, center_touch_point.y}; if (core.output_layout->get_output_at(center.x, center.y) != this->output) { return; } /** Make sure we don't interfere with already activated plugins */ if (!output->can_activate_plugin(this->grab_interface)) { return; } auto view = core.get_view_at({center.x, center.y}); if (view && (view->role == VIEW_ROLE_TOPLEVEL)) { action(view); } } void build_touch_and_hold_move() { if (touch_and_hold_move) { wf::get_core().rem_touch_gesture({touch_and_hold_move}); } auto touch_down = std::make_unique<wf::touch_action_t>(move_fingers, true); touch_down->set_move_tolerance(50); touch_down->set_duration(100); auto hold = std::make_unique<wf::hold_action_t>(move_delay); hold->set_move_tolerance(100); std::vector<std::unique_ptr<gesture_action_t>> actions; actions.emplace_back(std::move(touch_down)); actions.emplace_back(std::move(hold)); touch_and_hold_move = std::make_unique<gesture_t>(std::move(actions), [=] () { execute_view_action([] (wayfire_view view) { view->move_request(); }); }); } void build_tap_to_close() { if (tap_to_close) { wf::get_core().rem_touch_gesture({tap_to_close}); } auto touch_down = std::make_unique<wf::touch_action_t>(close_fingers, true); touch_down->set_move_tolerance(50); touch_down->set_duration(150); auto touch_up = std::make_unique<wf::touch_action_t>(close_fingers, false); touch_up->set_move_tolerance(50); touch_up->set_duration(150); std::vector<std::unique_ptr<gesture_action_t>> actions; actions.emplace_back(std::move(touch_down)); actions.emplace_back(std::move(touch_up)); tap_to_close = std::make_unique<gesture_t>(std::move(actions), [=] () { execute_view_action([] (wayfire_view view) { view->close(); }); }); } void fini() override { wf::get_core().rem_touch_gesture({touch_and_hold_move}); wf::get_core().rem_touch_gesture({tap_to_close}); } }; } DECLARE_WAYFIRE_PLUGIN(wf::extra_gestures_plugin_t);
31.896825
84
0.639711
[ "vector" ]
b309aeeea3f2a03b67da6bb0b3d21917452b178e
918
cpp
C++
02_WikiRacer/InternetTest/src/main.cpp
yangyueren/CS106L
b4267ffa4402909e20d751d7417a8957de51fb5c
[ "BSD-3-Clause" ]
null
null
null
02_WikiRacer/InternetTest/src/main.cpp
yangyueren/CS106L
b4267ffa4402909e20d751d7417a8957de51fb5c
[ "BSD-3-Clause" ]
null
null
null
02_WikiRacer/InternetTest/src/main.cpp
yangyueren/CS106L
b4267ffa4402909e20d751d7417a8957de51fb5c
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include <queue> #include <set> #include "wikiscraper.h" using std::cout; using std::cin; using std::endl; using std::string; void waitForInput() { string msg = " Take screenshot, then press enter to continue: "; cout << string(msg.size(), '=') << endl; cout << msg << endl; cout << string(msg.size(), '=') << endl; string s; (void)std::getline(std::cin, s); } int main() { WikiScraper w; waitForInput(); cout << w.getPageSource("Strawberry") << endl; waitForInput(); cout << "========================" << endl; cout << w.getPageSource("Mathematics") << endl; waitForInput(); cout << "========================" << endl; cout << w.getPageSource("Stanford_Universitya") << endl; waitForInput(); cout << "Done!" << endl; return 0; }
23.538462
68
0.527233
[ "vector" ]
b30a7befbb2e51efc204c25442a61815d23a26b8
1,691
hpp
C++
VoidEngine/Rendering/Shaders/_Shader.hpp
madstk1/VoidEngine
f7f5df83f24661454e258185faea72f95d592307
[ "MIT" ]
null
null
null
VoidEngine/Rendering/Shaders/_Shader.hpp
madstk1/VoidEngine
f7f5df83f24661454e258185faea72f95d592307
[ "MIT" ]
null
null
null
VoidEngine/Rendering/Shaders/_Shader.hpp
madstk1/VoidEngine
f7f5df83f24661454e258185faea72f95d592307
[ "MIT" ]
null
null
null
#ifndef VOID_RENDERING_SHADERS_SHADER_H__ #define VOID_RENDERING_SHADERS_SHADER_H__ #include <string> #include <vector> #include <VoidEngine/Core/Common.hpp> namespace VOID_NS { class ShaderLayout { public: typedef enum { Byte, UByte, Short, UShort, Int, UInt, HFloat, Float, Double } Type; typedef enum { L1D = 1, L2D = 2, L3D = 3, L4D = 4 } Dimension; typedef struct { Type type; Dimension dimension; bool normalized; u64 offset; } LayoutElement; ShaderLayout() {} ShaderLayout(u64 pointerSize) : m_PointerSize(pointerSize) {} ShaderLayout(u64 pointerSize, std::initializer_list<LayoutElement> elements) : m_PointerSize(pointerSize), m_Elements(elements) {} void AddElement(LayoutElement element) { m_Elements.push_back(element); } inline u64 GetPointerSize() { return m_PointerSize; } inline std::vector<LayoutElement> GetElements() { return m_Elements; } protected: u64 m_PointerSize; std::vector<LayoutElement> m_Elements; }; typedef enum { StageVertex = 0, StageFragment, StageCompute, StageCount } ShaderStage; struct ShaderCreationInfo { std::string name; std::vector<std::pair<ShaderStage, std::string>> sources; ShaderLayout layout; }; }; using namespace VOID_NS; #endif /* VOID_RENDERING_SHADERS_SHADER_H__ */
21.961039
84
0.563572
[ "vector" ]
b30c206b299ab73e8bedd04fcf7b70e14140b1cd
4,350
cpp
C++
plug-ins/snapDeformer/snapMeshDeformer.cpp
davidrichardnelson/maya
c0f2677a7ae73a2305d60db0041102f4e3558748
[ "MIT" ]
15
2016-01-16T16:20:53.000Z
2022-03-31T03:56:39.000Z
plug-ins/snapDeformer/snapMeshDeformer.cpp
davidrichardnelson/maya
c0f2677a7ae73a2305d60db0041102f4e3558748
[ "MIT" ]
null
null
null
plug-ins/snapDeformer/snapMeshDeformer.cpp
davidrichardnelson/maya
c0f2677a7ae73a2305d60db0041102f4e3558748
[ "MIT" ]
3
2016-02-25T02:00:38.000Z
2020-09-01T07:20:19.000Z
#include <maya/MFnMesh.h> #include <maya/MMatrix.h> #include <maya/MPointArray.h> #include <maya/MItGeometry.h> #include <maya/MFnNumericAttribute.h> #include <maya/MFnEnumAttribute.h> #include <maya/MFnTypedAttribute.h> #include <mayaFuntions.h> #include <KdTree.h> #include "snapMeshDeformer.h" MTypeId snapDeformer::id( 0x8000e ); MObject snapDeformer::weight; MObject snapDeformer::space; MObject snapDeformer::spaceSource; MObject snapDeformer::pointList; MObject snapDeformer::snapMesh; void *snapDeformer::creator() { return new snapDeformer; } MStatus snapDeformer::initialize() { MStatus stat; MFnNumericAttribute FnNumeric; MFnNumericAttribute FnNumericA; MFnTypedAttribute FnTyped; MFnEnumAttribute FnEnum; //weight weight = FnNumeric.create("weight", "we", MFnNumericData::kFloat); FnNumeric.setKeyable(true); FnNumeric.setStorable(true); FnNumeric.setReadable(true); FnNumeric.setWritable(true); FnNumeric.setDefault( 1.0 ); addAttribute( weight ); ///space target space = FnEnum.create("space", "sp", 0); FnEnum.addField("world",0); FnEnum.addField("object",1); FnEnum.setStorable(true); FnEnum.setKeyable(true); addAttribute(space); ///space source spaceSource = FnEnum.create("spaceSource", "sps", 0); FnEnum.addField("world",0); FnEnum.addField("object",1); FnEnum.setStorable(true); FnEnum.setKeyable(true); addAttribute(spaceSource); //pointlist pointList = FnNumericA.create("pointList", "pl", MFnNumericData::kInt); FnNumericA.setArray( true ); FnNumericA.setKeyable(false); FnNumericA.setStorable(true); FnNumericA.setReadable(true); FnNumericA.setWritable(true); FnNumericA.setIndexMatters(true); addAttribute( pointList ); //snapMesh snapMesh = FnTyped.create("snapMesh", "sm", MFnData::kMesh); FnTyped.setArray( false ); FnTyped.setReadable(true); FnTyped.setWritable(true); addAttribute( snapMesh ); attributeAffects(snapMesh, outputGeom); attributeAffects(pointList, outputGeom); attributeAffects(space, outputGeom); attributeAffects(spaceSource, outputGeom); attributeAffects(weight, outputGeom); return stat; } MStatus snapDeformer::deform(MDataBlock &data, MItGeometry &iter, const MMatrix &mat, unsigned int multiIndex) { MStatus stat; //lets see if we need to do anything MDataHandle DataHandle = data.inputValue(envelope, &stat); float env = DataHandle.asFloat(); if (env == 0) return stat; DataHandle = data.inputValue(weight, &stat); const float weight = DataHandle.asFloat(); if (weight == 0) return stat; env = (env*weight); //space target DataHandle = data.inputValue(space, &stat); int SpaceInt = DataHandle.asInt(); //space source DataHandle = data.inputValue(spaceSource, &stat); int SpaceSourceInt = DataHandle.asInt(); //pointlist MArrayDataHandle pointArrayHandle = data.inputArrayValue(pointList); //snapMesh MFnMesh SnapMesh; DataHandle = data.inputValue(snapMesh, &stat); if (!stat) return Err(stat,"Can't get mesh to snap to"); MObject SnapMeshObj = DataHandle.asMesh(); SnapMesh.setObject(SnapMeshObj); MPointArray snapPoints; if (SpaceSourceInt==0) SnapMesh.getPoints(snapPoints, MSpace::kWorld); else SnapMesh.getPoints(snapPoints, MSpace::kObject); iter.reset(); for ( ; !iter.isDone(); iter.next()) { //check for painted weights float currEnv = env * weightValue(data, multiIndex, iter.index()); //get point to snap to unsigned int index; stat = pointArrayHandle.jumpToElement(iter.index()); if (!stat) index = 0; else { DataHandle = pointArrayHandle.outputValue(); index = DataHandle.asInt(); } if (index != -1) { //calc point location MPoint currPoint; if (snapPoints.length() > index) currPoint = snapPoints[index]; if (SpaceInt == 0) currPoint *= mat.inverse(); if (currEnv !=1) { MPoint p = (currPoint- iter.position()); currPoint = iter.position() + (p*currEnv); } //set point location iter.setPosition(currPoint); } } return stat; }
25.438596
112
0.667356
[ "mesh", "object" ]
b30cdfb7befc49af7efa417320c6a3d9bbee6923
32,927
cpp
C++
library/src/main/cpp/impl/applicationfunctions.cpp
sdankbar/jaqumal
5878cce1df8e8029381044a5284332aa0954fbc0
[ "MIT" ]
3
2020-01-02T03:58:57.000Z
2021-05-19T18:11:06.000Z
library/src/main/cpp/impl/applicationfunctions.cpp
sdankbar/jaqumal
5878cce1df8e8029381044a5284332aa0954fbc0
[ "MIT" ]
null
null
null
library/src/main/cpp/impl/applicationfunctions.cpp
sdankbar/jaqumal
5878cce1df8e8029381044a5284332aa0954fbc0
[ "MIT" ]
null
null
null
/** * The MIT License * Copyright © 2020 Stephen Dankbar * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "applicationfunctions.h" #include "jniutilities.h" #include <eventbuilder.h> #include <eventdispatcher.h> #include <eventlogger.h> #include <invoketarget.h> #include <jpolyline.h> #include <dashedrectangle.h> #include <painter.h> #include <QQmlContext> #include <QTimer> #include <QDateTime> #include <QUuid> #include <QFont> #include <QFontInfo> #include <QFontMetrics> #include <QScreen> #include <QApplication> #include <iostream> #include <functional> #include <singletonmodelfunctions.h> #include <listmodelfunctions.h> #include <flattreemodelfunctions.h> #include <keyeventpreprocessor.h> #include <jdevelopmenttools.h> #include "qmlimageprovider.h" #include <QQmlContext> #include <QResource> #include <QQuickWindow> #include <csignal> #include <qmltest.h> #include <math.h> JNICALL void createQApplication(JNIEnv* env, jclass, jobjectArray argv) { ApplicationFunctions::mainEnv = env; const int32_t argc = env->GetArrayLength(argv); int* argcCopy = new int; *argcCopy = argc; char** argvCopy = new char*[argc]; for (int32_t i = 0; i < argc; ++i) { jstring str = static_cast<jstring>(env->GetObjectArrayElement(argv, i)); const char* array = env->GetStringUTFChars(str, NULL); argvCopy[i] = strdup(array); env->ReleaseStringUTFChars(str, array); } ApplicationFunctions::create(argcCopy, argvCopy); } JNICALL void deleteQApplication(JNIEnv* env, jclass) { if (ApplicationFunctions::check(env)) { ApplicationFunctions::deleteSingleton(); } } JNICALL void execQApplication(JNIEnv* env, jclass) { if (ApplicationFunctions::check(env)) { ApplicationFunctions::get()->exec(); } } JNICALL void pollQAplicationEvents(JNIEnv* env, jclass) { if (ApplicationFunctions::check(env)) { ApplicationFunctions::get()->pollEvents(); } } JNICALL void injectMousePressIntoApplication(JNIEnv* env, jclass, jint x, jint y, jint button, jint buttons, jint modifiers) { if (ApplicationFunctions::check(env)) { ApplicationFunctions::get()->injectMousePress(x, y, button, buttons, modifiers); } } JNICALL void injectMouseReleaseIntoApplication(JNIEnv* env, jclass, jint x, jint y, jint button, jint buttons, jint modifiers) { if (ApplicationFunctions::check(env)) { ApplicationFunctions::get()->injectMouseRelease(x, y, button, buttons, modifiers); } } JNICALL void injectMouseMoveIntoApplication(JNIEnv* env, jclass, jint x, jint y, jint button, jint buttons, jint modifiers) { if (ApplicationFunctions::check(env)) { ApplicationFunctions::get()->injectMouseMove(x, y, button, buttons, modifiers); } } JNICALL void injectWheelIntoApplication(JNIEnv* env, jclass, jint x, jint y, jint pixelX, jint pixelY, jint angleX, jint angleY, jint buttons, jint modifiers, jint phase, jboolean inverted) { if (ApplicationFunctions::check(env)) { ApplicationFunctions::get()->injectWheel(x, y, pixelX, pixelY, angleX, angleY, buttons, modifiers, phase, inverted); } } JNICALL void injectKeyPressIntoApplication(JNIEnv* env, jclass, jint key, jint modifiers, jstring text, jboolean autoRep, jint count) { if (ApplicationFunctions::check(env)) { ApplicationFunctions::get()->injectKeyPress(key, modifiers, JNIUtilities::toQString(env, text), autoRep, count); } } JNICALL void injectKeyReleaseIntoApplication(JNIEnv* env, jclass, jint key, jint modifiers, jstring text, jboolean autoRep, jint count) { if (ApplicationFunctions::check(env)) { ApplicationFunctions::get()->injectKeyRelease(key, modifiers, JNIUtilities::toQString(env, text), autoRep, count); } } JNICALL jstring getCompileQtVersion(JNIEnv* env, jclass) { return env->NewStringUTF(QT_VERSION_STR); } JNICALL jstring getRuntimeQtVersion(JNIEnv* env, jclass) { return env->NewStringUTF(qVersion()); } JNICALL void loadQMLFile(JNIEnv* env, jclass, jstring fileName) { if (ApplicationFunctions::check(env)) { ApplicationFunctions::get()->loadQML(JNIUtilities::toQString(env, fileName)); } } JNICALL void reloadQMLFile(JNIEnv* env, jclass, jstring fileName) { if (ApplicationFunctions::check(env)) { ApplicationFunctions::get()->reloadQML(JNIUtilities::toQString(env, fileName)); } } JNICALL void unloadQMLFile(JNIEnv* env, jclass) { if (ApplicationFunctions::check(env)) { ApplicationFunctions::get()->unloadQML(); } } JNICALL void setLoggingCallback(JNIEnv* env, jclass, jobject c) { if (ApplicationFunctions::check(env)) { ApplicationFunctions::get()->setLoggingObject(env->NewGlobalRef(c)); } } JNICALL void quitQApplication(JNIEnv* env, jclass) { if (ApplicationFunctions::check(env)) { ApplicationFunctions::get()->quitApplication(); } } JNICALL int runQMLTests(JNIEnv* env, jclass, jstring pathToQMLTestFile, jobjectArray importPaths) { QString path = JNIUtilities::toQString(env, pathToQMLTestFile); const int32_t count = env->GetArrayLength(importPaths); std::vector<QString> paths; for (int i = 0; i < count; ++i) { jstring str = static_cast<jstring>(env->GetObjectArrayElement(importPaths, i)); paths.push_back(JNIUtilities::toQString(env, str)); } return runQMLTest(path, paths); } JNICALL void addImageProvider(JNIEnv* env, jclass, jstring id, jobject c) { if (ApplicationFunctions::check(env)) { ApplicationFunctions::get()->addImageProviderObject( JNIUtilities::toQString(env, id), env->NewGlobalRef(c)); } } JNICALL jobjectArray getScreens(JNIEnv* env, jclass) { if (ApplicationFunctions::check(env)) { QList<QScreen*> screens = ApplicationFunctions::get()->getScreensList(); jobjectArray array = ApplicationFunctions::get()->createJScreenArray(env, screens.length()); for (int32_t i= 0; i < screens.length(); ++i) { QScreen* s = screens[i]; QRect geo = s->geometry(); env->SetObjectArrayElement( array, i, ApplicationFunctions::get()->createJScreen(env, geo.x(), geo.y(), geo.width(), geo.height(), s->physicalDotsPerInch())); } return array; } else { return nullptr; } } JNICALL void invoke(JNIEnv* env, jclass, jobject callback) { if (ApplicationFunctions::check(env)) { jobject globalRef = env->NewGlobalRef(callback); QMetaObject::invokeMethod(ApplicationFunctions::get(), [=]{ JNIEnv* qtEnv = ApplicationFunctions::mainEnv; ApplicationFunctions::get()->invokeCallback(qtEnv, globalRef); qtEnv->DeleteGlobalRef(globalRef); }, Qt::QueuedConnection); } } JNICALL void enableEventLogging(JNIEnv* env, jclass) { if (ApplicationFunctions::check(env)) { ApplicationFunctions::get()->createEventLogger(); } } JNICALL void setWindowsIcon(JNIEnv* env, jclass, jobject jImage) { if (ApplicationFunctions::check(env)) { QImage i = ApplicationFunctions::get()->toQImage(env, jImage); ApplicationFunctions::get()->setWindowIcon(QIcon(QPixmap::fromImage(i))); } } JNICALL jboolean registerResourceFile(JNIEnv* env, jclass, jstring rccFile, jstring mapRoot) { return QResource::registerResource( JNIUtilities::toQString(env, rccFile), JNIUtilities::toQString(env, mapRoot)); } JNICALL jboolean registerResourceData(JNIEnv* env, jclass, jint length, jbyteArray rccData, jstring mapRoot) { jbyte* array = env->GetByteArrayElements(rccData, NULL); uchar* copy = new uchar[length]; memcpy(copy, array, length); return QResource::registerResource(copy, JNIUtilities::toQString(env, mapRoot)); } JNICALL jboolean compareImageToActiveWindow(JNIEnv* env, jclass, jobject jImage) { if (ApplicationFunctions::check(env)) { QImage target = ApplicationFunctions::get()->toQImage(env, jImage); QImage source = ApplicationFunctions::get()->takeFocusedWindowScreenShot(); if (source.isNull() || target.isNull()) { return false; } else if (source.width() != target.width()) { return false; } else if (source.height() != target.height()) { return false; } else { uint64_t sqSum = 0; const int32_t pixelCount = source.width() * source.height(); const QRgb* sourcePixels = (const QRgb*)source.constBits(); const QRgb* targetPixels = (const QRgb*)target.constBits(); for (int i = 0; i < pixelCount; ++i) { const QRgb sColor = sourcePixels[i]; const QRgb tColor = targetPixels[i]; const int deltaR = qRed(sColor) - qRed(tColor); const int deltaG = qGreen(sColor) - qGreen(tColor); const int deltaB = qBlue(sColor)- qBlue(tColor); sqSum += (deltaR * deltaR) + (deltaG * deltaG) + (deltaB * deltaB); } double meanSquareError = sqSum / (3.0 * pixelCount); if (meanSquareError == 0) { // Avoid division by 0. return true; } else { double peakSignalToNoiseRatio = 10 * log10((255 * 255) / meanSquareError); return (peakSignalToNoiseRatio > 60); } } } else { return false; } } JNICALL void saveScreenshot(JNIEnv* env, jclass, jstring path) { if (ApplicationFunctions::check(env)) { QString qpath = JNIUtilities::toQString(env, path); QImage source = ApplicationFunctions::get()->takeFocusedWindowScreenShot(); source.save(qpath); } } void ApplicationFunctions::create(int* argc, char** argv) { qmlRegisterType<EventBuilder>("com.github.sdankbar.jaqumal", 0, 4, "EventBuilder"); qmlRegisterType<EventDispatcher>("com.github.sdankbar.jaqumal", 0, 4, "EventDispatcher"); qmlRegisterType<InvokeTarget>("com.github.sdankbar.jaqumal", 0, 4, "InvokeTarget"); qmlRegisterType<KeyEventPreProcessor>("com.github.sdankbar.jaqumal", 0, 4, "KeyEventPreProcessor"); qmlRegisterUncreatableType<GenericListModel>("com.github.sdankbar.jaqumal", 0, 4, "GenericListModel", "Cannot create GenericListModel"); qmlRegisterUncreatableType<GenericFlatTreeModel>("com.github.sdankbar.jaqumal", 0, 4, "GenericFlatTreeModel", "Cannot create GenericFlatTreeModel"); qmlRegisterUncreatableType<GenericObjectModel>("com.github.sdankbar.jaqumal", 0, 4, "GenericObjectModel", "Cannot create GenericObjectModel"); qmlRegisterType<JPolyline>("com.github.sdankbar.jaqumal", 0, 4, "JPolyline"); qmlRegisterType<DashedRectangle>("com.github.sdankbar.jaqumal", 0, 4, "DashedRectangle"); qmlRegisterType<Painter>("com.github.sdankbar.jaqumal", 0, 4, "Painter"); qmlRegisterType<JDevelopmentTools>("com.github.sdankbar.jaqumal", 0, 4, "JDevTools"); SINGLETON = new ApplicationFunctions(*argc, argv); } void ApplicationFunctions::deleteSingleton() { delete ApplicationFunctions::SINGLETON; ApplicationFunctions::SINGLETON = nullptr; } ApplicationFunctions* ApplicationFunctions::get() { return SINGLETON; } bool ApplicationFunctions::check(JNIEnv* env) { if (SINGLETON) { return true; } else { JNIUtilities::throwQMLException(env, "Attempted to use QApplication before QApplication was created"); return false; } } void ApplicationFunctions::invokeLoggingCallback(jobject obj, int type, const std::string& msg) { JNIEnv* threadEnv = JNIUtilities::attachThread(); jstring javaStr = threadEnv->NewStringUTF(msg.c_str()); threadEnv->CallVoidMethod(obj, loggingCallbackMethod, type, javaStr); if (threadEnv->ExceptionCheck()) { std::cerr << "Exception while logging: " << msg << std::endl; threadEnv->ExceptionClear(); } threadEnv->DeleteLocalRef(javaStr); if (mainEnv != threadEnv) { // Only need to detach if not a normal Java thread. JNIUtilities::dettachThread(); } } jclass ApplicationFunctions::loggingCallback; jmethodID ApplicationFunctions::loggingCallbackMethod; jclass ApplicationFunctions::jscreenClass; jmethodID ApplicationFunctions::jscreenContructor; jclass ApplicationFunctions::imageProviderClass; jmethodID ApplicationFunctions::imageProviderInvoke; jclass ApplicationFunctions::bufferedImageClass; jmethodID ApplicationFunctions::bufferedImageGetWidth; jmethodID ApplicationFunctions::bufferedImageGetHeight; jmethodID ApplicationFunctions::bufferedImageGetRGB; JNIEnv* ApplicationFunctions::mainEnv = nullptr; void ApplicationFunctions::initialize(JNIEnv* env) { loggingCallback = JNIUtilities::findClassGlobalReference(env, "com/github/sdankbar/qml/cpp/jni/interfaces/LoggingCallback"); loggingCallbackMethod = env->GetMethodID(loggingCallback, "invoke", "(ILjava/lang/String;)V"); jscreenClass= JNIUtilities::findClassGlobalReference(env, "com/github/sdankbar/qml/JScreen"); jscreenContructor= env->GetMethodID(jscreenClass, "<init>", "(IIIID)V"); imageProviderClass= JNIUtilities::findClassGlobalReference(env, "com/github/sdankbar/qml/cpp/jni/interfaces/ImageProviderCallback"); imageProviderInvoke= env->GetMethodID(imageProviderClass, "invoke", "(Ljava/lang/String;II)Ljava/awt/image/BufferedImage;"); bufferedImageClass= JNIUtilities::findClassGlobalReference(env, "java/awt/image/BufferedImage"); bufferedImageGetWidth= env->GetMethodID(bufferedImageClass, "getWidth", "()I"); bufferedImageGetHeight= env->GetMethodID(bufferedImageClass, "getHeight", "()I"); bufferedImageGetRGB= env->GetMethodID(bufferedImageClass, "getRGB", "(IIII[III)[I"); static JNINativeMethod methods[] = { JNIUtilities::createJNIMethod("createQApplication", "([Ljava/lang/String;)V", (void *)&createQApplication), JNIUtilities::createJNIMethod("deleteQApplication", "()V", (void *)&deleteQApplication), JNIUtilities::createJNIMethod("execQApplication", "()V", (void *)&execQApplication), JNIUtilities::createJNIMethod("pollQAplicationEvents", "()V", (void *)&pollQAplicationEvents), JNIUtilities::createJNIMethod("getCompileQtVersion", "()Ljava/lang/String;", (void *)&getCompileQtVersion), JNIUtilities::createJNIMethod("getRuntimeQtVersion", "()Ljava/lang/String;", (void *)&getRuntimeQtVersion), JNIUtilities::createJNIMethod("loadQMLFile", "(Ljava/lang/String;)V", (void *)&loadQMLFile), JNIUtilities::createJNIMethod("reloadQMLFile", "(Ljava/lang/String;)V", (void *)&reloadQMLFile), JNIUtilities::createJNIMethod("unloadQMLFile", "()V", (void *)&unloadQMLFile), JNIUtilities::createJNIMethod("setLoggingCallback", "(Lcom/github/sdankbar/qml/cpp/jni/interfaces/LoggingCallback;)V", (void *)&setLoggingCallback), JNIUtilities::createJNIMethod("quitQApplication", "()V", (void *)&quitQApplication), JNIUtilities::createJNIMethod("runQMLTests", "(Ljava/lang/String;[Ljava/lang/String;)I", (void *)&runQMLTests), JNIUtilities::createJNIMethod("addImageProvider", "(Ljava/lang/String;Lcom/github/sdankbar/qml/cpp/jni/interfaces/ImageProviderCallback;)V", (void *)&addImageProvider), JNIUtilities::createJNIMethod("getScreens", "()[Lcom/github/sdankbar/qml/JScreen;", (void *)&getScreens), JNIUtilities::createJNIMethod("invoke", "(Lcom/github/sdankbar/qml/cpp/jni/interfaces/InvokeCallback;)V", (void *)&invoke), JNIUtilities::createJNIMethod("enableEventLogging", "()V", (void *)&enableEventLogging), JNIUtilities::createJNIMethod("setWindowsIcon", "(Ljava/awt/image/BufferedImage;)V", (void *)&setWindowsIcon), JNIUtilities::createJNIMethod("compareImageToActiveWindow", "(Ljava/awt/image/BufferedImage;)Z", (void *)&compareImageToActiveWindow), JNIUtilities::createJNIMethod("registerResource", "(Ljava/lang/String;Ljava/lang/String;)Z", (void *)&registerResourceFile), JNIUtilities::createJNIMethod("registerResource", "(I[BLjava/lang/String;)Z", (void *)&registerResourceData), JNIUtilities::createJNIMethod("injectMousePressIntoApplication", "(IIIII)V", (void *)&injectMousePressIntoApplication), JNIUtilities::createJNIMethod("injectMouseReleaseIntoApplication", "(IIIII)V", (void *)&injectMouseReleaseIntoApplication), JNIUtilities::createJNIMethod("injectMouseMoveIntoApplication", "(IIIII)V", (void *)&injectMouseMoveIntoApplication), JNIUtilities::createJNIMethod("injectKeyPressIntoApplication", "(IILjava/lang/String;ZI)V", (void *)&injectKeyPressIntoApplication), JNIUtilities::createJNIMethod("injectKeyReleaseIntoApplication", "(IILjava/lang/String;ZI)V", (void *)&injectKeyReleaseIntoApplication), JNIUtilities::createJNIMethod("saveScreenshot", "(Ljava/lang/String;)V", (void *)&saveScreenshot), }; jclass javaClass = env->FindClass("com/github/sdankbar/qml/cpp/jni/ApplicationFunctions"); env->RegisterNatives(javaClass, methods, sizeof(methods) / sizeof(methods[0])); env->DeleteLocalRef(javaClass); } void ApplicationFunctions::uninitialize(JNIEnv* env) { env->DeleteGlobalRef(loggingCallback); env->DeleteGlobalRef(jscreenClass); env->DeleteGlobalRef(imageProviderClass); env->DeleteGlobalRef(bufferedImageClass); } ApplicationFunctions* ApplicationFunctions::SINGLETON = nullptr; void signal_handler(int) { if (ApplicationFunctions::get()) { ApplicationFunctions::get()->quitApplication(); } } ApplicationFunctions::ApplicationFunctions(int32_t& argc, char** argv) : m_qapp(new QApplication(argc, argv)), m_qmlEngine(new QQmlApplicationEngine(m_qapp)), m_uiSim(), m_logging(), m_eventLogger(nullptr) { m_qmlEngine->rootContext()->setContextProperty("log", QVariant::fromValue(&m_logging)); m_qmlEngine->rootContext()->setContextProperty("userInputSim", QVariant::fromValue(&m_uiSim)); m_qmlEngine->rootContext()->setContextProperty("Jaqumal", QVariant::fromValue(this)); // Install SIGTERM signal handler so application can shutdown cleanly std::signal(SIGTERM, signal_handler); } ApplicationFunctions::~ApplicationFunctions() { if (m_qapp) { m_qmlEngine->clearComponentCache(); m_qapp->closeAllWindows(); QList<QObject*> roots = m_qmlEngine->rootObjects(); for (QObject* obj: roots) { QQuickWindow* window = qobject_cast<QQuickWindow*>(obj); if (window) { delete window; } } delete m_qapp; m_qapp = nullptr; m_qmlEngine = nullptr; } // Cleanup signal handler. std::signal(SIGTERM, SIG_DFL); } void ApplicationFunctions::exec() { m_qapp->exec(); } void ApplicationFunctions::pollEvents() { m_qapp->processEvents(); m_qapp->sendPostedEvents(); } void ApplicationFunctions::quitApplication() { m_qapp->quit(); } void ApplicationFunctions::invokeCallback(JNIEnv* env, jobject c) { JNIUtilities::invokeCallback(env, c); } void ApplicationFunctions::loadQML(const QString& filePath) { m_qmlEngine->load(filePath); } void ApplicationFunctions::unloadQML() { QList<QObject*> roots = m_qmlEngine->rootObjects(); for (QObject* obj: roots) { QQuickWindow* window = qobject_cast<QQuickWindow*>(obj); if (window) { window->close(); window->deleteLater(); } } m_qmlEngine->clearComponentCache(); } void ApplicationFunctions::reloadQML(const QString& filePath) { unloadQML(); loadQML(filePath); } void ApplicationFunctions::setLoggingObject(jobject callbackObject) { m_logging.setCallback(callbackObject); } void ApplicationFunctions::createEventLogger() { if (m_eventLogger == nullptr) { m_eventLogger = new EventLogger(m_logging, m_qapp); m_qapp->installEventFilter(m_eventLogger); } } void ApplicationFunctions::addImageProviderObject(const QString& id, jobject javaImageProviderCallback) { m_qmlEngine->addImageProvider( id, new QMLImageProvider(createImageProviderFunctionCallback(mainEnv, javaImageProviderCallback))); } void ApplicationFunctions::setWindowIcon(const QIcon& icon) { m_qapp->setWindowIcon(icon); } QList<QScreen*> ApplicationFunctions::getScreensList() { return m_qapp->screens(); } jobjectArray ApplicationFunctions::createJScreenArray(JNIEnv* env, int32_t length) { return env->NewObjectArray(length, jscreenClass, nullptr); } jobject ApplicationFunctions::createJScreen(JNIEnv* env, int32_t x, int32_t y, int32_t w, int32_t h, double dpi) { return env->NewObject(jscreenClass, jscreenContructor, x, y, w, h, dpi); } std::function<QImage(const QString&,int32_t,int32_t)> ApplicationFunctions::createImageProviderFunctionCallback(JNIEnv* env, jobject obj) { std::function<QImage(const QString&,int32_t,int32_t)> func = [=] (const QString& id, int32_t w, int32_t h) { jstring jStr = JNIUtilities::toJString(env, id); jobject bufferedImage = env->CallObjectMethod(obj, imageProviderInvoke, jStr, w, h); env->DeleteLocalRef(jStr); if (env->ExceptionCheck()) { std::cerr << "Exception when calling image provider" << std::endl; env->ExceptionClear(); return QImage(); } else if (bufferedImage != nullptr) { return toQImage(env, bufferedImage); } else { return QImage(); } }; return func; } void cleanupMemory2(void* ptr) { delete static_cast<unsigned char*>(ptr); } QImage ApplicationFunctions::toQImage(JNIEnv* env, jobject bufferedImage) { jint w = env->CallIntMethod(bufferedImage, bufferedImageGetWidth); if (env->ExceptionCheck()) { std::cerr << "Exception when calling converting buffered image to QImage (getWidth)" << std::endl; env->ExceptionClear(); return QImage(); } jint h = env->CallIntMethod(bufferedImage, bufferedImageGetHeight); if (env->ExceptionCheck()) { std::cerr << "Exception when calling converting buffered image to QImage (getHeight)" << std::endl; env->ExceptionClear(); return QImage(); } jintArray pixelData = static_cast<jintArray>( env->CallObjectMethod(bufferedImage, bufferedImageGetRGB, 0, 0, w, h, nullptr, 0, w)); if (env->ExceptionCheck()) { std::cerr << "Exception when calling converting buffered image to QImage (getRGB)" << std::endl; env->ExceptionClear(); return QImage(); } else { const int32_t pixels = w * h; const int32_t byteCount = 4 * pixels; unsigned char* copy = new unsigned char[byteCount]; env->GetIntArrayRegion(pixelData, 0, pixels, reinterpret_cast<jint*>(copy)); return QImage(copy, w, h, QImage::Format_ARGB32, &cleanupMemory2); } } void ApplicationFunctions::addToContext(const QString& name, const QVariant& value) { m_objectLookupMap.insert(name, value); emit modelMapChanged(); m_qmlEngine->rootContext()->setContextProperty(name, value); } QVariant ApplicationFunctions::lookup(const QString& objectName) const { return m_objectLookupMap.value(objectName); } const QVariantMap& ApplicationFunctions::modelMap() const { return m_objectLookupMap; } void ApplicationFunctions::installEventFilterToApplication(QObject* obj) { m_qapp->installEventFilter(obj); } void ApplicationFunctions::removeEventFilterFromApplication(QObject* obj) { m_qapp->removeEventFilter(obj); } QWindow* ApplicationFunctions::getEventInjectionWindow() const { QWindow* w = QApplication::focusWindow(); if (w != nullptr) { return w; } QWindowList topLevel = QApplication::topLevelWindows(); if (!topLevel.isEmpty()) { return topLevel[0]; } else { return nullptr; } } QImage ApplicationFunctions::takeFocusedWindowScreenShot() const { QWindow* w = getEventInjectionWindow(); QQuickWindow* quickWindow = dynamic_cast<QQuickWindow*>(w); if (quickWindow != nullptr) { return quickWindow->grabWindow(); } else { return QImage(); } } void ApplicationFunctions::injectMousePress(int32_t x, int32_t y, int32_t button, int32_t buttons, int32_t modifiers) { QWindow* window = getEventInjectionWindow(); if (window != nullptr) { QMouseEvent* event = new QMouseEvent( QEvent::MouseButtonPress, QPointF(x, y), QPointF(x, y), QPointF(x + window->x(), y + window->y()), static_cast<Qt::MouseButton>(button), static_cast<Qt::MouseButtons>(buttons), static_cast<Qt::KeyboardModifiers>(modifiers), Qt::MouseEventSynthesizedByApplication); QCoreApplication::postEvent(window, event); } } void ApplicationFunctions::injectMouseRelease(int32_t x, int32_t y, int32_t button, int32_t buttons, int32_t modifiers) { QWindow* window = getEventInjectionWindow(); if (window != nullptr) { QMouseEvent* event = new QMouseEvent( QEvent::MouseButtonRelease, QPointF(x, y), QPointF(x, y), QPointF(x + window->x(), y + window->y()), static_cast<Qt::MouseButton>(button), static_cast<Qt::MouseButtons>(buttons), static_cast<Qt::KeyboardModifiers>(modifiers), Qt::MouseEventSynthesizedByApplication); QCoreApplication::postEvent(window, event); } } void ApplicationFunctions::injectMouseMove(int32_t x, int32_t y, int32_t button, int32_t buttons, int32_t modifiers) { QWindow* window = getEventInjectionWindow(); if (window != nullptr) { QMouseEvent* event = new QMouseEvent( QEvent::MouseMove, QPointF(x, y), QPointF(x, y), QPointF(x + window->x(), y + window->y()), static_cast<Qt::MouseButton>(button), static_cast<Qt::MouseButtons>(buttons), static_cast<Qt::KeyboardModifiers>(modifiers), Qt::MouseEventSynthesizedByApplication); QCoreApplication::postEvent(window, event); } } void ApplicationFunctions::injectKeyPress(int32_t key, int32_t modifiers, const QString& text, bool autoRep, int32_t count) { QWindow* window = getEventInjectionWindow(); if (window != nullptr) { QWindow* window = QGuiApplication::focusWindow(); QKeyEvent* event = new QKeyEvent(QEvent::KeyPress, key, static_cast<Qt::KeyboardModifiers>(modifiers), text, autoRep, count); QCoreApplication::postEvent(window, event); } } void ApplicationFunctions::injectKeyRelease(int32_t key, int32_t modifiers, const QString& text, bool autoRep, int32_t count) { QWindow* window = getEventInjectionWindow(); if (window != nullptr) { QWindow* window = QGuiApplication::focusWindow(); QKeyEvent* event = new QKeyEvent(QEvent::KeyRelease, key, static_cast<Qt::KeyboardModifiers>(modifiers), text, autoRep, count); QCoreApplication::postEvent(window, event); } } void ApplicationFunctions::injectWheel(int32_t x, int32_t y, int32_t pixelX, int32_t pixelY, int32_t angleX, int32_t angleY, int32_t buttons, int32_t modifiers, int32_t phase, bool inverted) { QWindow* window = getEventInjectionWindow(); if (window != nullptr) { QWindow* window = QGuiApplication::focusWindow(); QWheelEvent* event = new QWheelEvent( QPointF(x, y), QPointF(x + window->x(), y + window->y()), QPoint(pixelX, pixelY), QPoint(angleX, angleY), static_cast<Qt::MouseButtons>(buttons), static_cast<Qt::KeyboardModifiers>(modifiers), static_cast<Qt::ScrollPhase>(phase), inverted, Qt::MouseEventSynthesizedByApplication); QCoreApplication::postEvent(window, event); } }
36.913677
183
0.611838
[ "geometry", "vector" ]
b31088b95d7c17c9c25dd8547af03d6943520916
844
hpp
C++
renderer/backbuffer_menu_surface.hpp
caitisgreat/jkgfxmod
f861441a751e438e6bb1b930fb611e728bd44b61
[ "MIT" ]
57
2019-03-11T20:29:42.000Z
2022-03-11T19:26:01.000Z
renderer/backbuffer_menu_surface.hpp
caitisgreat/jkgfxmod
f861441a751e438e6bb1b930fb611e728bd44b61
[ "MIT" ]
71
2019-03-31T14:39:58.000Z
2022-02-12T05:25:39.000Z
renderer/backbuffer_menu_surface.hpp
caitisgreat/jkgfxmod
f861441a751e438e6bb1b930fb611e728bd44b61
[ "MIT" ]
10
2019-05-14T21:02:57.000Z
2021-06-06T23:19:16.000Z
#pragma once #include "ddrawsurface_impl.hpp" #include "renderer_fwd.hpp" #include <vector> namespace jkgm { class primary_menu_surface; class backbuffer_menu_surface : public DirectDrawSurface_impl { private: renderer *r; primary_menu_surface *surf; public: backbuffer_menu_surface(renderer *r, primary_menu_surface *surf); ULONG WINAPI AddRef() override; ULONG WINAPI Release() override; HRESULT WINAPI Blt(LPRECT a, LPDIRECTDRAWSURFACE b, LPRECT c, DWORD d, LPDDBLTFX e) override; HRESULT WINAPI GetSurfaceDesc(LPDDSURFACEDESC a) override; HRESULT WINAPI Lock(LPRECT a, LPDDSURFACEDESC b, DWORD c, HANDLE d) override; HRESULT WINAPI SetPalette(LPDIRECTDRAWPALETTE a) override; HRESULT WINAPI Unlock(LPVOID a) override; }; }
30.142857
90
0.699052
[ "vector" ]
b31acf816aee1864468c0e7feaa0283511f4af0d
4,031
cpp
C++
distributions/univariate/continuous/LogisticRand.cpp
StochasticEngineer/RandLib
fff111968f5369b7ddaffac44289bbb26cc5c0f3
[ "MIT" ]
61
2017-11-01T16:29:54.000Z
2020-06-20T01:34:30.000Z
distributions/univariate/continuous/LogisticRand.cpp
vishalbelsare/RandLib
fff111968f5369b7ddaffac44289bbb26cc5c0f3
[ "MIT" ]
8
2015-07-01T21:30:22.000Z
2017-10-18T22:15:43.000Z
distributions/univariate/continuous/LogisticRand.cpp
vishalbelsare/RandLib
fff111968f5369b7ddaffac44289bbb26cc5c0f3
[ "MIT" ]
8
2017-11-05T19:33:44.000Z
2020-06-20T01:34:28.000Z
#include "LogisticRand.h" template < typename RealType > LogisticRand<RealType>::LogisticRand(double location, double scale) { SetLocation(location); SetScale(scale); } template < typename RealType > String LogisticRand<RealType>::Name() const { return "Logistic(" + this->toStringWithPrecision(GetLocation()) + ", " + this->toStringWithPrecision(GetScale()) + ")"; } template < typename RealType > void LogisticRand<RealType>::SetLocation(double location) { mu = location; } template < typename RealType > void LogisticRand<RealType>::SetScale(double scale) { if (scale <= 0.0) throw std::invalid_argument("Logistic distribution: scale of should be positive"); s = scale; logS = std::log(s); } template < typename RealType > double LogisticRand<RealType>::f(const RealType & x) const { double numerator = std::exp((mu - x) / s); double denominator = (1 + numerator); denominator *= denominator; denominator *= s; return numerator / denominator; } template < typename RealType > double LogisticRand<RealType>::logf(const RealType & x) const { double x0 = (mu - x) / s; double y = RandMath::softplus(x0); y *= 2; y += logS; return x0 - y; } template < typename RealType > double LogisticRand<RealType>::F(const RealType & x) const { double expX = std::exp((mu - x) / s); return 1.0 / (1 + expX); } template < typename RealType > double LogisticRand<RealType>::S(const RealType & x) const { double expX = std::exp((mu - x) / s); return expX / (1 + expX); } template < typename RealType > RealType LogisticRand<RealType>::Variate() const { /// there can be used rejection method from Laplace or Cauchy (Luc Devroye, p. 471) or ziggurat return mu + s * std::log(1.0 / UniformRand<RealType>::StandardVariate(this->localRandGenerator) - 1); } template < typename RealType > long double LogisticRand<RealType>::Mean() const { return mu; } template < typename RealType > long double LogisticRand<RealType>::Variance() const { double sPi = s * M_PI; return sPi * sPi / 3; } template < typename RealType > std::complex<double> LogisticRand<RealType>::CFImpl(double t) const { double pist = M_PI * s * t; std::complex<double> y(0.0, t * mu); y = std::exp(y); y *= pist; y /= std::sinh(pist); return y; } template < typename RealType > long double LogisticRand<RealType>::Entropy() const { return 2 + logS; } template < typename RealType > RealType LogisticRand<RealType>::quantileImpl(double p) const { return mu - s * (std::log1pl(-p) - std::log(p)); } template < typename RealType > RealType LogisticRand<RealType>::quantileImpl1m(double p) const { return mu - s * (std::log(p) - std::log1pl(-p)); } template < typename RealType > RealType LogisticRand<RealType>::Median() const { return mu; } template < typename RealType > RealType LogisticRand<RealType>::Mode() const { return mu; } template < typename RealType > long double LogisticRand<RealType>::Skewness() const { return 0; } template < typename RealType > long double LogisticRand<RealType>::ExcessKurtosis() const { return 1.2; } template < typename RealType > void LogisticRand<RealType>::FitLocation(const std::vector<RealType> &sample) { double nHalf = 0.5 * sample.size(); RealType root = 0; if (!RandMath::findRootNewtonFirstOrder<RealType>([this, sample, nHalf](RealType m) { double f1 = 0, f2 = 0; for (const double & x : sample) { double aux = std::exp((m - x) / s); double denom = 1.0 + aux; f1 += 1.0 / denom; denom *= denom; f2 -= aux / denom; } f1 -= nHalf; return DoublePair(f1, f2); }, root)) throw std::runtime_error(this->fitErrorDescription(this->UNDEFINED_ERROR, "Error in root-finding procedure")); SetLocation(root); } template class LogisticRand<float>; template class LogisticRand<double>; template class LogisticRand<long double>;
24.430303
123
0.657901
[ "vector" ]
b31c6f6f217a4040bd77edfc3d3189589b0f2444
1,385
cpp
C++
src/engine/render/Model.cpp
HaedHutner/Explorer
f3de70b8d72d4b4e61734bde10ebd577e3082dc0
[ "MIT" ]
null
null
null
src/engine/render/Model.cpp
HaedHutner/Explorer
f3de70b8d72d4b4e61734bde10ebd577e3082dc0
[ "MIT" ]
null
null
null
src/engine/render/Model.cpp
HaedHutner/Explorer
f3de70b8d72d4b4e61734bde10ebd577e3082dc0
[ "MIT" ]
null
null
null
#include "Model.h" #include <utility> Model::Model() : meshes(std::vector<Mesh *>()), model(glm::mat4(1.0f)), position(glm::vec3()), rotation(glm::vec3()), scale(glm::vec3()) { } Model::Model(std::vector<Mesh *> meshes, const glm::vec3 &position, const glm::fvec3 &rotation, const glm::vec3 &scale) : meshes(std::move(meshes)), model(glm::mat4(1.0f)), position(position), rotation(rotation), scale(scale) { moveBy(position); rotateBy(rotation); scaleBy(scale); } glm::mat4 Model::get_model_matrix() { return model; } void Model::moveBy(const glm::vec3 &difference) { glm::translate(model, difference); } void Model::rotateBy(const glm::fvec3 &rotation) { if (rotation.x) rotateBy(rotation.x, glm::vec3(1, 0, 0)); if (rotation.y) rotateBy(rotation.y, glm::vec3(0, 1, 0)); if (rotation.z) rotateBy(rotation.z, glm::vec3(0, 0, 1)); } void Model::rotateBy(float amount, const glm::vec3 &direction) { glm::rotate(model, amount, direction); } void Model::scaleBy(const glm::vec3 &difference) { glm::scale(model, difference); } void Model::tick() { } void Model::draw(const ShaderProgram &shader_program) { shader_program.set_uniform_mat4("model", model); for (Mesh *mesh : meshes) { mesh->draw(shader_program); } } Model::~Model() { for (Mesh *mesh : meshes) { delete mesh; } }
25.648148
119
0.639711
[ "mesh", "vector", "model" ]
b31f1da4e8adf8aa253d1ade83ef82f6ffa73ca8
6,071
cpp
C++
src/db/Database.cpp
aogaki/WebApiELIADE
acea9dbe4e98a2b4ead670ca51c037c7c8bddf65
[ "Apache-2.0" ]
null
null
null
src/db/Database.cpp
aogaki/WebApiELIADE
acea9dbe4e98a2b4ead670ca51c037c7c8bddf65
[ "Apache-2.0" ]
null
null
null
src/db/Database.cpp
aogaki/WebApiELIADE
acea9dbe4e98a2b4ead670ca51c037c7c8bddf65
[ "Apache-2.0" ]
null
null
null
#include <bsoncxx/builder/stream/array.hpp> #include <bsoncxx/builder/stream/document.hpp> #include <bsoncxx/builder/stream/helpers.hpp> #include <bsoncxx/exception/exception.hpp> #include <bsoncxx/json.hpp> #include <iostream> #include <mongocxx/client.hpp> #include <mongocxx/exception/operation_exception.hpp> #include <mongocxx/options/insert.hpp> #include "Database.hpp" #include "oatpp/core/data/stream/BufferStream.hpp" #include "oatpp/parser/json/mapping/ObjectMapper.hpp" using bsoncxx::builder::stream::close_document; using bsoncxx::builder::stream::document; using bsoncxx::builder::stream::finalize; using bsoncxx::builder::stream::open_document; namespace db { Database::Database() : fEliadePool(std::make_shared<mongocxx::pool>( mongocxx::uri("mongodb://127.0.0.1/ELIADE"))) { } oatpp::Object<RunLogDto> Database::GetLastRun( oatpp::data::mapping::type::String expName, std::string collectionName) { auto conn = fEliadePool->acquire(); auto collection = (*conn)["ELIADE"][collectionName]; auto sortOpt = mongocxx::options::find{}; sortOpt.limit(1); auto order = bsoncxx::builder::stream::document{} << "start" << -1 << bsoncxx::builder::stream::finalize; sortOpt.sort(order.view()); auto key = bsoncxx::builder::stream::document{} << "expName" << expName->std_str() << bsoncxx::builder::stream::finalize; auto doc = collection.find_one({key}, sortOpt); auto dto = RunLogDto::createShared(); if (doc) { auto json = bsoncxx::to_json(doc->view()); oatpp::parser::json::mapping::ObjectMapper objMapper; dto = objMapper.readFromString<oatpp::Object<RunLogDto>>(json.c_str()); } return dto; } oatpp::List<oatpp::Object<RunLogDto>> Database::GetRunList( oatpp::data::mapping::type::String expName, std::string collectionName) { auto conn = fEliadePool->acquire(); auto collection = (*conn)["ELIADE"][collectionName]; auto sortOpt = mongocxx::options::find{}; // sortOpt.limit(10); auto order = bsoncxx::builder::stream::document{} << "start" << -1 << bsoncxx::builder::stream::finalize; sortOpt.sort(order.view()); auto key = bsoncxx::builder::stream::document{} << "expName" << expName->std_str() << bsoncxx::builder::stream::finalize; auto cursor = collection.find({key}, sortOpt); // auto dto = RunLogDto::createShared(); auto list = oatpp::List<oatpp::Object<RunLogDto>>::createShared(); for (auto &&doc : cursor) { auto json = bsoncxx::to_json(doc); oatpp::parser::json::mapping::ObjectMapper objMapper; auto dto = objMapper.readFromString<oatpp::Object<RunLogDto>>(json.c_str()); list->push_back(dto); } return list; } oatpp::Object<RunLogDto> Database::PostNewRun(oatpp::Object<RunLogDto> dto, std::string collectionName) { oatpp::parser::json::mapping::ObjectMapper objMapper; auto json = objMapper.writeToString(dto); auto doc = bsoncxx::from_json(json->std_str()); auto conn = fEliadePool->acquire(); auto collection = (*conn)["ELIADE"][collectionName]; auto result = collection.insert_one(doc.view()); dto->id = result->inserted_id().get_oid().value.to_string().c_str(); return dto; } oatpp::Object<RunLogDto> Database::PostUpdateRun(oatpp::Object<RunLogDto> dto, std::string collectionName) { auto conn = fEliadePool->acquire(); auto collection = (*conn)["ELIADE"][collectionName]; try { // Check id auto id = bsoncxx::oid(dto->id->std_str()); auto cursor = collection.find(document{} << "_id" << id << finalize); auto nDoc = std::distance(cursor.begin(), cursor.end()); if (nDoc != 1) throw bsoncxx::exception(); // Update the document in DB collection.update_one( document{} << "_id" << id << finalize, document{} << "$set" << open_document << "runNumber" << dto->runNumber << "start" << dto->start << "stop" << dto->stop << "expName" << dto->expName->std_str() << "comment" << dto->comment->std_str() << "dump" << dto->dump << "dataWriting" << dto->dataWriting << close_document << finalize); } catch (bsoncxx::exception e) { // This should be for any cases? // There is no same id in the DB. or multiple(logically this is not happen) // Make new document into DB bsoncxx::builder::stream::document buf{}; buf << "runNumber" << dto->runNumber << "start" << dto->start << "stop" << dto->stop << "expName" << dto->expName->std_str() << "comment" << dto->comment->std_str() << "dump" << dto->dump << "dataWriting" << dto->dataWriting; auto result = collection.insert_one(buf.view()); dto->id = result->inserted_id().get_oid().value.to_string().c_str(); buf.clear(); } return dto; } oatpp::Object<ExpDto> Database::GetDigiPar() { std::string dbName = "ELIADE"; auto conn = fEliadePool->acquire(); auto collection = (*conn)[dbName]["Digitizer"]; auto opts = mongocxx::options::find{}; opts.limit(1); auto order = bsoncxx::builder::stream::document{} << "Time" << -1 << bsoncxx::builder::stream::finalize; opts.sort(order.view()); auto doc = collection.find_one({}, opts); auto dto = ExpDto::createShared(); if (doc) { dto->_id = doc->view()["_id"].get_oid().value.to_string().c_str(); dto->Name = doc->view()["Name"].get_utf8().value.to_string().c_str(); dto->Time = doc->view()["Time"].get_int64().value; auto digitizersArray = doc->view()["Digitizers"].get_array().value; for (auto it = digitizersArray.begin(); it != digitizersArray.end(); it++) { auto view = (*it).get_document().view(); auto mapper = oatpp::parser::json::mapping::ObjectMapper::createShared(); auto obj = mapper->readFromString<oatpp::Object<DigitizerDto>>( bsoncxx::to_json(view).c_str()); dto->Digitizers->push_back(obj); } } return dto; } } // namespace db
35.711765
80
0.636304
[ "object" ]
b32181904be7c321f267dbfed7cbf7e3651e5874
4,278
cc
C++
2021/day09/lib.cc
kfarnung/advent-of-code
74604578379c518bd7ad959e0088ca55a6986515
[ "MIT" ]
1
2017-12-11T07:08:52.000Z
2017-12-11T07:08:52.000Z
2021/day09/lib.cc
kfarnung/advent-of-code
74604578379c518bd7ad959e0088ca55a6986515
[ "MIT" ]
2
2020-12-01T08:16:42.000Z
2021-05-12T04:54:34.000Z
2021/day09/lib.cc
kfarnung/advent-of-code
74604578379c518bd7ad959e0088ca55a6986515
[ "MIT" ]
null
null
null
#include "lib.h" #include <algorithm> #include <deque> #include <limits> #include <numeric> #include <set> namespace { std::vector<std::vector<uint8_t>> parse_grid(const std::vector<std::string> &input) { std::vector<std::vector<uint8_t>> grid; for (const auto &line : input) { std::vector<uint8_t> row; for (const auto &ch : line) { row.emplace_back(static_cast<uint8_t>(ch - '0')); } grid.emplace_back(std::move(row)); } return grid; } std::vector<std::pair<size_t, size_t>> find_low_points(const std::vector<std::vector<uint8_t>> &grid) { std::vector<std::pair<size_t, size_t>> low_points; for (size_t i = 0; i < grid.size(); ++i) { for (size_t j = 0; j < grid[i].size(); ++j) { uint8_t min_adjacent = std::numeric_limits<uint8_t>::max(); if (i > 0) { min_adjacent = std::min(min_adjacent, grid[i - 1][j]); } if (j > 0) { min_adjacent = std::min(min_adjacent, grid[i][j - 1]); } if (i < grid.size() - 1) { min_adjacent = std::min(min_adjacent, grid[i + 1][j]); } if (j < grid[i].size() - 1) { min_adjacent = std::min(min_adjacent, grid[i][j + 1]); } if (grid[i][j] < min_adjacent) { low_points.emplace_back(i, j); } } } return low_points; } } int64_t day09::run_part1(const std::vector<std::string> &input) { auto grid = parse_grid(input); auto low_points = find_low_points(grid); int64_t risk_levels = 0; for (const auto &point : low_points) { risk_levels += grid[point.first][point.second] + 1; } return risk_levels; } int64_t day09::run_part2(const std::vector<std::string> &input) { auto grid = parse_grid(input); auto low_points = find_low_points(grid); std::vector<int64_t> basin_sizes; for (const auto &point : low_points) { std::set<std::pair<size_t, size_t>> visited; std::deque<std::pair<size_t, size_t>> queue; int64_t basin_size = 0; queue.emplace_back(point); while (!queue.empty()) { auto current = queue.front(); queue.pop_front(); if (visited.find(current) != visited.end()) { continue; } visited.emplace(current); basin_size += 1; if (current.first > 0 && grid[current.first - 1][current.second] < 9 && visited.find(std::make_pair(current.first - 1, current.second)) == visited.end()) { queue.emplace_back(current.first - 1, current.second); } if (current.second > 0 && grid[current.first][current.second - 1] < 9 && visited.find(std::make_pair(current.first, current.second - 1)) == visited.end()) { queue.emplace_back(current.first, current.second - 1); } if (current.first < grid.size() - 1 && grid[current.first + 1][current.second] < 9 && visited.find(std::make_pair(current.first + 1, current.second)) == visited.end()) { queue.emplace_back(current.first + 1, current.second); } if (current.second < grid[current.first].size() - 1 && grid[current.first][current.second + 1] < 9 && visited.find(std::make_pair(current.first, current.second + 1)) == visited.end()) { queue.emplace_back(current.first, current.second + 1); } } basin_sizes.emplace_back(basin_size); } std::sort(begin(basin_sizes), end(basin_sizes)); int64_t basins_score = 1; for (size_t i = 0; i < 3; ++i) { basins_score *= basin_sizes[basin_sizes.size() - 1 - i]; } return basins_score; }
27.960784
105
0.496494
[ "vector" ]
b329e8b870cb327189b15df124f6da7d4bb9d50e
1,417
cpp
C++
Facebook/C++/Question-3-Solution.cpp
echpee/Hacktoberfest_Interview_Questions_2020
e62b3adaae36f209b7c703a8ec84336a7e57cf1d
[ "MIT" ]
2
2020-10-03T09:21:13.000Z
2020-10-26T05:58:26.000Z
Facebook/C++/Question-3-Solution.cpp
echpee/Hacktoberfest_Interview_Questions_2020
e62b3adaae36f209b7c703a8ec84336a7e57cf1d
[ "MIT" ]
15
2020-10-03T00:07:11.000Z
2020-10-25T08:58:48.000Z
Facebook/C++/Question-3-Solution.cpp
echpee/Hacktoberfest_Interview_Questions_2020
e62b3adaae36f209b7c703a8ec84336a7e57cf1d
[ "MIT" ]
23
2020-10-03T01:35:56.000Z
2020-10-25T16:33:29.000Z
#include <bits/stdc++.h> using namespace std; #define mp make_pair #define pb push_back #define f first #define s second // Function to find all pairs in both arrays // whose sum is equal to given value x void findPairs(int arr1[], int arr2[], int n, int m, int x) { // Insert all elements of first array in a hash int i , j; unordered_set<int> s; for (i = 0; i < n; i++) s.insert(arr1[i]); vector<pair<int,int>> v;// this vector is used to store the Pairs. int c = 0;// variable c is used to store the counts of Pairs // Subtract sum from second array elements one // by one and check it's present in array first // or not for (j = 0; j < m; j++) { if (s.find(x - arr2[j]) != s.end()) { c++; v.pb(mp(x - arr2[j] , arr2[j])); } } if(c > 0) { cout << "Pairs Count :- " << c << "\n"; cout << "Pairs are :- " << "\n"; for(i = 0; i < v.size();i++) cout << v[i].f << " " << v[i].s << " " << "\n"; } else cout << "No Pair Found" << "\n"; } // Driver code int main() { int arr1[] = { 1, 0, -4, 7, 6, 4 }; int arr2[] = { 0, 2, 4, -3, 2, 1 }; int x = 8; int n = sizeof(arr1) / sizeof(int); int m = sizeof(arr2) / sizeof(int); findPairs(arr1, arr2, n, m, x); return 0; }
26.735849
70
0.478476
[ "vector" ]
b333147806b452079d35f201a59e8b6095e78d4e
8,248
cpp
C++
c++调用py/Format Strings for PyArg_ParseTuple.cpp
keetsky/c_c-_python_mutprog
f918db6ef1624b8c16efe2b4d384dd4c6f72d3dd
[ "Apache-2.0" ]
3
2021-01-26T07:52:50.000Z
2021-11-25T11:28:36.000Z
c++调用py/Format Strings for PyArg_ParseTuple.cpp
keetsky/c_c-_python_mutprog
f918db6ef1624b8c16efe2b4d384dd4c6f72d3dd
[ "Apache-2.0" ]
null
null
null
c++调用py/Format Strings for PyArg_ParseTuple.cpp
keetsky/c_c-_python_mutprog
f918db6ef1624b8c16efe2b4d384dd4c6f72d3dd
[ "Apache-2.0" ]
null
null
null
next up previous Extending and Embedding the Python Interpreter contents Next: 1.8 Keyword Parsing with Up: 1. Extending Python with Previous: 1.6 Calling Python Functions 1.7 Format Strings for PyArg_ParseTuple() The PyArg_ParseTuple() function is declared as follows: int PyArg_ParseTuple(PyObject *arg, char *format, ...); The arg argument must be a tuple object containing an argument list passed from Python to a C function. The format argument must be a format string, whose syntax is explained below. The remaining arguments must be addresses of variables whose type is determined by the format string. For the conversion to succeed, the arg object must match the format and the format must be exhausted. Note that while PyArg_ParseTuple() checks that the Python arguments have the required types, it cannot check the validity of the addresses of C variables passed to the call: if you make mistakes there, your code will probably crash or at least overwrite random bits in memory. So be careful! A format string consists of zero or more ``format units''. A format unit describes one Python object; it is usually a single character or a parenthesized sequence of format units. With a few exceptions, a format unit that is not a parenthesized sequence normally corresponds to a single address argument to PyArg_ParseTuple(). In the following description, the quoted form is the format unit; the entry in (round) parentheses is the Python object type that matches the format unit; and the entry in [square] brackets is the type of the C variable(s) whose address should be passed. (Use the "&"operator to pass a variable's address.) Note that any Python object references which are provided to the caller are borrowed references; do not decrement their reference count! "s" (string) [char *] Convert a Python string to a C pointer to a character string. You must not provide storage for the string itself; a pointer to an existing string is stored into the character pointer variable whose address you pass. The C string is null-terminated. The Python string must not contain embedded null bytes; if it does, a TypeError exception is raised. "s#" (string) [char *, int] This variant on "s" stores into two C variables, the first one a pointer to a character string, the second one its length. In this case the Python string may contain embedded null bytes. "z" (string or None) [char *] Like "s", but the Python object may also be None, in which case the C pointer is set to NULL. "z#" (string or None) [char *, int] This is to "s#" as "z" is to "s". "b" (integer) [char] Convert a Python integer to a tiny int, stored in a C char. "h" (integer) [short int] Convert a Python integer to a C short int. "i" (integer) [int] Convert a Python integer to a plain C int. "l" (integer) [long int] Convert a Python integer to a C long int. "c" (string of length 1) [char] Convert a Python character, represented as a string of length 1, to a C char. "f" (float) [float] Convert a Python floating point number to a C float. "d" (float) [double] Convert a Python floating point number to a C double. "D" (complex) [Py_complex] Convert a Python complex number to a C Py_complex structure. "O" (object) [PyObject *] Store a Python object (without any conversion) in a C object pointer. The C program thus receives the actual object that was passed. The object's reference count is not increased. The pointer stored is not NULL. "O!" (object) [typeobject, PyObject *] Store a Python object in a C object pointer. This is similar to "O", but takes two C arguments: the first is the address of a Python type object, the second is the address of the C variable (of type PyObject *) into which the object pointer is stored. If the Python object does not have the required type, TypeError is raised. "O&" (object) [converter, anything] Convert a Python object to a C variable through a converter function. This takes two arguments: the first is a function, the second is the address of a C variable (of arbitrary type), converted to void *. The converter function in turn is called as follows: status = converter(object, address); where object is the Python object to be converted and address is the void * argument that was passed to PyArg_ConvertTuple(). The returned status should be 1 for a successful conversion and 0 if the conversion has failed. When the conversion fails, the converter function should raise an exception. "S" (string) [PyStringObject *] Like "O" but requires that the Python object is a string object. Raises TypeError if the object is not a string object. The C variable may also be declared as PyObject *. "(items)" (tuple) [matching-items] The object must be a Python sequence whose length is the number of format units in items. The C arguments must correspond to the individual format units in items. Format units for sequences may be nested. Note: Prior to Python version 1.5.2, this format specifier only accepted a tuple containing the individual parameters, not an arbitrary sequence. Code which previously caused TypeError to be raised here may now proceed without an exception. This is not expected to be a problem for existing code. It is possible to pass Python long integers where integers are requested; however no proper range checking is done -- the most significant bits are silently truncated when the receiving field is too small to receive the value (actually, the semantics are inherited from downcasts in C -- your mileage may vary). A few other characters have a meaning in a format string. These may not occur inside nested parentheses. They are: "|" Indicates that the remaining arguments in the Python argument list are optional. The C variables corresponding to optional arguments should be initialized to their default value -- when an optional argument is not specified, PyArg_ParseTuple() does not touch the contents of the corresponding C variable(s). ":" The list of format units ends here; the string after the colon is used as the function name in error messages (the ``associated value'' of the exception that PyArg_ParseTuple() raises). ";" The list of format units ends here; the string after the colon is used as the error message instead of the default error message. Clearly, ":" and ";" mutually exclude each other. Some example calls: int ok; int i, j; long k, l; char *s; int size; ok = PyArg_ParseTuple(args, ""); /* No arguments */ /* Python call: f() */ ok = PyArg_ParseTuple(args, "s", &s); /* A string */ /* Possible Python call: f('whoops!') */ ok = PyArg_ParseTuple(args, "lls", &k, &l, &s); /* Two longs and a string */ /* Possible Python call: f(1, 2, 'three') */ ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size); /* A pair of ints and a string, whose size is also returned */ /* Possible Python call: f((1, 2), 'three') */ { char *file; char *mode = "r"; int bufsize = 0; ok = PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize); /* A string, and optionally another string and an integer */ /* Possible Python calls: f('spam') f('spam', 'w') f('spam', 'wb', 100000) */ } { int left, top, right, bottom, h, v; ok = PyArg_ParseTuple(args, "((ii)(ii))(ii)", &left, &top, &right, &bottom, &h, &v); /* A rectangle and a point */ /* Possible Python call: f(((0, 0), (400, 300)), (10, 10)) */ } { Py_complex c; ok = PyArg_ParseTuple(args, "D:myfunction", &c); /* a complex, also providing a function name for errors */ /* Possible Python call: myfunction(1+2j) */ } next up previous Extending and Embedding the Python Interpreter contents Next: 1.8 Keyword Parsing with Up: 1. Extending Python with Previous: 1.6 Calling Python Functions Send comments on this document to python-docs@python.org.
58.084507
633
0.701382
[ "object" ]
b334c4cbdba00b08dbbca2c271f56e829638d4e8
15,819
cpp
C++
proj.android/Photon-AndroidNDK_SDK/Demos/demo_loadBalancing/src/NetworkLogic.cpp
h-iwata/MultiplayPaint
b170ec60bdda93c041ef59625ac2d6eba54d0335
[ "MIT" ]
1
2016-05-31T22:56:26.000Z
2016-05-31T22:56:26.000Z
proj.ios_mac/Photon-iOS_SDK/Demos/demo_loadBalancing/src/NetworkLogic.cpp
h-iwata/MultiplayPaint
b170ec60bdda93c041ef59625ac2d6eba54d0335
[ "MIT" ]
null
null
null
proj.ios_mac/Photon-iOS_SDK/Demos/demo_loadBalancing/src/NetworkLogic.cpp
h-iwata/MultiplayPaint
b170ec60bdda93c041ef59625ac2d6eba54d0335
[ "MIT" ]
null
null
null
#include "NetworkLogic.h" static const ExitGames::Common::JString appId = L"<no-app-id>"; // set your app id here static const ExitGames::Common::JString appVersion = L"1.0"; static const bool autoLobbbyStats = true; static const bool useDefaultRegion = false; static const ExitGames::Common::JString PLAYER_NAME = #if defined _EG_MARMALADE_PLATFORM # if defined I3D_ARCH_X86 # if defined _EG_MS_COMPILER L"Marmalade X86 Windows"; # else L"Marmalade X86 OS X"; # endif # elif defined I3D_ARCH_ARM L"Marmalade ARM"; # elif defined I3D_ARCH_MIPS L"Marmalade MIPS"; # else L"unknown Marmalade platform"; # endif #elif defined _EG_WINDOWS_PLATFORM L"Windows"; #elif defined _EG_IPHONE_PLATFORM L"iOS"; #elif defined _EG_IMAC_PLATFORM L"OS X"; #elif defined _EG_ANDROID_PLATFORM L"Android"; #elif defined _EG_BLACKBERRY_PLATFORM L"Blackberry"; #elif defined _EG_PS3_PLATFORM L"PS3"; #elif defined _EG_LINUX_PLATFORM L"Linux"; #elif defined _EG_PS4_PLATFORM L"PS4"; #else L"unknown platform"; #endif ExitGames::Common::JString& NetworkLogicListener::toString(ExitGames::Common::JString& retStr, bool /*withTypes*/) const { return retStr; } State StateAccessor::getState(void) const { return mState; } void StateAccessor::setState(State newState) { mState = newState; for(unsigned int i=0; i<mStateUpdateListeners.getSize(); i++) mStateUpdateListeners[i]->stateUpdate(newState); } void StateAccessor::registerForStateUpdates(NetworkLogicListener* listener) { mStateUpdateListeners.addElement(listener); } Input NetworkLogic::getLastInput(void) const { return mLastInput; } void NetworkLogic::setLastInput(Input newInput) { mLastInput = newInput; } State NetworkLogic::getState(void) const { return mStateAccessor.getState(); } // functions NetworkLogic::NetworkLogic(OutputListener* listener, const ExitGames::LoadBalancing::AuthenticationValues& authenticationValues) #ifdef _EG_MS_COMPILER # pragma warning(push) # pragma warning(disable:4355) #endif : mLoadBalancingClient(*this, appId, appVersion, PLAYER_NAME+GETTIMEMS(), ExitGames::Photon::ConnectionProtocol::UDP, authenticationValues, autoLobbbyStats, useDefaultRegion) , mLastActorNr(0) , mLastInput(INPUT_NON) , mpOutputListener(listener) #ifdef _EG_MS_COMPILER # pragma warning(pop) #endif { mStateAccessor.setState(STATE_INITIALIZED); mLoadBalancingClient.setDebugOutputLevel(DEBUG_RELEASE(ExitGames::Common::DebugLevel::INFO, ExitGames::Common::DebugLevel::WARNINGS)); // that instance of LoadBalancingClient and its implementation details mLogger.setListener(*this); mLogger.setDebugOutputLevel(DEBUG_RELEASE(ExitGames::Common::DebugLevel::INFO, ExitGames::Common::DebugLevel::WARNINGS)); // this class ExitGames::Common::Base::setListener(this); ExitGames::Common::Base::setDebugOutputLevel(DEBUG_RELEASE(ExitGames::Common::DebugLevel::INFO, ExitGames::Common::DebugLevel::WARNINGS)); // all classes that inherit from Base } void NetworkLogic::registerForStateUpdates(NetworkLogicListener* listener) { mStateAccessor.registerForStateUpdates(listener); } void NetworkLogic::connect(void) { mpOutputListener->writeLine(ExitGames::Common::JString(L"connecting to Photon")); mLoadBalancingClient.connect(); mStateAccessor.setState(STATE_CONNECTING); } void NetworkLogic::disconnect(void) { mLoadBalancingClient.disconnect(); } void NetworkLogic::opCreateRoom(void) { ExitGames::Common::JString tmp; mLoadBalancingClient.opCreateRoom(tmp=GETTIMEMS(), true, true, 4, ExitGames::Common::Hashtable(), ExitGames::Common::JVector<ExitGames::Common::JString>(), ExitGames::Common::JString(), 1, INT_MAX/2, 10000); mStateAccessor.setState(STATE_JOINING); mpOutputListener->writeLine(ExitGames::Common::JString(L"creating room ") + tmp + L"..."); } void NetworkLogic::opJoinRandomRoom(void) { mLoadBalancingClient.opJoinRandomRoom(); } void NetworkLogic::run(void) { State state = mStateAccessor.getState(); if(mLastInput == INPUT_EXIT && state != STATE_DISCONNECTING && state != STATE_DISCONNECTED) { disconnect(); mStateAccessor.setState(STATE_DISCONNECTING); mpOutputListener->writeLine(L"terminating application"); } else { switch(state) { case STATE_INITIALIZED: connect(); mStateAccessor.setState(STATE_CONNECTING); mpOutputListener->writeLine("connecting"); break; case STATE_CONNECTING: break; // wait for callback case STATE_CONNECTED: switch(mLastInput) { case INPUT_1: // create Game mpOutputListener->writeLine(L"\n========================="); opCreateRoom(); break; case INPUT_2: // join Game mpOutputListener->writeLine(L"\n========================="); // remove false to enable rejoin if(false && mLastJoinedRoom.length()) { mpOutputListener->writeLine(ExitGames::Common::JString(L"rejoining ") + mLastJoinedRoom + " with actorNr = " + mLastActorNr + "..."); mLoadBalancingClient.opJoinRoom(mLastJoinedRoom, true, mLastActorNr); } else { mpOutputListener->writeLine(ExitGames::Common::JString(L"joining random room...")); opJoinRandomRoom(); } mStateAccessor.setState(STATE_JOINING); break; default: // no or illegal input -> stay waiting for legal input break; } break; case STATE_JOINING: break; // wait for callback case STATE_JOINED: sendEvent(); switch(mLastInput) { case INPUT_1: // leave Game mLoadBalancingClient.opLeaveRoom(); mpOutputListener->writeLine(L""); mpOutputListener->writeLine(L"leaving room"); mStateAccessor.setState(STATE_LEAVING); break; case INPUT_2: // leave Game mLoadBalancingClient.opLeaveRoom(true); mpOutputListener->writeLine(L""); mpOutputListener->writeLine(L"leaving room (will come back)"); mStateAccessor.setState(STATE_LEAVING); break; default: // no or illegal input -> stay waiting for legal input break; } break; case STATE_LEAVING: break; // wait for callback case STATE_LEFT: mStateAccessor.setState(STATE_CONNECTED); break; case STATE_DISCONNECTING: break; // wait for callback default: break; } } mLastInput = INPUT_NON; mLoadBalancingClient.service(); } void NetworkLogic::sendEvent(void) { static int64 count = 0; mLoadBalancingClient.opRaiseEvent(false, ++count, 0); mpOutputListener->write(ExitGames::Common::JString(L"s") + count + L" "); } // protocol implementations void NetworkLogic::debugReturn(ExitGames::Common::DebugLevel::DebugLevel /*debugLevel*/, const ExitGames::Common::JString& string) { mpOutputListener->debugReturn(string); } void NetworkLogic::connectionErrorReturn(int errorCode) { EGLOG(ExitGames::Common::DebugLevel::ERRORS, L"code: %d", errorCode); mpOutputListener->writeLine(ExitGames::Common::JString(L"received connection error ") + errorCode); mStateAccessor.setState(STATE_DISCONNECTED); } void NetworkLogic::clientErrorReturn(int errorCode) { EGLOG(ExitGames::Common::DebugLevel::ERRORS, L"code: %d", errorCode); mpOutputListener->writeLine(ExitGames::Common::JString(L"received error ") + errorCode + L" from client"); } void NetworkLogic::warningReturn(int warningCode) { EGLOG(ExitGames::Common::DebugLevel::WARNINGS, L"code: %d", warningCode); mpOutputListener->writeLine(ExitGames::Common::JString(L"received warning ") + warningCode + L" from client"); } void NetworkLogic::serverErrorReturn(int errorCode) { EGLOG(ExitGames::Common::DebugLevel::ERRORS, L"code: %d", errorCode); mpOutputListener->writeLine(ExitGames::Common::JString(L"received error ") + errorCode + " from server"); } void NetworkLogic::joinRoomEventAction(int playerNr, const ExitGames::Common::JVector<int>& /*playernrs*/, const ExitGames::LoadBalancing::Player& player) { EGLOG(ExitGames::Common::DebugLevel::INFO, L"%ls joined the game", player.getName().cstr()); mpOutputListener->writeLine(L""); mpOutputListener->writeLine(ExitGames::Common::JString(L"player ") + playerNr + L" " + player.getName() + L" has joined the game"); } void NetworkLogic::leaveRoomEventAction(int playerNr, bool isInactive) { EGLOG(ExitGames::Common::DebugLevel::INFO, L""); mpOutputListener->writeLine(L""); mpOutputListener->writeLine(ExitGames::Common::JString(L"player ") + playerNr + L" has left the game"); } void NetworkLogic::disconnectEventAction(int playerNr) { EGLOG(ExitGames::Common::DebugLevel::INFO, L""); mpOutputListener->writeLine(L""); mpOutputListener->writeLine(ExitGames::Common::JString(L"player ") + playerNr + L" has disconnected"); } void NetworkLogic::customEventAction(int /*playerNr*/, nByte /*eventCode*/, const ExitGames::Common::Object& eventContent) { // you do not receive your own events, unless you specify yourself as one of the receivers explicitly, so you must start 2 clients, to receive the events, which you have sent, as sendEvent() uses the default receivers of opRaiseEvent() (all players in same room like the sender, except the sender itself) EGLOG(ExitGames::Common::DebugLevel::ALL, L""); mpOutputListener->write(ExitGames::Common::JString(L"r") + ExitGames::Common::ValueObject<long long>(eventContent).getDataCopy() + L" "); } void NetworkLogic::connectReturn(int errorCode, const ExitGames::Common::JString& errorString) { EGLOG(ExitGames::Common::DebugLevel::INFO, L""); if(errorCode) { EGLOG(ExitGames::Common::DebugLevel::ERRORS, L"%ls", errorString.cstr()); mStateAccessor.setState(STATE_DISCONNECTING); return; } mpOutputListener->writeLine(L"connected"); mStateAccessor.setState(STATE_CONNECTED); } void NetworkLogic::disconnectReturn(void) { EGLOG(ExitGames::Common::DebugLevel::INFO, L""); mpOutputListener->writeLine(L"disconnected"); mStateAccessor.setState(STATE_DISCONNECTED); } void NetworkLogic::createRoomReturn(int localPlayerNr, const ExitGames::Common::Hashtable& /*gameProperties*/, const ExitGames::Common::Hashtable& /*playerProperties*/, int errorCode, const ExitGames::Common::JString& errorString) { EGLOG(ExitGames::Common::DebugLevel::INFO, L""); if(errorCode) { EGLOG(ExitGames::Common::DebugLevel::ERRORS, L"%ls", errorString.cstr()); mpOutputListener->writeLine(L"opCreateRoom() failed: " + errorString); mStateAccessor.setState(STATE_CONNECTED); return; } mLastJoinedRoom = mLoadBalancingClient.getCurrentlyJoinedRoom().getName(); mLastActorNr = localPlayerNr; EGLOG(ExitGames::Common::DebugLevel::INFO, L"localPlayerNr: %d", localPlayerNr); mpOutputListener->writeLine(L"... room " + mLoadBalancingClient.getCurrentlyJoinedRoom().getName() + " has been created"); mpOutputListener->writeLine(L"regularly sending dummy events now"); mStateAccessor.setState(STATE_JOINED); } void NetworkLogic::joinRoomReturn(int localPlayerNr, const ExitGames::Common::Hashtable& /*gameProperties*/, const ExitGames::Common::Hashtable& /*playerProperties*/, int errorCode, const ExitGames::Common::JString& errorString) { EGLOG(ExitGames::Common::DebugLevel::INFO, L""); if(errorCode) { mLastJoinedRoom = ""; mLastActorNr = 0; EGLOG(ExitGames::Common::DebugLevel::ERRORS, L"%ls", errorString.cstr()); mpOutputListener->writeLine(L"opJoinRoom() failed: " + errorString); mStateAccessor.setState(STATE_CONNECTED); return; } EGLOG(ExitGames::Common::DebugLevel::INFO, L"localPlayerNr: %d", localPlayerNr); mpOutputListener->writeLine(L"... room " + mLoadBalancingClient.getCurrentlyJoinedRoom().getName() + " has been successfully joined"); mpOutputListener->writeLine(L"regularly sending dummy events now"); mStateAccessor.setState(STATE_JOINED); } void NetworkLogic::joinRandomRoomReturn(int localPlayerNr, const ExitGames::Common::Hashtable& /*gameProperties*/, const ExitGames::Common::Hashtable& /*playerProperties*/, int errorCode, const ExitGames::Common::JString& errorString) { EGLOG(ExitGames::Common::DebugLevel::INFO, L""); if(errorCode) { EGLOG(ExitGames::Common::DebugLevel::ERRORS, L"%ls", errorString.cstr()); mpOutputListener->writeLine(L"opJoinRandomRoom() failed: " + errorString); mStateAccessor.setState(STATE_CONNECTED); return; } mLastJoinedRoom = mLoadBalancingClient.getCurrentlyJoinedRoom().getName(); mLastActorNr = localPlayerNr; EGLOG(ExitGames::Common::DebugLevel::INFO, L"localPlayerNr: %d", localPlayerNr); mpOutputListener->writeLine(L"... room " + mLoadBalancingClient.getCurrentlyJoinedRoom().getName() + " has been successfully joined"); mpOutputListener->writeLine(L"regularly sending dummy events now"); mStateAccessor.setState(STATE_JOINED); } void NetworkLogic::leaveRoomReturn(int errorCode, const ExitGames::Common::JString& errorString) { EGLOG(ExitGames::Common::DebugLevel::INFO, L""); if(errorCode) { EGLOG(ExitGames::Common::DebugLevel::ERRORS, L"%ls", errorString.cstr()); mpOutputListener->writeLine(L"opLeaveRoom() failed: " + errorString); mStateAccessor.setState(STATE_DISCONNECTING); return; } mStateAccessor.setState(STATE_LEFT); mpOutputListener->writeLine(L"room has been successfully left"); } void NetworkLogic::joinLobbyReturn(void) { EGLOG(ExitGames::Common::DebugLevel::INFO, L""); mpOutputListener->writeLine(L"joined lobby"); } void NetworkLogic::leaveLobbyReturn(void) { EGLOG(ExitGames::Common::DebugLevel::INFO, L""); mpOutputListener->writeLine(L"left lobby"); } void NetworkLogic::onLobbyStatsResponse(const ExitGames::Common::JVector<ExitGames::LoadBalancing::LobbyStatsResponse>& lobbyStats) { EGLOG(ExitGames::Common::DebugLevel::INFO, L"onLobbyStatsUpdate: %ls", lobbyStats.toString().cstr()); mpOutputListener->writeLine(L"LobbyStats: " + lobbyStats.toString()); } void NetworkLogic::onLobbyStatsUpdate(const ExitGames::Common::JVector<ExitGames::LoadBalancing::LobbyStatsResponse>& lobbyStats) { EGLOG(ExitGames::Common::DebugLevel::INFO, L"onLobbyStatsUpdate: %ls", lobbyStats.toString().cstr()); mpOutputListener->writeLine(L"LobbyStats: " + lobbyStats.toString()); } void NetworkLogic::onAvailableRegions(const ExitGames::Common::JVector<ExitGames::Common::JString>& availableRegions, const ExitGames::Common::JVector<ExitGames::Common::JString>& availableRegionServers) { EGLOG(ExitGames::Common::DebugLevel::INFO, L"onAvailableRegions: %ls", availableRegions.toString().cstr(), availableRegionServers.toString().cstr()); mpOutputListener->writeLine(L"onAvailableRegions: " + availableRegions.toString() + L" / " + availableRegionServers.toString()); // select first region from list mpOutputListener->writeLine(L"selecting region: " + availableRegions[0]); mLoadBalancingClient.selectRegion(availableRegions[0]); }
38.963054
306
0.693723
[ "object" ]
b3389de53ddc680d48778fc864bf5147469ed3f0
1,451
hpp
C++
distribution_model/boost/statistics/detail/distribution/model/key/prior_model_dataset_spec.hpp
rogard/boost_sandbox_statistics
16aacbc716a31a9f7bb6c535b1c90dc343282a23
[ "BSL-1.0" ]
null
null
null
distribution_model/boost/statistics/detail/distribution/model/key/prior_model_dataset_spec.hpp
rogard/boost_sandbox_statistics
16aacbc716a31a9f7bb6c535b1c90dc343282a23
[ "BSL-1.0" ]
null
null
null
distribution_model/boost/statistics/detail/distribution/model/key/prior_model_dataset_spec.hpp
rogard/boost_sandbox_statistics
16aacbc716a31a9f7bb6c535b1c90dc343282a23
[ "BSL-1.0" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // distribution::model::key::prior_model_dataset_spec.hpp // // // // Copyright 2009 Erwann Rogard. Distributed under the Boost // // Software License, Version 1.0. (See accompanying file // // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // /////////////////////////////////////////////////////////////////////////////// #ifndef BOOST_STATISTICS_DETAIL_DISTRIBUTION_MODEL_KEY_PRIOR_MODEL_PRIOR_MODEL_DATASET_SPEC_HPP_ER_2009 #define BOOST_STATISTICS_DETAIL_DISTRIBUTION_MODEL_KEY_PRIOR_MODEL_PRIOR_MODEL_DATASET_SPEC_HPP_ER_2009 #include <boost/parameter/parameters.hpp> #include <boost/statistics/detail/distribution/model/key/prior.hpp> #include <boost/statistics/detail/distribution/model/key/model.hpp> #include <boost/statistics/detail/distribution/model/key/dataset.hpp> namespace boost{ namespace statistics{ namespace detail{ namespace distribution{ namespace model{ struct prior_model_dataset_spec{ typedef boost::parameter::parameters< boost::parameter::required<tag::prior>, boost::parameter::required<tag::model>, boost::parameter::required<tag::dataset> > type; }; }// model }// distribution }// detail }// statistics }// boost #endif
40.305556
103
0.605789
[ "model" ]
b34029635cb5e6bbace0876d60f587a8dbb98366
1,458
cpp
C++
Backtracking/37. Sudoku Solver.cpp
prashantsingh20/LeetCode-Solutions
d8219691820c9103d368c4ea4edf4f837a0a20ad
[ "MIT" ]
2
2021-07-07T19:09:55.000Z
2021-07-14T04:20:47.000Z
Backtracking/37. Sudoku Solver.cpp
prashantsingh20/LeetCode-Solutions
d8219691820c9103d368c4ea4edf4f837a0a20ad
[ "MIT" ]
null
null
null
Backtracking/37. Sudoku Solver.cpp
prashantsingh20/LeetCode-Solutions
d8219691820c9103d368c4ea4edf4f837a0a20ad
[ "MIT" ]
null
null
null
/* 37. Sudoku Solver https://leetcode.com/problems/sudoku-solver/ */ class Solution { public: bool safe(int i, int j, char c, map<string, bool>& mp, bool erase) { string x = "row" + to_string(i) + " "; string y = "col" + to_string(j) + " "; string z = "box" + to_string(i / 3) + to_string(j / 3) + " "; x.push_back(c), y.push_back(c), z.push_back(c); if (erase) { mp.erase(x), mp.erase(y), mp.erase(z); return 0; } if (mp.count(x) || mp.count(y) || mp.count(z)) return 0; mp[x] = mp[y] = mp[z] = true; return 1; } bool helper(vector<vector<char> >& board, int row, int col, map<string, bool>& mp) { if (col >= 9) row++, col = 0; if (row >= 9) return 1; if (board[row][col] != '.') return helper(board, row, col + 1, mp); for (char num = '1'; num <= '9'; num++) { if (!safe(row, col, num, mp, 0)) continue; board[row][col] = num; if (helper(board, row, col + 1, mp)) return 1; safe(row, col, num, mp, true); } board[row][col] = '.'; return 0; } void solveSudoku(vector<vector<char> >& board) { map<string, bool> mp; // Marking existing numbers of Sudoku for (int i = 0; i < 9; i++) for (int j = 0; j < 9; j++) if(board[i][j]!='.') safe(i, j, board[i][j], mp, 0); bool ans = helper(board, 0, 0, mp); } };
26.035714
83
0.484911
[ "vector" ]